text:
!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var n;"undefined"!=typeof window?n=window:"undefined"!=typeof global?n=global:"undefined"!=typeof self&&(n=self),n.ReactInlineSVG=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
'use strict';

var Response = _dereq_('./response');

function RequestError(message, props) {
    var err = new Error(message);
    err.name = 'RequestError';
    this.name = err.name;
    this.message = err.message;
    if (err.stack) {
        this.stack = err.stack;
    }

    this.toString = function () {
        return this.message;
    };

    for (var k in props) {
        if (props.hasOwnProperty(k)) {
            this[k] = props[k];
        }
    }
}

RequestError.prototype = Error.prototype;

RequestError.create = function (message, req, props) {
    var err = new RequestError(message, props);
    Response.call(err, req);
    return err;
};

module.exports = RequestError;

},{"./response":4}],2:[function(_dereq_,module,exports){
'use strict';

var i,
    cleanURL = _dereq_('../plugins/cleanurl'),
    XHR = _dereq_('./xhr'),
    delay = _dereq_('./utils/delay'),
    createError = _dereq_('./error').create,
    Response = _dereq_('./response'),
    Request = _dereq_('./request'),
    extend = _dereq_('xtend'),
    once = _dereq_('./utils/once');

function factory(defaults, plugins) {
    defaults = defaults || {};
    plugins = plugins || [];

    function http(req, cb) {
        var xhr, plugin, done, k, timeoutId, supportsLoadAndErrorEvents;

        req = new Request(extend(defaults, req));

        for (i = 0; i < plugins.length; i++) {
            plugin = plugins[i];
            if (plugin.processRequest) {
                plugin.processRequest(req);
            }
        }

        // Give the plugins a chance to create the XHR object
        for (i = 0; i < plugins.length; i++) {
            plugin = plugins[i];
            if (plugin.createXHR) {
                xhr = plugin.createXHR(req);
                break; // First come, first serve
            }
        }
        xhr = xhr || new XHR();

        req.xhr = xhr;

        // Use a single completion callback. This can be called with or without
        // an error. If no error is passed, the request will be examined to see
        // if it was successful.
        done = once(delay(function (rawError) {
            clearTimeout(timeoutId);
            xhr.onload = xhr.onerror = xhr.onabort = xhr.onreadystatechange = xhr.ontimeout = xhr.onprogress = null;

            var err = getError(req, rawError);

            var res = err && err.isHttpError ? err : new Response(req);
            for (i = 0; i < plugins.length; i++) {
                plugin = plugins[i];
                if (plugin.processResponse) {
                    plugin.processResponse(res);
                }
            }
            if (err) {
                if (req.onerror) {
                    req.onerror(err);
                }
            } else {
                if (req.onload) {
                    req.onload(res);
                }
            }
            if (cb) {
                cb(err, res);
            }
        }));

        supportsLoadAndErrorEvents = ('onload' in xhr) && ('onerror' in xhr);
        xhr.onload = function () { done(); };
        xhr.onerror = done;
        xhr.onabort = function () { done(); };

        // We'd rather use `onload`, `onerror`, and `onabort` since they're the
        // only way to reliably detect successes and failures but, if they
        // aren't available, we fall back to using `onreadystatechange`.
        xhr.onreadystatechange = function () {
            if (xhr.readyState !== 4) return;

            if (req.aborted) return done();

            if (!supportsLoadAndErrorEvents) {
                // Assume a status of 0 is an error. This could be a false
                // positive, but there's no way to tell when using
                // `onreadystatechange` ):
                // See matthewwithanm/react-inlinesvg#10.
                var err = xhr.status === 0 ? new Error('Internal XHR Error') : null;
                return done(err);
            }
        };

        // IE sometimes fails if you don't specify every handler.
        // See http://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment
        xhr.ontimeout = function () { /* noop */ };
        xhr.onprogress = function () { /* noop */ };

        xhr.open(req.method, req.url);

        if (req.timeout) {
            // If we use the normal XHR timeout mechanism (`xhr.timeout` and
            // `xhr.ontimeout`), `onreadystatechange` will be triggered before
            // `ontimeout`. There's no way to recognize that it was triggered by
            // a timeout, and we'd be unable to dispatch the right error.
            timeoutId = setTimeout(function () {
                req.timedOut = true;
                done();
                try {
                    xhr.abort();
                } catch (err) {}
            }, req.timeout);
        }

        for (k in req.headers) {
            if (req.headers.hasOwnProperty(k)) {
                xhr.setRequestHeader(k, req.headers[k]);
            }
        }

        xhr.send(req.body);

        return req;
    }

    var method,
        methods = ['get', 'post', 'put', 'head', 'patch', 'delete'],
        verb = function (method) {
            return function (req, cb) {
                req = new Request(req);
                req.method = method;
                return http(req, cb);
            };
        };
    for (i = 0; i < methods.length; i++) {
        method = methods[i];
        http[method] = verb(method);
    }

    http.plugins = function () {
        return plugins;
    };

    http.defaults = function (newValues) {
        if (newValues) {
            return factory(extend(defaults, newValues), plugins);
        }
        return defaults;
    };

    http.use = function () {
        var newPlugins = Array.prototype.slice.call(arguments, 0);
        return factory(defaults, plugins.concat(newPlugins));
    };

    http.bare = function () {
        return factory();
    };

    http.Request = Request;
    http.Response = Response;

    return http;
}

module.exports = factory({}, [cleanURL]);

/**
 * Analyze the request to see if it represents an error. If so, return it! An
 * original error object can be passed as a hint.
 */
function getError(req, err) {
    if (req.aborted)
        return createError('Request aborted', req, {name: 'Abort'});

    if (req.timedOut)
        return createError('Request timeout', req, {name: 'Timeout'});

    var xhr = req.xhr;
    var type = Math.floor(xhr.status / 100);

    var kind;
    switch (type) {
        case 0:
        case 2:
            // These don't represent errors unless the function was passed an
            // error object explicitly.
            if (!err) return;
            return createError(err.message, req);
        case 4:
            // Sometimes 4XX statuses aren't errors.
            if (xhr.status === 404 && !req.errorOn404) return;
            kind = 'Client';
            break;
        case 5:
            kind = 'Server';
            break;
        default:
            kind = 'HTTP';
    }
    var msg = kind + ' Error: ' +
              'The server returned a status of ' + xhr.status +
              ' for the request "' +
              req.method.toUpperCase() + ' ' + req.url + '"';
    return createError(msg, req);
}

},{"../plugins/cleanurl":10,"./error":1,"./request":3,"./response":4,"./utils/delay":5,"./utils/once":6,"./xhr":7,"xtend":9}],3:[function(_dereq_,module,exports){
'use strict';

function Request(optsOrUrl) {
    var opts = typeof optsOrUrl === 'string' ? {url: optsOrUrl} : optsOrUrl || {};
    this.method = opts.method ? opts.method.toUpperCase() : 'GET';
    this.url = opts.url;
    this.headers = opts.headers || {};
    this.body = opts.body;
    this.timeout = opts.timeout || 0;
    this.errorOn404 = opts.errorOn404 != null ? opts.errorOn404 : true;
    this.onload = opts.onload;
    this.onerror = opts.onerror;
}

Request.prototype.abort = function () {
    if (this.aborted) return;
    this.aborted = true;
    this.xhr.abort();
    return this;
};

Request.prototype.header = function (name, value) {
    var k;
    for (k in this.headers) {
        if (this.headers.hasOwnProperty(k)) {
            if (name.toLowerCase() === k.toLowerCase()) {
                if (arguments.length === 1) {
                    return this.headers[k];
                }

                delete this.headers[k];
                break;
            }
        }
    }
    if (value != null) {
        this.headers[name] = value;
        return value;
    }
};

module.exports = Request;

},{}],4:[function(_dereq_,module,exports){
'use strict';

var Request = _dereq_('./request');

function Response(req) {
    var i, lines, m,
        xhr = req.xhr;
    this.request = req;
    this.xhr = xhr;
    this.headers = {};

    // Browsers don't like you trying to read XHR properties when you abort the
    // request, so we don't.
    if (req.aborted || req.timedOut) return;

    this.status = xhr.status || 0;
    this.text = xhr.responseText;
    this.body = xhr.response || xhr.responseText;
    this.contentType = xhr.contentType || (xhr.getResponseHeader && xhr.getResponseHeader('Content-Type'));

    if (xhr.getAllResponseHeaders) {
        lines = xhr.getAllResponseHeaders().split('\n');
        for (i = 0; i < lines.length; i++) {
            if ((m = lines[i].match(/\s*([^\s]+):\s+([^\s]+)/))) {
                this.headers[m[1]] = m[2];
            }
        }
    }

    this.isHttpError = this.status >= 400;
}

Response.prototype.header = Request.prototype.header;

module.exports = Response;

},{"./request":3}],5:[function(_dereq_,module,exports){
'use strict';

// Wrap a function in a `setTimeout` call. This is used to guarantee async
// behavior, which can avoid unexpected errors.

module.exports = function (fn) {
    return function () {
        var
            args = Array.prototype.slice.call(arguments, 0),
            newFunc = function () {
                return fn.apply(null, args);
            };
        setTimeout(newFunc, 0);
    };
};

},{}],6:[function(_dereq_,module,exports){
'use strict';

// A "once" utility.
module.exports = function (fn) {
    var result, called = false;
    return function () {
        if (!called) {
            called = true;
            result = fn.apply(this, arguments);
        }
        return result;
    };
};

},{}],7:[function(_dereq_,module,exports){
module.exports = window.XMLHttpRequest;

},{}],8:[function(_dereq_,module,exports){
(function() {
  var URL, URL_PATTERN, defaults, urllite,
    __hasProp = {}.hasOwnProperty;

  URL_PATTERN = /^(?:(?:([^:\/?\#]+:)\/+|(\/\/))(?:([a-z0-9-\._~%]+)(?::([a-z0-9-\._~%]+))?@)?(([a-z0-9-\._~%!$&'()*+,;=]+)(?::([0-9]+))?)?)?([^?\#]*?)(\?[^\#]*)?(\#.*)?$/;

  urllite = function(raw, opts) {
    return urllite.URL.parse(raw, opts);
  };

  urllite.URL = URL = (function() {
    function URL(props) {
      var k, v, _ref;
      for (k in defaults) {
        if (!__hasProp.call(defaults, k)) continue;
        v = defaults[k];
        this[k] = (_ref = props[k]) != null ? _ref : v;
      }
      this.host || (this.host = this.hostname && this.port ? "" + this.hostname + ":" + this.port : this.hostname ? this.hostname : '');
      this.origin || (this.origin = this.protocol ? "" + this.protocol + "//" + this.host : '');
      this.isAbsolutePathRelative = !this.host && this.pathname.charAt(0) === '/';
      this.isPathRelative = !this.host && this.pathname.charAt(0) !== '/';
      this.isRelative = this.isSchemeRelative || this.isAbsolutePathRelative || this.isPathRelative;
      this.isAbsolute = !this.isRelative;
    }

    URL.parse = function(raw) {
      var m, pathname, protocol;
      m = raw.toString().match(URL_PATTERN);
      pathname = m[8] || '';
      protocol = m[1];
      return new urllite.URL({
        protocol: protocol,
        username: m[3],
        password: m[4],
        hostname: m[6],
        port: m[7],
        pathname: protocol && pathname.charAt(0) !== '/' ? "/" + pathname : pathname,
        search: m[9],
        hash: m[10],
        isSchemeRelative: m[2] != null
      });
    };

    return URL;

  })();

  defaults = {
    protocol: '',
    username: '',
    password: '',
    host: '',
    hostname: '',
    port: '',
    pathname: '',
    search: '',
    hash: '',
    origin: '',
    isSchemeRelative: false
  };

  module.exports = urllite;

}).call(this);

},{}],9:[function(_dereq_,module,exports){
module.exports = extend

function extend() {
    var target = {}

    for (var i = 0; i < arguments.length; i++) {
        var source = arguments[i]

        for (var key in source) {
            if (source.hasOwnProperty(key)) {
                target[key] = source[key]
            }
        }
    }

    return target
}

},{}],10:[function(_dereq_,module,exports){
'use strict';

module.exports = {
    processRequest: function (req) {
        req.url = req.url.replace(/[^%]+/g, function (s) {
            return encodeURI(s);
        });
    }
};

},{}],11:[function(_dereq_,module,exports){
'use strict';

var
    urllite = _dereq_('urllite/lib/core'),
    once = _dereq_('../lib/utils/once'),
    warningShown = false;

var supportsXHR = once(function () {
    return (
        typeof window !== "undefined" &&
        window !== null &&
        window.XMLHttpRequest &&
        'withCredentials' in new window.XMLHttpRequest()
    );
});

// This plugin creates a Microsoft `XDomainRequest` in supporting browsers when
// the URL being requested is on a different domain. This is necessary to
// support IE9, which only supports CORS via its proprietary `XDomainRequest`
// object. We need to check the URL because `XDomainRequest` *doesn't* work for
// same domain requests (unless your server sends CORS headers).
// `XDomainRequest` also has other limitations (no custom headers), so we try to
// catch those and error.
module.exports = {
    createXHR: function (req) {
        var a, b, k;

        if (typeof window === "undefined" || window === null) {
            return;
        }

        a = urllite(req.url);
        b = urllite(window.location.href);

        // Don't do anything for same-domain requests.
        if (!a.host) {
            return;
        }
        if (a.protocol === b.protocol && a.host === b.host && a.port === b.port) {
            return;
        }

        // Show a warning if there are custom headers. We do this even in
        // browsers that won't use XDomainRequest so that users know there's an
        // issue right away, instead of if/when they test in IE9.
        if (!warningShown && req.headers) {
            for (k in req.headers) {
                if (req.headers.hasOwnProperty(k)) {
                    warningShown = true;
                    if (window && window.console && window.console.warn) {
                        window.console.warn("Request headers are ignored in old IE when using the oldiexdomain plugin.");
                    }
                    break;
                }
            }
        }

        // Don't do anything if we can't do anything (:
        // Don't do anything if the browser supports proper XHR.
        if (window.XDomainRequest && !supportsXHR()) {
            // We've come this far. Might as well make an XDomainRequest.
            var xdr = new window.XDomainRequest();
            xdr.setRequestHeader = function() {}; // Ignore request headers.
            return xdr;
        }
    }
};

},{"../lib/utils/once":6,"urllite/lib/core":8}],12:[function(_dereq_,module,exports){
module.exports = once

once.proto = once(function () {
  Object.defineProperty(Function.prototype, 'once', {
    value: function () {
      return once(this)
    },
    configurable: true
  })
})

function once (fn) {
  var f = function () {
    if (f.called) return f.value
    f.called = true
    return f.value = fn.apply(this, arguments)
  }
  f.called = false
  return f
}

},{}],13:[function(_dereq_,module,exports){
var InlineSVGError, PropTypes, React, Status, configurationError, createError, delay, getHash, http, httpplease, ieXDomain, isSupportedEnvironment, me, once, span, supportsInlineSVG, uniquifyIDs, unsupportedBrowserError,
  __slice = [].slice,
  __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

React = (window.React);

once = _dereq_('once');

httpplease = _dereq_('httpplease');

ieXDomain = _dereq_('httpplease/plugins/oldiexdomain');

PropTypes = React.PropTypes;

span = React.DOM.span;

http = httpplease.use(ieXDomain);

Status = {
  PENDING: 'pending',
  LOADING: 'loading',
  LOADED: 'loaded',
  FAILED: 'failed',
  UNSUPPORTED: 'unsupported'
};

supportsInlineSVG = once(function() {
  var div;
  if (!document) {
    return false;
  }
  div = document.createElement('div');
  div.innerHTML = '<svg />';
  return div.firstChild && div.firstChild.namespaceURI === 'http://www.w3.org/2000/svg';
});

delay = function(fn) {
  return function() {
    var args, newFunc;
    args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
    newFunc = function() {
      return fn.apply(null, args);
    };
    setTimeout(newFunc, 0);
  };
};

isSupportedEnvironment = once(function() {
  return ((typeof window !== "undefined" && window !== null ? window.XMLHttpRequest : void 0) || (typeof window !== "undefined" && window !== null ? window.XDomainRequest : void 0)) && supportsInlineSVG();
});

uniquifyIDs = (function() {
  var idPattern, mkAttributePattern;
  mkAttributePattern = function(attr) {
    return "(?:(?:\\s|\\:)" + attr + ")";
  };
  idPattern = RegExp("(?:(" + (mkAttributePattern('id')) + ")=\"([^\"]+)\")|(?:(" + (mkAttributePattern('href')) + "|" + (mkAttributePattern('role')) + "|" + (mkAttributePattern('arcrole')) + ")=\"\\#([^\"]+)\")|(?:=\"url\\(\\#([^\\)]+)\\)\")", "g");
  return function(svgText, svgID) {
    var uniquifyID;
    uniquifyID = function(id) {
      return "" + id + "___" + svgID;
    };
    return svgText.replace(idPattern, function(m, p1, p2, p3, p4, p5) {
      if (p2) {
        return "" + p1 + "=\"" + (uniquifyID(p2)) + "\"";
      } else if (p4) {
        return "" + p3 + "=\"#" + (uniquifyID(p4)) + "\"";
      } else if (p5) {
        return "=\"url(#" + (uniquifyID(p5)) + ")\"";
      }
    });
  };
})();

getHash = function(str) {
  var chr, hash, i, _i, _ref;
  hash = 0;
  if (!str) {
    return hash;
  }
  for (i = _i = 0, _ref = str.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
    chr = str.charCodeAt(i);
    hash = (hash << 5) - hash + chr;
    hash = hash & hash;
  }
  return hash;
};

InlineSVGError = (function(_super) {
  __extends(InlineSVGError, _super);

  InlineSVGError.prototype.name = 'InlineSVGError';

  InlineSVGError.prototype.isSupportedBrowser = true;

  InlineSVGError.prototype.isConfigurationError = false;

  InlineSVGError.prototype.isUnsupportedBrowserError = false;

  function InlineSVGError(message) {
    this.message = message;
  }

  return InlineSVGError;

})(Error);

createError = function(message, attrs) {
  var err, k, v;
  err = new InlineSVGError(message);
  for (k in attrs) {
    if (!__hasProp.call(attrs, k)) continue;
    v = attrs[k];
    err[k] = v;
  }
  return err;
};

unsupportedBrowserError = function(message) {
  if (message == null) {
    message = 'Unsupported Browser';
  }
  return createError(message, {
    isSupportedBrowser: false,
    isUnsupportedBrowserError: true
  });
};

configurationError = function(message) {
  return createError(message, {
    isConfigurationError: true
  });
};

module.exports = me = React.createClass({
  statics: {
    Status: Status
  },
  displayName: 'InlineSVG',
  propTypes: {
    wrapper: PropTypes.func,
    src: PropTypes.string.isRequired,
    className: PropTypes.string,
    preloader: PropTypes.func,
    onLoad: PropTypes.func,
    onError: PropTypes.func,
    supportTest: PropTypes.func,
    uniquifyIDs: PropTypes.bool
  },
  getDefaultProps: function() {
    return {
      wrapper: span,
      supportTest: isSupportedEnvironment,
      uniquifyIDs: true
    };
  },
  getInitialState: function() {
    return {
      status: Status.PENDING
    };
  },
  componentDidMount: function() {
    if (this.state.status !== Status.PENDING) {
      return;
    }
    if (this.props.supportTest()) {
      if (this.props.src) {
        return this.setState({
          status: Status.LOADING
        }, this.load);
      } else {
        return delay((function(_this) {
          return function() {
            return _this.fail(configurationError('Missing source'));
          };
        })(this))();
      }
    } else {
      return delay((function(_this) {
        return function() {
          return _this.fail(unsupportedBrowserError());
        };
      })(this))();
    }
  },
  fail: function(error) {
    var status;
    status = error.isUnsupportedBrowserError ? Status.UNSUPPORTED : Status.FAILED;
    return this.setState({
      status: status
    }, (function(_this) {
      return function() {
        var _base;
        return typeof (_base = _this.props).onError === "function" ? _base.onError(error) : void 0;
      };
    })(this));
  },
  handleLoad: function(err, res) {
    if (err) {
      return this.fail(err);
    }
    if (!this.isMounted()) {
      return;
    }
    return this.setState({
      loadedText: res.text,
      status: Status.LOADED
    }, (function(_this) {
      return function() {
        var _base;
        return typeof (_base = _this.props).onLoad === "function" ? _base.onLoad() : void 0;
      };
    })(this));
  },
  load: function() {
    var m, text;
    if (m = this.props.src.match(/data:image\/svg[^,]*?(;base64)?,(.*)/)) {
      text = m[1] ? atob(m[2]) : decodeURIComponent(m[2]);
      return this.handleLoad(null, {
        text: text
      });
    } else {
      return http.get(this.props.src, this.handleLoad);
    }
  },
  getClassName: function() {
    var className;
    className = "isvg " + this.state.status;
    if (this.props.className) {
      className += " " + this.props.className;
    }
    return className;
  },
  render: function() {
    return this.props.wrapper({
      className: this.getClassName(),
      dangerouslySetInnerHTML: this.state.loadedText ? {
        __html: this.processSVG(this.state.loadedText)
      } : void 0
    }, this.renderContents());
  },
  processSVG: function(svgText) {
    if (this.props.uniquifyIDs) {
      return uniquifyIDs(svgText, getHash(this.props.src));
    } else {
      return svgText;
    }
  },
  renderContents: function() {
    switch (this.state.status) {
      case Status.UNSUPPORTED:
        return this.props.children;
      case Status.PENDING:
      case Status.LOADING:
        if (this.props.preloader) {
          return new this.props.preloader;
        }
    }
  }
});

},{"httpplease":2,"httpplease/plugins/oldiexdomain":11,"once":12}]},{},[13])
(13)
});


text:
import gevent
import gevent.monkey; gevent.monkey.patch_all()
import sys

from couchbase.bucket import Bucket

def test(x):
    c = Bucket('couchbase://localhost/default', experimental_gevent_support=True)
    c.upsert("tmp-" + str(x), 1)
    sys.stdout.write(str(x) + " ")
    sys.stdout.flush()

print("Gevent starting..")
gevent.joinall([gevent.spawn(test, x) for x in xrange(100)])
print("")

redpajama_set_name: RedPajamaGithub


text:
module CanvasBag {
    export interface Node {
        getType():any;
        setProperties(properties: any);
        getProperties(): any;
        contains(point: Point) : boolean;
        move(offsetX:number, offsetY:number);
        click?: () => void;
        isJoinAble?: () => boolean;
        isDraggable?: () => boolean;
        detectInnerElement? : (point: Point) => Node;
    }
}


text:
  LOG_ASSERT((va_error) == VA_STATUS_SUCCESS) \
      << name << " failed, VA error: " << vaErrorStr(va_error);

#endif  // MEDIA_GPU_VAAPI_TEST_MACROS_H_


text:
from rdflib.URIRef import URIRef

class Namespace(URIRef):

    def __getitem__(self, key, default=None):
        return URIRef(self + key)


text:
package com.javadevjournal.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class StarterDemoApplicationTests {

	@Test
	public void contextLoads() {
	}

}


text:
package Paws::ElasticTranscoder::CreatePipelineResponse;
  use Moose;
  has Pipeline => (is => 'ro', isa => 'Paws::ElasticTranscoder::Pipeline');
  has Warnings => (is => 'ro', isa => 'ArrayRef[Paws::ElasticTranscoder::Warning]');

  has _request_id => (is => 'ro', isa => 'Str');
1;

### main pod documentation begin ###

=head1 NAME

Paws::ElasticTranscoder::CreatePipelineResponse

=head1 ATTRIBUTES

=head2 Pipeline => L<Paws::ElasticTranscoder::Pipeline>

A section of the response body that provides information about the
pipeline that is created.

=head2 Warnings => ArrayRef[L<Paws::ElasticTranscoder::Warning>]

Elastic Transcoder returns a warning if the resources used by your
pipeline are not in the same region as the pipeline.

Using resources in the same region, such as your Amazon S3 buckets,
Amazon SNS notification topics, and AWS KMS key, reduces processing
time and prevents cross-regional charges.

=head2 _request_id => Str

=cut


text:
public class Trapezoid {
	public static void main(String[] args) {
		System.out.println("Input the Height");
		int height = IO.readInt();
		for (int i = 0; i < height; i++) {
			//print each line for the trapezoid
			//when height is n, height of trapoid is also n
			//on line i(start from 0), there is height-1-i space, and 2i+1 stars
			//and spaces are to the left of the stars
			for (int j = 0; j < height - 1 - i; j++) {
				System.out.print(" ");
			}
			for (int j = 0; j < 2 * i + 1 ; j++) {
				System.out.print("*");
			}
			System.out.println();
		}
	}
}


text:
Capybara.javascript_driver = :webkit

Given /^I see the "(.*)" panel$/ do |panel_name|
  str = panel_name.downcase.split(" ").join("_")
  expect(page).to have_css("div##{str}")
end

Given /^the following users exist:$/ do |users|
  users.hashes.each do |user|
    User.create!(user)
  end
end

Given /^the following calendars have been linked:$/  do |calendar_list|
  calendar_list.hashes.each do |calendar|
      Sync.create!(calendar)
  end
end

Then /^I should see events from "(.*)"$/  do |calendar_name|
  events = Events.where(name: calendar_name, status: "upcoming")
  events.each do |event|
      expect(page).to have_content(event.name)
  end
end

Then /^I should see the event "(.*)".$/ do |event_name|
  expect(page).to have_content(event_name)
end

When /^I visit the "(.*)" page$/  do |page_name|
  visit path_to(page_name)
end

Then /^I should see "(.*)" in the "(.*)" panel$/ do |event, panel_name|
  with_scope(panel_name) { step %{I should see "#{event}"}}
end

Given /^I create a new( super | regular )admin "(.*)" with password "(.*)"$/ do |root, email, password|
  visit '/accounts/new'
  find_field("user_email").set email
  find_field("user_password").set password
  if root == ' super '
    find("user_level").check
  end
  click_button "Create Admin"
end

When /^I sign in as "(.*)" with password "(.*)"$/ do |email, password|
  visit '/users/sign_in'
  find_field("user_email").set email
  find_field("user_password").set password
  click_button "Log in"
end

When(/^I fill in "([^"]*)" field with "([^"]*)"$/) do |field, value|
  find_field(field).set value
end


text:
#include "webrtc/modules/audio_processing/aec3/aec_state.h"

#include "webrtc/modules/audio_processing/logging/apm_data_dumper.h"
#include "webrtc/test/gtest.h"

namespace webrtc {

// Verify the general functionality of AecState
TEST(AecState, NormalUsage) {
  ApmDataDumper data_dumper(42);
  AecState state;
  RenderBuffer render_buffer(Aec3Optimization::kNone, 3, 30,
                             std::vector<size_t>(1, 30));
  std::array<float, kFftLengthBy2Plus1> E2_main = {};
  std::array<float, kFftLengthBy2Plus1> Y2 = {};
  std::vector<std::vector<float>> x(3, std::vector<float>(kBlockSize, 0.f));
  EchoPathVariability echo_path_variability(false, false);

  std::vector<std::array<float, kFftLengthBy2Plus1>>
      converged_filter_frequency_response(10);
  for (auto& v : converged_filter_frequency_response) {
    v.fill(0.01f);
  }
  std::vector<std::array<float, kFftLengthBy2Plus1>>
      diverged_filter_frequency_response = converged_filter_frequency_response;
  converged_filter_frequency_response[2].fill(100.f);
  converged_filter_frequency_response[2][0] = 1.f;

  // Verify that linear AEC usability is false when the filter is diverged and
  // there is no external delay reported.
  state.Update(diverged_filter_frequency_response, rtc::Optional<size_t>(),
               render_buffer, E2_main, Y2, x[0], false);
  EXPECT_FALSE(state.UsableLinearEstimate());

  // Verify that linear AEC usability is true when the filter is converged
  std::fill(x[0].begin(), x[0].end(), 101.f);
  for (int k = 0; k < 3000; ++k) {
    state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2),
                 render_buffer, E2_main, Y2, x[0], false);
  }
  EXPECT_TRUE(state.UsableLinearEstimate());

  // Verify that linear AEC usability becomes false after an echo path change is
  // reported
  state.HandleEchoPathChange(EchoPathVariability(true, false));
  state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2),
               render_buffer, E2_main, Y2, x[0], false);
  EXPECT_FALSE(state.UsableLinearEstimate());

  // Verify that the active render detection works as intended.
  std::fill(x[0].begin(), x[0].end(), 101.f);
  state.HandleEchoPathChange(EchoPathVariability(true, true));
  state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2),
               render_buffer, E2_main, Y2, x[0], false);
  EXPECT_FALSE(state.ActiveRender());

  for (int k = 0; k < 1000; ++k) {
    state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2),
                 render_buffer, E2_main, Y2, x[0], false);
  }
  EXPECT_TRUE(state.ActiveRender());

  // Verify that echo leakage is properly reported.
  state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2),
               render_buffer, E2_main, Y2, x[0], false);
  EXPECT_FALSE(state.EchoLeakageDetected());

  state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2),
               render_buffer, E2_main, Y2, x[0], true);
  EXPECT_TRUE(state.EchoLeakageDetected());

  // Verify that the ERL is properly estimated
  for (auto& x_k : x) {
    x_k = std::vector<float>(kBlockSize, 0.f);
  }

  x[0][0] = 5000.f;
  for (size_t k = 0; k < render_buffer.Buffer().size(); ++k) {
    render_buffer.Insert(x);
  }

  Y2.fill(10.f * 10000.f * 10000.f);
  for (size_t k = 0; k < 1000; ++k) {
    state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2),
                 render_buffer, E2_main, Y2, x[0], false);
  }

  ASSERT_TRUE(state.UsableLinearEstimate());
  const std::array<float, kFftLengthBy2Plus1>& erl = state.Erl();
  EXPECT_EQ(erl[0], erl[1]);
  for (size_t k = 1; k < erl.size() - 1; ++k) {
    EXPECT_NEAR(k % 2 == 0 ? 10.f : 1000.f, erl[k], 0.1);
  }
  EXPECT_EQ(erl[erl.size() - 2], erl[erl.size() - 1]);

  // Verify that the ERLE is properly estimated
  E2_main.fill(1.f * 10000.f * 10000.f);
  Y2.fill(10.f * E2_main[0]);
  for (size_t k = 0; k < 1000; ++k) {
    state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2),
                 render_buffer, E2_main, Y2, x[0], false);
  }
  ASSERT_TRUE(state.UsableLinearEstimate());
  {
    const auto& erle = state.Erle();
    EXPECT_EQ(erle[0], erle[1]);
    for (size_t k = 1; k < erle.size() - 1; ++k) {
      EXPECT_NEAR(k % 2 == 0 ? 8.f : 1.f, erle[k], 0.1);
    }
    EXPECT_EQ(erle[erle.size() - 2], erle[erle.size() - 1]);
  }

  E2_main.fill(1.f * 10000.f * 10000.f);
  Y2.fill(5.f * E2_main[0]);
  for (size_t k = 0; k < 1000; ++k) {
    state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2),
                 render_buffer, E2_main, Y2, x[0], false);
  }

  ASSERT_TRUE(state.UsableLinearEstimate());
  {
    const auto& erle = state.Erle();
    EXPECT_EQ(erle[0], erle[1]);
    for (size_t k = 1; k < erle.size() - 1; ++k) {
      EXPECT_NEAR(k % 2 == 0 ? 5.f : 1.f, erle[k], 0.1);
    }
    EXPECT_EQ(erle[erle.size() - 2], erle[erle.size() - 1]);
  }
}

// Verifies the a non-significant delay is correctly identified.
TEST(AecState, NonSignificantDelay) {
  AecState state;
  RenderBuffer render_buffer(Aec3Optimization::kNone, 3, 30,
                             std::vector<size_t>(1, 30));
  std::array<float, kFftLengthBy2Plus1> E2_main;
  std::array<float, kFftLengthBy2Plus1> Y2;
  std::array<float, kBlockSize> x;
  EchoPathVariability echo_path_variability(false, false);
  x.fill(0.f);

  std::vector<std::array<float, kFftLengthBy2Plus1>> frequency_response(30);
  for (auto& v : frequency_response) {
    v.fill(0.01f);
  }

  // Verify that a non-significant filter delay is identified correctly.
  state.HandleEchoPathChange(echo_path_variability);
  state.Update(frequency_response, rtc::Optional<size_t>(), render_buffer,
               E2_main, Y2, x, false);
  EXPECT_FALSE(state.FilterDelay());
}

// Verifies the delay for a converged filter is correctly identified.
TEST(AecState, ConvergedFilterDelay) {
  constexpr int kFilterLength = 10;
  AecState state;
  RenderBuffer render_buffer(Aec3Optimization::kNone, 3, 30,
                             std::vector<size_t>(1, 30));
  std::array<float, kFftLengthBy2Plus1> E2_main;
  std::array<float, kFftLengthBy2Plus1> Y2;
  std::array<float, kBlockSize> x;
  EchoPathVariability echo_path_variability(false, false);
  x.fill(0.f);

  std::vector<std::array<float, kFftLengthBy2Plus1>> frequency_response(
      kFilterLength);

  // Verify that the filter delay for a converged filter is properly identified.
  for (int k = 0; k < kFilterLength; ++k) {
    for (auto& v : frequency_response) {
      v.fill(0.01f);
    }
    frequency_response[k].fill(100.f);
    frequency_response[k][0] = 0.f;
    state.HandleEchoPathChange(echo_path_variability);
    state.Update(frequency_response, rtc::Optional<size_t>(), render_buffer,
                 E2_main, Y2, x, false);
    EXPECT_TRUE(k == (kFilterLength - 1) || state.FilterDelay());
    if (k != (kFilterLength - 1)) {
      EXPECT_EQ(k, state.FilterDelay());
    }
  }
}

// Verify that the externally reported delay is properly reported and converted.
TEST(AecState, ExternalDelay) {
  AecState state;
  std::array<float, kFftLengthBy2Plus1> E2_main;
  std::array<float, kFftLengthBy2Plus1> E2_shadow;
  std::array<float, kFftLengthBy2Plus1> Y2;
  std::array<float, kBlockSize> x;
  E2_main.fill(0.f);
  E2_shadow.fill(0.f);
  Y2.fill(0.f);
  x.fill(0.f);
  RenderBuffer render_buffer(Aec3Optimization::kNone, 3, 30,
                             std::vector<size_t>(1, 30));
  std::vector<std::array<float, kFftLengthBy2Plus1>> frequency_response(30);
  for (auto& v : frequency_response) {
    v.fill(0.01f);
  }

  for (size_t k = 0; k < frequency_response.size() - 1; ++k) {
    state.HandleEchoPathChange(EchoPathVariability(false, false));
    state.Update(frequency_response, rtc::Optional<size_t>(k * kBlockSize + 5),
                 render_buffer, E2_main, Y2, x, false);
    EXPECT_TRUE(state.ExternalDelay());
    EXPECT_EQ(k, state.ExternalDelay());
  }

  // Verify that the externally reported delay is properly unset when it is no
  // longer present.
  state.HandleEchoPathChange(EchoPathVariability(false, false));
  state.Update(frequency_response, rtc::Optional<size_t>(), render_buffer,
               E2_main, Y2, x, false);
  EXPECT_FALSE(state.ExternalDelay());
}

}  // namespace webrtc


text:
Discussion at https://golang.org/issue/18802

## Abstract

As it stands, Go programs do not have a good way to avoid contention when
combining highly concurrent code with shared memory locations that frequently
require mutation. This proposal describes a new package and type to satisfy this
need.

## Background

There are several scenarios in which a Go program might want to have shared data
that is mutated frequently. We will briefly discuss some of these scenarios,
such that we can evaluate the proposed API against these concrete use-cases.

### Counters

In RPC servers or in scientific computing code, there is often a need for global
counters. For instance, in an RPC server, a global counter might count the
number of requests received by the server, or the number of bytes received by
the server. Go makes it easy to write RPC servers which are inherently
concurrent, often processing each connection and each request on a concurrent
goroutine. This means that in the context of a multicore machine, several
goroutines can be incrementing the same global counter in parallel. Using an API
like `atomic.AddInt64` will ensure that such a counter is lock-free, but
parallel goroutines will be contending for the same cache line, so this counter
will not experience linear scalability as the number of cores is increased.
(Indeed, one might even expect scalability to unexpectedly decrease due to
increased core-to-core communication).

It's probably also worth noting that there are other similar use-cases in this
space (e.g. types that record distributions rather than just sums, max-value
trackers, etc).

### Read-write locks

It is common in programs to have data that is read frequently, but written very
rarely. In these cases, a common synchronization primitive is `sync.RWMutex`,
which offers an `RLock`/`RUnlock` API for readers. When no writers are
interacting with an `RWMutex`, an arbitrary number of goroutines can use the
read-side of the `RWMutex` without blocking.

However, in order to correctly pair calls to `RLock` with calls to `RUnlock`,
`RWMutex` internally maintains a counter, which is incremented during `RLock`
and decremented during `RUnlock`. There is also other shared mutable state that
is atomically updated inside the `RWMutex` during these calls (and during
calls to `Lock` and `Unlock`). For reasons similar to the previous example, if
many goroutines are acquiring and releasing read-locks concurrently and the
program is running on a multicore machine, then it is likely that the
performance of `RWMutex.RLock`/`RWMutex.RUnlock` will not scale linearly with
the number of cores given to the program.

### RPC clients

In programs that make many RPC calls in parallel, there can be
contention on shared mutable state stored inside the RPC or HTTP clients. For
instance, an RPC client might support connecting to a pool of servers, and
implements a configurable load balancing policy to select a connection to use
for a given RPC; these load balancing policies often need to maintain state for
each connection in the pool of managed connections. For instance, an
implementation of the "Least-Loaded" policy needs to maintain a counter of
active requests per connection, such that a new request can select the
connection with the least number of active requests. In scenarios where a client
is performing a large number of requests in parallel (perhaps enqueueing many
RPCs before finally waiting on them at a later point in the program), then
contention on this internal state can start to affect the rate at which the
requests can be dispatched.

### Order-independent accumulators

In data-processing pipelines, code running in a particular stage may want to
'batch' its output, such that it only sends data downstream in N-element
batches, rather than sending single elements through the pipeline at a time. In
the single-goroutine case and where the element type is 'byte', then the
familiar type `bufio.Writer` implements this pattern. Indeed, one
option for the general data-processing pipeline, is to have a single goroutine
run every stage in the pipeline from end-to-end, and then instantiate a small
number of parallel pipeline instances. This strategy effectively handles
pipelines composed solely of stages dominated by CPU-time. However, if a
pipeline contains any IO (e.g. initially reading the input from a distributed
file system, making RPCs, or writing the result back to a distributed file
system), then this setup will not be efficient, as a single stall in IO will
take out a significant chunk of your throughput.

To mitigate this problem, IO bound stages need to run many goroutines. Indeed,
a clever framework (like Apache Beam) can detect these sorts of situations
dynamically, by measuring the rate of stage input compared to the rate of stage
output; they can even reactively increase or decrease the "concurrency level" of
a stage in response to these measurements. In Beam's case, it might do this by
dynamically changing the number of threads-per-binary, or number of
workers-per-stage.

When stages have varying concurrency levels, but are connected to each other in
a pipeline structure, it is important to place a concurrency-safe abstraction
between the stages to buffer elements waiting to be processed by the next stage.
Ideally, this structure would minimize the contention experienced by the caller.

## The Proposed API

To solve these problems, we propose an API with a single new type
`percpu.Sharded`. Here is an outline of the proposed API.

```go
// Package percpu provides low-level utilities for avoiding contention on
// multicore machines.
package percpu

// A Sharded is a container of homogenously typed values.
//
// On a best effort basis, the runtime will strongly associate a given value
// with a CPU core. That is to say, retrieving a value twice on the same CPU
// core will return the same value with high probablity. Note that the runtime
// cannot guarantee this fact, and clients must assume that retrieved values
// can be shared between concurrently executing goroutines.
//
// Once a value is placed in a Sharded, the Sharded will retain a reference to
// this value permanently. Clients can control the maximum number of distinct
// values created using the SetMaxShards API.
//
// A Sharded must not be copied after first use.
//
// All methods are safe to call from multiple goroutines.
type Sharded struct {
  // contains unexported fields
}

// SetMaxShards sets a limit on the maximum number of elements stored in the
// Sharded.
//
// It will not apply retroactively, any elements already created will remain
// inside the Sharded.
//
// If maxShards is less than 1, Sharded will panic.
func (s *Sharded) SetMaxShards(maxShards int)

// GetOrCreate retrieves a value roughly associated with the current CPU. If
// there is no such value, then createFn is called to create a value, store it
// in the Sharded, and return it.
//
// All calls to createFn are serialized; this means that one must complete
// before the next one is started.
//
// createFn should not return nil, or Sharded will panic.
//
// If createFn is called with a ShardInfo.ShardIndex equal to X, no future call
// to GetOrCreate will call createFn again with a ShardInfo.ShardIndex equal to
// X.
func (s *Sharded) GetOrCreate(createFn func(ShardInfo) interface{}) interface{}

// Get retrieves any preexisting value associated with the current CPU. If
// there is no such value, nil is returned.
func (s *Sharded) Get() interface{}

// Do iterates over a snapshot of all elements stored in the Sharded, and calls
// fn once for each element.
//
// If more elements are created during the iteration itself, they may be
// visible to the iteration, but this is not guaranteed. For stronger
// guarantees, see DoLocked.
func (s *Sharded) Do(fn func(interface{}))

// DoLocked iterates over all the elements stored in the Sharded, and calls fn
// once for each element.
//
// DoLocked will observe a consistent snapshot of the elements in the Sharded;
// any previous creations will complete before the iteration begins, and all
// subsequent creations will wait until the iteration ends.
func (s *Sharded) DoLocked(fn func(interface{}))

// ShardInfo contains information about a CPU core.
type ShardInfo struct {
  // ShardIndex is strictly less than any call to any prior call to SetMaxShards.
  ShardIndex int
}
```

## Evaluating the use-cases

Here, we evaluate the proposed API in light of the use-cases described above.

### Counters

A counter API can be fairly easily built on top of `percpu.Sharded`.
Specifically, it would offer two methods `IncrementBy(int64)`, and `Sum() int64`.
The former would only allow positive increments (if required, clients can build
negative increments by composing two counters of additions and subtractions).

The implementation of `IncrementBy`, would call `GetOrCreate`, passing a
function that returned an `*int64`. To avoid false sharing between cache lines,
it would probably return it as an interior pointer into a struct with
appropriate padding. Once the pointer is retrieved from `GetOrCreate`, the
function would then use `atomic.AddInt64` on that pointer with the value passed
to `IncrementBy`.

The implementation of `Sum` would call `Do` to retrieve a snapshot of all
previously created values, then sum up their values using `atomic.LoadInt64`.

If the application is managing many long-lived counters, then one possible
optimization would be to implement the `Counter` type in terms of a
`counterBatch` (which logically encapsulates `N` independent counters). This can
drastically limit the padding required to fix false sharing between cache lines.

### Read-write locks

It is a little tricky to implement a drop-in replacement for `sync.RWMutex` on
top of `percpu.Sharded`. Naively, one could imagine a sharded lock composed of
many internal `sync.RWMutex` instances. Calling `RLock()` on the aggregate lock
would grab a single `sync.RWMutex` instance using `GetOrCreate` and then call
`RLock()` on that instance. Unfortunately, because there is no state passed
between `RLock()` and `RUnlock()` (something we should probably consider fixing
for Go 2), we cannot implement `RUnlock()` efficiently, as the `percpu.Sharded`
might have migrated to a different shard and therefore we've lost the
association to the original `RLock()`.

That said, since such a sharded lock would be considerably more memory-hungry
than a normal `sync.RWMutex`, callers should only replace truly contended
mutexes with a sharded lock, so requiring them to make minor API changes should
not be too onerous (particularly for mutexes, which should always be private
implementation details, and therefore not cross API boundaries). In particular,
one could have `RLock()` on the sharded lock return a `RLockHandle` type, which
has a `RUnlock()` method. This `RLockHandle` could keep an internal pointer to
the `sync.RWMutex` that was initially chosen, and it can then `RUnlock()` that
specific instance.

It's worth noting that it's also possible to drastically change the standard
library's `sync.RWMutex` implementation itself to be scalable by default using
`percpu.Sharded`; this is why the implementation sketch below is careful not not
use the `sync` package to avoid circular dependencies. See Facebook's
[SharedMutex](https://github.com/facebook/folly/blob/a440441d2c6ba08b91ce3a320a61cf0f120fe7f3/folly/SharedMutex.h#L148)
class to get a sense of how this could be done. However, that requires
significant research and deserves a proposal of its own.

### RPC clients

It's straightforward to use `percpu.Sharded` to implement a sharded RPC client.

This is a case where its likely that the default implementation will continue to
be unsharded, and a program will need to explicitly say something like
`grpc.Dial("some-server", grpc.ShardedClient(4))` (where the "4" might come from
an application flag). This kind of client-contrallable sharding is one place
where the `SetMaxShards` API can be useful.

### Order-independent accumulators

This can be implemented using `percpu.Sharded`. For instance, a writer would
call `GetOrCreate` to retrieve a shard-local buffer, they would acquire a lock,
and insert the element into the buffer. If the buffer became full, they would
flush it downstream.

A watchdog goroutine could walk the buffers periodically using `AppendAll`, and
flush partially-full buffers to ensure that elements are flushed fairly
promptly. If it finds no elements to flush, it could start incrementing a
counter of "useless" scans, and stop scanning after it reaches a threshold. If a
writer is enqueuing the first element in a buffer, and it sees the counter over
the threshold, it could reset the counter, and wake the watchdog.

## Sketch of Implementation

What follows is a rough sketch of an implementation of `percpu.Sharded`. This is
to show that this is implementable, and to give some context to the discussion
of performance below.

First, a sketch of an implementation for `percpu.sharder`, an internal helper
type for `percpu.Sharded`.

```go
const (
  defaultUserDefinedMaxShards = 32
)

type sharder struct {
  maxShards int32
}

func (s *sharder) SetMaxShards(maxShards int) {
  if maxShards < 1 {
    panic("maxShards < 1")
  }
  atomic.StoreInt32(&s.maxShards, roundDownToPowerOf2(int32(maxShards)))
}

func (s *sharder) userDefinedMaxShards() int32 {
  s := atomic.LoadInt32(&s.maxShards)
  if s == 0 {
    return defaultUserDefinedMaxShards
  }
  return s
}

func (s *sharder) shardInfo() ShardInfo {
  shardId := runtime_getShardIndex()

  // If we're in race mode, then all bets are off. Half the time, randomize the
  // shardId completely, the rest of the time, use shardId 0.
  //
  // If we're in a test but not in race mode, then we want an implementation
  // that keeps cache contention to a minimum so benchmarks work properly, but
  // we still want to flush out any assumption of a stable mapping to shardId.
  // So half the time, we double the id. This catches fewer problems than what
  // we get in race mode, but it should still catch one class of issue (clients
  // assuming that two sequential calls to Get() will return the same value).
  if raceEnabled {
    rnd := runtime_fastRand()
    if rnd%2 == 0 {
      shardId = 0
    } else {
      shardId += rnd / 2
    }
  } else if testing {
    if runtime_fastRand()%2 == 0 {
      shardId *= 2
    }
  }

  shardId &= runtimeDefinedMaxShards()-1
  shardId &= userDefinedMaxShards()-1

  return ShardInfo{ShardIndex: shardId}
}

func runtimeDefinedMaxShards() int32 {
  max := runtime_getMaxShards()
  if (testing || raceEnabled) && max < 4 {
    max = 4
  }
  return max
}

// Implemented in the runtime, should effectively be
// roundUpToPowerOf2(min(GOMAXPROCS, NumCPU)).
// (maybe caching that periodically in the P).
func runtime_getMaxShards() int32 {
  return 4
}

// Implemented in the runtime, should effectively be the result of the getcpu
// syscall, or similar. The returned index should densified if possible (i.e.
// if binary is locked to cores 2 and 4), they should return 0 and 1
// respectively, not 2 and 4.
//
// Densification can be best-effort, and done with a process-wide mapping table
// maintained by sysmon periodically.
//
// Does not have to be bounded by runtime_getMaxShards(), or indeed by
// anything.
func runtime_getShardIndex() int32 {
  return 0
}

// Implemented in the runtime. Only technically needs an implementation for
// raceEnabled and tests. Should be scalable (e.g. using a per-P seed and
// state).
func runtime_fastRand() int32 {
  return 0
}
```

Next, a sketch of `percpu.Sharded` itself.

```go
type Sharded struct {
  sharder

  lock uintptr
  data atomic.Value // *shardedData
  typ  unsafe.Pointer
}

func (s *Sharded) loadData() *shardedData {
  return s.data.Load().(*shardedData)
}

func (s *Sharded) getFastPath(createFn func(ShardInfo) interface{}) (out interface{}) {
  shardInfo := s.shardInfo()

  curData := s.loadData()
  if curData == nil || shardInfo.ShardIndex >= len(curData.elems) {
    if createFn == nil {
      return nil
    }
    return s.getSlowPath(shardInfo, createFn)
  }

  existing := curData.load(shardInfo.ShardIndex)
  if existing == nil {
    if createFn == nil {
      return nil
    }
    return s.getSlowPath(shardInfo, createFn)
  }

  outp := (*ifaceWords)(unsafe.Pointer(&out))
  outp.typ = s.typ
  outp.data = existing
  return
}

func (s *Sharded) getSlowPath(shardInfo ShardInfo, createFn func(ShardInfo) interface{}) (out interface{}) {
  runtime_lock(&s.lock)
  defer runtime_unlock(&s.lock)

  curData := s.loadData()
  if curData == nil || shardInfo.ShardIndex >= len(curData.elems) {
    curData = allocShardedData(curData, shardInfo)
    s.data.Store(curData)
  }

  existing := curData.load(shardInfo.ShardIndex)
  if existing != nil {
    outp := (*ifaceWords)(unsafe.Pointer(&out))
    outp.typ = s.typ
    outp.data = existing
    return
  }

  newElem := createFn(shardInfo)
  if newElem == nil {
    panic("createFn returned nil value")
  }

  newElemP := *(*ifaceWords)(unsafe.Pointer(&newElem))

  // If this is the first call to createFn, then stash the type-pointer for
  // later verification.
  //
  // Otherwise, verify its the same as the previous.
  if s.typ == nil {
    s.typ = newElemP.typ
  } else if s.typ != newElemP.typ {
    panic("percpu: GetOrCreate was called with function that returned inconsistently typed value")
  }

  // Store back the new value.
  curData.store(shardInfo.ShardIndex, newElemP.val)

  // Return it.
  outp := (*ifaceWords)(unsafe.Pointer(&out))
  outp.typ = s.typ
  outp.data = newElemP.val
}

func (s *Sharded) loadData() *shardedData {
  return s.data.Load().(*shardedData)
}

func (s *Sharded) GetOrCreate(createFn func(ShardInfo) interface{}) interface{} {
  if createFn == nil {
    panic("createFn nil")
  }
  return s.getFastPath(createFn)
}

func (s *Sharded) Get() interface{} {
  return s.getFastPath(nil)
}

func (s *Sharded) Do(fn func(interface{})) {
  curData := s.loadData()
  if curData == nil {
    return nil
  }

  for i := range curData.elems {
    elem := curData.load(i)
    if elem == nil {
      continue
    }

    var next interface{}
    nextP := (*ifaceWords)(unsafe.Pointer(&next))
    nextP.typ = s.typ
    nextP.val = elem

    fn(next)
  }

  return elems
}

func (s *Sharded) DoLocked(fn func(interface{})) {
  runtime_lock(&s.lock)
  defer runtime_unlock(&s.lock)
  s.Do(fn)
}

type shardedData struct {
  elems []unsafe.Pointer
}
```

## Performance

### `percpu.sharder`

As presented, calling `shardInfo` on a `percpu.sharder` makes two calls to the
runtime, and does a single atomic load.

However, both of the calls to the runtime would be satisfied with stale values.
So, an obvious avenue of optimization is to squeeze these two pieces of
information (effectively "current shard", and "max shards") into a single word,
and cache it on the `P` when first calling the `shardInfo` API. To accommodate
changes in the underlying values, a `P` can store a timestamp when it last
computed these values, and clear the cache when the value is older than `X` and
the `P` is in the process of switching goroutines.

This means that effectively, `shardInfo` will consist of 2 atomic loads, and a
little bit of math on the resulting values.

### `percpu.Sharded`

In the get-for-current-shard path, `percpu.Sharded` will call `shardInfo`, and
then perform 2 atomic loads (to retrieve the list of elements and to retrieve
the specific element for the current shard, respectively). If either of these
loads fails, it might fall back to a much-slower slow path. In the fast path,
there's no allocation.

In the get-all path, `percpu.Sharded` will perform a single atomic followed by a
`O(n)` atomic loads, proportional to the number of elements stored in the
`percpu.Sharded`. It will not allocate.

# Discussion

## Garbage collection of stale values in `percpu.Sharded`

With the given API, if `GOMAXPROCS` is temporarily increased (or the CPUs
assigned to the given program), and then decreased to its original value, a
`percpu.Sharded` might have allocated additional elements to satisfy the
additional CPUs. These additional elements would not be eligible for garbage
collection, as the `percpu.Sharded` would retain an internal reference.

First, its worth noting that we cannot unilaterally shrink the number of
elements stored in a `percpu.Sharded`, because this might affect program
correctness. For instance, this could result in counters losing values, or in
breaking the invariants of sharded locks.

The presented solution just sidesteps this problem by defaulting to a fairly low
value of `MaxShards`. This can be overridden by the user with explicit action
(though the runtime has the freedom to bound the number more strictly than the
user's value, e.g. to limit the size of internal data-structures to reasonable
levels.).

One thing to keep in mind, clients who require garbage collection of stale
values can build this on top of `percpu.Sharded`. For instance, one could
imagine a design where clients would maintain a counter recording each use. A
watchdog goroutine can then scan the elements and if a particular value has not
been used for some period of time, swap in a `nil` pointer, and then gracefully
tear down the value (potentially transferring the logical data encapsulated to
other elements in the `percpu.Sharded`).

Requiring clients to implement their own GC in this way seems kinda gross, but
on the other hand, its unclear to me how to generically solve this problem
without knowledge of the client use-case. One could imagine some sort of
reference-counting design, but again, without knowing the semantics of the
use-case, its hard to know if its safe to clear the reference to the type.

Also, for a performance-oriented type, like `percpu.Sharded`, it seems
unfortunate to add unnecessary synchronization to the fast path of the type (and
I don't see how to implement something in this direction without adding
synchronization).

## Why is `ShardInfo` a struct and not just an int?

This is mostly to retain the ability to extend the API in a compatible manner.
One concrete avenue is to add additional details to allow clients to optimize
their code for the NUMA architecture of the machine. For instance, for a sharded
buffering scheme (i.e. the "Order-independent accumulator" above), it might make
sense to have multiple levels of buffering in play, with another level at the
NUMA-node layer.

## Is `ShardInfo.ShardIndex` returning an id for the CPU, or the `P` executing the goroutine?

This is left unspecified, but the name of the package seems to imply the former.
In practice, I think we want a combination.

That is to say, we would prefer that a program running on a 2-core machine with
`GOMAXPROCS` set to 100 should use 2 shards, not 100. On the other hand, we
would also prefer that a program running on a 100-core machine with `GOMAXPROCS`
set to 2 should also use 2 shards, not 100.

This ideal state should be achievable on systems that provide reasonable APIs to
retrieve the id of the current CPU.

That said, any implementation effort would likely start with a simple portable
implementation which uses the id of the local `P`. This will allow us to get a
sense of the performance of the type, and to serve as a fallback implementation
for platforms where the necessary APIs are either not available, or require
privileged execution.

## Is it a good idea for `percpu.Sharded` to behave differently during tests?

This is a good question; I am not certain of the answer here. I am confident
that during race mode, we should definitely randomize the behaviour of
`percpu.Sharded` significantly (and the implementation sketch above does that).
However, for tests, the answer seems less clear to me.

As presented, the implementation sketch above randomizes the value by flipping
randomly between two values for every CPU. That seems like it will catch bugs
where the client assumes that sequential calls to `Get`/`GetOrCreate` will return
the same values. That amount of randomness seems warranted to me, though I'd
understand if folks would prefer to avoid it in favor of keeping non-test code
and test code behaving identically.

On a more mundane note: I'm not entirely sure if this is implementable with
zero-cost. One fairly efficient strategy would be an internal package that
exposes an "IsTesting bool", which is set by the `testing` package and read by
the `percpu` package. But ideally, this could be optimized away at compile time;
I don't believe we have any mechanism to do this now.

## Should we expose `ShardInfo.ShardIndex` at all?

I think so. Even if we don't, clients can retrieve an effectively equivalent
value by just incrementing an atomic integer inside the `createFn` passed to
`GetOrCreate`. For pre-allocated use-cases (e.g. see the Facebook `SharedMutex`
linked above), it seems important to let clients index into pre-allocated
memory.

## Should we expose both of Get and GetOrCreate?

We could define `GetOrCreate` to behave like `Get` if the passed `createFn` is
nil. This is less API (and might be more efficient, until mid-stack inlining
works), but seems less semantically clean to me. It seems better to just have
clients say what they want explicitly.

## Should we expose both of Do and DoLocked?

If we had to choose one of those, then I would say we should expose `Do`. This
is because it is the higher performance, minimal-synchronization version, and
`DoLocked` can be implemented on top. That said, I do think we should just
provide both. The implementation is simple, and implementing it on top feels
odd.

Of the 4 use-cases presented above, 2 would probably use `Do` (counters and
order-independent accumulators), and 2 would probably use `DoLocked` (read-write
locks, and RPC clients (for the latter, probably just for implementing
`Close()`)).

## Naming

I'm not particularly wedded to any of the names in the API sketch above, so I'm
happy to see it changed to whatever people prefer.

# Backwards compatibility

The API presented above is straightforward to implement without any runtime
support; in particular, this could be implemented as a thin wrapper around a
`sync.Once`. This will not effectively reduce contention, but it would still be
a correct implementation. It's probably a good idea to implement such a shim,
and put it in the `x/sync` repo, with appropriate build tags and type-aliases to
allow clients to immediately start using the new type.


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

<title>E-Index</title>
<meta name="date" content="2015-05-13">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A C E F H I L M N P R S T

E

equals(Object) - Method in class net.datastructures.SinglyLinkedList

A C E F H I L M N P R S T

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
/* jshint node: true */
'use strict';

module.exports = {
  name: 'markdown-buttons'
};


text:
package org.apache.tamaya.spisupport;

import org.apache.tamaya.spi.ConfigurationContext;
import org.apache.tamaya.spi.FilterContext;
import org.apache.tamaya.spi.PropertyFilter;
import org.apache.tamaya.spi.PropertyValue;

import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Implementation of the Configuration API. This class uses the current {@link ConfigurationContext} to evaluate the
 * chain of {@link org.apache.tamaya.spi.PropertySource} and {@link PropertyFilter}
 * instances to evaluate the current Configuration.
 */
public final class PropertyFiltering{
    /**
     * The logger.
     */
    private static final Logger LOG = Logger.getLogger(PropertyFiltering.class.getName());
    /**
     * The maximal number of filter cycles performed before aborting.
     */
    private static final int MAX_FILTER_LOOPS = 10;

    /**
     * Private singleton constructor.
     */
    private PropertyFiltering(){}

    /**
     * Filters a single createValue.
     * @param value the raw createValue, not {@code null}.
     * @param context the context
     * @return the filtered createValue, including {@code null}.
     */
    public static PropertyValue applyFilter(PropertyValue value, ConfigurationContext context) {
        FilterContext filterContext = new FilterContext(value, context);
        return filterValue(value, filterContext);
    }

    /**
     * Filters a single createValue.
     * @param values the full values, not {@code null}.
     * @param context the context
     * @return the filtered createValue, including {@code null}.
     */
    public static List<PropertyValue> applyFilters(List<PropertyValue> values, ConfigurationContext context) {
        List<PropertyValue> result = new ArrayList<>();
        FilterContext filterContext = new FilterContext(values, context);
        for (PropertyValue val : values) {
            PropertyValue filtered = filterValue(val, filterContext);
            if(filtered!=null) {
                result.add(filtered);
            }
        }
        return result;
    }

    /**
     * Filters all properties.
     * @param rawProperties the unfiltered properties, not {@code null}.
     * @param context the context
     * @return the filtered createValue, including {@code null}.
     */
    public static Map<String, PropertyValue> applyFilters(Map<String, PropertyValue> rawProperties, ConfigurationContext context) {
        Map<String, PropertyValue> result = new HashMap<>();
        // Apply filters to values, prevent values filtered to null!
        for (Map.Entry<String, PropertyValue> entry : rawProperties.entrySet()) {
            FilterContext filterContext = new FilterContext(entry.getValue(), rawProperties, context);
            PropertyValue filtered = filterValue(filterContext.getProperty(), filterContext);
            if(filtered!=null){
                result.put(filtered.getKey(), filtered);
            }
        }
        return result;
    }

    /**
     * Basic filter logic.
     * @param context the filter context, not {@code null}.
     * @return the filtered createValue.
     */
    private static PropertyValue filterValue(PropertyValue inputValue, FilterContext context) {
        PropertyValue filteredValue = inputValue;

        for (int i = 0; i < MAX_FILTER_LOOPS; i++) {
            int changes = 0;
            for (PropertyFilter filter : context.getConfigurationContext().getPropertyFilters()) {
                String value = filteredValue!=null?filteredValue.getValue():null;
                filteredValue = filter.filterProperty(filteredValue, context);
                String newValue = filteredValue!=null?filteredValue.getValue():null;

                if (!Objects.equals(value, newValue)) {
                    changes++;
                    LOG.finest("Filter - " + filteredValue + " by " + filter);
                }
                if (filteredValue == null) {
                    LOG.finest("Filter removed entry - " + inputValue + ": " + filter);
                    break;
                }
            }
            if (changes == 0) {
                LOG.finest("Finishing filter loop, no changes detected.");
                break;
            } else if (filteredValue == null) {
                break;
            } else {
                if (i == (MAX_FILTER_LOOPS - 1)) {
                    if (LOG.isLoggable(Level.WARNING)) {
                        LOG.warning("Maximal filter loop count reached, aborting filter evaluation after cycles: " + i);
                    }
                } else {
                    LOG.finest("Repeating filter loop, changes detected: " + changes);
                }
            }
        }
        return filteredValue;
    }

}


text:
using namespace std;

int coverDistance(int d){
  int count[d+1];
  count[0]=1; //Base case where to get to 0, it's only 1 option
  count[1]=1; //Base case where to get to step 1, you can only take the 1 step option
  count[2]=2; //Base case where to get to step 2, you can either take 2 1's or 1 2's.
  for(int i=3;i<=d;i++){
    //If you want to reach i, you can reach i from either i-1, i-2, and i-3 steps. Therefore you add all possibilities
    count[i]=count[i-1]+count[i-2]+count[i-3];  //Becuase you can only take 1, 2 or 3 steps.
  }
  return count[d];
}

int main(){
    int dist = 4;
    cout << coverDistance(dist)<<endl;
    return 0;
}


text:
<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );

Permissions::require_authorized ( Permissions::USER_ADMIN );
?>
<!DOCTYPE html>

<?php
$this->load->view ( 'include/head_common.php' );
?>

<title>CompSoc :: Edit User</title>

<?php
$this->load->view ( 'include/navbar.php' );
?>

    <?php
				$this->load->view ( 'include/notification_message.php' );
				?>

    <?php
				$validation_errors = validation_errors ();
				if ($validation_errors !== '' || isset ( $errormessage )) :
					?>

                <?php
					echo $validation_errors;
					echo (isset ( $errormessage ) ? $errormessage : '');
					?>

    <?php endif; ?>

    <?php if(isset($message)): ?>

                <?php
					echo (isset ( $message ) ? $message : '');
					?>

    <?php endif; ?>

    <?php
				$this->load->view ( 'include/flashdata_message.php' );
				?>

CompSoc @ University of Leicester

Edit User Details

            <?php echo form_open('user/edit'); ?>

            <input id="userid" name="userid" type="hidden" value="<?php echo set_value('userid', $userid);?>" /> Email: <input id="email" name="email" type="text" class="form-control"
					placeholder="Email" value="<?php echo set_value('email', $email); ?>" />
 Full
					Name: <input id="fullname" name="fullname" type="text" class="form-control" placeholder="Full Name"
					value="<?php echo set_value('fullname', $fullname); ?>" />

 Github
					ID: <input id="githubID" name="githubID" type="text" class="form-control" placeholder="Github ID"
					value="<?php echo set_value('githubID', $githubID); ?>" />
 Linkedin
					URL: <input id="linkedinURL" name="linkedinURL" type="text" class="form-control" placeholder="Linkedin URL"
					value="<?php echo set_value('linkedinURL', $linkedinURL); ?>" />
 Steam ID:
				<input id="steamID" name="steamID" type="text" class="form-control" placeholder="Steam ID"
					value="<?php echo set_value('steamID' , $steamID); ?>" />
 Twitter
					Handle: <input id="twitterID" name="twitterID" type="text" class="form-control"
					placeholder="Twitter Handle" value="<?php echo set_value("twitterID", $twitterID); ?>">

Permissions:

				Confirmed: <input id="p_confirmed" name="p_confirmed" type="checkbox" value="1"
					<?php echo ($permissions['confirmed'] == 1 ? 'checked':''); ?> />
 User Admin: <input
					id="p_user" name="p_user" type="checkbox" value="1" <?php echo ($permissions['user'] == 1 ? 'checked':''); ?> />

				Points Admin: <input id="p_points" name="p_points" type="checkbox" value="1"
					<?php echo ($permissions['points'] == 1 ? 'checked':''); ?> />
 Portfolio Admin:
				<input id="p_portfolio" name="p_portfolio" type="checkbox" value="1"
					<?php echo ($permissions['portfolio'] == 1 ? 'checked':''); ?> />
 Batch User Admin:
				<input id="p_batch" name="p_batch" type="checkbox" value="1"
					<?php echo ($permissions['batch'] == 1 ? 'checked':''); ?> />
 <input type="submit" value="Update" name="submit"
					id="submit" class="btn btn-primary">

        <?php echo form_close(); ?>

    <?php
				$this->load->view ( 'include/footer.php' );
				$this->load->view ( 'include/bootstrapjs.php' );
				?>


text:
import {Component, ElementRef, Inject, Input, OnInit} from '@angular/core';
import {DOCUMENT} from '@angular/platform-browser';
import {ActivatedRoute, NavigationEnd, Router} from '@angular/router';
import {Subject, fromEvent} from 'rxjs';
import {debounceTime, takeUntil} from 'rxjs/operators';

interface Link {
  /* id of the section*/
  id: string;

  /* header type h3/h4 */
  type: string;

  /* If the anchor is in view of the page */
  active: boolean;

  /* name of the anchor */
  name: string;

  /* top offset px of the anchor */
  top: number;
}

@Component({
  selector: 'table-of-contents',
  styleUrls: ['./table-of-contents.scss'],
  templateUrl: './table-of-contents.html'
})
export class TableOfContents implements OnInit {

  @Input() links: Link[] = [];
  @Input() container: string;
  @Input() headerSelectors = '.docs-markdown-h3,.docs-markdown-h4';

  _rootUrl = this._router.url.split('#')[0];
  private _scrollContainer: any;
  private _destroyed = new Subject();
  private _urlFragment = '';

  constructor(private _router: Router,
              private _route: ActivatedRoute,
              private _element: ElementRef,
              @Inject(DOCUMENT) private _document: Document) {

    this._router.events.pipe(takeUntil(this._destroyed)).subscribe((event) => {
      if (event instanceof NavigationEnd) {
        const rootUrl = _router.url.split('#')[0];
        if (rootUrl !== this._rootUrl) {
          this.links = this.createLinks();
          this._rootUrl = rootUrl;
        }
      }
    });

    this._route.fragment.pipe(takeUntil(this._destroyed)).subscribe(fragment => {
      this._urlFragment = fragment;

      const target = document.getElementById(this._urlFragment);
      if (target) {
        target.scrollIntoView();
      }
    });
  }

  ngOnInit(): void {
    // On init, the sidenav content element doesn't yet exist, so it's not possible
    // to subscribe to its scroll event until next tick (when it does exist).
    Promise.resolve().then(() => {
      this._scrollContainer = this.container ?
        this._document.querySelectorAll(this.container)[0] : window;

      if (this._scrollContainer) {
        fromEvent(this._scrollContainer, 'scroll').pipe(
            takeUntil(this._destroyed),
            debounceTime(10))
            .subscribe(() => this.onScroll());
      }
    });
  }

  ngAfterViewInit() {
    this.updateScrollPosition();
  }

  ngOnDestroy(): void {
    this._destroyed.next();
  }

  updateScrollPosition(): void {
    this.links = this.createLinks();

    const target = document.getElementById(this._urlFragment);
    if (target) {
      target.scrollIntoView();
    }
  }

  /** Gets the scroll offset of the scroll container */
  private getScrollOffset(): number {
    const {top} = this._element.nativeElement.getBoundingClientRect();
    if (typeof this._scrollContainer.scrollTop !== 'undefined') {
      return this._scrollContainer.scrollTop + top;
    } else if (typeof this._scrollContainer.pageYOffset !== 'undefined') {
      return this._scrollContainer.pageYOffset + top;
    }
  }

  private createLinks(): Link[] {
    const links = [];
    const headers =
        Array.from(this._document.querySelectorAll(this.headerSelectors)) as HTMLElement[];

    if (headers.length) {
      for (const header of headers) {
        // remove the 'link' icon name from the inner text
        const name = header.innerText.trim().replace(/^link/, '');
        const {top} = header.getBoundingClientRect();
        links.push({
          name,
          type: header.tagName.toLowerCase(),
          top: top,
          id: header.id,
          active: false
        });
      }
    }

    return links;
  }

  private onScroll(): void {
    for (let i = 0; i < this.links.length; i++) {
      this.links[i].active = this.isLinkActive(this.links[i], this.links[i + 1]);
    }
  }

  private isLinkActive(currentLink: any, nextLink: any): boolean {
    // A link is considered active if the page is scrolled passed the anchor without also
    // being scrolled passed the next link
    const scrollOffset = this.getScrollOffset();
    return scrollOffset >= currentLink.top && !(nextLink && nextLink.top < scrollOffset);
  }

}


text:
from flask import Flask, request, jsonify
app = Flask(__name__)

import sys, os, datetime
from config import config

"""
from sqlalchemy import create_engine
engine = create_engine('mysql+pymysql://jcsesznegi:swejaK3r!@localhost/japan_culture_quiz', convert_unicode=True)

from models import testvar, users

from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey, Text, DateTime
metadata = MetaData()
users = Table('users', metadata,
    Column('id', Integer, primary_key=True),
    Column('name', String(255)),
    Column('email', String(255)),
    Column('user_agent', Text),
    Column('insert_date', DateTime),
)
metadata.create_all(engine)
conn = engine.connect()

from sqlalchemy.sql import select

s = select( [users] )
result = conn.execute(s)
for row in result:
    print(row)

"""

from database import db_session, init_db
from models import User

@app.teardown_appcontext
def shutdown_session(exception=None):
    db_session.remove()

init_db()

"""
f = '%Y-%m-%d %H:%M:%S'
now = datetime.datetime.now()

u = User('test2', 'test2@localhost', '', now.strftime(f))
db_session.add(u)
db_session.commit()

User.query.all()
print(User.query.filter(User.name == 'test2').first())

sys.exit()

print( _config.get('route_index_users') )
sys.exit()
"""

@app.route( config.get('route_user_index'), methods=['POST'] )
def user_index():
    user_string = ""
    user_list = User.query.all()
    for u in user_list:
        if not user_string:
            user_string = u.name
        else:
            user_string = user_string + ", " + u.name
    return user_string

@app.route( config.get('route_user_add'), methods=['POST'] )
def user_add():
    f = '%Y-%m-%d %H:%M:%S'
    now = datetime.datetime.now()
    name = request.values['name']
    email = request.values['email']
    user_agent = request.headers.get('User-Agent')
    insert_date = now.strftime(f)
    u = User(name, email, user_agent, insert_date)
    db_session.add(u)
    db_session.commit()
    return 'Added user!?'

@app.route( config.get('route_user_delete'), methods=['POST'] )
def user_delete():
    id = int(request.values['id'])
    u = User.query.get(id)
    db_session.delete(u)
    db_session.commit()
    return jsonify(msg='Deleted user!?')

@app.route( config.get('route_user_update'), methods=['POST'] )
def user_update():
    id = int(request.values['id'])
    u = User.query.get(id)
    u.name = request.values['name']
    u.email = request.values['email']
    u.user_agent = request.headers.get('User-Agent')
    db_session.commit()
    return 'Updated user!?'

if __name__ == '__main__':
    app.run(debug=True)

"""
# Turn on debug mode.
import cgitb
cgitb.enable()

# Print necessary headers.
print("Content-Type: text/html")
print()

print ("Hello, world!")

"""


text:
Backwards compatible cucumber promise support.

_All these features are implemented in the core `cucumber` starting with
version `0.5.0`. If you are using it you don't need `cucumber-promise` anymore_

## Usage

Just wrap your implementation steps function into `cpromise`, and
use promises, or implement steps without explicitly calling the
callback function.

```javascript
var cpromise = require("cucumber-promise").cpromise;

module.exports = cpromise(function() {
    // the old way works
    this.Given(/^I run a test with cucumber\-promise$/, function(callback) {
        callback();
    });

    // code without callbacks works
    this.Then(/^I run code without callbacks$/, function() {
        // if no callback it's present, this also works
    });

    // and promises also work
    this.Then(/^I run a promise call$/, function() {
        return new Promise(function(fulfill, reject) {
            // promise resolving
            fulfill();
        });
    });
});
```

## Install

In order to install this just run:

```sh
npm install --save-dev cucumber-promise
```


text:
(function() {

    /**
     * Fills _resourcesInfo hashmap with the reources info and the following structure:
     * {
     *       "{resource-id}": {
     *           path:"yourpath/../sdfsdf",
     *           params: ['param1', 'param2'],
     *           queryParams: ['queryParam1']
     *       },
     *       ...
     *   }
     * Also fill the _existentParametersList array with each resource parameter name.
     * @param onReady
     */
    var loadApiResourcesInfo = function loadApiResourcesInfo(requestJSON, onReady, onError) {

        var _resourcesInfo = {};
        var _existentParametersList = [];

        requestJSON("/api/", null, function(data) {

            //var paths = data['swaggerjson']['paths'];
            var paths = [{
                path :"/metrics",
                variable: "id"
            },{
                path :"/tbdata",
                variable: "id"
            }];

            var apiPaths = data['swaggerjson']['paths'];

            //Count number of elements in paths
            var pathsLength = 0;
            for(var i in paths) pathsLength++;

            //Function to check if it has finished and call the callback
            var pathsProcessed = 0;
            var pathProcessed = function() {
                if(++pathsProcessed === pathsLength && 'function' === typeof onReady) {
                    onReady({
                        _resourcesInfo: _resourcesInfo,
                        _existentParametersList: _existentParametersList
                    });
                }
            };

            //Initialize the _resourcesInfo object
            _resourcesInfo = {};

            //var isMetricList = /\/data\/$/;
            //var isMetricListWithoutParams = /^((?!\{).)*\/data\/$/;
            //var isSpecificMetric = /\/\{mid\}$/;

            //TODO: Get this information from SDH-API Swagger.json file
            var statInfo = [
                // API static Information description
                { "id" : "userinfo", "path" : "/users/{uid}", params: {'uid': {name: 'uid',in: 'path',required: true}}, "description" : "User Information" },
                { "id" : "repoinfo", "path" : "/repositories/{rid}", params: {'rid': {name: 'rid',in: 'path',required: true}}, "description" : "Repository Information" },
                { "id" : "productinfo", "path" : "/products/{prid}", params: {'prid': {name: 'prid',in: 'path',required: true}}, "description" : "Product Information" },
                { "id" : "projectinfo", "path" : "/projects/{pjid}", params: {'pjid': {name: 'pjid',in: 'path',required: true}}, "description" : "Project Information" },
                { "id" : "orginfo", "path" : "/", "description" : "Organization Information" },
                { "id" : "userlist", "path" : "/users/", "description" : "Users List" },
                { "id" : "productlist", "path" : "/products/", "description" : "Products List" },
                { "id" : "projectlist", "path" : "/projects/", "description" : "Projects List" },
                { "id" : "repolist", "path" : "/repositories/", "description" : "Repository List" },
                { "id" : "metriclist", "path" : "/metrics/", "description" : "Metrics list" },
                { "id" : "tbdlist", "path" : "/tbd/", "description" : "Time-based data list" }
            ];

            for(var i = statInfo.length - 1; i >= 0; --i ) {
                var info = statInfo[i];
                _resourcesInfo[info['id']] = {
                    path: info['path'],
                    requiredParams: (info.params != null ? info.params :  {}), //list of url param names
                    optionalParams: {} //list of query params
                };
            }
            //TODO: END TODO ----------------------------

            //Iterate over the path of the api
            for(var x = paths.length - 1; x >= 0; --x ) {

                var path = paths[x]['path'];

                // Make an api request to retrieve all the data
                requestJSON(path, null, function(p, data) {

                    //Iterate over the resources
                    for(var j = 0, len = data.length; j < len; ++j) {

                        var resourceInfo = data[j];
                        var resourceId = resourceInfo['id'];
                        var resourcePath = resourceInfo['path'];

                        // Fill the _resourcesInfo array
                        _resourcesInfo[resourceId] = {
                            path: resourcePath,
                            requiredParams: {}, //list of url param names
                            optionalParams: {} //list of query params
                        };

                        //Get the general resource path info (like /data/{mid})
                        var generalResourcePath = resourcePath.substring(0, resourcePath.lastIndexOf('/')) + '/{'+paths[p]['variable']+'}';
                        var generalResourcePathInfo = apiPaths[generalResourcePath];

                        if(generalResourcePathInfo == null) {
                            console.error("General resource path ("+generalResourcePathInfo+") does not exist in API path list.");
                            continue;
                        }

                        //Add the url params and query params to the list
                        if(generalResourcePathInfo['get']['parameters'] != null) {
                            var parameters = generalResourcePathInfo['get']['parameters'];

                            //Add all parameters and avoid 'mid'
                            for(var i = 0, len_i = parameters.length; i < len_i; i++) {

                                var paramName = parameters[i]['name'];

                                //Add the parameter in params or queryParams
                                if(paramName === paths[p]['variable']) {
                                    //Ignore it
                                } else if (parameters[i]['required'] == true || resourceInfo['params'].indexOf(paramName) !== -1) {
                                    _resourcesInfo[resourceId]['requiredParams'][paramName] = {
                                        name: paramName,
                                        in: parameters[i]['in'],
                                        required: true
                                    };
                                } else if(resourceInfo['optional'].indexOf(paramName) !== -1) {
                                    _resourcesInfo[resourceId]['optionalParams'][paramName] = {
                                        name: paramName,
                                        in: parameters[i]['in'],
                                        required: false
                                    };
                                }

                                //Add it to the list of possible parameters (cache)
                                if(_existentParametersList.indexOf(parameters[i]['name']) === -1) {
                                    _existentParametersList.push(parameters[i]['name']);
                                }
                            }
                        }
                    }

                    pathProcessed(); //Finished processing this path
                }.bind(null, x), 2, onError);

            }

        }, 3, onError);
    };

    // AMD compliant
    if ( typeof define === "function" && define.amd) {
        define( [], function () {
            return loadApiResourcesInfo;
        } );
    } else {
        console.error("require.js is needed");
    }

})();


text:
r"""This is the GRR client for Fleetspeak enabled installations.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

import pdb
import sys

from absl import app
from absl import flags

# pylint: disable=unused-import
from grr_response_client import client_plugins
# pylint: enable=unused-import

from grr_response_client import client_startup
from grr_response_client import fleetspeak_client
from grr_response_client import installer
from grr_response_core import config
from grr_response_core.config import contexts

flags.DEFINE_bool("install", False, "Specify this to install the client.")

flags.DEFINE_bool(
    "break_on_start", False,
    "If True break into a pdb shell immediately on startup. This"
    " can be used for debugging the client manually.")

def main(unused_args):
  config.CONFIG.AddContext(contexts.CLIENT_CONTEXT,
                           "Context applied when we run the client process.")

  client_startup.ClientInit()

  if flags.FLAGS.install:
    installer.RunInstaller()
    sys.exit(0)

  if not config.CONFIG["Client.fleetspeak_enabled"]:
    raise ValueError(
        "This is a Fleetspeak client, yet 'Client.fleetspeak_enabled' is "
        "'False'.")

  if flags.FLAGS.break_on_start:
    pdb.set_trace()
  else:
    fleetspeak_client.GRRFleetspeakClient().Run()

if __name__ == "__main__":
  app.run(main)


text:
package cromwell.engine.workflow.lifecycle

import cats.data.Validated.{Invalid, Valid}
import common.assertion.CromwellTimeoutSpec
import cromwell.core.WorkflowOptions
import cromwell.core.callcaching.CallCachingMode
import cromwell.engine.workflow.lifecycle.materialization.MaterializeWorkflowDescriptorActor
import org.scalatest.Assertion
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import org.scalatest.prop.TableDrivenPropertyChecks

import scala.util.{Success, Try}

class ValidatingCallCachingModeSpec extends AnyFlatSpec with CromwellTimeoutSpec with Matchers with TableDrivenPropertyChecks {

  def makeOptions(writeOpt: Option[Boolean], readOpt: Option[Boolean]) = {
    val writeValue = writeOpt map { v => s""""write_to_cache": $v""" }
    val readValue = readOpt map { v => s""""read_from_cache": $v""" }
    val workflowOptions = Seq(writeValue, readValue).flatten.mkString(",\n")

    WorkflowOptions.fromJsonString(s"{$workflowOptions}")
  }

  val options = Seq(None, Some(true), Some(false))
  val callCachingEnabled = true
  val invalidBadCaсheResults = true

  val allCombinations = (for {
    writeOption <- options
    readOption <- options
  } yield (makeOptions(writeOption, readOption))).toSet

  // writeCache is ON when config is ON and write_to_cache is None or true
  val writeCacheOnCombinations = (for {
    writeOption <- options if writeOption.isEmpty || writeOption.get
    readOption <- options
  } yield (makeOptions(writeOption, readOption))).toSet

  // readCache is ON when config is ON and read_from_cache is None or true
  val readCacheOnCombinations = (for {
    writeOption <- options
    readOption <- options if readOption.isEmpty || readOption.get
  } yield (makeOptions(writeOption, readOption))).toSet

  val writeCacheOffCombinations = allCombinations -- writeCacheOnCombinations
  val readCacheOffCombinations = allCombinations -- readCacheOnCombinations

  validateCallCachingMode(
    "write cache on options",
    writeCacheOnCombinations,
    callCachingEnabled,
    invalidBadCaсheResults) { _.writeToCache should be(true) }
  validateCallCachingMode(
    "read cache on options",
    readCacheOnCombinations,
    callCachingEnabled,
    invalidBadCaсheResults) { _.readFromCache should be(true) }
  validateCallCachingMode(
    "write cache off options",
    writeCacheOffCombinations,
    callCachingEnabled,
    invalidBadCaсheResults) { _.writeToCache should be(false) }
  validateCallCachingMode(
    "read cache off options",
    readCacheOffCombinations,
    callCachingEnabled,
    invalidBadCaсheResults) { _.readFromCache should be(false) }

  private def validateCallCachingMode(testName: String,
                                      wfOptions: Set[Try[WorkflowOptions]],
                                      callCachingEnabled: Boolean,
                                      invalidBadCacheResults: Boolean)
                                      (verificationFunction: CallCachingMode => Assertion): Unit = {
    it should s"correctly identify $testName" in {
      wfOptions foreach  {
        case Success(wfOptions) =>
          MaterializeWorkflowDescriptorActor.validateCallCachingMode(wfOptions,
            callCachingEnabled, invalidBadCacheResults) match {
            case Valid(activity) => verificationFunction(activity)
            case Invalid(errors) =>
              val errorsList = errors.toList.mkString(", ")
              fail(s"Failure generating Call Config Mode: $errorsList")
          }
        case x => fail(s"Unexpected test tuple: $x")
      }
    }
  }
}


text:
var toArray = function(v) {
	return Array.prototype.slice.call(v);
};

var isArray = Array.isArray;

function isUndefined(v) {
	return typeof v == 'undefined';
}

function isDefined(v) {
	return !isUndefined(v);
}

function inherits(ctor, ctorSrc, attrs) {
	ctor.prototype = Object.create(ctorSrc.prototype);

	if(isObject(attrs)) {
		extend(ctor.prototype, attrs);
	}
}

function forEach (array, iterator, context) {
	var length;

	if(isArray(array)) {
		for(i = 0, length = array.length; i < length; i++) {
			iterator.call(context, array[i], i, array);
		}
	} else if (isObject(array)) {
		var keys = Object.keys(array);
		var ii = keys.length, i, key, value;

		for(i = 0; i < ii; i++) {
			key = keys[i];
			value = array[key];

			iterator.call(context, value, key, array);
		}
	}
	return array;
}

function extend (target) {
	if(!target) target = {};

	var sources = toArray(arguments).slice(1).filter(isDefined);

	var source,
			value,
			keys,
			key,
			ii = sources.length,
			jj,
			i,
			j;

	for(i = 0; i < ii; i++) {
		if((source = sources[i]) && isObject(source)) {
			keys = Object.keys(source);
			jj = keys.length;

			for(j = 0; j < jj; j++) {
				key 					= keys[j];
				value 				= source[key];

				target[key] 	= value;
			}
		}
	}

	return target;
}

function isObject (value) {
	return value !== null && (typeof value === 'object');
}

function noop () {
	return undefined;
}

function constant (value) {
	return function() {
		return value;
	};
}


text:
<?php
/**
 * Created by PhpStorm.
 * Title    : Control_ListManager
 * Content  : define class to get board list
 * User     : 2-WDJ 1401213 Seungmin Lee
 * Date     : 2017-09-18 10:23
 */

    // 1. create Manager Object
    include_once '../model/Model_SelectDAO.php';
    include_once './Control_SessionManager.php';
    $objDAO = new SelectDAO();
    $sesMag = new SessionManager();

    // 2. define class BoardManager
    class ListManager {
        // 01) set variable
        private $pageNum, $searchType, $searchContent;

        // 02) define construct
        function __construct($argPageNum, $argSearchType, $argSearchContent) {
            $this->pageNum = $argPageNum;

            if(!is_null($argSearchType) && !is_null($argSearchContent)) {
                $this->searchType = $argSearchType;
                $this->searchContent = $argSearchContent;
            }
        }

        // 03) get list of page
        function getPageList() {
            // 1) set variable
            global $objDAO, $sesMag;

            // 2) get board data
            $result['boardList'] = $objDAO->selectBoardList($this->pageNum,
                $this->searchType, $this->searchContent);

            // 3) get pagination data
            $result['maxList'] = $objDAO->selectMaxPage();

            // 4) check login
            $result['login'] = $sesMag->checkLogin();

            return json_encode($result, true);
        }
    }

    // 3. set variable
    $pNum       = $_POST['page_number'];
    $sType      = isset($_POST['search_type']) ? $_POST['search_type'] : null;
    $sContent   = isset($_POST['search_content']) ? $_POST['search_content'] : null;

    // 4. check received data and act function
    $listManager = new ListManager($pNum, $sType, $sContent);
    echo $listManager -> getPageList();
?>