text:
/* OUCS for ePub March 2011 */
.homepagesideheading {
    margin-top: 0px;
    margin-bottom: 5px;
    padding: 2pt;
    color: #333;
    background-color: #fff;
    text-align: left;
}
.genlinks {
    font-size: 0.8em;
    border: 1px solid #eee;
    margin: 10px 0em 10px 0em;
    background-color: #fff;
    position: relative;
    clear: both;
}
.genlinks p {
    padding: 5px;
}
span.rsstitle {
    font-size: 0.9em;
    font-weight: bold;
    background-color: #97ADFF;
    color: #333;
}
span.rsstitle a {
    color: #333;
    padding: 2px;
    background-color: #ffffff;
}
.rssdate {
    display: none;
}
.rsscreationdate {
    display: none;
}
span.rssdescription {
    font-size: 0.8em;
    margin-bottom: 5px;
    padding: 5px;
    padding-left: 6px;
    border-bottom: 5px solid #00236B;
    display: block;
    background-color: #ffffff;
}
/* images */
a img {
    border: none;
}
img.border {
    border: 1px solid black;
}
img.bordergrey {
    border: 3px solid #ccc;
    padding: 5px;
}
.pic-wrapped img {
    float: left;
    padding: 5px;
    clear: left;
    margin: 0px 1.25em 0px 0px;
}
.floatimage {
    float: left;
    margin-right: 6px;
    vertical-align: top;
    margin-bottom: 5px;
}
img.sld {
    float: right;
    top: 0;
}
img.wrap {
    float: left;
    margin: 5px;
}
img.centreimage {
    margin-left: auto;
    margin-right: auto;
    display: block;
}
div.centreimage {
    display: inline;
}
/* end images styles */
/* figures */
img.center {
    margin-left: 20pt;
}
.centre {
    margin-left: auto;
    margin-right: auto;
    display: block;
    text-align: center;
}
span.centre img {
    border: 0;
}
div.pic-right {
    float: right;
    padding: 5px;
}
div.pic-right-clear {
    float: right;
    padding: 5px;
    clear: both;
}
div.pic-left {
    float: left;
    padding: 5px;
    clear: left;
    margin: 0.35em 0px;
}
div#floatright.ab {
    float: right;
    padding: 5px;
    width: 125px;
}
div#floatright150.ab {
    float: right;
    padding: 5px;
    width: 150px;
    border: 1px solid red;
}
div#floatright150 {
    float: right;
    padding: 5px;
    width: 150px;
}
div#pullout.ab {
    background-color: #eee;
    border: 1px solid #BBBBBB;
    color: #555555;
    float: right;
    font-size: 1.2em;
    width: 19em;
}
.spaceimage {
    margin: 10px;
/* used to space images out in lists */
}
.margin-right {
    margin-right: 20px;
}
.pullquote {
    margin: 20px;
    border: 1px solid #CCCCCC;
    padding: 5px;
    background-color: #EEEFFF;
    font-size: 0.9em;
}
p.pullQuote {
    clear: both;
}
span.pullQuote {
    display: block;
    float: right;
    font-size: 140%;
    font-style: italic;
    margin: 0.5cm;
}
/* tables */
.rules {
    width: 90%;
    padding: 5px;
}
.label {
    background-color: #ccc;
    padding: 5px;
    color: #333;
    text-align: left;
}
table {
    margin-top: 18pt;
    border-collapse: collapse;
    color: black;
    margin-bottom: 10px;
}
table.annrep {
    width: 40%;
    border-collapse: collapse;
    margin-bottom: 10px;
    text-align: center;
}
table.hc_annrep {
    width: 80%;
    border-collapse: collapse;
    margin-bottom: 10px;
}
table.annrep td, table.annrep th, table.hc_annrep td, table.hc_annrep th {
    border: 1px solid black;
}
table.fiveyr {
    width: 90%;
    padding: 5px;
}
.grade1 {
/* light faded red */background-color: #f66
}
.grade2 {
/* light hard orange */background-color: #f93
}
.grade3 {
/* light faded yellow */background-color: #ff6
}
.grade4 {
/* light dull spring */background-color: #9c6
}
.grade5 {
/* pale dull azure */background-color: #9cf
}
.grade6 {
/* greyish */background-color: #eee
}
th {
    text-align: left;
    background-color: #AAAAAA;
    font-weight: bold;
    color: #fff;
}
td:first-child {
    text-align: left;
}
td.alignleft {
    text-align: left;
}
td.aligncenter {
    text-align: center;
}
td.alignright {
    text-align: right;
}
td.alignboth {
    text-align: justify;
}
td {
    padding: 2px;
    font-size: 0.9em;
}
/* Table cell background colours */
.divlabel {
    background-color: #BBBBBB;
    font-size: large;
    font-weight: bold;
    padding: 5px;
    text-align: center;
}
.Label {
    background-color: #DDEEEE;
    color: #000333;
    font-weight: bold;
    padding: 3px;
}
/* --------------------------- */
.clear {
    clear: both;
}
#col-b {
    background-color: #fff;
}
#tbdata h2 {
    color: #000066;
    margin: 0;
}
#info {
    top: 50px;
    position: relative;
    border: solid red 1px;
    margin-bottom: 10px;
}
.sidelist li a:hover {
    border-right: none;
    border-bottom: 1px solid #fff;
    text-decoration: none;
}
#footer {
    border-top: 3px solid #000066;
    text-align: center;
    font-family: arial,sans-serif;
    font-size: 0.8em;
    clear: both;
}
/* Side menu styles */
#menu ul li a {
    color: #000;
    text-decoration: none;
}
#menu ul li {
    margin: 0;
    padding: 2.5px;
    list-style: none;
    display: block;
    border-bottom: 1px solid #eee;
}
#menu ul li a:hover {
    color: #000;
    text-decoration: underline;
    background-color: #fff;
    display: block;
}
#menu ul {
    margin: 0;
    padding: 0;
}
/* ----------------------------------------------- */
#footer img {
    right: 50%;
    padding: 5px;
}
#mainMenu {
    position: relative;
    text-align: center;
/* width: 99%;needed for ie to work properly! see ie sheet */
    background-color: #eee;
    border-bottom: 1px solid #000;
    border-top: 1px solid #000;
    color: #000;
    margin: 0px;
    padding: 2px 0px 2px 10px;
}
#menuList {
    margin: 0px;
    padding: 0px;
}
#menuList ul {
    margin: 0px;
    padding: 0px;
    margin-left: auto;
    margin-right: auto;
}
#menuList li {
    display: inline;
    list-style: none;
}
body {
    margin: 0;
    padding: 0;
    font-family: Verdana, Tahoma, Geneva, Arial, Helvetica, sans-serif;
    background-color: #fff;
}
/* end of new header styles */
.box,.main-content {
    margin: 0 1em;
}
/* This next css is used to hide and show text using a javascript function */
.posthidden {
    display: none
}
.postshown {
    display: inline
}
.QandA {
    display: block;
    margin: 15px;
    padding: 15px;
    border: 1px solid gray;
}
.impnote {
    display: block;
    margin: 15px;
    padding: 15px;
    border: 1px solid gray;
    width: 70%;
}
.removebutton {
    list-style: none;
    background-color: #FAFAD2;
    padding-top: 10px;
    padding-bottom: 10px;
}
/* End hide show styles */
#bookmarking {
    float: right;
}
/* Boxed styles for side areas */
.boxed {
    border: 1px solid #CCCCCC;
    padding: 5px;
    background-color: #EEEFFF;
    font-size: 0.9em;
}
.shadow {
    box-shadow: 10px 10px 5px#888;
    -moz-box-shadow: 5px 5px 7px#888;
    -webkit-box-shadow: 5px 5px 7px#888;
}
#col-c.boxed {
    margin-right: 5px;
    margin-top: 45px;
}
/* card-like effect of staff pictures on the about pages */
.caption {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 0.8em;
    clear: both;
    padding: 0 5px 5px 0;
    font-weight: bold;
    margin: 5px;
    }
td ,th {
    padding: 0.25em;
    border: 1px solid gray !important;
}
div.caption, div.floatimageRight p, div.floatimageLeft p {
    margin-top: 6pt;
    margin-bottom: 12pt;
    font-size: 80%;
    font-style: italic;
}
div.floatimage {
    border: 1px solid #666;
    padding: 5px;
    width: 30%;
    margin-right: 20px;
}
.cardlist {
    list-style-position: inside;
}
div.teidiv0 h1, h2 {
    clear: both;
}
h1 {
    text-align: left;
}
h2 {
    margin-top: 4em;
}
/* End card like effect */
/* 2 column code */

dl dt {
    font-weight: bold;
    margin-top: 10px;
}
.alpha {
    color: #000066;
    font-weight: bold;
    font-size: larger;
    border-bottom: 2px solid #0082EF;
}
/* course booking */
.book {
    color: red;
    font-weight: bold;
}
table.sortable thead {
    background-color: #eee;
    color: #666666;
    font-weight: bold;
    cursor: pointer;
}
/* sections in document */
ul.tocContainer {
    font-size: smaller;
    list-style: none;
}
li.toclist0 {
    text-indent: -1em;
    margin-left: -2em;
    list-style: none;
}
li.toclist0 {
    text-indent: -1em;
    margin-left: -2em;
    list-style: none;
}
li.toc {
    list-style: none;
}
/* breadcrumb trail */
#breadcrumb {
    padding-top: 5px;
}
ul.breadcrumb {
    display: inline;
    font-size: 0.8em;
    margin-left: 0;
    padding-left: 0;
}
ul.breadcrumb li:before: "▶";
ul.breadcrumb-first li:before: "▶";

ul.breadcrumb li {
    padding-left: 12px;
    padding-right: 5px;
    display: inline;
    color: #000;
}
a.breadcrumb:link,a.breadcrumb:link:visited {
    font-family: arial,sans-serif;
    color: #000066;
    font-weight: bold;
    text-decoration: none;
    padding-right: 5px;
}
/* ------------------------------------ */
/* Styles for topics definition list */
dl.topics {
    margin: 5px;
}
dl.topics dt {
    padding: 5px 5px 3px 3px;
    color: #000;
/* width: 14em; */
    border-bottom: 2px solid #0082EF;
    font-weight: bold;
}
dl.topics dd {
    padding: 10px 5px;
    background-color: #fff;
}
dl.topics dd a {
    font-size: 0.9em;
    color: #000;
}
/* top menu navigation code */
div#mainMenu ul.topnav {
    padding: 5px;
    margin: 0px;
    margin-left: 10px;
    display: inline;
}
div#mainMenu ul.topnav li {
    display: inline;
    list-style: none;
    border-right: 1px solid #fff;
    margin: 3px;
    padding-right: 5px;
    text-align: center;
/* check */
    font-weight: normal;
}
div#mainMenu ul.topnav li a {
    color: #000;
    font-weight: bold;
    text-decoration: none;
}
div#mainMenu ul.topnav li a:hover {
    text-decoration: underline;
}
div#mainMenu ul.topnav li a.skiplinks {
    border: none;
    border-right: 1px solid #fff;
    padding-right: 15px;
    color: #ccc;
    font-weight: normal;
    font-style: italic;
    display: inline;
/* align: left; */
}
div#mainMenu ul.topnav li a.skiplinks:hover {
    border: none;
    border-right: 1px solid #fff;
    padding-right: 15px;
    color: #000;
    font-weight: normal;
    font-style: italic;
    display: inline;
}
div#mainMenu {
    background-color: #EEEFFF;
    border-top: 1px solid #fff;
}
#mainMenu {
    position: relative;
    text-align: center;
/* width: 99%;needed for ie to work properly! see ie sheet */
/* background-color: #eee; */
    background-color: #EEEFFF;
    border-bottom: 1px solid #000;
    border-top: 1px solid #000;
    color: #000;
    margin: 0px;
    padding: 2px 0px 2px 10px;
}
#menuList {
    margin: 0px;
    padding: 0px;
}
#menuList ul {
    margin: 0px;
    padding: 0px;
    margin-left: auto;
    margin-right: auto;
}
#menuList li {
    display: inline;
    list-style: none;
}
/* End of top menu code */
/* End of mainMenu styles */
/* Aligning next and back links to the righthand side of page */
p.right {
    text-align: right;
    margin: 0 0 10px 0;
}
/* end */
/* Adding in RSS styles from published stylesheets/oucs.css */
ul.rss {
    list-style: none;
    margin: 0;
    padding: 0;
}
ul.rss li {
    margin: 0;
    padding: 2px;
    text-align: left;
}
ul.rss li a {
    display: block;
    color: #000;
    text-decoration: none;
    line-height: 1.5em;
    font-weight: normal;
    border-bottom: 1px solid #eee;
}
.rss li a:hover {
    color: #fff;
    text-decoration: none;
    background-color: #223A9A;
    display: block;
}
/* code variants */
code.Button {
    white-space: nowrap;
    color: Red;
    border: 1px solid #999;
    padding: 0 4px;
    background-color: #eee;
    -webkit-box-shadow: inset -1pt -1pt 0 0 #888, inset 1pt 1pt 0 0 white;
    -moz-box-shadow: inset -1pt -1pt 0 0 #888, inset 1pt 1pt 0 0 white;
    box-shadow: inset -1pt -1pt 0 0 #888, inset 1pt 1pt 0 0 white;
/*
  font-family: monospace;
  white-space: nowrap;
  color: red;
  font-weight: bold;
  background-color: rgb(75%,75%,75%)
 */
}
code.Command {
    font-family: monospace;
    color: blue;
    font-weight: bold;
}
code.Value {
    font-family: monospace;
    color: green;
}
code.Code {
    font-family: monospace;
    color: red;
}
code.Field {
    font-family: monospace;
    white-space: nowrap;
    color: red;
}
code.Filespec {
    font-family: monospace;
    color: red;
}
code.Input {
    font-family: monospace;
    color: green;
}
code.Key {
    font-variant: small-caps;
    font-size: 120%;
    text-decoration: underline;
    color: green;
}
code.Link {
    font-family: monospace;
    white-space: nowrap;
    color: green;
    text-decoration: underline;
}
code.Menu {
    font-family: monospace;
    white-space: nowrap;
    color: red;
}
code.Keyword {
    font-family: monospace;
    color: blue;
}
code.Output {
    font-family: monospace;
    color: red;
}
.Screen {
    display: block;
    white-space: pre;
    background-color: #FFCC99;
}
.Program {
    display: block;
    white-space: pre;
}
code.Icon {
    font-family: monospace;
    white-space: nowrap;
    text-decoration: underline;
}
code.Label {
    font-style: italic;
    white-space: nowrap;
}
span.term {
    font-style: italic;
}
/* End of code variants */
/* colour text */
.green {
    color: green;
}
.red {
    color: red;
}
.yellow {
    color: yellow;
}
/* in tables, the colour is for teh background */
td.label {
    text-align: left;
}
td.green {
    background-color: green;
    color: black;
}
td.red {
    background-color: red;
    color: black;
}
td.yellow {
    background-color: yellow;
    color: black;
}
td.blue {
    background-color: blue;
    color: black;
}
td.turquoise {
    background-color: #66FFFF;
    color: black;
}
td.orange {
    background-color: #FFCC66;
    color: black;
}
/* Lists */
.no-bullets {
    list-style-image: none;
    list-style-type: none;
}
.lower-alpha {
    list-style-type: lower-alpha;
}
.upper-roman {
    list-style-type: upper-alpha;
}
.lower-roman {
    list-style-type: lower-roman;
}
.upper-roman {
    list-style-type: upper-roman;
}
/* FormMail */
.valueisinerror {
    color: red;
}
.displaynone {
    display: none;
}
p.alert {
    border: 2px solid #999999;
    padding: 5px;
}
p.listhead {
    font-weight: bold;
}
/* special coursedesc gloss list */
div.coursedesc {
    margin-left: 0.5em;
}
span.coursedesc-label {
    margin-left: 0em;
    font-weight: bold;
    padding-right: 1em;
}
/*
  a.pdf {
  padding-left: 20px;
  background: url(/icons/pdf.gif) no-repeat bottom left;
  }
 */
/* remove till fix images */
#footer p {
    margin-left: 25%;
    text-align: left;
}
/* show/hide buttons styles */
.showHideButton {
    font-weight: bold;
    font-style: italic;
    background-color: #eee;
/*
  padding: 2px;
  border-left: 3px solid #aaa;
  border-bottom: 3px solid #aaa;
 */
}
.showHideMore {
    background-color: #ffc;
}
/* for literal XML */
span.element {
    font-weight: bold;
    color: black;
}
span.elementname {
    font-weight: bold;
    color: #222288;
}
span.attribute {
    color: #222288;
}
span.attributevalue {
    color: black;
}
span.comment {
    color: black;
    font-style: italic;
}
span.namespace {
    color: #222288;
}
/* literal code */
li pre {
    text-indent: 0px;
}
div.cdata {
    white-space: pre;
}
div.pre,pre {
    background-color: #FFFFCC;
    font-family: monospace;
    padding: 5px;
    margin: 2px;
    white-space: pre;
}
div.pre_eg,pre.eg {
    padding: 5px;
    margin: 5px;
    font-family: monospace;
    background-color: #DDDDDD;
    white-space: pre;
}
div.blockquote {
    margin: 10px
}
span.bibl {
    display: block;
    font-style: italic
}
.important {
    font-weight: bold;
    color: red;
}
/* notes */
div.noteHeading {
    margin-top: 9pt;
    border: 0;
    border-top: 1pt;
    border-style: solid;
    padding-top: 6pt;
    font-size: larger;
    font-weight: bold;
}
div.noteBody {
    display: inline;
}
div.note {
    margin-left: 1em;
    margin-bottom: 2pt;
    text-indent: -1em;
}
/* Tables */
caption {
    margin-top: 1em;
    text-align: left;
    font-size: 80%;
    font-weight: bold;
    caption-side: bottom;
}
.centretext {
    text-align: center;
}
/*  end Tables */

.Indented {
	margin-left: 2em;
}

.ITLP_Emphasis {
	font-style: italic;
}

.item {
	padding-bottom: 0.5em;
}

.ITLP_Ex_Heading .ITLP_Table_Heading{
	background-color: gray;
}

p, div.p {
    margin-top: 0.5em;
    line-height: 125%;
}
.caption {
    margin-top: 6pt;
    margin-bottom: 12pt;
    display: block;
    font-style: italic;
}

/* for ePub */
div.EpubCoverPage {
    -webkit-hyphens:none;
    font-family: serif;
    height:860;
    font-size:30pt;
    font-weight: bold;
    padding-top: 15pt;
    margin: 12pt;
    border: solid red 1pt;
    text-align:center;
   }


text:
package nativeandroid.jenoa;

public interface FromNativeConverter {
	Object fromNative(Object nativeValue, FromNativeContext context);
	Class nativeType();
}

redpajama_set_name: RedPajamaGithub


text:
package ldif

import (
	"github.com/jsimonetti/ldapserv/ldap"
	log "gopkg.in/inconshreveable/log15.v2"
)

func (l *LdifBackend) Delete(w ldap.ResponseWriter, m *ldap.Message) {
	r := m.GetDeleteRequest()
	l.Log.Debug("Deleting entry", log.Ctx{"entry": r})
	res := ldap.NewDeleteResponse(ldap.LDAPResultSuccess)
	w.Write(res)
}


text:
package com.google.cloud.dialogflow.cx.v3beta1.stub;

import static com.google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroupsClient.ListLocationsPagedResponse;
import static com.google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroupsClient.ListTransitionRouteGroupsPagedResponse;

import com.google.api.core.BetaApi;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.dialogflow.cx.v3beta1.CreateTransitionRouteGroupRequest;
import com.google.cloud.dialogflow.cx.v3beta1.DeleteTransitionRouteGroupRequest;
import com.google.cloud.dialogflow.cx.v3beta1.GetTransitionRouteGroupRequest;
import com.google.cloud.dialogflow.cx.v3beta1.ListTransitionRouteGroupsRequest;
import com.google.cloud.dialogflow.cx.v3beta1.ListTransitionRouteGroupsResponse;
import com.google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup;
import com.google.cloud.dialogflow.cx.v3beta1.UpdateTransitionRouteGroupRequest;
import com.google.cloud.location.GetLocationRequest;
import com.google.cloud.location.ListLocationsRequest;
import com.google.cloud.location.ListLocationsResponse;
import com.google.cloud.location.Location;
import com.google.protobuf.Empty;
import javax.annotation.Generated;

// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
 * Base stub class for the TransitionRouteGroups service API.
 *
 * <p>This class is for advanced usage and reflects the underlying API directly.
 */
@BetaApi
@Generated("by gapic-generator-java")
public abstract class TransitionRouteGroupsStub implements BackgroundResource {

  public UnaryCallable<ListTransitionRouteGroupsRequest, ListTransitionRouteGroupsPagedResponse>
      listTransitionRouteGroupsPagedCallable() {
    throw new UnsupportedOperationException(
        "Not implemented: listTransitionRouteGroupsPagedCallable()");
  }

  public UnaryCallable<ListTransitionRouteGroupsRequest, ListTransitionRouteGroupsResponse>
      listTransitionRouteGroupsCallable() {
    throw new UnsupportedOperationException("Not implemented: listTransitionRouteGroupsCallable()");
  }

  public UnaryCallable<GetTransitionRouteGroupRequest, TransitionRouteGroup>
      getTransitionRouteGroupCallable() {
    throw new UnsupportedOperationException("Not implemented: getTransitionRouteGroupCallable()");
  }

  public UnaryCallable<CreateTransitionRouteGroupRequest, TransitionRouteGroup>
      createTransitionRouteGroupCallable() {
    throw new UnsupportedOperationException(
        "Not implemented: createTransitionRouteGroupCallable()");
  }

  public UnaryCallable<UpdateTransitionRouteGroupRequest, TransitionRouteGroup>
      updateTransitionRouteGroupCallable() {
    throw new UnsupportedOperationException(
        "Not implemented: updateTransitionRouteGroupCallable()");
  }

  public UnaryCallable<DeleteTransitionRouteGroupRequest, Empty>
      deleteTransitionRouteGroupCallable() {
    throw new UnsupportedOperationException(
        "Not implemented: deleteTransitionRouteGroupCallable()");
  }

  public UnaryCallable<ListLocationsRequest, ListLocationsPagedResponse>
      listLocationsPagedCallable() {
    throw new UnsupportedOperationException("Not implemented: listLocationsPagedCallable()");
  }

  public UnaryCallable<ListLocationsRequest, ListLocationsResponse> listLocationsCallable() {
    throw new UnsupportedOperationException("Not implemented: listLocationsCallable()");
  }

  public UnaryCallable<GetLocationRequest, Location> getLocationCallable() {
    throw new UnsupportedOperationException("Not implemented: getLocationCallable()");
  }

  @Override
  public abstract void close();
}


text:
package com.longluo.baselib.util;

import android.content.Context;

import static android.R.id.message;

/**
 * Toast
 */
public class ToastUtils {
    public static ExtraToast mToast;

    public static void showToast(Context context, String message) {
        showToast(context, message, ExtraToast.LENGTH_SHORT);
    }

    //显示字符串
    public static void showToast(final Context context, final String message, int duration) {
        if (mToast == null) {
            mToast = ExtraToast.makeText(context, message, duration);
        } else {
            mToast.setText(message);
        }
        mToast.show();
    }

    //显示资源文件
    public static void showToast(final Context context, final int messageResId, int duration) {
        if (mToast == null) {
            mToast = ExtraToast.makeText(context, messageResId, duration);
        } else {
            mToast.setText(message);
        }
        mToast.show();
    }

    //隐藏吐司
    public static void hideToast() {
        if (mToast == null) {
            return;
        }
        mToast.hide();
    }
}


text:
(function($) {
$.fn.unserializeForm = function(values) {
	var form   = $(this);
	var values = decodeURIComponent(values.replace(/\+/g, ' ')).split("&");

	$.each(values, function() {
		var properties = this.split("=");
		var field = form.find(':input[name="' + properties[0] + '"]').first();

		if (field.attr('type') == 'checkbox')
			form.find('input[value="'+ properties[1] +'"]').prop('checked', true);
		else if (field.is('input') || field.is('textarea'))
			field.val(properties[1]);
		else if (field.is('select'))
			field.val(properties[1]);
	});
}
})(jQuery);


text:
package net.tutorial.misc;

/**
 * Created by pongpantola.
 */
public class GenderAgePair {
    private String gender;
    private String age;

    public GenderAgePair(String gender, String age){
        this.gender = gender;
        this.age = age;
    }

    public String getGender(){
        return gender;
    }

    public String getAge(){
        return age;
    }

    public void setGender(String gender){
        this.gender = gender;
    }

    public void setAge(String age){
        this.age = age;
    }

}


text:
package jp.rubi3.apromise;

import android.support.annotation.Nullable;

/**
 *
 * Callback
 *
 * Created by halmakey on 2015/03/12.
 */
public interface Callback<D> {
    /***
     * callback
     *
     * @param result previous result
     * @throws Exception to reject
     */
    void callback(@Nullable D result) throws Exception;
}


text:
using UnrealBuildTool;
using System.Collections.Generic;

public class VaRestDemoEditorTarget : TargetRules
{
	public VaRestDemoEditorTarget(TargetInfo Target) : base(Target)
	{
		Type = TargetType.Editor;

        bUseUnityBuild = false;

        ExtraModuleNames.AddRange( new string[] { "VaRestDemo" } );
	}
}


text:
div.app-user {
  max-width: 500px;
  margin: 50px auto;
  border: 1px solid #E0E0E0;
  border-radius: 5px;
}

div.app-user h2 {
  margin: 0;
  padding: 10px;
  color: white;
  background-color: #CC0033;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
}

div.app-user div.form {
  padding: 10px 20px;
}

div.app-user div.form span.required {
  color: #CC0033;
  font-size: bold;
}

div.app-user div.form label {
  width: 100%;
  margin: 10px 0;
  display: block;
  font-size: 13px;
  font-weight: bold;
}

div.app-user div.form div.checkbox label {
  width: auto;
  display: inline-block;
}

div.app-user div.form input, div.app-user div.form select {
  width: 100%;
  display: block;
  min-height: 34px;
  padding: 7px 8px;
  font-size: 13px;
  color: #333;
  vertical-align: middle;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 3px;
  outline: none;
  box-shadow: inset 0 1px 2px rgba(0,0,0,0.075);
  transition: all 0.15s ease-in-out;
}

div.app-user div.form input.error {
  border-color: #CC0033;
}

div.app-user div.form input.good {
  border-color: #1fa67a;
}

div.app-user div.form div.checkbox input {
  width: auto;
  display: inline-block;
  min-height: 0px;
  padding: 0;
  box-shadow: none;
}

div.app-user div.form input.submit {
  transition: all 0.3s ease;
}

div.app-user div.form input.submit:hover {
  color: white;
  background-color: #CC0033;
}

div.app-user div.form input.submit:disabled {
  opacity: 0.5;
}

div.app-user div.form input.submit:disabled:hover {
  color: #333;
  background-color: #fff;
}

div.app-user div.form .links {
    margin: 30px 0 10px 0;
}

div.app-user div.form .links::after {
  content: ' ';
  display: block;
  clear: both;
}

div.app-user div.form .links .oublimdp {
    float: left;
}

div.app-user div.form .links .register {
    float: right;
}

div.app-user div.form div.g-recaptcha {
  margin: 10px 0;
}


text:
using System;
using System.Linq;
using Microsoft.WindowsAzure.Management.Sql;

namespace Microsoft.WindowsAzure.Management.Sql.Models
{
    /// <summary>
    /// The response returned from the Create Server operation.
    /// </summary>
    public partial class ServerCreateResponse : OperationResponse
    {
        private string _serverName;

        /// <summary>
        /// Gets or sets the name of the server that was created.
        /// </summary>
        public string ServerName
        {
            get { return this._serverName; }
            set { this._serverName = value; }
        }

        /// <summary>
        /// Initializes a new instance of the ServerCreateResponse class.
        /// </summary>
        public ServerCreateResponse()
        {
        }
    }
}


text:
package qrhl.tactic

import org.scalatest.funsuite.AnyFunSuite
import qrhl.isabellex.{IsabelleX, RichTerm}
import qrhl.toplevel.{Toplevel, ToplevelTest}
import IsabelleX.{globalIsabelle => GIsabelle}

class ExpressionTest extends AnyFunSuite {
  test("read print roundtrip") {
    val tl = ToplevelTest.makeToplevelWithTheory()
    tl.execCmd("classical var x : int")
    val str = "Cla[ x=(1::int) ]"
    //    val state = tl.state
    val e = RichTerm(tl.state.isabelle, str, GIsabelle.predicateT)
    println(e)
    assert(e.toString=="ℭ\uD835\uDD29\uD835\uDD1E[x = 1]")
  }

  test("encodeAsExpression") {
    val tl = ToplevelTest.makeToplevelWithTheory()
    tl.execCmd("classical var x : int")
    val state = tl.state
    val e = state.parseExpression(GIsabelle.predicateT,"Cla[ x=(1::int) ]")
    val t = e.encodeAsExpression(tl.state.isabelle)
    println(e)
    println(t)
    assert(t.typ == GIsabelle.expressionT(GIsabelle.predicateT))
  }

  test("encodeAsExpression roundtrip") {
    val tl = ToplevelTest.makeToplevelWithTheory()
    tl.execCmd("classical var x : int")
    val state = tl.state
    val e = state.parseExpression(GIsabelle.predicateT,"Cla[ x=(1::int) ]")
    println(e)
    val t = e.encodeAsExpression(tl.state.isabelle)
    println(t)
    val e2 = RichTerm.decodeFromExpression(tl.state.isabelle, t.isabelleTerm)
    println(e2)

    assert(e.isabelleTerm==e2.isabelleTerm)
    assert(e.typ==e2.typ)
    assert(e==e2)

  }

  test("encodeAsExpression roundtrip 2") {
    val tl = ToplevelTest.makeToplevelWithTheory()
    tl.execCmd("classical var x : int")
    val state = tl.state
    val e = state.parseExpression(GIsabelle.predicateT,"Cla[ x1=x2 ]")
    println(e)
    val t = e.encodeAsExpression(tl.state.isabelle)
    println(t)
    val e2 = RichTerm.decodeFromExpression(tl.state.isabelle, t.isabelleTerm)
    println(e2)

    assert(e.isabelleTerm==e2.isabelleTerm)
    assert(e.typ==e2.typ)
    assert(e==e2)

  }

  test("encodeAsExpression roundtrip 3") {
    val tl = ToplevelTest.makeToplevelWithTheory()
    tl.execCmd("classical var x : int")
    tl.execCmd("classical var c : int")
    val state = tl.state
    val e = state.parseExpression(GIsabelle.predicateT,"Cla[ x1=x2 ∧ c1=c2 ]")
    println(e)
    val t = e.encodeAsExpression(tl.state.isabelle)
    println(t)
    val e2 = RichTerm.decodeFromExpression(tl.state.isabelle, t.isabelleTerm)
    println(e2)

    assert(e.isabelleTerm==e2.isabelleTerm)
    assert(e.typ==e2.typ)
    assert(e==e2)
  }
}


text:
#ifndef __BESTFIRSTSTACK__
#define __BESTFIRSTSTACK__

#include "Stack.h"

class BestFirstStack : public Stack {
private:
	DB* db;
	std::vector<double> values;
public:
	BestFirstStack(DB* d);
	~BestFirstStack();
	void push(Node* n);
	Node* pop();
};

#endif


text:
var pretty = require('js-object-pretty-print').pretty;
var validate = require('./lib/validate.js').validate;

validate([
	"test/html/valid/full/*",
	"test/html/invalid/full/*"
], {
	customtags: ['custom-tag']
}).then(function(data) {
	console.log('Result:');
	console.log(pretty(data));
}, function(err) {
	console.log('ERROR: ' + err);
});


text:
*This is a fork of "jjalaire/sigma" I added backwardreporting of javascript events overNode and clickNode to r-server when using shiny apps. The currently clicked or hovered Nodes are accessible within R as input variables input$clickNode and input$overNode respectively.
Additionally the lasso plugin from "linkourious" is implemented and can be activated by hitting alt+l. The selected nodes are then made availible to shiny Server as input$selection
I also updated the shiny example inst/examples/edisapora-shiny.R to reflect this functionality.*

### sigma

An R package with an interface to the [sigma.js](http://sigmajs.org) graph visualization library.

This package is intended as a simple demonstration of building R bindings to JavaScript libraries using the [htmlwidgets](https://github.com/ramnathv/htmlwidgets) framework.

#### Installation

You can install the **sigma** package from GitHub as follows:

```r
devtools::install_github("supersambo/sigma")
```

#### Usage

The `sigma` function takes a [GEXF](http://gexf.net/format/) (Graph Exchange XML Format) file and produces an interactive visualization. For example:

```r
library(sigma)
sigma(system.file("examples/ediaspora.gexf.xml", package = "sigma"))
```

You can also use the **sigma** function within [R Markdown](http://rmarkdown.rstudio.com) documents and even within [Shiny](http://shiny.rstudio.com) applications. For example:

```r
library(shiny)
library(sigma)

gexf <- system.file("examples/ediaspora.gexf.xml", package = "sigma")

ui = shinyUI(fluidPage(
sidebarPanel(
checkboxInput("drawEdges", "Draw Edges", value = TRUE),
checkboxInput("drawNodes", "Draw Nodes", value = TRUE),

textOutput("clickNode"),
textOutput("overNode")
),
mainPanel(
sigmaOutput('sigma')
)
))

server = function(input, output) {

output$clickNode <- renderText({
paste("clickNode:",input$clickNode)
})

output$overNode <- renderText({
paste("overNode:",input$overNode)
})

output$sigma <- renderSigma(
sigma(gexf,
drawEdges = input$drawEdges,
drawNodes = input$drawNodes)
)
}

shinyApp(ui = ui, server = server)
```

#### License

```
The MIT License (MIT)

Copyright (C) 2013-2014, Alexis Jacomy, http://sigmajs.org
Copyright (C) 2014, JJ Allaire

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
```


text:
package graphql.schema.idl;

import graphql.DeprecatedAt;
import graphql.PublicApi;
import graphql.language.NamedNode;
import graphql.language.NodeParentTree;
import graphql.schema.DataFetcher;
import graphql.schema.GraphQLAppliedDirective;
import graphql.schema.GraphQLCodeRegistry;
import graphql.schema.GraphQLDirective;
import graphql.schema.GraphQLDirectiveContainer;
import graphql.schema.GraphQLFieldDefinition;
import graphql.schema.GraphQLFieldsContainer;
import graphql.schema.GraphqlElementParentTree;

import java.util.Map;

/**
 * {@link graphql.schema.idl.SchemaDirectiveWiring} is passed this object as parameters
 * when it builds out behaviour
 *
 * @param <T> the type of the object in play
 */
@PublicApi
public interface SchemaDirectiveWiringEnvironment<T extends GraphQLDirectiveContainer> {

    /**
     * @return the runtime element in play
     */
    T getElement();

    /**
     * This returns the directive that the {@link graphql.schema.idl.SchemaDirectiveWiring} was registered
     * against during calls to {@link graphql.schema.idl.RuntimeWiring.Builder#directive(String, SchemaDirectiveWiring)}
     *

     * If this method of registration is not used (say because
     * {@link graphql.schema.idl.WiringFactory#providesSchemaDirectiveWiring(SchemaDirectiveWiringEnvironment)} or
     * {@link graphql.schema.idl.RuntimeWiring.Builder#directiveWiring(SchemaDirectiveWiring)} was used)
     * then this will return null.
     *
     * @return the directive that was registered under specific directive name or null if it was not
     * registered this way
     *
     * @deprecated use {@link #getAppliedDirective()}
     */
    @Deprecated
    @DeprecatedAt("2022-06-21")
    GraphQLDirective getDirective();

    /**
     * This returns the applied directive that the {@link graphql.schema.idl.SchemaDirectiveWiring} was registered
     * against during calls to {@link graphql.schema.idl.RuntimeWiring.Builder#directive(String, SchemaDirectiveWiring)}
     *

     * If this method of registration is not used (say because
     * {@link graphql.schema.idl.WiringFactory#providesSchemaDirectiveWiring(SchemaDirectiveWiringEnvironment)} or
     * {@link graphql.schema.idl.RuntimeWiring.Builder#directiveWiring(SchemaDirectiveWiring)} was used)
     * then this will return null.
     *
     * @return the applied directive that was registered under specific directive name or null if it was not
     * registered this way
     */
    GraphQLAppliedDirective getAppliedDirective();

    /**
     * @return all of the directives that are on the runtime element
     *
     * @deprecated use {@link #getAppliedDirectives()} instead
     */
    @Deprecated
    @DeprecatedAt("2022-06-21")
    Map<String, GraphQLDirective> getDirectives();

    /**
     * Returns a named directive or null
     *
     * @param directiveName the name of the directive
     *
     * @return a named directive or null
     *
     * @deprecated use {@link #getAppliedDirective(String)}  instead
     */
    @Deprecated
    @DeprecatedAt("2022-06-21")
    GraphQLDirective getDirective(String directiveName);

    /**
     * @return all of the directives that are on the runtime element
     */
    Map<String, GraphQLAppliedDirective> getAppliedDirectives();

    /**
     * Returns a named applied directive or null
     *
     * @param directiveName the name of the directive
     *
     * @return a named directive or null
     */
    GraphQLAppliedDirective getAppliedDirective(String directiveName);

    /**
     * Returns true if the named directive is present
     *
     * @param directiveName the name of the directive
     *
     * @return true if the named directive is present
     */
    boolean containsDirective(String directiveName);

    /**
     * The node hierarchy depends on the element in question.  For example {@link graphql.language.ObjectTypeDefinition} nodes
     * have no parent, however a {@link graphql.language.Argument} might be on a {@link graphql.language.FieldDefinition}
     * which in turn might be on a {@link graphql.language.ObjectTypeDefinition} say
     *
     * @return hierarchical graphql language node information
     */
    NodeParentTree<NamedNode<?>> getNodeParentTree();

    /**
     * The type hierarchy depends on the element in question.  For example {@link graphql.schema.GraphQLObjectType} elements
     * have no parent, however a {@link graphql.schema.GraphQLArgument} might be on a {@link graphql.schema.GraphQLFieldDefinition}
     * which in turn might be on a {@link graphql.schema.GraphQLObjectType} say
     *
     * @return hierarchical graphql type information
     */
    GraphqlElementParentTree getElementParentTree();

    /**
     * @return the type registry
     */
    TypeDefinitionRegistry getRegistry();

    /**
     * @return a mpa that can be used by implementors to hold context during the SDL build process
     */
    Map<String, Object> getBuildContext();

    /**
     * @return a builder of the current code registry builder
     */
    GraphQLCodeRegistry.Builder getCodeRegistry();

    /**
     * @return a {@link graphql.schema.GraphQLFieldsContainer} when the element is contained with a fields container
     */
    GraphQLFieldsContainer getFieldsContainer();

    /**
     * @return a {@link GraphQLFieldDefinition} when the element is as field or is contained within one
     */
    GraphQLFieldDefinition getFieldDefinition();

    /**
     * This is useful as a shortcut to get the current fields existing data fetcher
     *
     * @return a {@link graphql.schema.DataFetcher} when the element is as field or is contained within one
     *
     * @throws graphql.AssertException if there is not field in context at the time of the directive wiring callback
     */
    DataFetcher<?> getFieldDataFetcher();

    /**
     * This is a shortcut method to set a new data fetcher in the underlying {@link graphql.schema.GraphQLCodeRegistry}
     * against the current field.
     *

     * Often schema directive wiring modify behaviour by wrapping or replacing data fetchers on
     * fields.  This method is a helper to make this easier in code.
     *
     * @param newDataFetcher the new data fetcher to use for this field
     *
     * @return the environments {@link #getFieldDefinition()} to allow for a more fluent code style
     *
     * @throws graphql.AssertException if there is not field in context at the time of the directive wiring callback
     */
    GraphQLFieldDefinition setFieldDataFetcher(DataFetcher<?> newDataFetcher);

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System.Configuration;
using System.Web.Http;

using System.Threading.Tasks;
using System.Web.Helpers;

namespace WebAPIImageUpload.Controllers
{
    public class ImageController : ApiController
    {
        private readonly CloudBlobContainer blobContainer;

        public ImageController()
        {
            var storageConnectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

            var storageAccount = CloudStorageAccount.Parse(storageConnectionString);

            // We are going to use Blob Storage, so we need a blob client.
            var blobClient = storageAccount.CreateCloudBlobClient();

            // Data in blobs are organized in containers.
            // Here, we create a new, empty container.
            blobContainer = blobClient.GetContainerReference("myfirstcontainer");
            blobContainer.CreateIfNotExists();

            // We also set the permissions to "Public", so anyone will be able to access the file.
            // By default, containers are created with private permissions only.
            blobContainer.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
        }

        [HttpPost]
        [Route("image/upload")]
        public async Task<IHttpActionResult> Upload()
        {
            var image = WebImage.GetImageFromRequest();
            var imageBytes = image.GetBytes();

            // The parameter to the GetBlockBlobReference method will be the name
            // of the image (the blob) as it appears on the storage server.
            // You can name it anything you like; in this example, I am just using
            // the actual filename of the uploaded image.
            var blockBlob = blobContainer.GetBlockBlobReference(image.FileName);
            blockBlob.Properties.ContentType = "image/" + image.ImageFormat;

            await blockBlob.UploadFromByteArrayAsync(imageBytes, 0, imageBytes.Length);

            return Ok();
        }
    }
}


text:
import sys
import signal
import getopt
from datetime import datetime
from pytibrv.Tibrv import *
from pytibrv.TibrvFt import *

# Module Variables
_running = True

def signal_proc(signal, frame):
    global _running
    _running = False
    print()
    print('CRTL-C PRESSED')

def usage():
    print()
    print('tibrvfttime.py [options]')
    print('')
    print('options:')
    print('    [--service service]          RVD Service')
    print('    [--network network]          RVD Network')
    print('    [--daemon daemon]            RVD Daemon')
    print('    [--ft-service ft-svc]        RVFT Service')
    print('    [--ft-network ft-net]        RVFT Network')
    print('    [--ft-daemon  ft-daemon]     RVFT Daemon')
    print('    [--ft-weight weight]         RVFT Weight, default 50')
    print()
    sys.exit(1)

def get_params(argv):

    params = ['service=', 'network=', 'daemon=',
              'ft-service=', 'ft-network=', 'ft-daemon=', 'ft-weight='
             ]
    try:
        opts, args = getopt.getopt(argv, '', params)

    except getopt.GetoptError:
        usage()

    service = None
    network = None
    daemon = None
    ft_svc = None
    ft_net = None
    ft_daemon = None
    ft_weight = 50

    for opt, arg in opts:
        if opt == '--service':
            service = arg
        elif opt == '--network':
            network = arg
        elif opt == '--daemon':
            daemon = arg
        elif opt == '--ft-service':
            ft_svc = arg
        elif opt == '--ft-network':
            ft_net = arg
        elif opt == '--ft-daemon':
            ft_daemon = arg
        elif opt == '--ft-weight':
            ft_weight = arg
        else:
            usage()

    if len(args) != 0:
        usage()

    return service, network, daemon, ft_svc, ft_net, ft_daemon, ft_weight

class App:
    def __init__(self):
        self.tx = None
        self.timerId = None
        self.ft_tx = None
        self.ft_mem = None
        self.active = False
        self.subj = ''
        self.progname = ''

def advCB(event: TibrvEvent, message: TibrvMsg, closure):

    print('#### RVFT ADVISORY: {}'.format(message.sendSubject))
    print('Advisory message is: {}'.format(str(message)))

    return

def pubTime(event: TibrvEvent, message: TibrvMsg, closure):

    ap = closure

    # do nothing if not active
    if not ap.active:
        return

    tt = TibrvMsgDateTime.now()

    msg = TibrvMsg()

    err = msg.addDateTime('DATA', tt)
    if err != TIBRV_OK:
        print('Error generating timestamp data: {}'.format(TibrvStatus.text(err)))
        tibrvMsg_Destroy(msg)
        return

    err = ap.tx.send(msg, ap.subj)

    if err != TIBRV_OK:
        print('Error publishing timestamp message: {}'.format(TibrvStatus.text(err)))

    print(datetime.now(), '>', str(msg))

    msg.destroy()

def processInstruction(id: TibrvFtMember, groupName: str, action: int, closure):

    ap = closure

    if action == TIBRVFT_PREPARE_TO_ACTIVATE:
        print('####### PREPARE TO ACTIVATE: {}'.format(groupName))

    elif action == TIBRVFT_ACTIVATE:
        print('####### ACTIVATE: {}'.format(groupName))
        ap.active = True

    elif action == TIBRVFT_DEACTIVATE:
        print('####### DEACTIVATE: {}'.format(groupName))
        ap.active = False

    return

# MAIN PROGRAM
def main(argv):

    service, network, daemon, ft_svc, ft_net, ft_daemon, ft_weight = get_params(argv[1:])
    timeInt = 10.0
    groupName = 'TIBRVFT_TIME_EXAMPLE'
    numactive = 1
    hbInterval = 1.5
    prepareInterval = 0
    activateInterval = 4.8

    ap = App()
    ap.progname = argv[0]
    ap.subj = 'TIBRVFT_TIME'

    err = Tibrv.open()
    if err != TIBRV_OK:
        print('{}: Failed to open TIB/RV: {}'.format('', ap.progname, TibrvStatus.text(err)))
        sys.exit(1)

    ap.tx = TibrvTx()
    err = ap.tx.create(service, network, daemon)
    if err != TIBRV_OK:
        print('{}: Failed to initialize transport: {}'.format('', ap.progname, TibrvStatus.text(err)))
        sys.exit(1)

    print('Active group member will publish time every {} seconds.'.format(timeInt))
    print('Subject is {}'.format(ap.subj))
    print('Inactive will not publish time')

    que = TibrvQueue()
    ap.timerId = TibrvTimer()
    err = ap.timerId.create(que, TibrvTimerCallback(pubTime), timeInt, ap)

    if err != TIBRV_OK:
        print('Error adding repeating timer: -- {}'.foramt(TibrvStatus.text(err)))
        sys.exit(3)

    # create RVFT
    ap.ft_tx = TibrvTx()
    err = ap.ft_tx.create(ft_svc, ft_net, ft_daemon)
    if err != TIBRV_OK:
        print('{}: Failed to initialize fault tolerant transport -- {}'.format(
                    ap.progname, TibrvStatus.text(err)))
        sys.exit(3)

    # join RVFT
    ap.ft_mem = TibrvFtMember()
    err = ap.ft_mem.create(que, TibrvFtMemberCallback(processInstruction), ap.ft_tx,
                        groupName, ft_weight, numactive,
                        hbInterval, prepareInterval, activateInterval,
                        ap)

    if err != TIBRV_OK:
        print('{} : Failed to join group - {}'.format(ap.progname,TibrvStatus.text(err)))
        sys.exit(4)

    # Subscribe to RVFT advisories
    advId = TibrvListener()
    err = advId.create(que, TibrvMsgCallback(advCB), ap.ft_tx,
                       '_RV.*.RVFT.*.' + groupName,
                       ap)

    if err != TIBRV_OK:
        print('{} : Failed to start listening to advisories - {}'.format(
                    ap.progname, TibrvStatus.text(err)))
        sys.exit(5)

    # Set Signal Handler for Ctrl-C
    global _running
    signal.signal(signal.SIGINT, signal_proc)

    while _running:
        que.timedDispatch(0.5)

    advId.destroy()
    ap.timerId.destroy()
    ap.ft_mem.destroy()

    Tibrv.close()

    return

if __name__ == "__main__":
    main(sys.argv)


text:
{% for post in paginator.posts %}

        {{ post.title }}

        {{ post.excerpt }}

      Read More

{% endfor %}

{% if paginator.total_pages > 1 %}

    {% if paginator.previous_page %}
      Newer
    {% endif %}
    {% if paginator.next_page %}
      Older
    {% endif %}

{% endif %}


text:
Gem generates constant JSON. As consequence, you can MD5 it and this will remain the same.

## Installation

Add this line to your application's Gemfile:

    gem 'aerials'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install aerials

## Usage

### JSON generation rules:
- No extra spaces
- Always use double quotes for keys and array/hash values ("")
- Always add slashes to double quotes (replace " with \")
- Always use UTF8 (TODO)
- Always sort by keys on each level (arrays should be sorted by values)
- Always sort as strings

### Example:

    struct = {
        array: [2, '1'],
        hash: {
            'a' => '1'
        },
        a: 2,
    }
    Aerials.create_json struct

    # will eq
    # '{"a":"2","array":["1","2"],"hash":{"a":"1"}}'

You can exclude fields:

    Aerials.create_json(struct, exclude: [:controller])

Or use default Rails exclusion:

    Aerials.create_json_rails struct
    # equals to:
    Aerials.create_json struct, exclude: [:action, :controller, :key]

## Contributing

1. Fork it ( https://github.com/appelsin/aerials )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
#define LOG_TAG "BufferQueue"
#define ATRACE_TAG ATRACE_TAG_GRAPHICS
//#define LOG_NDEBUG 0

#define GL_GLEXT_PROTOTYPES
#define EGL_EGLEXT_PROTOTYPES

#include <EGL/egl.h>
#include <EGL/eglext.h>

#include <gui/BufferQueue.h>
#include <gui/ISurfaceComposer.h>
#include <private/gui/ComposerService.h>

#include <utils/Log.h>
#include <gui/SurfaceTexture.h>
#include <utils/Trace.h>

// Macros for including the BufferQueue name in log messages
#define ST_LOGV(x, ...) ALOGV("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
#define ST_LOGD(x, ...) ALOGD("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
#define ST_LOGI(x, ...) ALOGI("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
#define ST_LOGW(x, ...) ALOGW("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
#define ST_LOGE(x, ...) ALOGE("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)

#define ATRACE_BUFFER_INDEX(index)                                            \
    if (ATRACE_ENABLED()) {                                                   \
        char ___traceBuf[1024];                                               \
        snprintf(___traceBuf, 1024, "%s: %d", mConsumerName.string(),         \
                (index));                                                     \
        android::ScopedTrace ___bufTracer(ATRACE_TAG, ___traceBuf);           \
    }

namespace android {

// Get an ID that's unique within this process.
static int32_t createProcessUniqueId() {
    static volatile int32_t globalCounter = 0;
    return android_atomic_inc(&globalCounter);
}

static const char* scalingModeName(int scalingMode) {
    switch (scalingMode) {
        case NATIVE_WINDOW_SCALING_MODE_FREEZE: return "FREEZE";
        case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW: return "SCALE_TO_WINDOW";
        case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP: return "SCALE_CROP";
        default: return "Unknown";
    }
}

#ifdef QCOM_BSP
/*
 * Checks if memory needs to be reallocated for this buffer.
 *
 * @param: Geometry of the current buffer.
 * @param: Required Geometry.
 * @param: Geometry of the updated buffer.
 *
 * @return True if a memory reallocation is required.
 */
static bool needNewBuffer(const QBufGeometry currentGeometry,
                   const QBufGeometry requiredGeometry,
                   const QBufGeometry updatedGeometry)
{
    // no allocation required if there is change in resoultion or format.
    if (updatedGeometry.mWidth && updatedGeometry.mHeight &&
        updatedGeometry.mFormat) {
        return false;
    }
    // If the current buffer info matches the updated info,
    // we do not require any memory allocation.
    if (currentGeometry.mWidth != requiredGeometry.mWidth ||
        currentGeometry.mHeight != requiredGeometry.mHeight ||
        currentGeometry.mFormat != requiredGeometry.mFormat) {
        // Current and required geometry do not match. Allocation
        // required.
        return true;
    }
    return false;
}

/*
 * Geometry update for the currently queued buffer is required or not.
 *
 * @param: buffer currently queued buffer.
 * @param: Updated width
 * @param: Updated height
 * @param: Updated format
 *
 * @return True if a buffer needs to be updated with new attributes.
 */
static bool isBufferGeometryUpdateRequired(sp<GraphicBuffer> buffer,
                                 const QBufGeometry updatedGeometry)
{
    if (buffer == 0) {
        ALOGW("isBufferGeometryUpdateRequired: graphic buffer is NULL");
        return false;
    }

    if (!updatedGeometry.mWidth || !updatedGeometry.mHeight ||
        !updatedGeometry.mFormat) {
        // No update required. Return.
        return false;
    }
    if (buffer->width == updatedGeometry.mWidth &&
        buffer->height == updatedGeometry.mHeight &&
        buffer->format == updatedGeometry.mFormat) {
        // The buffer has already been updated. Return.
        return false;
    }
    return true;
}
#endif

BufferQueue::BufferQueue(bool allowSynchronousMode,
        const sp<IGraphicBufferAlloc>& allocator) :
    mDefaultWidth(1),
    mDefaultHeight(1),
    mMaxAcquiredBufferCount(1),
    mDefaultMaxBufferCount(2),
    mOverrideMaxBufferCount(0),
    mSynchronousMode(false),
    mAllowSynchronousMode(allowSynchronousMode),
    mConnectedApi(NO_CONNECTED_API),
    mAbandoned(false),
    mFrameCounter(0),
    mBufferHasBeenQueued(false),
    mDefaultBufferFormat(PIXEL_FORMAT_RGBA_8888),
    mConsumerUsageBits(0),
    mTransformHint(0)
{
    // Choose a name using the PID and a process-unique ID.
    mConsumerName = String8::format("unnamed-%d-%d", getpid(), createProcessUniqueId());

    ST_LOGV("BufferQueue");
    if (allocator == NULL) {
        sp<ISurfaceComposer> composer(ComposerService::getComposerService());
        mGraphicBufferAlloc = composer->createGraphicBufferAlloc();
        if (mGraphicBufferAlloc == 0) {
            ST_LOGE("createGraphicBufferAlloc() failed in BufferQueue()");
        }
    } else {
        mGraphicBufferAlloc = allocator;
    }
#ifdef QCOM_BSP
    mNextBufferInfo.set(0, 0, 0);
#endif
}

BufferQueue::~BufferQueue() {
    ST_LOGV("~BufferQueue");
}

status_t BufferQueue::setDefaultMaxBufferCountLocked(int count) {
    if (count < 2 || count > NUM_BUFFER_SLOTS)
        return BAD_VALUE;

    mDefaultMaxBufferCount = count;
    mDequeueCondition.broadcast();

    return OK;
}

bool BufferQueue::isSynchronousMode() const {
    Mutex::Autolock lock(mMutex);
    return mSynchronousMode;
}

void BufferQueue::setConsumerName(const String8& name) {
    Mutex::Autolock lock(mMutex);
    mConsumerName = name;
}

status_t BufferQueue::setDefaultBufferFormat(uint32_t defaultFormat) {
    Mutex::Autolock lock(mMutex);
    mDefaultBufferFormat = defaultFormat;
    return OK;
}

status_t BufferQueue::setConsumerUsageBits(uint32_t usage) {
    Mutex::Autolock lock(mMutex);
    mConsumerUsageBits = usage;
    return OK;
}

status_t BufferQueue::setTransformHint(uint32_t hint) {
    ST_LOGV("setTransformHint: %02x", hint);
    Mutex::Autolock lock(mMutex);
    mTransformHint = hint;
    return OK;
}

status_t BufferQueue::setBufferCount(int bufferCount) {
    ST_LOGV("setBufferCount: count=%d", bufferCount);

    sp<ConsumerListener> listener;
    {
        Mutex::Autolock lock(mMutex);

        if (mAbandoned) {
            ST_LOGE("setBufferCount: SurfaceTexture has been abandoned!");
            return NO_INIT;
        }
        if (bufferCount > NUM_BUFFER_SLOTS) {
            ST_LOGE("setBufferCount: bufferCount larger than slots available");
            return BAD_VALUE;
        }

        // Error out if the user has dequeued buffers
        int maxBufferCount = getMaxBufferCountLocked();
        for (int i=0 ; i<maxBufferCount; i++) {
            if (mSlots[i].mBufferState == BufferSlot::DEQUEUED) {
                ST_LOGE("setBufferCount: client owns some buffers");
                return -EINVAL;
            }
        }

        const int minBufferSlots = getMinMaxBufferCountLocked();
        if (bufferCount == 0) {
            mOverrideMaxBufferCount = 0;
            mDequeueCondition.broadcast();
            return OK;
        }

        if (bufferCount < minBufferSlots) {
            ST_LOGE("setBufferCount: requested buffer count (%d) is less than "
                    "minimum (%d)", bufferCount, minBufferSlots);
            return BAD_VALUE;
        }

        // here we're guaranteed that the client doesn't have dequeued buffers
        // and will release all of its buffer references.
        //
        // XXX: Should this use drainQueueAndFreeBuffersLocked instead?
        freeAllBuffersLocked();
        mOverrideMaxBufferCount = bufferCount;
        mBufferHasBeenQueued = false;
        mDequeueCondition.broadcast();
        listener = mConsumerListener;
    } // scope for lock

    if (listener != NULL) {
        listener->onBuffersReleased();
    }

    return OK;
}

#ifdef QCOM_BSP
status_t BufferQueue::setBuffersSize(int size) {
    ST_LOGV("setBuffersSize: size=%d", size);
    Mutex::Autolock lock(mMutex);
    mGraphicBufferAlloc->setGraphicBufferSize(size);
    return NO_ERROR;
}
#endif

int BufferQueue::query(int what, int* outValue)
{
    ATRACE_CALL();
    Mutex::Autolock lock(mMutex);

    if (mAbandoned) {
        ST_LOGE("query: SurfaceTexture has been abandoned!");
        return NO_INIT;
    }

    int value;
    switch (what) {
    case NATIVE_WINDOW_WIDTH:
        value = mDefaultWidth;
        break;
    case NATIVE_WINDOW_HEIGHT:
        value = mDefaultHeight;
        break;
    case NATIVE_WINDOW_FORMAT:
        value = mDefaultBufferFormat;
        break;
    case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS:
        value = getMinUndequeuedBufferCountLocked();
        break;
    case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND:
        value = (mQueue.size() >= 2);
        break;
    default:
        return BAD_VALUE;
    }
    outValue[0] = value;
    return NO_ERROR;
}

status_t BufferQueue::requestBuffer(int slot, sp<GraphicBuffer>* buf) {
    ATRACE_CALL();
    ST_LOGV("requestBuffer: slot=%d", slot);
    Mutex::Autolock lock(mMutex);
    if (mAbandoned) {
        ST_LOGE("requestBuffer: SurfaceTexture has been abandoned!");
        return NO_INIT;
    }
    int maxBufferCount = getMaxBufferCountLocked();
    if (slot < 0 || maxBufferCount <= slot) {
        ST_LOGE("requestBuffer: slot index out of range [0, %d]: %d",
                maxBufferCount, slot);
        return BAD_VALUE;
    } else if (mSlots[slot].mBufferState != BufferSlot::DEQUEUED) {
        // XXX: I vaguely recall there was some reason this can be valid, but
        // for the life of me I can't recall under what circumstances that's
        // the case.
        ST_LOGE("requestBuffer: slot %d is not owned by the client (state=%d)",
                slot, mSlots[slot].mBufferState);
        return BAD_VALUE;
    }
    mSlots[slot].mRequestBufferCalled = true;
    *buf = mSlots[slot].mGraphicBuffer;
    return NO_ERROR;
}

status_t BufferQueue::dequeueBuffer(int *outBuf, sp<Fence>& outFence,
        uint32_t w, uint32_t h, uint32_t format, uint32_t usage) {
    ATRACE_CALL();
    ST_LOGV("dequeueBuffer: w=%d h=%d fmt=%#x usage=%#x", w, h, format, usage);

    if ((w && !h) || (!w && h)) {
        ST_LOGE("dequeueBuffer: invalid size: w=%u, h=%u", w, h);
        return BAD_VALUE;
    }

    status_t returnFlags(OK);
    EGLDisplay dpy = EGL_NO_DISPLAY;
    EGLSyncKHR eglFence = EGL_NO_SYNC_KHR;

    { // Scope for the lock
        Mutex::Autolock lock(mMutex);

        if (format == 0) {
            format = mDefaultBufferFormat;
        }
        // turn on usage bits the consumer requested
        usage |= mConsumerUsageBits;

        int found = -1;
        int dequeuedCount = 0;
        bool tryAgain = true;
        while (tryAgain) {
            if (mAbandoned) {
                ST_LOGE("dequeueBuffer: SurfaceTexture has been abandoned!");
                return NO_INIT;
            }

            const int maxBufferCount = getMaxBufferCountLocked();

            // Free up any buffers that are in slots beyond the max buffer
            // count.
            for (int i = maxBufferCount; i < NUM_BUFFER_SLOTS; i++) {
                assert(mSlots[i].mBufferState == BufferSlot::FREE);
                if (mSlots[i].mGraphicBuffer != NULL) {
                    freeBufferLocked(i);
                    returnFlags |= ISurfaceTexture::RELEASE_ALL_BUFFERS;
                }
            }

            // look for a free buffer to give to the client
            found = INVALID_BUFFER_SLOT;
            dequeuedCount = 0;
            for (int i = 0; i < maxBufferCount; i++) {
                const int state = mSlots[i].mBufferState;
                if (state == BufferSlot::DEQUEUED) {
                    dequeuedCount++;
                }

                if (state == BufferSlot::FREE) {
                    /* We return the oldest of the free buffers to avoid
                     * stalling the producer if possible.  This is because
                     * the consumer may still have pending reads of the
                     * buffers in flight.
                     */
                    if ((found < 0) ||
                            mSlots[i].mFrameNumber < mSlots[found].mFrameNumber) {
                        found = i;
                    }
                }
            }

            // clients are not allowed to dequeue more than one buffer
            // if they didn't set a buffer count.
            if (!mOverrideMaxBufferCount && dequeuedCount) {
                ST_LOGE("dequeueBuffer: can't dequeue multiple buffers without "
                        "setting the buffer count");
                return -EINVAL;
            }

            // See whether a buffer has been queued since the last
            // setBufferCount so we know whether to perform the min undequeued
            // buffers check below.
            if (mBufferHasBeenQueued) {
                // make sure the client is not trying to dequeue more buffers
                // than allowed.
                const int newUndequeuedCount = maxBufferCount - (dequeuedCount+1);
                const int minUndequeuedCount = getMinUndequeuedBufferCountLocked();
                if (newUndequeuedCount < minUndequeuedCount) {
                    ST_LOGE("dequeueBuffer: min undequeued buffer count (%d) "
                            "exceeded (dequeued=%d undequeudCount=%d)",
                            minUndequeuedCount, dequeuedCount,
                            newUndequeuedCount);
                    return -EBUSY;
                }
            }

            // If no buffer is found, wait for a buffer to be released or for
            // the max buffer count to change.
            tryAgain = found == INVALID_BUFFER_SLOT;
            if (tryAgain) {
                mDequeueCondition.wait(mMutex);
            }
        }

        if (found == INVALID_BUFFER_SLOT) {
            // This should not happen.
            ST_LOGE("dequeueBuffer: no available buffer slots");
            return -EBUSY;
        }

        const int buf = found;
        *outBuf = found;

        ATRACE_BUFFER_INDEX(buf);

        const bool useDefaultSize = !w && !h;
        if (useDefaultSize) {
            // use the default size
            w = mDefaultWidth;
            h = mDefaultHeight;
        }

        // buffer is now in DEQUEUED (but can also be current at the same time,
        // if we're in synchronous mode)
        mSlots[buf].mBufferState = BufferSlot::DEQUEUED;

        const sp<GraphicBuffer>& buffer(mSlots[buf].mGraphicBuffer);
#ifdef QCOM_BSP
        QBufGeometry currentGeometry;
        if (buffer != NULL)
            currentGeometry.set(buffer->width, buffer->height, buffer->format);
        else
            currentGeometry.set(0, 0, 0);

        QBufGeometry requiredGeometry;
        requiredGeometry.set(w, h, format);

        QBufGeometry updatedGeometry;
        updatedGeometry.set(mNextBufferInfo.mWidth, mNextBufferInfo.mHeight,
                            mNextBufferInfo.mFormat);
#endif

        if ((buffer == NULL) ||
#ifdef QCOM_BSP
            needNewBuffer(currentGeometry, requiredGeometry, updatedGeometry) ||
#else
            (uint32_t(buffer->width)  != w) ||
            (uint32_t(buffer->height) != h) ||
            (uint32_t(buffer->format) != format) ||
#endif
            ((uint32_t(buffer->usage) & usage) != usage))
        {
            mSlots[buf].mAcquireCalled = false;
            mSlots[buf].mGraphicBuffer = NULL;
            mSlots[buf].mRequestBufferCalled = false;
            mSlots[buf].mEglFence = EGL_NO_SYNC_KHR;
            mSlots[buf].mFence.clear();
            mSlots[buf].mEglDisplay = EGL_NO_DISPLAY;

            returnFlags |= ISurfaceTexture::BUFFER_NEEDS_REALLOCATION;
        }

        dpy = mSlots[buf].mEglDisplay;
        eglFence = mSlots[buf].mEglFence;
        outFence = mSlots[buf].mFence;
        mSlots[buf].mEglFence = EGL_NO_SYNC_KHR;
        mSlots[buf].mFence.clear();
    }  // end lock scope

    if (returnFlags & ISurfaceTexture::BUFFER_NEEDS_REALLOCATION) {
        status_t error;
        sp<GraphicBuffer> graphicBuffer(
                mGraphicBufferAlloc->createGraphicBuffer(
                        w, h, format, usage, &error));
        if (graphicBuffer == 0) {
            ST_LOGE("dequeueBuffer: SurfaceComposer::createGraphicBuffer "
                    "failed");
            return error;
        }

        { // Scope for the lock
            Mutex::Autolock lock(mMutex);

            if (mAbandoned) {
                ST_LOGE("dequeueBuffer: SurfaceTexture has been abandoned!");
                return NO_INIT;
            }

            mSlots[*outBuf].mGraphicBuffer = graphicBuffer;
        }
    }

    if (eglFence != EGL_NO_SYNC_KHR) {
        EGLint result = eglClientWaitSyncKHR(dpy, eglFence, 0, 1000000000);
        // If something goes wrong, log the error, but return the buffer without
        // synchronizing access to it.  It's too late at this point to abort the
        // dequeue operation.
        if (result == EGL_FALSE) {
            ST_LOGE("dequeueBuffer: error waiting for fence: %#x", eglGetError());
        } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
            ST_LOGE("dequeueBuffer: timeout waiting for fence");
        }
        eglDestroySyncKHR(dpy, eglFence);
    }

    ST_LOGV("dequeueBuffer: returning slot=%d buf=%p flags=%#x", *outBuf,
            mSlots[*outBuf].mGraphicBuffer->handle, returnFlags);

    return returnFlags;
}

#ifdef QCOM_BSP
status_t BufferQueue::updateBuffersGeometry(int w, int h, int f) {
    ST_LOGV("updateBuffersGeometry: w=%d h=%d f=%d", w, h, f);
    Mutex::Autolock lock(mMutex);
    mNextBufferInfo.set(w, h, f);
    return NO_ERROR;
}
#endif

status_t BufferQueue::setSynchronousMode(bool enabled) {
    ATRACE_CALL();
    ST_LOGV("setSynchronousMode: enabled=%d", enabled);
    Mutex::Autolock lock(mMutex);

    if (mAbandoned) {
        ST_LOGE("setSynchronousMode: SurfaceTexture has been abandoned!");
        return NO_INIT;
    }

    status_t err = OK;
    if (!mAllowSynchronousMode && enabled)
        return err;

    if (!enabled) {
        // going to asynchronous mode, drain the queue
        err = drainQueueLocked();
        if (err != NO_ERROR)
            return err;
    }

    if (mSynchronousMode != enabled) {
        // - if we're going to asynchronous mode, the queue is guaranteed to be
        // empty here
        // - if the client set the number of buffers, we're guaranteed that
        // we have at least 3 (because we don't allow less)
        mSynchronousMode = enabled;
        mDequeueCondition.broadcast();
    }
    return err;
}

status_t BufferQueue::queueBuffer(int buf,
        const QueueBufferInput& input, QueueBufferOutput* output) {
    ATRACE_CALL();
    ATRACE_BUFFER_INDEX(buf);

    Rect crop;
    uint32_t transform;
    int scalingMode;
    int64_t timestamp;
    sp<Fence> fence;

    input.deflate(&timestamp, &crop, &scalingMode, &transform, &fence);

    ST_LOGV("queueBuffer: slot=%d time=%#llx crop=[%d,%d,%d,%d] tr=%#x "
            "scale=%s",
            buf, timestamp, crop.left, crop.top, crop.right, crop.bottom,
            transform, scalingModeName(scalingMode));

    sp<ConsumerListener> listener;

    { // scope for the lock
        Mutex::Autolock lock(mMutex);
        if (mAbandoned) {
            ST_LOGE("queueBuffer: SurfaceTexture has been abandoned!");
            return NO_INIT;
        }
        int maxBufferCount = getMaxBufferCountLocked();
        if (buf < 0 || buf >= maxBufferCount) {
            ST_LOGE("queueBuffer: slot index out of range [0, %d]: %d",
                    maxBufferCount, buf);
            return -EINVAL;
        } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) {
            ST_LOGE("queueBuffer: slot %d is not owned by the client "
                    "(state=%d)", buf, mSlots[buf].mBufferState);
            return -EINVAL;
        } else if (!mSlots[buf].mRequestBufferCalled) {
            ST_LOGE("queueBuffer: slot %d was enqueued without requesting a "
                    "buffer", buf);
            return -EINVAL;
        }

#ifdef QCOM_BSP
        // Update the buffer Geometry if required
        QBufGeometry updatedGeometry;
        updatedGeometry.set(mNextBufferInfo.mWidth,
                            mNextBufferInfo.mHeight, mNextBufferInfo.mFormat);
#endif
        const sp<GraphicBuffer>& graphicBuffer(mSlots[buf].mGraphicBuffer);
#ifdef QCOM_BSP
        //  Update the geometry of this buffer without reallocation.
        if(isBufferGeometryUpdateRequired(graphicBuffer, updatedGeometry)) {
            status_t res = graphicBuffer->perform(graphicBuffer->handle,
                                GRALLOC_MODULE_PERFORM_UPDATE_BUFFER_GEOMETRY,
                                updatedGeometry.mWidth,
                                updatedGeometry.mHeight,
                                updatedGeometry.mFormat);
            if(res == NO_ERROR) {
                graphicBuffer->width  = updatedGeometry.mWidth;
                graphicBuffer->height = updatedGeometry.mHeight;
                graphicBuffer->format = updatedGeometry.mFormat;
                // set flags to destroy old eglImage and create new eglImage.
                mSlots[buf].mAcquireCalled = false;
                mSlots[buf].mEglDisplay = EGL_NO_DISPLAY;
            }
        }
#endif
        Rect bufferRect(graphicBuffer->getWidth(), graphicBuffer->getHeight());
        Rect croppedCrop;
        crop.intersect(bufferRect, &croppedCrop);
        if (croppedCrop != crop) {
            ST_LOGE("queueBuffer: crop rect is not contained within the "
                    "buffer in slot %d", buf);
            return -EINVAL;
        }

        if (mSynchronousMode) {
            // In synchronous mode we queue all buffers in a FIFO.
            mQueue.push_back(buf);

            // Synchronous mode always signals that an additional frame should
            // be consumed.
            listener = mConsumerListener;
        } else {
            // In asynchronous mode we only keep the most recent buffer.
            if (mQueue.empty()) {
                mQueue.push_back(buf);

                // Asynchronous mode only signals that a frame should be
                // consumed if no previous frame was pending. If a frame were
                // pending then the consumer would have already been notified.
                listener = mConsumerListener;
            } else {
                Fifo::iterator front(mQueue.begin());
                // buffer currently queued is freed
                mSlots[*front].mBufferState = BufferSlot::FREE;
                // reset the frame number of the freed buffer
                mSlots[*front].mFrameNumber = 0;
                // and we record the new buffer index in the queued list
                *front = buf;
            }
        }

        mSlots[buf].mTimestamp = timestamp;
        mSlots[buf].mCrop = crop;
        mSlots[buf].mTransform = transform;
        mSlots[buf].mFence = fence;

        switch (scalingMode) {
            case NATIVE_WINDOW_SCALING_MODE_FREEZE:
            case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
            case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
                break;
            default:
                ST_LOGE("unknown scaling mode: %d (ignoring)", scalingMode);
                scalingMode = mSlots[buf].mScalingMode;
                break;
        }

        mSlots[buf].mBufferState = BufferSlot::QUEUED;
        mSlots[buf].mScalingMode = scalingMode;
        mFrameCounter++;
        mSlots[buf].mFrameNumber = mFrameCounter;

        mBufferHasBeenQueued = true;
        mDequeueCondition.broadcast();

        output->inflate(mDefaultWidth, mDefaultHeight, mTransformHint,
                mQueue.size());

        ATRACE_INT(mConsumerName.string(), mQueue.size());
    } // scope for the lock

    // call back without lock held
    if (listener != 0) {
        listener->onFrameAvailable();
    }
    return OK;
}

void BufferQueue::cancelBuffer(int buf, sp<Fence> fence) {
    ATRACE_CALL();
    ST_LOGV("cancelBuffer: slot=%d", buf);
    Mutex::Autolock lock(mMutex);

    if (mAbandoned) {
        ST_LOGW("cancelBuffer: BufferQueue has been abandoned!");
        return;
    }

    int maxBufferCount = getMaxBufferCountLocked();
    if (buf < 0 || buf >= maxBufferCount) {
        ST_LOGE("cancelBuffer: slot index out of range [0, %d]: %d",
                maxBufferCount, buf);
        return;
    } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) {
        ST_LOGE("cancelBuffer: slot %d is not owned by the client (state=%d)",
                buf, mSlots[buf].mBufferState);
        return;
    }
    mSlots[buf].mBufferState = BufferSlot::FREE;
    mSlots[buf].mFrameNumber = 0;
    mSlots[buf].mFence = fence;
    mDequeueCondition.broadcast();
}

status_t BufferQueue::connect(int api, QueueBufferOutput* output) {
    ATRACE_CALL();
    ST_LOGV("connect: api=%d", api);
    Mutex::Autolock lock(mMutex);

    if (mAbandoned) {
        ST_LOGE("connect: BufferQueue has been abandoned!");
        return NO_INIT;
    }

    if (mConsumerListener == NULL) {
        ST_LOGE("connect: BufferQueue has no consumer!");
        return NO_INIT;
    }

    int err = NO_ERROR;
    switch (api) {
        case NATIVE_WINDOW_API_EGL:
        case NATIVE_WINDOW_API_CPU:
        case NATIVE_WINDOW_API_MEDIA:
        case NATIVE_WINDOW_API_CAMERA:
            if (mConnectedApi != NO_CONNECTED_API) {
                ST_LOGE("connect: already connected (cur=%d, req=%d)",
                        mConnectedApi, api);
                err = -EINVAL;
            } else {
                mConnectedApi = api;
                output->inflate(mDefaultWidth, mDefaultHeight, mTransformHint,
                        mQueue.size());
            }
            break;
        default:
            err = -EINVAL;
            break;
    }

    mBufferHasBeenQueued = false;

    return err;
}

status_t BufferQueue::disconnect(int api) {
    ATRACE_CALL();
    ST_LOGV("disconnect: api=%d", api);

    int err = NO_ERROR;
    sp<ConsumerListener> listener;

    { // Scope for the lock
        Mutex::Autolock lock(mMutex);

        if (mAbandoned) {
            // it is not really an error to disconnect after the surface
            // has been abandoned, it should just be a no-op.
            return NO_ERROR;
        }

        switch (api) {
            case NATIVE_WINDOW_API_EGL:
            case NATIVE_WINDOW_API_CPU:
            case NATIVE_WINDOW_API_MEDIA:
            case NATIVE_WINDOW_API_CAMERA:
                if (mConnectedApi == api) {
                    drainQueueAndFreeBuffersLocked();
                    mConnectedApi = NO_CONNECTED_API;
#ifdef QCOM_BSP
                    mNextBufferInfo.set(0, 0, 0);
#endif
                    mDequeueCondition.broadcast();
                    listener = mConsumerListener;
                } else {
                    ST_LOGE("disconnect: connected to another api (cur=%d, req=%d)",
                            mConnectedApi, api);
                    err = -EINVAL;
                }
                break;
            default:
                ST_LOGE("disconnect: unknown API %d", api);
                err = -EINVAL;
                break;
        }
    }

    if (listener != NULL) {
        listener->onBuffersReleased();
    }

    return err;
}

void BufferQueue::dump(String8& result) const
{
    char buffer[1024];
    BufferQueue::dump(result, "", buffer, 1024);
}

void BufferQueue::dump(String8& result, const char* prefix,
        char* buffer, size_t SIZE) const
{
    Mutex::Autolock _l(mMutex);

    String8 fifo;
    int fifoSize = 0;
    Fifo::const_iterator i(mQueue.begin());
    while (i != mQueue.end()) {
       snprintf(buffer, SIZE, "%02d ", *i++);
       fifoSize++;
       fifo.append(buffer);
    }

    int maxBufferCount = getMaxBufferCountLocked();

    snprintf(buffer, SIZE,
            "%s-BufferQueue maxBufferCount=%d, mSynchronousMode=%d, default-size=[%dx%d], "
            "default-format=%d, transform-hint=%02x, FIFO(%d)={%s}\n",
            prefix, maxBufferCount, mSynchronousMode, mDefaultWidth,
            mDefaultHeight, mDefaultBufferFormat, mTransformHint,
            fifoSize, fifo.string());
    result.append(buffer);

    struct {
        const char * operator()(int state) const {
            switch (state) {
                case BufferSlot::DEQUEUED: return "DEQUEUED";
                case BufferSlot::QUEUED: return "QUEUED";
                case BufferSlot::FREE: return "FREE";
                case BufferSlot::ACQUIRED: return "ACQUIRED";
                default: return "Unknown";
            }
        }
    } stateName;

    for (int i=0 ; i<maxBufferCount ; i++) {
        const BufferSlot& slot(mSlots[i]);
        snprintf(buffer, SIZE,
                "%s%s[%02d] "
                "state=%-8s, crop=[%d,%d,%d,%d], "
                "xform=0x%02x, time=%#llx, scale=%s",
                prefix, (slot.mBufferState == BufferSlot::ACQUIRED)?">":" ", i,
                stateName(slot.mBufferState),
                slot.mCrop.left, slot.mCrop.top, slot.mCrop.right,
                slot.mCrop.bottom, slot.mTransform, slot.mTimestamp,
                scalingModeName(slot.mScalingMode)
        );
        result.append(buffer);

        const sp<GraphicBuffer>& buf(slot.mGraphicBuffer);
        if (buf != NULL) {
            snprintf(buffer, SIZE,
                    ", %p [%4ux%4u:%4u,%3X]",
                    buf->handle, buf->width, buf->height, buf->stride,
                    buf->format);
            result.append(buffer);
        }
        result.append("\n");
    }
}

void BufferQueue::freeBufferLocked(int slot) {
    ST_LOGV("freeBufferLocked: slot=%d", slot);
    mSlots[slot].mGraphicBuffer = 0;
    if (mSlots[slot].mBufferState == BufferSlot::ACQUIRED) {
        mSlots[slot].mNeedsCleanupOnRelease = true;
    }
    mSlots[slot].mBufferState = BufferSlot::FREE;
    mSlots[slot].mFrameNumber = 0;
    mSlots[slot].mAcquireCalled = false;

    // destroy fence as BufferQueue now takes ownership
    if (mSlots[slot].mEglFence != EGL_NO_SYNC_KHR) {
        eglDestroySyncKHR(mSlots[slot].mEglDisplay, mSlots[slot].mEglFence);
        mSlots[slot].mEglFence = EGL_NO_SYNC_KHR;
    }

    mSlots[slot].mFence.clear();
}

#ifdef STE_HARDWARE
void BufferQueue::freeBlitBufferLocked(int slot) {
    ST_LOGV("freeBufferLocked: slot=%d", slot);
    mBlitSlots[slot].mGraphicBuffer = 0;
    if (mBlitSlots[slot].mBufferState == BufferSlot::ACQUIRED) {
        mBlitSlots[slot].mNeedsCleanupOnRelease = true;
    }
    mBlitSlots[slot].mBufferState = BufferSlot::FREE;
    mBlitSlots[slot].mFrameNumber = 0;
    mBlitSlots[slot].mAcquireCalled = false;

    // destroy fence as BufferQueue now takes ownership
    if (mBlitSlots[slot].mEglFence != EGL_NO_SYNC_KHR) {
        eglDestroySyncKHR(mBlitSlots[slot].mEglDisplay, mBlitSlots[slot].mEglFence);
        mBlitSlots[slot].mEglFence = EGL_NO_SYNC_KHR;
    }

    mBlitSlots[slot].mFence.clear();
}
#endif

void BufferQueue::freeAllBuffersLocked() {
    ALOGW_IF(!mQueue.isEmpty(),
            "freeAllBuffersLocked called but mQueue is not empty");
    mQueue.clear();
    mBufferHasBeenQueued = false;
    for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
        freeBufferLocked(i);
    }
#ifdef STE_HARDWARE
    for (int i = 0; i < NUM_BLIT_BUFFER_SLOTS; i++) {
        freeBlitBufferLocked(i);
    }
#endif
}

status_t BufferQueue::acquireBuffer(BufferItem *buffer) {
    ATRACE_CALL();
    Mutex::Autolock _l(mMutex);

    // Check that the consumer doesn't currently have the maximum number of
    // buffers acquired.  We allow the max buffer count to be exceeded by one
    // buffer, so that the consumer can successfully set up the newly acquired
    // buffer before releasing the old one.
    int numAcquiredBuffers = 0;
    for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
        if (mSlots[i].mBufferState == BufferSlot::ACQUIRED) {
            numAcquiredBuffers++;
        }
    }

#ifdef STE_HARDWARE
    int numBlitAcquiredBuffers = 0;
    for (int i = 0; i < NUM_BLIT_BUFFER_SLOTS; i++) {
        if (mBlitSlots[i].mBufferState == BufferSlot::ACQUIRED) {
            numBlitAcquiredBuffers++;
        }
    }
#endif

    if (numAcquiredBuffers >= mMaxAcquiredBufferCount+1) {
#ifdef STE_HARDWARE
       // We assume we are using blit slots if the normal slots exceed the max count
       // TODO: Make a way to check the one in use instead of checking both.
        if (numBlitAcquiredBuffers >= mMaxAcquiredBufferCount+1) {
            ST_LOGE("acquireBuffer: max acquired blit buffer count reached: %d (max=%d)",
                    numBlitAcquiredBuffers, mMaxAcquiredBufferCount);
            return INVALID_OPERATION;
        }
#else
        ST_LOGE("acquireBuffer: max acquired buffer count reached: %d (max=%d)",
                numAcquiredBuffers, mMaxAcquiredBufferCount);
        return INVALID_OPERATION;
#endif
    }

    // check if queue is empty
    // In asynchronous mode the list is guaranteed to be one buffer
    // deep, while in synchronous mode we use the oldest buffer.
    if (!mQueue.empty()) {
        Fifo::iterator front(mQueue.begin());
        int buf = *front;

        ATRACE_BUFFER_INDEX(buf);

        if (mSlots[buf].mAcquireCalled) {
            buffer->mGraphicBuffer = NULL;
        } else {
            buffer->mGraphicBuffer = mSlots[buf].mGraphicBuffer;
        }
        buffer->mCrop = mSlots[buf].mCrop;
        buffer->mTransform = mSlots[buf].mTransform;
        buffer->mScalingMode = mSlots[buf].mScalingMode;
        buffer->mFrameNumber = mSlots[buf].mFrameNumber;
        buffer->mTimestamp = mSlots[buf].mTimestamp;
        buffer->mBuf = buf;
        buffer->mFence = mSlots[buf].mFence;

        mSlots[buf].mAcquireCalled = true;
        mSlots[buf].mNeedsCleanupOnRelease = false;
        mSlots[buf].mBufferState = BufferSlot::ACQUIRED;
        mSlots[buf].mFence.clear();

        mQueue.erase(front);
        mDequeueCondition.broadcast();

        ATRACE_INT(mConsumerName.string(), mQueue.size());
    } else {
        return NO_BUFFER_AVAILABLE;
    }

    return OK;
}

status_t BufferQueue::releaseBuffer(int buf, EGLDisplay display,
        EGLSyncKHR eglFence, const sp<Fence>& fence) {
    ATRACE_CALL();
    ATRACE_BUFFER_INDEX(buf);

    Mutex::Autolock _l(mMutex);

    if (buf == INVALID_BUFFER_SLOT) {
        return -EINVAL;
    }

    mSlots[buf].mEglDisplay = display;
    mSlots[buf].mEglFence = eglFence;
    mSlots[buf].mFence = fence;

    // The buffer can now only be released if its in the acquired state
    if (mSlots[buf].mBufferState == BufferSlot::ACQUIRED) {
        mSlots[buf].mBufferState = BufferSlot::FREE;
    } else if (mSlots[buf].mNeedsCleanupOnRelease) {
        ST_LOGV("releasing a stale buf %d its state was %d", buf, mSlots[buf].mBufferState);
        mSlots[buf].mNeedsCleanupOnRelease = false;
        return STALE_BUFFER_SLOT;
    } else {
        ST_LOGE("attempted to release buf %d but its state was %d", buf, mSlots[buf].mBufferState);
        return -EINVAL;
    }

    mDequeueCondition.broadcast();
    return OK;
}

status_t BufferQueue::consumerConnect(const sp<ConsumerListener>& consumerListener) {
    ST_LOGV("consumerConnect");
    Mutex::Autolock lock(mMutex);

    if (mAbandoned) {
        ST_LOGE("consumerConnect: BufferQueue has been abandoned!");
        return NO_INIT;
    }

    mConsumerListener = consumerListener;

    return OK;
}

status_t BufferQueue::consumerDisconnect() {
    ST_LOGV("consumerDisconnect");
    Mutex::Autolock lock(mMutex);

    if (mConsumerListener == NULL) {
        ST_LOGE("consumerDisconnect: No consumer is connected!");
        return -EINVAL;
    }

    mAbandoned = true;
    mConsumerListener = NULL;
    mQueue.clear();
    freeAllBuffersLocked();
    mDequeueCondition.broadcast();
    return OK;
}

status_t BufferQueue::getReleasedBuffers(uint32_t* slotMask) {
    ST_LOGV("getReleasedBuffers");
    Mutex::Autolock lock(mMutex);

    if (mAbandoned) {
        ST_LOGE("getReleasedBuffers: BufferQueue has been abandoned!");
        return NO_INIT;
    }

    uint32_t mask = 0;
    for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
        if (!mSlots[i].mAcquireCalled) {
            mask |= 1 << i;
        }
    }
    *slotMask = mask;

    ST_LOGV("getReleasedBuffers: returning mask %#x", mask);
    return NO_ERROR;
}

status_t BufferQueue::setDefaultBufferSize(uint32_t w, uint32_t h)
{
    ST_LOGV("setDefaultBufferSize: w=%d, h=%d", w, h);
    if (!w || !h) {
        ST_LOGE("setDefaultBufferSize: dimensions cannot be 0 (w=%d, h=%d)",
                w, h);
        return BAD_VALUE;
    }

    Mutex::Autolock lock(mMutex);
    mDefaultWidth = w;
    mDefaultHeight = h;
    return OK;
}

status_t BufferQueue::setDefaultMaxBufferCount(int bufferCount) {
    ATRACE_CALL();
    Mutex::Autolock lock(mMutex);
    return setDefaultMaxBufferCountLocked(bufferCount);
}

status_t BufferQueue::setMaxAcquiredBufferCount(int maxAcquiredBuffers) {
    ATRACE_CALL();
    Mutex::Autolock lock(mMutex);
    if (maxAcquiredBuffers < 1 || maxAcquiredBuffers > MAX_MAX_ACQUIRED_BUFFERS) {
        ST_LOGE("setMaxAcquiredBufferCount: invalid count specified: %d",
                maxAcquiredBuffers);
        return BAD_VALUE;
    }
    if (mConnectedApi != NO_CONNECTED_API) {
        return INVALID_OPERATION;
    }
    mMaxAcquiredBufferCount = maxAcquiredBuffers;
    return OK;
}

void BufferQueue::freeAllBuffersExceptHeadLocked() {
    int head = -1;
    if (!mQueue.empty()) {
        Fifo::iterator front(mQueue.begin());
        head = *front;
    }
    mBufferHasBeenQueued = false;
    for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
        if (i != head) {
            freeBufferLocked(i);
        }
    }
}

status_t BufferQueue::drainQueueLocked() {
    while (mSynchronousMode && !mQueue.isEmpty()) {
        mDequeueCondition.wait(mMutex);
        if (mAbandoned) {
            ST_LOGE("drainQueueLocked: BufferQueue has been abandoned!");
            return NO_INIT;
        }
        if (mConnectedApi == NO_CONNECTED_API) {
            ST_LOGE("drainQueueLocked: BufferQueue is not connected!");
            return NO_INIT;
        }
    }
    return NO_ERROR;
}

status_t BufferQueue::drainQueueAndFreeBuffersLocked() {
    status_t err = drainQueueLocked();
    if (err == NO_ERROR) {
        if (mSynchronousMode) {
            freeAllBuffersLocked();
        } else {
            freeAllBuffersExceptHeadLocked();
        }
    }
    return err;
}

int BufferQueue::getMinMaxBufferCountLocked() const {
    return getMinUndequeuedBufferCountLocked() + 1;
}

int BufferQueue::getMinUndequeuedBufferCountLocked() const {
    return mSynchronousMode ? mMaxAcquiredBufferCount :
            mMaxAcquiredBufferCount + 1;
}

int BufferQueue::getMaxBufferCountLocked() const {
    int minMaxBufferCount = getMinMaxBufferCountLocked();

    int maxBufferCount = mDefaultMaxBufferCount;
    if (maxBufferCount < minMaxBufferCount) {
        maxBufferCount = minMaxBufferCount;
    }
    if (mOverrideMaxBufferCount != 0) {
        assert(mOverrideMaxBufferCount >= minMaxBufferCount);
        maxBufferCount = mOverrideMaxBufferCount;
    }

    // Any buffers that are dequeued by the producer or sitting in the queue
    // waiting to be consumed need to have their slots preserved.  Such
    // buffers will temporarily keep the max buffer count up until the slots
    // no longer need to be preserved.
    for (int i = maxBufferCount; i < NUM_BUFFER_SLOTS; i++) {
        BufferSlot::BufferState state = mSlots[i].mBufferState;
        if (state == BufferSlot::QUEUED || state == BufferSlot::DEQUEUED) {
            maxBufferCount = i + 1;
        }
    }

    return maxBufferCount;
}

BufferQueue::ProxyConsumerListener::ProxyConsumerListener(
        const wp<BufferQueue::ConsumerListener>& consumerListener):
        mConsumerListener(consumerListener) {}

BufferQueue::ProxyConsumerListener::~ProxyConsumerListener() {}

void BufferQueue::ProxyConsumerListener::onFrameAvailable() {
    sp<BufferQueue::ConsumerListener> listener(mConsumerListener.promote());
    if (listener != NULL) {
        listener->onFrameAvailable();
    }
}

void BufferQueue::ProxyConsumerListener::onBuffersReleased() {
    sp<BufferQueue::ConsumerListener> listener(mConsumerListener.promote());
    if (listener != NULL) {
        listener->onBuffersReleased();
    }
}

}; // namespace android


text:
"""
Author: Keith Bourgoin, Emmett Butler
"""
__license__ = """
Copyright 2015 Parse.ly, Inc.

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

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

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

__all__ = ["KafkaClient"]

from .handlers import ThreadingHandler, GEventHandler
import logging

from .cluster import Cluster
from .handlers import ThreadingHandler

log = logging.getLogger(__name__)

class KafkaClient(object):
    """
    A high-level pythonic client for Kafka

    NOTE: `KafkaClient` holds weak references to `Topic` instances via
    :class:`pykafka.cluster.TopicDict`. To perform operations directly on these topics,
    such as examining their partition lists, client code must hold a strong reference to
    the topics it cares about. If client code doesn't need to examine `Topic` instances
    directly, no strong references are necessary.
    """
    def __init__(self,
                 hosts='127.0.0.1:9092',
                 zookeeper_hosts=None,
                 socket_timeout_ms=30 * 1000,
                 offsets_channel_socket_timeout_ms=10 * 1000,
                 use_greenlets=False,
                 exclude_internal_topics=True,
                 source_address=''):
        """Create a connection to a Kafka cluster.

        Documentation for source_address can be found at
        https://docs.python.org/2/library/socket.html#socket.create_connection

        :param hosts: Comma-separated list of kafka hosts to which to connect.
        :type hosts: bytes
        :param zookeeper_hosts: KazooClient-formatted string of ZooKeeper hosts to which
            to connect. If not `None`, this argument takes precedence over `hosts`
        :type zookeeper_hosts: bytes
        :param socket_timeout_ms: The socket timeout (in milliseconds) for
            network requests
        :type socket_timeout_ms: int
        :param offsets_channel_socket_timeout_ms: The socket timeout (in
            milliseconds) when reading responses for offset commit and
            offset fetch requests.
        :type offsets_channel_socket_timeout_ms: int
        :param use_greenlets: Whether to perform parallel operations on greenlets
            instead of OS threads
        :type use_greenlets: bool
        :param exclude_internal_topics: Whether messages from internal topics
            (specifically, the offsets topic) should be exposed to the consumer.
        :type exclude_internal_topics: bool
        :param source_address: The source address for socket connections
        :type source_address: str `'host:port'`
        """
        self._seed_hosts = zookeeper_hosts if zookeeper_hosts is not None else hosts
        self._source_address = source_address
        self._socket_timeout_ms = socket_timeout_ms
        self._offsets_channel_socket_timeout_ms = offsets_channel_socket_timeout_ms
        self._handler = GEventHandler() if use_greenlets else ThreadingHandler()
        self.cluster = Cluster(
            hosts,
            self._handler,
            socket_timeout_ms=self._socket_timeout_ms,
            offsets_channel_socket_timeout_ms=self._offsets_channel_socket_timeout_ms,
            exclude_internal_topics=exclude_internal_topics,
            source_address=self._source_address,
            zookeeper_hosts=zookeeper_hosts
        )
        self.brokers = self.cluster.brokers
        self.topics = self.cluster.topics

    def __repr__(self):
        return "<{module}.{name} at {id_} (hosts={hosts})>".format(
            module=self.__class__.__module__,
            name=self.__class__.__name__,
            id_=hex(id(self)),
            hosts=self._seed_hosts,
        )

    def update_cluster(self):
        """Update known brokers and topics.

        Updates each Topic and Broker, adding new ones as found,
        with current metadata from the cluster.
        """
        self.cluster.update()


text:
layout: page
title: "MUEL 4081: Introduction to Music Technology Statistics"
comments: true
description: "blanks"
keywords: "MUEL,4081,CU,Boulder"
---

#### GRADE AND WORKLOAD STATISTICS

**Percent withdrawn**: 2.9%

**Percent incomplete**: 0.0%

**Average grade** (4.0 scale): 3.4

**Standard deviation in grades** (4.0 scale): 0.36

**Average workload** (raw): 2.49

**Standard deviation in workload** (raw): 0.42

#### COURSE AND INSTRUCTOR RATINGS/INFORMATION

**Average course rating** (6 point scale): 5.49

**Standard deviation in course rating** (6 point scale): 0.29

**Average instructor rating** (6 point scale): 5.52

**Standard deviation in instructor rating** (6 point scale): 0.41

**Instructors**: John Clay Allen, Sara Corry, John Drumheller, Nathan Alan Hall, Brian Donald Kelly, Herbert Hugh Lobel, John Paul Merz, Kevin Michael Olson

#### GENERAL CLASS INFORMATION

**Years provided**: Fall 2012, Spring 2013, Fall 2013, Spring 2014, Fall 2014, Spring 2015, Fall 2015, Spring 2016, Fall 2016, Spring 2017

**Credits**: 3

**RAP/Honors class?** Neither

**Number of Sections**: 20

**Department**: MUSC

**College**: College of Music

**Level**: Upper

**Activity**: LEC - Lecture


text:
__author__ = 'Miel Donkers <miel.donkers@gmail.com>'

import logging

from sqlalchemy import create_engine, MetaData, Column, Table, Integer, DateTime, select, desc

log = logging.getLogger(__name__)

class EventStore:
    """
    The EventStore manages database connections and provides methods to store alarm notification events and retrieve them.

    As this object references an SQLAlchemy Engine object, only one EventStore instance should be created per application.
    """

    def __init__(self):
        # Init de database connection
        self.engine = create_engine('sqlite:///alarm_events.db')
        # Table definition
        metadata = MetaData()
        self.alarm_events = Table('alarm_events', metadata,
                                  Column('id', Integer, primary_key=True),
                                  Column('timestamp', DateTime, nullable=False))
        # Init the database, creates corresponding tables when not available
        metadata.create_all(self.engine)

    def close(self):
        """
        Dispose of the connection-pool, releasing all connections
        """
        self.engine.dispose()

    def store_event(self, timestamp):
        with self.engine.begin() as connection:
            result = connection.execute(self.alarm_events.insert(), timestamp=timestamp)
            log.debug('Event inserted correctly, generated primary key: {}'.format(result.inserted_primary_key))

    def find_last_events(self, max_events=2):
        """
        Return the last alarm events that were stored in the database, ordered from most recent to oldest.
        :param max_events: The maximum number of events to query for, default = 2
        :return: Ordered list of alarm events, from most recent to oldest
        """
        connection = self.engine.connect()

        select_statement = select([self.alarm_events]).order_by(desc("timestamp")).limit(max_events)
        result = connection.execute(select_statement)

        timestamp_results = tuple(row[self.alarm_events.c.timestamp] for row in result)
        log.debug('Got result from alarm_events, query limited to {max} records. Results: {rows}'
                  .format(max=max_events, rows=', '.join(str(tstamp) for tstamp in timestamp_results)))

        result.close()
        connection.close()
        return timestamp_results


text:
/**
 * DataBinding Module
 *
 * @module DataBinding
 * @default module:DataBinding.DataBinding
 */
import { makeTemplate, createTemplateInstance } from './lib/Template.js';
import { attachBindings } from './lib/Bind';
import { polyInvoke } from './lib/Util.js';
import ViewPort from './lib/ViewPort.js';
import * as Config from './lib/Config';
import './lib/bindings/IfBinding.js';
import './lib/bindings/ElementToScopeBinding.js';
import './lib/bindings/HtmlBinding.js';
import './lib/bindings/CloakBinding.js';
import './lib/bindings/AttributeBinding';
import './lib/bindings/AnimationBinding';
import './lib/bindings/TemplateRepeatBinding';
import './lib/bindings/EventBinding';
import './lib/bindings/StyleBinding';
import './lib/bindings/AutoBinding';
import './lib/bindings/ClassBinding';
import './lib/bindings/EnabledBinding';
import './lib/bindings/TwoWayBinding.js';

NodeList.prototype.forEach = NamedNodeMap.prototype.forEach = Array.prototype.forEach;

let style = document.createElement('style');

style.innerHTML = `
    :not(.animated) > :not(.animated) > :not(.animated) > [bind-display="false"]:not(.animated) {
        display: none !important;
    }

    :not(.animated) > :not(.animated) > :not(.animated) > [bind-visible="false"]:not(.animated) {
        visibility: hidden;
    }
`;

polyInvoke(document.head).appendChild(style);

export const DataBindingMeta = {
    enableLogging: Config.enableLogging,
    enableVerboseLogging: Config.enableVerboseLogging,

    get object() { return DataBinding; }
};

/**
 * [DataBinding description]
 *
 * @type {module:DataBinding.ModuleInterface}
 */
// [meta*]
export let DataBinding = {
    makeTemplate : makeTemplate,
    ViewPort : ViewPort,
    createTemplateInstance: createTemplateInstance,
    attachBindings,
};

export { ANIMATION_BINDING_LOOPED } from './lib/bindings/AnimationBinding';
export { default as BindingApi } from './lib/BindingApi';

export default DataBinding;

/**
 * @interface ModuleInterface
 * @borrows module:DataBinding/Bind.bindNode as bindNode
 * @borrows module:DataBinding/Template.makeTemplate as makeTemplate
 * @borrows module:DataBinding/ViewPort.ViewPort
 * @static
 *
 */