text:
"""
Akara transform middleware (XSLT and more)

XSLT:

xslt_transform_manager manages a pool of Amara XSLT processor instances
to dispatch requests rapidly.

Note on extensions:

If you wish to use any XPath or XSLT extensions put the extension modules
into a directory and indicate that directory in your server config such
that it's made available as environ['http://purl.org/xml3k/akara/transform/extensions'].
An example:

-- % --
... = '/usr/share/amara/extensions'
-- % --

For more on Amara XSLT extensions See <http://4suite.org/docs/CoreManual.xml> <- FIXME: update
"""

# Used for locking the cache of XSLT processors
import thread
# Used to check whether or not an XSLT stylesheet has been modified
from stat import ST_MTIME
from os import stat

import amara
from amara.lib import iri
from amara.lib import inputsource
from amara.xpath.util import parameterize
from amara.xslt.processor import processor
from amara import sax

USER_AGENT_REGEXEN = [
'.*MSIE 5.5.*',
'.*MSIE 6.0.*',
'.*MSIE 7.0.*',
'.*Gecko/2005.*',
'.*Gecko/2006.*',
'.*Opera/9.*',
'.*AppleWebKit/31.*',
'.*AppleWebKit/4.*',
]

USER_AGENT_REGEXEN = [ re.compile(regex) for regex in USER_AGENT_REGEXEN ]
WSGI_NS = u'http://www.wsgi.org/'

MTYPE_PAT = re.compile('.*/.*xml.*')

#We use processor pooling, but we eventually want to get it to the point where we can just
#cache compiled stylesheets

#FIXME: does not yet handle extensions

DUMMY_SOURCE_DOC_URI = "http://purl.org/xml3k/akara/transform/source-doc"

class processor_info:
    def __init__(self, lock, last_modified, instance):
        #Even if you're using multiple processes rather than threads use locking, just to be safe
        self.lock = lock
        self.last_modified = last_modified
        self.instance = {}

class processor_pool:
    """
    A hash table (LRU trimmed) that caches from XSLT transform tuples to prepared
    processor instances
    """
    def __init__(self):
        #Even if you're using multiple processes rather than threads use locking, just to be safe
        self._main_lock = thread.allocate_lock()
        self._granular_locks = {}
        self._processors = {}

    def get_processor(self, transform_hash, ext_functions=None, ext_elements=None):
        try:
            # First make sure we avoid race conditions...
            self._main_lock.acquire()
            if transform_hash not in self._granular_locks:
                self._granular_locks[transform_hash] = thread.allocate_lock()
        finally:
            self._main_lock.release()

        proc = None
        try:
            self._granular_locks[transform_hash].acquire()
            # If we do not have that stylesheet yet in the pool, let's add it
            if not self._processors.has_key(transform_hash):
                processor = Processor()
                self._processors[transform_hash] = processor_info(
                    thread.allocate_lock(), stat(transform_hash)[ST_MTIME], processor
                )
                for (ns, local), func in ext_functions.items():
                    processor.registerExtensionFunction(ns, local, func)
                for (ns, local), elem in ext_elements.items():
                    processor.registerExtensionElement(ns, local, elem)

                self._processors[transform_hash].instance.append_transform(iri.os_path_to_uri(transform_hash))
            # If the stylesheet has been modified, reload it
            elif stat(transform_hash)[ST_MTIME] != self._processors[transform_hash].last_modified:
                self._processors[transform_hash].instance.reset()
                self._processors[transform_hash].last_modified = stat(transform_hash)[ST_MTIME]
                self._processors[transform_hash].instance.append_transform(iri.os_path_to_uri(transform_hash))

            # now we can lock the processor...
            self._processors[transform_hash]['lock'].acquire()
            proc = self._processors[transform_hash].instance
        finally:
            self._granular_locks[transform_hash].release()
        # ... and return it
        return proc

    def release_processor(self, transform_hash):
        try:
            if self._processors[transform_hash]['lock'].locked():
               self._processors[transform_hash]['lock'].release()
        except: pass

class find_xslt_pis(sax.ContentHandler):
    def __init__(self, parser):
        parser.setContentHandler(self)
        self.parser = parser
        return

    def startDocument(self):
        self.ecount = 0
        self.xslt_pi = None

    def startElementNS(self, name, qname, attribs):
        self.ecount += 1
        if self.ecount == 2:
            #We're now within the doc proper, so we're done
            self.parser.setProperty(sax.PROPERTY_YIELD_RESULT, self.xslt_pi)
        return

    def processingInstruction(self, target, data):
        if target == u'xml-stylesheet':
            data = data.split()
            pseudo_attrs = {}
            for d in data:
                seg = d.split('=')
                if len(seg) == 2:
                    pseudo_attrs[seg[0]] = seg[1][1:-1]

            # PI must have both href, type pseudo-attributes;
            # type pseudo-attr must match valid XSLT types;
            # media pseudo-attr must match preferred media
            # (which can be None)
            if (pseudo_attrs.has_key('href')
                and pseudo_attrs.has_key('type')
                and pseudo_attrs['type'] in Processor.XSLT_IMT):
                    self.xslt_pi = pseudo_attrs['href']
                    self.parser.setProperty(sax.PROPERTY_YIELD_RESULT, self.xslt_pi)
        return

ACTIVE_FLAG = 'http://purl.org/xml3k/akara/transform/active'
SERVER_SIDE_FLAG = 'http://purl.org/xml3k/akara/transform/force-server-side'
CACHEABLE_FLAG = 'http://purl.org/xml3k/akara/transform/cacheable'

class xslt_transform_manager(object):
    """
    Middleware for XSLT transform processing.

    Also optionally checks for XSLT transform capability in the client and
    performs the transform on the server side if one is required, and the
    client can't do it
    """
    def __init__(self, app, use_wsgi_env=True, stock_xslt_params=None,
                 ext_modules=None):
        """
        use_wsgi_env - Optional bool determining whether to make the
            WSGI environment available to the XSLT as top level parameter
            overrides (e.g. wsgi:SCRIPT_NAME and wsgi:wsgi.url_scheme).
            Only passes on values it can handle (UTF-8 strings, Unicode,
            numbers, boolean, lists of "nodes").  Default to True
        stock_xslt_params - optional dict of dicts to also pass along as XSLT
            params.  The outer dict is onf the form: {<namespace>: <inner-dict>}
            And the inner dicts are of the form {pname: pvalue}.  The keys
            (pname) may be given as unicode objects if they have no namespace,
            or as (uri, localname) tuples if they do.  The values are
            (UTF-8 strings, Unicode, numbers, boolean, lists of "nodes").
            This is usually used for passing configuration info into XSLT
        ext_modules - Optional list of modules with XPath and XSLT extensions
        """
        #Set-up phase
        self.wrapped_app = app
        self.use_wsgi_env = use_wsgi_env
        self.stock_xslt_params = stock_xslt_params or {}
        self.ext_modules = ext_modules or []
        self.processor_cache = {}
        self.path_cache = {}
        return

    def __call__(self, environ, start_response):
        #Guess whether the client supports XML+XSLT?
        #See: http://copia.ogbuji.net/blog/2006-08-26/LazyWeb_Ho
        client_ua = environ.get('HTTP_USER_AGENT', '')
        path = environ['PATH_INFO']
        send_browser_xslt = True in [ ua_pat.match(client_ua) is not None
                                for ua_pat in USER_AGENT_REGEXEN ]

        #We'll hack a bit for dealing with Python's imperfect nested scopes.
        response_params = []
        def start_response_wrapper(status, response_headers, exc_info=None):
            #Assume response does not use XSLT; do not activate middleware
            environ[ACTIVE_FLAG] = False
            #Check for response content type to see whether it is XML
            for name, value in response_headers:
                #content-type value is a media type, defined as
                #media-type = type "/" subtype *( ";" parameter )
                media_type = value.split(';')[0]
                if ( name.lower() == 'content-type'
                     and MTYPE_PAT.match(media_type)):
                     #.endswith('/xml')
                     #      or media_type.find('/xml+') != -1 )):
                    environ[ACTIVE_FLAG] = True
            response_params.extend([status, response_headers, exc_info])
            #Replace any write() callable with a dummy that gives an error
            #The idea is to refuse support for apps that use write()
            def dummy_write(data):
                raise RuntimeError('applyxslt does not support the deprecated write() callable in WSGI apps')
            return dummy_write

        #Get the iterator from the application that will yield response
        #body fragments
        iterable = self.wrapped_app(environ, start_response_wrapper)
        (status, response_headers, exc_info) = response_params
        force_server_side = environ.get(SERVER_SIDE_FLAG, False)
        send_browser_xslt = send_browser_xslt and not force_server_side
        #import pprint; pprint.pprint(environ)

        #This function processes each chunk of output (simple string) from
        #the app, returning The modified chunk to be passed on to the server
        def next_response_block(response_iter):
            if send_browser_xslt or not environ[ACTIVE_FLAG]:
                #The client can handle XSLT, or it's not an XML source doc,
                #so nothing for this middleware to do
                start_response(status, response_headers, exc_info)
                for block in response_iter.next():
                    yield block
            elif path in self.path_cache:
                print >> sys.stderr, 'Using cached result for path', path
                imt, content = self.path_cache[path]
                response_headers.append(('content-type', imt))
                start_response(status, response_headers, exc_info)
                yield content
            else:
                yield produce_final_output(''.join(response_iter))
            return

        #After the app has finished sending its response body fragments
        #if transform is required, it's necessary to send one more chunk,
        #with the fully transformed result
        def produce_final_output(response, response_headers=response_headers):
            log = sys.stderr
            if not send_browser_xslt and environ[ACTIVE_FLAG]:
                use_pi = False
                if force_server_side and force_server_side != True:
                    #True is a special flag meaning "don't delegate to the browser but still check for XSLT PIs"
                    xslt = force_server_side
                else:
                    #Check for a Stylesheet PI
                    parser = sax.reader()
                    parser.setFeature(sax.FEATURE_GENERATOR, True)
                    handler = find_xslt_pis(parser)
                    pi_iter = parser.parse(inputsource(response))
                    try:
                        #Note: only grabs the first PI.  Consider whether we should handle multiple
                        xslt = pi_iter.next()
                    except StopIteration:
                        xslt = None
                    use_pi = True
                if xslt:
                    xslt = xslt.encode('utf-8')
                    result = StringIO()
                    #self.xslt_sources = environ.get(
                    #    'wsgixml.applyxslt.xslt_sources', {})
                    source = InputSource.DefaultFactory.fromString(
                        response, uri=get_request_url(environ))
                    params = {}
                    for ns in self.stock_xslt_params:
                        params.update(setup_xslt_params(ns, self.stock_xslt_params[ns]))
                    start = time.time()

                    '''
                        processor = self.processorPool.get_processor(
                            stylesheet, self.ext_functions, self.ext_elements)
                        cherrypy.response.body = processor.run(
                            DefaultFactory.fromString(picket.document,
                                                      picket.uri),
                            topLevelParams=picket.parameters)
                        if self.default_content_type:
                            cherrypy.response.headers['Content-Type'] = self.default_content_type
                        if picket.content_type:
                            cherrypy.response.headers['Content-Type'] = picket.content_type
                    finally:
                        self.processorPool.release_processor(stylesheet)
                        '''

                    if xslt in self.processor_cache:
                        processor = self.processor_cache[xslt]
                        #Any transform would have already been loaded
                        use_pi = False
                        print >> log, 'Using cached processor instance for transform', xslt
                    else:
                        print >> log, 'Creating new processor instance for transform', xslt
                        processor = Processor.Processor()
                        if self.ext_modules:
                            processor.registerExtensionModules(self.ext_modules)
                        if self.use_wsgi_env:
                            params.update(setup_xslt_params(WSGI_NS, environ))
                        #srcAsUri = OsPathToUri()
                        #if False:
                        if environ.has_key('paste.recursive.include'):
                            #paste's recursive facilities are available, to
                            #so we can get the XSLT with a middleware call
                            #rather than a full Web invocation
                            #print environ['paste.recursive.include']
                            xslt_resp = environ['paste.recursive.include'](xslt)
                            #FIXME: this should be relative to the XSLT, not XML
                            #print xslt_resp, xslt_resp.body
                            isrc = InputSource.DefaultFactory.fromString(
                                xslt_resp.body, get_request_url(environ))
                            processor.appendStylesheet(isrc)
                        else:
                            #We have to make a full Web call to get the XSLT.
                            #4Suite will do that for us in processing the PI
                            if not use_pi:
                                uri = Uri.Absolutize(xslt, get_request_url(environ))
                                isrc = InputSource.DefaultFactory.fromUri(uri)
                                processor.appendStylesheet(isrc)
                        self.processor_cache[xslt] = processor
                    processor.run(source, outputStream=result,
                                  ignorePis=not use_pi, topLevelParams=params)

                    #Strip content-length if present (needs to be
                    #recalculated by server)
                    #Also strip content-type, which will be replaced below
                    response_headers = [ (name, value)
                        for name, value in response_headers
                            if ( name.lower()
                                 not in ['content-length', 'content-type'])
                    ]
                    #Put in the updated content type
                    imt = processor.outputParams.mediaType
                    content = result.getvalue()
                    if environ.get(CACHEABLE_FLAG):
                        self.path_cache[path] = imt, content
                    response_headers.append(('content-type', imt))
                    start_response(status, response_headers, exc_info)
                    end = time.time()
                    print >> log, '%s: elapsed time: %0.3f\n'%(xslt, end-start)
                    #environ['wsgi.errors'].write('%s: elapsed time: %0.3f\n'%(xslt, end-start))
                    return content

            #If it reaches this point, no XSLT was applied.
            return

        return iterwrapper(iterable, next_response_block)

class PicketFilter(BaseFilter):
    """
    A filter that applies XSLT templates to XML content
    For any published method with this filter attached, return an
    instance of the Picket class if you want an XSLT transform invoked.
    The string output of the transform becomes the Web response body
    """
    def __init__(self, default_stylesheet=None, default_content_type=None, extension_dir=None):
        self.processorPool = ProcessorPool()
        self.default_stylesheet = default_stylesheet
        self.default_content_type = default_content_type
        self.extensionDir = extension_dir #cherrypy.config.get("picket.extensionDir")
        self.ext_functions, self.ext_elements = _getExtensions(self.extensionDir)

    def before_finalize(self):
        picket = cherrypy.response.body

        if not isinstance(picket, Picket): return

        stylesheet = self.default_stylesheet

        if picket.stylesheet:
            stylesheet = picket.stylesheet

        if stylesheet is None:
            # If a stylesheet was not set, then raise an error
            raise ValueError, "Missing XSLT stylesheet"

        extDir = cherrypy.config.get("picket.extensionDir")
        if extDir != self.extensionDir:
            self.extensionDir =extDir
            self.ext_functions, self.ext_elements = _getExtensions(self.extensionDir)

        try:
            processor = self.processorPool.get_processor(
                stylesheet, self.ext_functions, self.ext_elements)
            cherrypy.response.body = processor.run(
                DefaultFactory.fromString(picket.document,
                                          picket.uri),
                topLevelParams=picket.parameters)
            if self.default_content_type:
                cherrypy.response.headers['Content-Type'] = self.default_content_type
            if picket.content_type:
                cherrypy.response.headers['Content-Type'] = picket.content_type
        finally:
            self.processorPool.release_processor(stylesheet)

def _getExtensions(extensionDirectory):
    import glob
    import os

    retval = ({}, {})
    try:
        os.path.isdir(extensionDirectory)
    except TypeError:
        return retval

    for extensionPath in glob.glob(extensionDirectory + "/*.py"):
        try:
            ns = {}
            execfile(extensionPath, ns, ns)
            retval[0].update(ns.get("ExtFunctions", {}))
            retval[1].update(ns.get("ExtElements", {}))
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            pass

    return retval

import os

from wsgixml.applyxslt import xsltize
import pkg_resources

from cStringIO import StringIO

from Ft.Lib import Uri, UriException
from Ft.Xml import InputSource, CreateInputSource
from Ft.Xml.InputSource import InputSourceFactory
from Ft.Xml.Xslt.Processor import Processor
from Ft.Xml.Xslt.StylesheetReader import StylesheetReader
from Ft.Xml import Domlette, Parse

from pprint import pprint

class LocalTemplateResolver(Uri.FtUriResolver):

    def normalize(self, uri_ref, base_uri):
        return Uri.Absolutize(uri_ref, base_uri)

    def _orig_resolve(self, uri, baseUri=None):
        """
        This function takes a URI or a URI reference plus a base URI, produces
        a normalized URI using the normalize function if a base URI was given,
        then attempts to obtain access to an entity representing the resource
        identified by the resulting URI, returning the entity as a stream (a
        Python file-like object).

        Raises a UriException if the URI scheme is unsupported or if a stream
        could not be obtained for any reason.
        """
        if baseUri is not None:
            uri = self.normalize(uri, baseUri)
            scheme = Uri.GetScheme(uri)
        else:
            scheme = Uri.GetScheme(uri)
            # since we didn't use normalize(), we need to verify here
            if scheme not in Uri.DEFAULT_URI_SCHEMES:
                if scheme is None:
                    raise ValueError('When the URI to resolve is a relative '
                        'reference, it must be accompanied by a base URI.')
                else:
                    raise UriException(UriException.UNSUPPORTED_SCHEME,
                                       scheme=scheme,
                                       resolver=self.__class__.__name__)

        # Bypass urllib for opening local files. This means we don't get all
        # the extra metadata that urllib adds to the stream (Last-modified,
        # Content-Length, a poorly guessed Content-Type, and the URI), but
        # we also avoid its potentially time-consuming socket.gethostbyname()
        # calls, which aren't even warranted and are part of urllib's dubious
        # interpretation of RFC 1738.
        if scheme == 'file':
            path = Uri.UriToOsPath(uri, attemptAbsolute=False)
            try:
                stream = file(path, 'rb')
            except IOError, e:
                raise UriException(UriException.RESOURCE_ERROR,
                                   loc='%s (%s)' % (uri, path),
                                   uri=uri, msg=str(e))
        else:
            # urllib2.urlopen, wrapped by us, will suffice for http, ftp,
            # data and gopher
            try:
                stream = Uri.UrlOpen(uri)
            except IOError, e:
                raise UriException(UriException.RESOURCE_ERROR,
                                   uri=uri, loc=uri, msg=str(e))
        return stream

    def resolve(self, uri, base_uri=None):
        here = os.path.abspath('.')
        if uri.startswith('local:'):
            uri = uri[6:]
            resource = os.path.join(self.templates, uri)
            if os.path.exists(resource):
                return file(resource, 'rb')
            raise UriException(UriException.RESOURCE_ERROR,
                               uri=uri, loc=uri,
                               msg="The file did not exist in '%s'" % self.templates)
        elif uri.startswith('pkg:'):
            # format: package#path/to/file.xslt
            usage = 'usage: package_name#path/to/file'
            uri = uri[4:]
            package, sep, path = uri.partition('#')
            if not package or path:
                raise UriException(
                    UriException.RESOURCE_ERROR,
                    uri=uri, loc=uri,
                    msg="Invalid pkg_resources uri. \n %s" % usage
                )
            if pkg_resources.resource_exists(package, path):
                return pkg_resources.resource_stream(package, path)
            raise UriException(
                UriException.RESOURCE_ERROR,
                uri=uri, loc=uri,
                msg="'%s' was not found in the python package '%s'" % (path, package)
            )
        else:
            return self._orig_resolve(uri, base_uri)

XParams = 'xsltemplate.params'
XTemplate = 'xsltemplate.template'
XSource = 'xsltemplate.source'

class TemplateMiddleware(object):

    def __init__(self, app_conf, app, **kw):

        self.ns = unicode(app_conf.get('xsltemplate_namespace',
                                       'http://ionrock.org/ns/xsltemplate'))
        if app_conf.get('use_index_xml'):
            self.content = app_conf['use_index_xml']
        self.template_key = XTemplate
        self.params_key = XParams
        self.source_key = XSource
        self.tdir = app_conf.get('template_directory', 'templates')
        self.resolver = LocalTemplateResolver()
        self.resolver.templates = self.tdir
        self.xslt_factory = InputSourceFactory(resolver=self.resolver)
        self.rs = '%s.xslt'
        self.app = app
        if kw.get('extensions'):
            self.extensions = kw['extensions']
        else:
            self.extensions = None

    def start_response(self, status, headers, exc_info=None):
        self.status = status
        self.headers = headers
        self.exc_info = exc_info

    def __call__(self, environ, start_response):
        source = ''.join(self.app(environ, self.start_response))
        if not source and self.content:
            source = self.content
        if environ.get(self.template_key):
            xslt = environ[self.template_key]
            params = environ.get(self.params_key, {})
            source = self.do_render(source, xslt, params)
        for i, value in enumerate(self.headers):
            k, v = value
            if k.lower() == 'content-length':
                del self.headers[i]
        start_response(self.status, self.headers, self.exc_info)
        return [source]

    def get_processor(self):
        proc = Processor()
        if self.extensions:
            for ext in self.extensions:
                proc.registerExtensionFunction(*(ext))
        return proc

    def get(self, fn):
        if fn.startswith('pkg://'):
            package, sep, path = fn[6:].partition('#')
            if pkg_resources.resource_exists(package, path):
                return self.xslt_factory.fromString(pkg_resources.resource_string(package, path))
        path = Uri.OsPathToUri(os.path.join(self.tdir, fn))
        try:
            xslt = self.xslt_factory.fromUri(path)
        except UriException, e:
            xslt = self.xslt_factory.fromString(
                fn, Uri.OsPathToUri(os.path.abspath('.'))
            )
        return xslt

    def run(self, xml, xslt, params):
        proc = self.get_processor()
        xml = CreateInputSource(xml)
        xslt = self.get(xslt)
        proc.appendStylesheet(xslt)
        out = proc.run(xml, topLevelParams=params)
        del proc
        return out

    def do_render(self, xml, xslt, params):
        params['check_params'] = "Yup they are working!"
        nodes = {}
        for k, v in params.items():
            if isinstance(v, list):
                nodes[k] = v
        params = self.setup_xslt_params(params)
        for k, v in nodes.items():
            params[(self.ns, k)] = v
        return self.run(xml, xslt, params=params)

    def setup_xslt_params(self, params):
        xsltparams = dict([ ((self.ns, k), params[k])
                            for k in params
                            if xsltize(params[k]) is not None ])
        return xsltparams

class IndexXMLMiddleware(object):
    def __init__(self, app_conf, app):
        self.app_conf = app_conf
        self.content = '<?xml version="1.0"?><page />'
        if self.app_conf.get('index_xml'):
            if os.path.exists(self.app_conf['index_xml']):
                self.content = open(self.app_conf['index_xml'],'rb').read()
        self.app = app

    def start_response(self, status, headers, exc_info=None):
        self.status = status
        self.headers = headers
        self.exc_info = exc_info

    def __call__(self, environ, start_response, exc_info=None):
        c = self.app(environ, self.start_response)
        start_response(self.status, self.headers, self.exc_info)
        if c:
            return c
        return [self.content]

def set_params(environ, params):
    values = environ.get(XParams, {})
    values.update(params)
    environ[XParams] = values

def set_template(environ, template):
    environ[XTemplate] = template

def node_set(xml):
    return Parse(xml)

class TemplateConstants(object):

    def __init__(self, constants_dict, app, use_environ=True):
        self.constants = constants_dict
        self.use_environ = use_environ
        self.app = app

    def __call__(self, environ, start_response):
        if self.use_environ:
            # strip out xsltemplates params
            set_params(environ,
                       dict([ (k, v) for k, v in environ.items()
                              if not k.startswith(XParams) ]))
        set_params(environ, self.constants)
        return self.app(environ, start_response)


text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_CXX11_NEURAL_NETWORKS_SOFTMAX_H
#define EIGEN_CXX11_NEURAL_NETWORKS_SOFTMAX_H

namespace Eigen {

/** SoftMax
  * \ingroup CXX11_NeuralNetworks_Module
  *
  * \brief Applies a softmax
  *
  * The input parameter is expected to be a col-major tensor with a rank of 2 (depth and other).
  *
  * The result can be assigned to a tensor of rank and dimensions equal to that of the input. The result will be laid out in col-major order.
  *
*/

namespace {
class SoftmaxOp {
 public:
  EIGEN_ALWAYS_INLINE SoftmaxOp(const float beta) : beta_(beta) { }

  template <typename Input> EIGEN_ALWAYS_INLINE
  typename Input::Dimensions dimensions(const Input& input) const {
    return input.dimensions();
  }

  template <typename Input, typename Output, typename Device>
  void eval(const Input& input, Output& output, const Device& device) const
  {
#if !defined(EIGEN_HAS_INDEX_LIST)
    // nvcc doesn't support cxx11
    Eigen::array<typename internal::traits<Input>::Index, 1> depth_dim;
    depth_dim[0] = 0;
    Eigen::array<typename internal::traits<Input>::Index, 2> bcast;
    bcast[0] = dimensions(input)[0];
    bcast[1] = 1;
    DSizes<typename internal::traits<Input>::Index, 2> dims2d;
    dims2d[0] = 1;
    dims2d[1] = dimensions(input)[1];
#else
    // Take advantage of cxx11 to give the compiler information it can use to
    // optimize the code.
    Eigen::IndexList<Eigen::type2index<0>> depth_dim;
    Eigen::IndexList<int, Eigen::type2index<1>> bcast;
    bcast.set(0, dimensions(input)[0]);
    Eigen::IndexList<Eigen::type2index<1>, typename internal::traits<Input>::Index> dims2d;
    dims2d.set(1, dimensions(input)[1]);
#endif

    output.device(device) = ((input - input.maximum(depth_dim).eval().reshape(dims2d).broadcast(bcast)) * beta_).exp();
    output.device(device) = output / (output.sum(depth_dim).eval().reshape(dims2d).broadcast(bcast));
  }

 private:
  const float beta_;
};
}

template <typename Input>
EIGEN_ALWAYS_INLINE
static const TensorCustomUnaryOp<const SoftmaxOp, const Input>
SoftMax(const Input& input, const float beta)
{
  EIGEN_STATIC_ASSERT(internal::traits<Input>::Layout == ColMajor, YOU_MADE_A_PROGRAMMING_MISTAKE);
  EIGEN_STATIC_ASSERT(internal::traits<Input>::NumDimensions == 2, YOU_MADE_A_PROGRAMMING_MISTAKE);

  const SoftmaxOp op(beta);
  return input.customOp(op);
}

} // end namespace Eigen

#endif // EIGEN_CXX11_NEURAL_NETWORKS_SOFTMAX_H

redpajama_set_name: RedPajamaGithub


text:
import sys
import socket
import signal
import threading
import urllib
from urlparse import urlparse, parse_qs
import os
import importlib
import json
import httplib

# our stuff

import halonsupport
import sos

global _listener
#_listener = None

global _currentDevice
_currentDevice = ""

libs = { }
HOST = ""
PORT = 6789

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# helpers

def IsInt(str):
    try:
        int(str)
        return True
    except:
        return False

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# SIGINT handler
#
def signal_handler(signal, frame):

    global _listener

    print ''
    sos.sos_warn('SIGINT received: ending...')
    _listener.close()
    sys.exit()

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# attempt to load the specified device handler and, if it
# loads okay, initialise it by calling its Init() method
#
def open_device(name):
    sos.sos_info("opening " + name + ".device...")

    global libs
    global _currentDevice

    sos.SetDevice(name)

    try:
        lib = importlib.import_module("rs_" + name, package=None)
        success = getattr(lib, 'init')()
        sos.ClrDevice()

        if success:
	    sos.sos_ok(name + ".device loaded ok")
            libs[name] = lib

        else:
	    sos.sos_fail(name + ".device failed to initialise")

    except:
        sos.ClrDevice()
	sos.sos_fail(name + ".device not found")

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# load up device handlers - should be more dynamic (e.g.
# from a .conf file, or enumerating a directory)
#
def get_devices():
    print ""
    sos.sos_info("Loading device handlers...")
    open_device("null")
    open_device("max7219")
    open_device("blink1")
    open_device("unicornhat")
    open_device("pcd8544")
    open_device("unicornhathd")
#    open_device("xxx")			# test failure

    sos.sos_note("Loaded device handlers")

#    print libs

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# helper: retrieve the requested URL from a standard HTTP request
#
def get_url(request):
    uri = ''
    lines = request.split('\r\n', 1)
    if len(lines) > 0:
        header = lines[0]
        chunks = header.split(' ')
        if len(chunks) == 3:
            uri = chunks[1]

    #return urllib.unquote(uri.lstrip('/'))
    return uri.lstrip('/')

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# query handler
# return bool,string Tuple (e.g True,"OK") if query was
# handled, or false otherwise
#
def handle(queryDict):
    global libs
    _device = ""

    if 'device' in queryDict:
        _device = queryDict['device'][0]

    try:
        dev = libs[_device]
        if dev == None:
            print "[FAIL]: bad: " + _device
            return False, "bad device '" + _device + "'"

    except:
        print "[FAIL]: unknown device: " + _device
        return False, "Unknown device '" + _device + "'"

    # return the result of calling handler->handle()
    return getattr(dev, 'handle')(queryDict)

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# v3 query handler
# return int,string,int Tuple (e.g True,"OK",format) if query was
# handled, or false otherwise
#
def handle_v3(device, unit, command, queryDict):
    global libs

    status = 418
    hint = "Beverage containment error - refer to handbook"
    replyformat = 0 # json

    #sos.sos_info("Using V3 API")
    sos.sos_info("(v3) looking for device '" + device + "'...")

    # remember that queryDict is a dictionary of keys and [values]

    formatlist = queryDict.get("replyformat", [])
    if "raw" in formatlist:
        replyformat = 1 # raw format

    try:
        # this raises KeyError if the device isn't found...
        dev = libs[device]
        sos.SetDevice(device)

        # return the result of calling handler->handleNew()...
        # "status" must be a standard HTTP status and should be a RESTful one
        # on failure, "hint" can be used to explain what went wrong
        # on success, "hint" can be used to include supplementary information
	# format is 0 for json wrapper; 1 for raw

        status,hint = getattr(dev, 'handleNew')(unit, command, queryDict, 3)

    except KeyError:
        status = 404
        hint = "Unknown device '" + device + "'"

    except AttributeError:
        status = 501
        hint = "This device does not support the V3 API"
        sos.sos_fail(hint)

    except TypeError:
        status = 501
        hint = "This device does not support the V3 API"
        sos.sos_fail(hint)

    # fall-through and tell us what type of exception occurred...
    except Exception as guru:
        status = 500
        hint = "I/O error: " + type(guru).__name__
        sos.sos_fail(hint)

    sos.ClrDevice()

    success = (status >= 200 and status <= 299)

    #sos.sos_info("reply format to use is " + str(replyformat))

    if (replyformat == 1):
	# return the hint only
        payload = hint

    else:
        # translate the result into JSON...
        value = ''
        if success:
            value = hint
            hint = ''

        payload = { 'success': success, 'payload': { 'hint': hint, 'value': value } }
        payload = json.dumps(payload, indent=2)

    return status, success, payload

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# v2 query handler
# return bool,string Tuple (e.g True,"OK") if query was
# handled, or false otherwise
#
def handle_v2(device, unit, queryDict):
    global libs

    result = False
    hint = "Unknown device '" + device + "'"

    sos.sos_info("Using V2 API")
    sos.sos_info("Looking for device '" + device + "'...")

    try:
        dev = libs[device]
        if dev != None:
            sos.SetDevice(device)

            # return the result of calling handler->handle()
            result,hint = getattr(dev, 'handle')(queryDict, 2, unit)

        else:
            sos.sos_fail(hint)

    except TypeError:
        hint = "This device does not support the V2 API"
        sos.sos_fail(hint)

    except Exception, e:
        hint = "Error communicating with device: " + str(e)
        sos.sos_fail(hint)

    sos.ClrDevice()

    # translate the result into JSON...

    myResult = { 'success': False, 'status': 200, 'hint': "" }

    # on failure, hint can be used to explain what went wrong
    # on success, hint can be used to include supplementary information

    myResult['success'] = result
    myResult['hint'] = hint

    # status is either 200 (success) or 400 (failure) for now...
    if not result:
        myResult['status'] = 400

    # still return true/false back up...
    return result, json.dumps(myResult, indent=2)

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# NOT USED
#
def do_io_thread(deviceObj, queryDict, apiVersion, unit):

    # return the result of calling handler->handle()
    result,hint = getattr(deviceObject, 'handle')(queryDict, apiVersion, unit)

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# connection handler
#
def client_thread(conn):

    global sos

    request = conn.recv(4096)
    uri = get_url(request)
    sos.sos_note("Request is '" + uri + "'")

    success = False
    status = 200
    response = 'BadRequest'

    try:
        o = urlparse(uri.strip('/'))
        #print 'query: ' + o.query
        #print 'path: ' + o.path

    except:
        sos.sos_fail("Couldn't parse the URL")

    # if empty path return welcome text...

    if o.path == "":
        sos.sos_warn("Empty path: returning our version info")
	success = True
        response = 'Welcome to Halon ' + halonsupport.Version() + '!
Copyright (c) 2020 full phat products
See http://fullphat.net/redsquare/ for more details
'

    elif o.path == "favicon.ico":
        sos.sos_info("Ignoring favicon request...")
	success = True

    else:
        # split the path up...
        path = o.path.split('/')

        # check api version...
        if path[0] == 'v1':
            # return result of v1 handler...
            d = parse_qs(o.query)
            success,response = handle(d)

        elif path[0] == 'v2':
            # v2 api expects following syntax: /v2/{device}[/{unit=0}]?args...
            unit = 0
            if len(path) > 1:
                # get unit
                if len(path) > 2:
                    s = path[2]
                    if IsInt(s):
                        unit = int(s)
                    else:
                        sos.sos_warn("(V2) '" + s + "' is not a valid unit number")

                # return result of v2 handler...
                d = parse_qs(o.query)
                success,response = handle_v2(path[1], unit, d)

            else:
                sos.sos_warn("(V2) Missing device from path")

	elif path[0] == 'v3':
            # v3 api expects following syntax: /v3/{device}/{unit}/command[?args...]
            unit = 0
            if len(path) == 4:
                # get unit
                s = path[2]
                if IsInt(s):
                    unit = int(s)
                else:
                    sos.sos_warn("(V3) '" + s + "' is not a valid unit number")

                # return result of v3 handler...
                d = parse_qs(o.query)
                status,success,response = handle_v3(path[1], unit, path[3], d)

            else:
                sos.sos_fail("(V3) URI path must be '/v3/{device}/{unit}/{command}[?{args}]")
                response = "URI path must be '/v3/{device}/{unit}/{command}[?{args}]"

        else:
            sos.sos_fail("Invalid api version specified")

    # build the http reply...
    #body = "" + response + ""

    body = response
    reply = 'HTTP/1.1 ' + str(status) + ' ' + httplib.responses[status] + '\r\nContent-Length: ' + str(len(body)) + '\r\n\r\n' + body
    #+ '\r\n\r\n'

    # send it and close the socket...
    if success:
        sos.sos_ok('Sending success reply "' + response.replace("\n", "").replace("\r", "") + '"...')

    else:
        sos.sos_warn('Sending failure reply "' + response.replace("\n", "").replace("\r", "") + '"...')

    conn.sendall(reply)
    conn.close()

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# main()
#

global _listener

print ''
sos.sos_note('Halon ' + halonsupport.Version())
print 'Copyright (c) 2016-2018 full phat products'

if len(sys.argv) > 1:
    if sys.argv[1] == '-?' or sys.argv[1] == '--help':
        print 'Usage: python Halon.py [port]'
        sys.exit()

    try:
        PORT = int(sys.argv[1])

    except:
        sos.sos_fail('Invalid port specified: ' + sys.argv[1])
        sys.exit()

# main start...

# set up the socket...
sos.sos_info("Opening socket...")
_listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    _listener.bind((HOST, PORT))

except socket.error as msg:
    #print '  [Error] Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sos.sos_fail('Bind failed: you most likely already have something listening on port ' + str(PORT))
    sys.exit()

# install SIGINT signal handler...
signal.signal(signal.SIGINT, signal_handler)

# load up our device handlers...
get_devices()

# start listening...
_listener.listen(10)

print ""
sos.sos_note('Halon ' + halonsupport.Version())
sos.sos_note('Listening on port ' + str(PORT))
print ""

# loop until we get a SIGINT...

while 1:
    # accept a connection
    conn, addr = _listener.accept()
    sos.sos_info('Connection made from ' + addr[0] + ':' + str(addr[1]))
    client_thread(conn)

#    thread = threading.Thread(target=client_thread, args=(conn,))
#    thread.daemon = True
#    thread.start()


text:
#include <bits/libc-lock.h>
#include <dlfcn.h>
#include <execinfo.h>
#include <stdlib.h>
#include <unwind.h>

struct trace_arg
{
  void **array;
  _Unwind_Word cfa;
  int cnt;
  int size;
};

#ifdef SHARED
static _Unwind_Reason_Code (*unwind_backtrace) (_Unwind_Trace_Fn, void *);
static _Unwind_Ptr (*unwind_getip) (struct _Unwind_Context *);
static _Unwind_Word (*unwind_getcfa) (struct _Unwind_Context *);
static void *libgcc_handle;

/* Dummy version in case libgcc_s does not contain the real code.  */
static _Unwind_Word
dummy_getcfa (struct _Unwind_Context *ctx __attribute__ ((unused)))
{
  return 0;
}

static void
init (void)
{
  libgcc_handle = __libc_dlopen ("libgcc_s.so.1");

  if (libgcc_handle == NULL)
    return;

  unwind_backtrace = __libc_dlsym (libgcc_handle, "_Unwind_Backtrace");
  unwind_getip = __libc_dlsym (libgcc_handle, "_Unwind_GetIP");
  if (unwind_getip == NULL)
    unwind_backtrace = NULL;
  unwind_getcfa = (__libc_dlsym (libgcc_handle, "_Unwind_GetCFA")
		   ?: dummy_getcfa);
}
#else
# define unwind_backtrace _Unwind_Backtrace
# define unwind_getip _Unwind_GetIP
# define unwind_getcfa _Unwind_GetCFA
#endif

static _Unwind_Reason_Code
backtrace_helper (struct _Unwind_Context *ctx, void *a)
{
  struct trace_arg *arg = a;

  /* We are first called with address in the __backtrace function.
     Skip it.  */
  if (arg->cnt != -1)
    {
      arg->array[arg->cnt] = (void *) unwind_getip (ctx);

      /* Check whether we make any progress.  */
      _Unwind_Word cfa = unwind_getcfa (ctx);

      if (arg->cnt > 0 && arg->array[arg->cnt - 1] == arg->array[arg->cnt]
	  && cfa == arg->cfa)
	return _URC_END_OF_STACK;
      arg->cfa = cfa;
    }
  if (++arg->cnt == arg->size)
    return _URC_END_OF_STACK;
  return _URC_NO_REASON;
}

int
__backtrace (array, size)
     void **array;
     int size;
{
  struct trace_arg arg = { .array = array, .cfa = 0, .size = size, .cnt = -1 };
#ifdef SHARED
  __libc_once_define (static, once);

  __libc_once (once, init);
  if (unwind_backtrace == NULL)
    return 0;
#endif

  if (size >= 1)
    unwind_backtrace (backtrace_helper, &arg);

  /* _Unwind_Backtrace on IA-64 seems to put NULL address above
     _start.  Fix it up here.  */
  if (arg.cnt > 1 && arg.array[arg.cnt - 1] == NULL)
    --arg.cnt;
  return arg.cnt != -1 ? arg.cnt : 0;
}
weak_alias (__backtrace, backtrace)
libc_hidden_def (__backtrace)

#ifdef SHARED
/* Free all resources if necessary.  */
libc_freeres_fn (free_mem)
{
  unwind_backtrace = NULL;
  if (libgcc_handle != NULL)
    {
      __libc_dlclose (libgcc_handle);
      libgcc_handle = NULL;
    }
}
#endif


text:
#ifndef MRUBY_IREP_H
#define MRUBY_IREP_H

#include "common.h"
#include <mruby/compile.h>

/**
 * Compiled mruby scripts.
 */
MRB_BEGIN_DECL

enum irep_pool_type {
  IREP_TT_STR   = 0,          /* string (need free) */
  IREP_TT_SSTR  = 2,          /* string (static) */
  IREP_TT_INT32 = 1,          /* 32bit integer */
  IREP_TT_INT64 = 3,          /* 64bit integer */
  IREP_TT_BIGINT = 7,         /* big integer (not yet supported) */
  IREP_TT_FLOAT = 5,          /* float (double/float) */
};

#define IREP_TT_NFLAG 1       /* number (non string) flag */
#define IREP_TT_SFLAG 2       /* static string flag */

typedef struct mrb_pool_value {
  uint32_t tt;     /* packed type and length (for string) */
  union {
    const char *str;
    int32_t i32;
    int64_t i64;
#ifndef MRB_NO_FLOAT
    mrb_float f;
#endif
  } u;
} mrb_pool_value;

enum mrb_catch_type {
  MRB_CATCH_RESCUE = 0,
  MRB_CATCH_ENSURE = 1,
};

struct mrb_irep_catch_handler {
  uint8_t type;         /* enum mrb_catch_type */
  uint8_t begin[4];     /* The starting address to match the handler. Includes this. */
  uint8_t end[4];       /* The endpoint address that matches the handler. Not Includes this. */
  uint8_t target[4];    /* The address to jump to if a match is made. */
};

/* Program data array struct */
typedef struct mrb_irep {
  uint16_t nlocals;        /* Number of local variables */
  uint16_t nregs;          /* Number of register variables */
  uint16_t clen;           /* Number of catch handlers */
  uint8_t flags;

  const mrb_code *iseq;
  /*
   * A catch handler table is placed after the iseq entity.
   * The reason it doesn't add fields to the structure is to keep the mrb_irep structure from bloating.
   * The catch handler table can be obtained with `mrb_irep_catch_handler_table(irep)`.
   */
  const mrb_pool_value *pool;
  const mrb_sym *syms;
  const struct mrb_irep * const *reps;

  const mrb_sym *lv;
  /* debug info */
  struct mrb_irep_debug_info* debug_info;

  uint32_t ilen;
  uint16_t plen, slen;
  uint16_t rlen;
  uint16_t refcnt;
} mrb_irep;

#define MRB_ISEQ_NO_FREE 1
#define MRB_IREP_NO_FREE 2
#define MRB_IREP_STATIC  (MRB_ISEQ_NO_FREE | MRB_IREP_NO_FREE)

MRB_API mrb_irep *mrb_add_irep(mrb_state *mrb);

/** load mruby bytecode functions
* Please note! Currently due to interactions with the GC calling these functions will
* leak one RProc object per function call.
* To prevent this save the current memory arena before calling and restore the arena
* right after, like so
* int ai = mrb_gc_arena_save(mrb);
* mrb_value status = mrb_load_irep(mrb, buffer);
* mrb_gc_arena_restore(mrb, ai);
*/

/* @param [const uint8_t*] irep code, expected as a literal */
MRB_API mrb_value mrb_load_irep(mrb_state*, const uint8_t*);

/*
 * @param [const void*] irep code
 * @param [size_t] size of irep buffer. If -1 is given, it is considered unrestricted.
 */
MRB_API mrb_value mrb_load_irep_buf(mrb_state*, const void*, size_t);

/* @param [const uint8_t*] irep code, expected as a literal */
MRB_API mrb_value mrb_load_irep_cxt(mrb_state*, const uint8_t*, mrbc_context*);

/*
 * @param [const void*] irep code
 * @param [size_t] size of irep buffer. If -1 is given, it is considered unrestricted.
 */
MRB_API mrb_value mrb_load_irep_buf_cxt(mrb_state*, const void*, size_t, mrbc_context*);

void mrb_irep_free(mrb_state*, struct mrb_irep*);
void mrb_irep_incref(mrb_state*, struct mrb_irep*);
void mrb_irep_decref(mrb_state*, struct mrb_irep*);
void mrb_irep_cutref(mrb_state*, struct mrb_irep*);
void mrb_irep_remove_lv(mrb_state *mrb, mrb_irep *irep);

struct mrb_insn_data {
  uint8_t insn;
  uint16_t a;
  uint16_t b;
  uint16_t c;
  const mrb_code *addr;
};

struct mrb_insn_data mrb_decode_insn(const mrb_code *pc);

static inline const struct mrb_irep_catch_handler *
mrb_irep_catch_handler_table(const struct mrb_irep *irep)
{
  if (irep->clen > 0) {
    return (const struct mrb_irep_catch_handler*)(irep->iseq + irep->ilen);
  }
  else {
    return (const struct mrb_irep_catch_handler*)NULL;
  }
}

#define mrb_irep_catch_handler_pack(n, v)   uint32_to_bin(n, v)
#define mrb_irep_catch_handler_unpack(v)    bin_to_uint32(v)

MRB_END_DECL

#endif  /* MRUBY_IREP_H */


text:
import * as React from 'react'
import { RadiumStyles, Omit } from '../..'

export interface TextProps extends Omit<React.HTMLAttributes<HTMLElement>, 'style'> {
  children: React.ReactNode

  /**
   * Overrides the default HTML element type. Each typography variant has a default HTML element (e.g. h1, p),
   * but this is only a best guess. Always ensure you're using the correct header markup -- element
   * types with Snacks typography should be used to describe document structure, not visual style.
   */
  elementType?: keyof JSX.IntrinsicElements

  /** Overrides the variant's default font weight. */
  fontWeight?: 'light' | 'regular' | 'semiBold' | 'bold'

  /** Typography variant to be used. */
  variant:
    | 'T.11'
    | 'T.12'
    | 'T.14'
    | 'T.16'
    | 'T.18'
    | 'T.22'
    | 'T.28'
    | 'T.36'
    | 'T.46'
    | 'T.58'
    | 'T.64'
    | 'T.72'
    | 'T.82'
    | 'T.92'

  style?: RadiumStyles
}

declare const Text: React.ComponentClass<TextProps>

export default Text


text:
package com.lenddo.javaapi.models.applicationdetails;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class MothersMaidenName {

    @SerializedName("first")
    @Expose
    private String first;
    @SerializedName("middle")
    @Expose
    private String middle;
    @SerializedName("last")
    @Expose
    private String last;

    public String getFirst() {
        return first;
    }

    public void setFirst(String first) {
        this.first = first;
    }

    public String getMiddle() {
        return middle;
    }

    public void setMiddle(String middle) {
        this.middle = middle;
    }

    public String getLast() {
        return last;
    }

    public void setLast(String last) {
        this.last = last;
    }

}


text:
/// <reference path="./index.d.ts" />
/// <reference path="./ble.d.ts" />
/// <reference types="web-bluetooth" />

declare interface IHardwareModule {
    // 디바이스 데이터 송수신 라이프사이클

    // TODO serialport or undefined 를 어떻게 처리해야하나?
    requestInitialData: (serialPort?: any, payload?: string) => any;
    checkInitialData: (data: any, options: IHardwareModuleConfig) => boolean | undefined;
    requestRemoteData: (handler: any) => void;
    handleRemoteData?: (handler: any) => void;
    validateLocalData?: (data: any) => boolean;
    handleLocalData: (data: any) => void;
    requestLocalData: (commandQueue?: any[] /* for ble. 추후 모듈 상속으로 제거 */) => any;

    // 연결 절차
    connect?: () => void;
    afterConnect?: (router: any, callback?: (state: string) => void) => void;
    disconnect?: (connector: any) => void;

    // 기타 최초 연결 수립시 사용되는 함수. 사용처가 통일되지 않아 정리 대상
    init?: (handler: any, config: any) => void; // deprecate into hook
    setSocket?: (server: any) => void; // deprecate into hook
    setHandler?: (handler: any) => void; // not recommended to use
    setSerialPort?: (serialPort: any) => void; // deprecate
    resetProperty?: () => any; // after init, send to device
    getProperty?: () => any; // using master device. after requestLocalData send to device
    socketReconnection?: () => void; // need rename
    reset?: () => void; // need rename it called socket client(Entry web) is closed

    // 모듈이 프로그램 자체에 영향을 줄수 있으므로 제거 및 로직 개선 필요
    eventController: (state: any) => void;
    lostController?: (connector: any, routerSendStateFunction: (state: string) => void) => void;

    // 커스텀 버튼. 모듈화 적용시 제조사측에서 작성한 커스텀 버튼 코드를 체크할 수 없으므로 추후 개선이 필요
    canShowCustomButton?: () => boolean;
    customButtonClicked?: (key: any) => void;

    // for HID (modern)
    registerIntervalSend?: (registerFunction: IRegisterIntervalSendArg) => void;

    // for BLE
    getProfiles?: () => IBleProfileInformation[];

    // https://developer.mozilla.org/en-US/docs/Web/API/Bluetooth/requestDevice
    getScanOptions?: () => RequestDeviceOptions;
}

type IRegisterIntervalSendArg = (sendDataFunction: () => any, interval: number) => void;


text:
import cloudinary.api as cda
import cloudinary
from cloudinary import uploader
import threading
import json
import re

cloudinary.config(
  cloud_name = "dominicbett",
  api_key = "897862543535181",
  api_secret = "AJcDSocxqA43s5sf3qxD06"
)

class Images:
	def __init__(self, name, url):
		self.name = name
		self.url = url

cloudinaryURLs = []

with open("../ExtractPhotos/imageURLData.txt", 'r') as lines:
	for line in lines:
		try:
			url = line.strip()
			print "Uploading: %s" % url
			image_name = url.split("/")[-1].split(".")[0]
			response = cloudinary.uploader.upload(url, public_id=image_name, folder="Aphorites/")
			cloudinaryURL = response["url"]
			name = re.findall(r"(.*?)-[0-9_]+?", image_name)[0]
			name = name.replace("-", " ")
			image = Images(name, cloudinaryURL)
			cloudinaryURLs.append(image)
		except Exception, e:
			print e
			continue

def obj_dict(obj):
		return obj.__dict__
serializedData = json.dumps(cloudinaryURLs, default=obj_dict)

#print serializedData
with open('data.json','w') as f:
	f.write(str(serializedData))
f.close()
print "DONE!"


text:
#ifndef __SR_GRAMMARIMPL_H
#define __SR_GRAMMARIMPL_H

#include "ArrayList.h"
#include "HashMap.h"
#include "SR_Grammar.h"
#include "SR_Nametags.h"
#include "ESR_ReturnCode.h"
#include "ESR_SessionType.h"
#include "SR_EventLog.h"
#include "SR_Recognizer.h"

/* Semproc stuff */
#include "SR_SemanticGraph.h"
#include "SR_SemanticProcessor.h"

#include "simapi.h"

/**
 * SR_Grammar implementation.
 */
typedef struct SR_GrammarImpl_t
{
  /**
   * Interface functions that must be implemented.
   */
  SR_Grammar Interface;

  /**
   * Associates a grammar with a Recognizer.
   *
   * @param self SR_Grammar handle
   * @param recognizer The recognizer
   */
  // ESR_ReturnCode(*setupAcousticModels)(SR_Grammar* self, SR_AcousticModels* models);
  ESR_ReturnCode(*setupRecognizer)(SR_Grammar* self, SR_Recognizer* recognizer);
  /**
   * Dissociates a grammar from a Recognizer.
   *
   * @param self SR_Grammar handle
   */
  ESR_ReturnCode(*unsetupRecognizer)(SR_Grammar* self);

  /**
   * Legacy CREC syntax.
   */
  CA_Syntax* syntax;
  /**
   * Recognizer associated with SR_Grammar.
   */
  // SR_AcousticModels* models;
  SR_Recognizer* recognizer;

  /**
   * Vocabulary.
   */
  SR_Vocabulary* vocabulary;

  /**
   * Semantic Graph
   */
  SR_SemanticGraph* semgraph;

  /**
   * Semantic Processor
   */
  SR_SemanticProcessor* semproc;

  /**
   * Grammar-specific parameters.
   */
  ESR_SessionType* parameters;

  /**
   * Event Log reference set internally by regognizer during its association with this grammar
   */
  SR_EventLog* eventLog;

  /**
   * Event log, logging level.
   */
  size_t logLevel;

  /**
   * Indicates if the grammar has been activated.
   */
  ESR_BOOL isActivated;
}
SR_GrammarImpl;

/**
 * Default implementation.
 */
SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_CompileRule(SR_Grammar* self, const LCHAR* name);
/**
 * Default implementation.
 */
SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_AddRuleFromList(SR_Grammar* self, SR_Vocabulary* vocabulary, const LCHAR* name);
/**
 * Default implementation.
 */
SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_Compile(SR_Grammar* self);
/**
 * Default implementation.
 */
SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_AddRule(SR_Grammar* self, const LCHAR* name, const LCHAR* value);
/**
 * Default implementation.
 */
SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_DeleteRule(SR_Grammar* self, const LCHAR* name);
/**
 * Default implementation.
 */
SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_ContainsRule(SR_Grammar* self, const LCHAR* name, ESR_BOOL* result);
/**
 * Default implementation.
 */
SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_AddWordToSlot(SR_Grammar* self, const LCHAR* slot,
																												 const LCHAR* word, const LCHAR* pronunciation,
																												 int weight, const LCHAR* tag);
/**
 * Default implementation.
 */
SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_ResetAllSlots(SR_Grammar* self);
/**
 * Default implementation.
 */
SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_AddNametagToSlot(SR_Grammar* self, const LCHAR* slot,
																														const SR_Nametag* nametag, int weight,
																														const LCHAR* tag);
/**
 * Default implementation.
 */
SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_Create(SR_Grammar** self);
/**
 * Default implementation.
 */
SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_Destroy(SR_Grammar* self);
/**
 * Default implementation.
 */
SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_Save(SR_Grammar* self, const LCHAR* filename);
/**
 * Default implementation.
 */
SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_CheckParse(SR_Grammar* self, const LCHAR* transcription, SR_SemanticResult** result, size_t* resultCount);
/**
 * Default implementation.
 */
SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_SetDispatchFunction(SR_Grammar* self, const LCHAR* name, void* userData, SR_GrammarDispatchFunction function);
/**
 * Default implementation.
 */
SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_SetParameter(SR_Grammar* self, const LCHAR* key, void* value);
/**
 * Default implementation.
 */
SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_SetSize_tParameter(SR_Grammar* self, const LCHAR* key, size_t value);
/**
 * Default implementation.
 */
SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_GetParameter(SR_Grammar* self, const LCHAR* key, void** value);
/**
 * Default implementation.
 */
SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_GetSize_tParameter(SR_Grammar* self, const LCHAR* key, size_t* value);
/**
 * Default implementation.
 */
// SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_SetupModels(SR_Grammar* self, SR_AcousticModels* models);
SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_SetupRecognizer(SR_Grammar* self, SR_Recognizer* recognizer);
/**
 * Default implementation.
 */
SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_UnsetupRecognizer(SR_Grammar* self);
/**
 * Default implementation.
 */
SREC_GRAMMAR_API ESR_ReturnCode SR_Grammar_SetupVocabulary(SR_Grammar *self, SR_Vocabulary *vocabulary);

#endif /* __SR_GRAMMARIMPL_H */


text:
package org.zstack.network.securitygroup;

import org.zstack.header.message.APIMessage;
import org.zstack.header.message.APIParam;
import org.zstack.header.network.l3.L3NetworkVO;

/**
 * @api
 * detach security group from a l3Network
 *
 * @category security group
 *
 * @since 0.1.0
 *
 * @cli
 *
 * @httpMsg
 *
 * @msg
 * {
"org.zstack.network.securitygroup.APIDetachSecurityGroupFromL3NetworkMsg": {
"securityGroupUuid": "3d9d1a6a472440a4b53d2389c111336c",
"l3NetworkUuid": "2a4b46c9ce154d759dc0e933c4f84ae6",
"session": {
"uuid": "2a4038cebb1a411fb2f549e5119996b8"
},
"timeout": 1800000,
"id": "6fd757b4b4964a4ebc4d636dda67c8cc",
"serviceId": "api.portal"
}
}
 *
 * @result
 * see :ref:`APIDetachSecurityGroupFromL3NetworkEvent`
 */

public class APIDetachSecurityGroupFromL3NetworkMsg extends APIMessage {
    /**
     * @desc security group uuid
     */
    @APIParam(resourceType = SecurityGroupVO.class)
    private String securityGroupUuid;
    /**
     * @desc l3Network uuid
     */
    @APIParam(resourceType = L3NetworkVO.class)
    private String l3NetworkUuid;

    public String getSecurityGroupUuid() {
        return securityGroupUuid;
    }

    public void setSecurityGroupUuid(String securityGroupUuid) {
        this.securityGroupUuid = securityGroupUuid;
    }

    public String getL3NetworkUuid() {
        return l3NetworkUuid;
    }

    public void setL3NetworkUuid(String l3NetworkUuid) {
        this.l3NetworkUuid = l3NetworkUuid;
    }
}


text:
using System;

namespace DiscUtils.Ntfs
{
    [Flags]
    internal enum VolumeInformationFlags : ushort
    {
        None = 0x00,
        Dirty = 0x01,
        ResizeLogFile = 0x02,
        UpgradeOnMount = 0x04,
        MountedOnNT4 = 0x08,
        DeleteUSNUnderway = 0x10,
        RepairObjectIds = 0x20,
        DisableShortNameCreation = 0x80,
        ModifiedByChkDsk = 0x8000
    }
}


text:
{% extends "_base.html" %}
{% block content %}

FlaskTaskr

Please login to see your task list.

Or Register for an account.

        <form action="" method="post" class="ui form">
            {{ form.csrf_token }}

                {{ form.name.label }}
                {{ form.name }}

                {{ form.password.label }}
                {{ form.password }}

            <button
                type="submit"
                class="ui button green"
            >
                Submit
            </button>
        </form>

{% endblock content %}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Silo Error Code Monitoring | Microsoft Orleans Documentation </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Silo Error Code Monitoring | Microsoft Orleans Documentation ">
    <meta name="generator" content="docfx 2">

    <link rel="shortcut icon" href="../../../favicon.ico">
    <link rel="stylesheet" href="../../../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../../../styles/docfx.css">
    <link rel="stylesheet" href="../../../styles/main.css">
    <meta property="docfx:navrel" content="../../../toc.html">
    <meta property="docfx:tocrel" content="../../toc.html">

    <meta property="docfx:rel" content="../../../">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

Search Results for

          Show / Hide Table of Contents

Silo Error Code Monitoring

Group
Log Type
Log Code Values
Threshold
Description

Azure Problems
Warning or Error
100800 - 100899
Any Error or Warning
Transient problems reading or writing to Azure table store will be logged as Warning. Transient read errors will automatically be retried. A final Error log message means there is a real problem connecting to Azure table storage.

Membership Connectivity Problems
Warning or Error
100600 - 100699
Any Error or Warning
Warning logs are an early indication of network connectivity problems and/or silo restart / migration. Ping timeouts and silo-dead votes will show up as Warning messages. Silo detecting it was voted dead will show as Error message.

Grain call timeouts
Warning
100157
Multiple Warnings logged in short space of time
Grain-call timeout problems are generally caused by temporary network connectivity issues or silo restart / reboot problems. The system should recover after a short time (depending on Liveness config settings) at which point Timeouts should clear. Ideally, monitoring for just the bulk log code 600157 variety of these warnings should be sufficient.

Silo Restart / Migration
Warning
100601 or 100602
Any Warning
Warning printed when silo detects it was restarted on same machine {100602) or migrated to different machine (100601)

Network Socket Problems
Warning or Error
101000 to 101999, 100307,100015, 100016
Any Error or Warning
Socket disconnects are logged as Warning messages. Problems opening sockets or during message transmission are logged as Errors.

Grain problems
Warning or Error
101534
Any Error or Warning
Detection of "stuck" requests for non-reentrant grains . The error code is reported every time a request takes longer than 5x request timeout time to execute.

                    Improve this Doc

In This Article

              Back to top

            Generated by DocFX


text:
const EventEmitter = require('events')
const lmerge = require('lodash.merge')
const uniqid = require('uuid/v4')
const debug = require('debug')
const debugManager = debug('spa')

const DEFAULT_OPTIONS = () => {
  return {
    id: uniqid(),
    initiator: false,
    channelConfig: {},
    channelName: uniqid(),
    config: { iceServers: [ { urls: 'stun:stun.l.google.com:19302' } ] },
    constraints: {},
    offerConstraints: {},
    answerConstraints: {},
    reconnectTimer: false,
    sdpTransform: function (sdp) { return sdp },
    stream: false,
    streams: [],
    trickle: true,
    wrtc: {}, // RTCPeerConnection/RTCSessionDescription/RTCIceCandidate
    objectMode: false
  }
}

class Manager {
  constructor () {
    this._statistics = {
      message: 0
    }
    this.manager = new Map()
    this._options = {
      latency: (send) => { setTimeout(send, 0) }
    }
    debugManager('manager initialized')
  }
  get stats () {
    return this._statistics
  }

  newPeer (peer) {
    debugManager('new peer added. Size:', this.manager.size)
    this.manager.set(peer.id, peer)
  }

  connect (from, to) {
    debugManager('peer connected from/to: ', from, to)
    this.manager.get(to)._connectWith(from)
    this.manager.get(from)._connectWith(to)
  }

  destroy (from, to) {
    debugManager('peer disconnected from/to: ', from, to)
    if (this.manager.get(from)) {
      this.manager.get(from)._close()
      this.manager.delete(from)
    }
    if (this.manager.get(to)) {
      this.manager.get(to)._close()
      this.manager.delete(to)
    }
  }

  send (from, to, msg, retry = 0) {
    // this._options.latency(() => {
    this._send(from, to, msg, retry)
    // })
  }

  _send (from, to, msg, retry = 0) {
    try {
      if (!this.manager.has(from) || !this.manager.has(to)) throw new Error('need a from and to peer.')
      this.manager.get(to).emit('data', msg)
      this._statistics.message++
    } catch (e) {
      throw new Error('cannot send the message. perhaps your destination is not reachable.', e)
    }
  }
}
const manager = new Manager()

module.exports = class SimplePeerAbstract extends EventEmitter {
  constructor (options) {
    super()
    this._manager = manager
    this._options = lmerge(DEFAULT_OPTIONS(), options)
    this.id = this._options.id
    this.WEBRTC_SUPPORT = true // yes but this a fake
    this._isNegotiating = false
    this.connected = false
    this.disconnected = false
    this.connectedWith = undefined
    this.messageBuffer = []
    debugManager('peer initiated:', this.id, this._options.initiator)
    if (this._options.initiator) {
      // workaround to wait for a listener on 'signal'
      process.nextTick(() => {
        this._init()
      })
    }
    this._manager.newPeer(this)
  }

  static get manager () {
    return manager
  }

  send (data) {
    if (!this.connectedWith) {
      this.messageBuffer.push(data)
    } else {
      if (this.messageBuffer.length > 0) {
        this._reviewMessageBuffer()
      }
      if (this.connectedWith) {
        this._send(this.connectedWith, data)
      } else {
        this.messageBuffer.push(data)
      }
    }
  }

  destroy () {
    this._manager.destroy(this.id, this.connectedWith)
  }

  signal (data) {
    if (data.type === 'init') {
      this._isNegotiating = true
      debugManager('offer-init received:', data)
      this.emit('signal', this._createAccept(data))
    } else if (data.type === 'accept') {
      debugManager('offer-accept received:', data)
      this._connect(data)
    }
  }

  _error (error) {
    debugManager(error)
    this.emit('error', error)
  }

  _close () {
    debugManager('[%s] is closed.', this.id)
    this.emit('close')
  }

  _init () {
    this._isNegotiating = true
    const offer = this._createOffer()
    this.emit('signal', offer)
  }

  _createOffer () {
    const newOffer = {
      offerId: uniqid(),
      type: 'init',
      offer: {
        initiator: this.id
      }
    }
    return newOffer
  }
  _createAccept (offer) {
    const acceptedOffer = this._createOffer()
    acceptedOffer.type = 'accept'
    acceptedOffer.offerId = offer.offerId
    acceptedOffer.offer.initiator = offer.offer.initiator
    acceptedOffer.offer.acceptor = this.id
    return acceptedOffer
  }

  _reviewMessageBuffer () {
    debugManager('Review the buffer: ', this.messageBuffer.length)
    while (this.connectedWith && this.messageBuffer.length !== 0) {
      this._send(this.messageBuffer.pop())
    }
  }

  _send (to = this.connectedWith, data) {
    if (!to) throw new Error('It must have a destination.')
    this._manager.send(this.id, to, data)
  }

  _connect (offer) {
    if (!offer.offer.acceptor) throw new Error('It must have an acceptor')
    this._manager.connect(offer.offer.initiator, offer.offer.acceptor)
  }

  _connectWith (connectedWith) {
    this.connected = true
    this._isNegotiating = false
    this.connectedWith = connectedWith
    this.emit('connect')
  }
}


text:
package org.apache.drill.exec.record;

import org.apache.drill.exec.vector.ValueVector;

public interface TransferPair {
  public void transfer();
  public void splitAndTransfer(int startIndex, int length);
  public ValueVector getTo();
  public void copyValueSafe(int from, int to);
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Model;

/**
 *
 * @author Deus Ex Machina
 */
public class Problema {

    String titulo;
    String descripcion;
    Integer idProblema;
    String fI;
    String fL;

    public Problema(String t,String d,Integer id){
        titulo = t;
        descripcion=d;
        idProblema=id;
    }
    public Problema(String t,String d,Integer id, String fi, String fl){
        titulo = t;
        descripcion=d;
        idProblema=id;
        fI=fi;
        fL=fl;
    }
    public String getTitulo(){
        return this.titulo;
    }
    public String getDesc(){
        return this.descripcion;
    }

    public Integer getidP(){
        return this.idProblema;
    }
    public String getFechaInicio(){
        return this.fI;
    }
    public String getFechaLimite(){
        return this.fL;
    }
}


text:
require 'test_helper'

class Api::UmgapControllerTest < ActionController::TestCase
  test 'should get index' do
    get :index
    assert_response :success
    assert_template :index
    assert_equal 'Unipept MetaGenomics Analysis Pipeline', assigns(:title)
    assert_equal 'Overview', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
    assert_not_nil assigns(:sidebar_subnav)
  end

  test 'should get casestudies' do
    get :casestudies
    assert_response :success
    assert_template :casestudies
    assert_equal 'UMGAP case studies', assigns(:title)
    assert_equal 'Case studies', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
    assert_not_nil assigns(:sidebar_subnav)
  end

  test 'should get casestudy_advanced' do
    get :casestudy_advanced
    assert_response :success
    assert_template :casestudy_advanced
    assert_equal 'Case study: configure your own metagenomics pipeline', assigns(:title)
    assert_equal 'Case studies', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
    assert_not_nil assigns(:sidebar_subnav)
  end

  test 'should get casestudy_basic' do
    get :casestudy_basic
    assert_response :success
    assert_template :casestudy_basic
    assert_equal 'Case study: running a preconfigured metagenomics pipeline', assigns(:title)
    assert_equal 'Case studies', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
    assert_not_nil assigns(:sidebar_subnav)
  end

  test 'should get casestudy_comparative' do
    get :casestudy_comparative
    assert_response :success
    assert_template :casestudy_comparative
    assert_equal 'Case study: running a comparative analysis on 8 samples', assigns(:title)
    assert_equal 'Case studies', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
    assert_not_nil assigns(:sidebar_subnav)
  end

  test 'should get fastq2fasta' do
    get :fastq2fasta
    assert_response :success
    assert_template :fastq2fasta
    assert_equal 'The umgap fastq2fasta command', assigns(:title)
    assert_equal 'fastq2fasta', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
  end

  test 'should get translate' do
    get :translate
    assert_response :success
    assert_template :translate
    assert_equal 'The umgap translate command', assigns(:title)
    assert_equal 'translate', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
  end

  test 'should get prot2tryp' do
    get :prot2tryp
    assert_response :success
    assert_template :prot2tryp
    assert_equal 'The umgap prot2tryp command', assigns(:title)
    assert_equal 'prot2tryp', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
  end

  test 'should get prot2kmer' do
    get :prot2kmer
    assert_response :success
    assert_template :prot2kmer
    assert_equal 'The umgap prot2kmer command', assigns(:title)
    assert_equal 'prot2kmer', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
  end

  test 'should get filter' do
    get :filter
    assert_response :success
    assert_template :filter
    assert_equal 'The umgap filter command', assigns(:title)
    assert_equal 'filter', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
  end

  test 'should get pept2lca' do
    get :pept2lca
    assert_response :success
    assert_template :pept2lca
    assert_equal 'The umgap pept2lca command', assigns(:title)
    assert_equal 'pept2lca', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
  end

  test 'should get prot2tryp2lca' do
    get :prot2tryp2lca
    assert_response :success
    assert_template :prot2tryp2lca
    assert_equal 'The umgap prot2tryp2lca command', assigns(:title)
    assert_equal 'prot2tryp2lca', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
  end

  test 'should get prot2kmer2lca' do
    get :prot2kmer2lca
    assert_response :success
    assert_template :prot2kmer2lca
    assert_equal 'The umgap prot2kmer2lca command', assigns(:title)
    assert_equal 'prot2kmer2lca', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
  end

  test 'should get bestof' do
    get :bestof
    assert_response :success
    assert_template :bestof
    assert_equal 'The umgap bestof command', assigns(:title)
    assert_equal 'bestof', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
  end

  test 'should get seedextend' do
    get :seedextend
    assert_response :success
    assert_template :seedextend
    assert_equal 'The umgap seedextend command', assigns(:title)
    assert_equal 'seedextend', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
  end

  test 'should get uniq' do
    get :uniq
    assert_response :success
    assert_template :uniq
    assert_equal 'The umgap uniq command', assigns(:title)
    assert_equal 'uniq', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
  end

  test 'should get taxa2agg' do
    get :taxa2agg
    assert_response :success
    assert_template :taxa2agg
    assert_equal 'The umgap taxa2agg command', assigns(:title)
    assert_equal 'taxa2agg', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
  end

  test 'should get snaptaxon' do
    get :snaptaxon
    assert_response :success
    assert_template :snaptaxon
    assert_equal 'The umgap snaptaxon command', assigns(:title)
    assert_equal 'snaptaxon', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
  end

  test 'should get taxa2freq' do
    get :taxa2freq
    assert_response :success
    assert_template :taxa2freq
    assert_equal 'The umgap taxa2freq command', assigns(:title)
    assert_equal 'taxa2freq', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
  end

  test 'should get taxa2tree' do
    get :taxa2tree
    assert_response :success
    assert_template :taxa2tree
    assert_equal 'The umgap taxa2tree command', assigns(:title)
    assert_equal 'taxa2tree', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
  end

  test 'should get taxonomy' do
    get :taxonomy
    assert_response :success
    assert_template :taxonomy
    assert_equal 'The umgap taxonomy command', assigns(:title)
    assert_equal 'taxonomy', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
  end

  test 'should get splitkmers' do
    get :splitkmers
    assert_response :success
    assert_template :splitkmers
    assert_equal 'The umgap splitkmers command', assigns(:title)
    assert_equal 'splitkmers', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
  end

  test 'should get joinkmers' do
    get :joinkmers
    assert_response :success
    assert_template :joinkmers
    assert_equal 'The umgap joinkmers command', assigns(:title)
    assert_equal 'joinkmers', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
  end

  test 'should get buildindex' do
    get :buildindex
    assert_response :success
    assert_template :buildindex
    assert_equal 'The umgap buildindex command', assigns(:title)
    assert_equal 'buildindex', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
  end

  test 'should get printindex' do
    get :printindex
    assert_response :success
    assert_template :printindex
    assert_equal 'The umgap printindex command', assigns(:title)
    assert_equal 'printindex', assigns(:sidebar_name)
    assert_not_nil assigns(:sidebar_nav)
  end

end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<title>Python: package ProxyMiddleware</title>

<big><big>ProxyMiddleware</big></big>	index
/home/foxk5/ProxyMiddleware/ProxyMiddleware/__init__.py

<big>Package Contents</big>

<tt>      </tt>

ProxyMiddleware


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Pakist. J. Bot. 31(2): 426 (1999)

#### Original name
Coniothyrium oblongatum Abbas, B. Sutton & Ghaffar

### Remarks
null


text:
package it.er.util;

public class Test extends ImageFile{

}


text:
$(document).on('ready', function (e) {

  ajaxLoadInfo();

  $('.navbar-nav li a').on('click', function (event) {
    event.preventDefault();
    var $self = $(this);
    if ($self.attr('id') !== "currently-on"){
      changeCurrentTab($self);
      ajaxLoadInfo($self);
    }
  })
});

var changeCurrentTab = function ($target) {
  $('#currently-on').removeAttr('id');
  $target.attr('id', 'currently-on');
};

var ajaxLoadInfo = function ($targetLink) {
  $('.loading-wheel').show();
  var myUrl = "http://jkrth617.github.io/info/about.html";
  var myType = "GET";
  if($targetLink){
    myUrl = $targetLink.attr("href");
  }
  $.ajax({
    url: myUrl,
    type: myType,
  }).then(function(response) {
    $('.loading-wheel').hide();
    debugger;
    var bodyContent = parseHTMLResponse(response)
    $('[data-role="info-target"]').html(response);
  }).fail(function(deffered) {
    $('.loading-wheel').hide();
    alert("Sorry, There was a problem fetching the data");
  });
};

var parseHTMLResponse = function (htmlString) {
  return $(htmlString).filter('body')[0];//not hitting any matches
};


text:
import datetime
import unittest

from opencensus.common import utils
from opencensus.trace import link, span_context
from opencensus.trace import span_data as span_data_module
from opencensus.trace import stack_trace, status, time_event

class TestSpanData(unittest.TestCase):
    def test_create_span_data(self):
        span_data_module.SpanData(
            name='root',
            context=None,
            span_id='6e0c63257de34c92',
            parent_span_id='6e0c63257de34c93',
            attributes={'key1': 'value1'},
            start_time=utils.to_iso_str(),
            end_time=utils.to_iso_str(),
            stack_trace=None,
            links=None,
            status=None,
            annotations=None,
            message_events=None,
            same_process_as_parent_span=None,
            child_span_count=None,
            span_kind=0,
        )

    def test_span_data_immutable(self):
        span_data = span_data_module.SpanData(
            name='root',
            context=None,
            span_id='6e0c63257de34c92',
            parent_span_id='6e0c63257de34c93',
            attributes={'key1': 'value1'},
            start_time=utils.to_iso_str(),
            end_time=utils.to_iso_str(),
            stack_trace=None,
            links=None,
            status=None,
            annotations=None,
            message_events=None,
            same_process_as_parent_span=None,
            child_span_count=None,
            span_kind=0,
        )
        with self.assertRaises(AttributeError):
            span_data.name = 'child'

        with self.assertRaises(AttributeError):
            span_data.new_attr = 'a'

    def test_format_legacy_trace_json(self):
        trace_id = '2dd43a1d6b2549c6bc2a1a54c2fc0b05'
        span_data = span_data_module.SpanData(
            name='root',
            context=span_context.SpanContext(
                trace_id=trace_id,
                span_id='6e0c63257de34c92'
            ),
            span_id='6e0c63257de34c92',
            parent_span_id='6e0c63257de34c93',
            attributes={'key1': 'value1'},
            start_time=utils.to_iso_str(),
            end_time=utils.to_iso_str(),
            stack_trace=stack_trace.StackTrace(stack_trace_hash_id='111'),
            links=[link.Link('1111', span_id='6e0c63257de34c92')],
            status=status.Status(code=0, message='pok'),
            annotations=[
                time_event.Annotation(
                    timestamp=datetime.datetime(1970, 1, 1),
                    description='description'
                )
            ],
            message_events=[
                time_event.MessageEvent(
                    timestamp=datetime.datetime(1970, 1, 1),
                    id=0,
                )
            ],
            same_process_as_parent_span=False,
            child_span_count=0,
            span_kind=0,
        )
        trace_json = span_data_module.format_legacy_trace_json([span_data])
        self.assertEqual(trace_json.get('traceId'), trace_id)
        self.assertEqual(len(trace_json.get('spans')), 1)


text:
using GraphQL.Types;

namespace GraphQL.Tests.Bugs;

// https://github.com/graphql-dotnet/graphql-dotnet/issues/2557
public class Bug2557 : QueryTestBase<Bug2557.MySchema>
{
    [Fact]
    public void NoDefault_NoArg() => AssertQuerySuccess("{ noDefault }", """{ "noDefault": "getArgumentDefault" }""");

    [Fact]
    public void NoDefault_LiteralArg() => AssertQuerySuccess("""{ noDefault (arg: "test") }""", """{ "noDefault": "test" }""");

    [Fact]
    public void NoDefault_LiteralNullArg() => AssertQuerySuccess("{ noDefault (arg: null) }", """{ "noDefault": "getArgumentDefault" }""");

    [Fact]
    public void NoDefault_VariableDefaultUnspecifiedArg() => AssertQuerySuccess("query($arg: String) { noDefault (arg: $arg) }", """{ "noDefault": "getArgumentDefault" }""");

    [Fact]
    public void NoDefault_VariableDefaultNullArg() => AssertQuerySuccess("query($arg: String = null) { noDefault (arg: $arg) }", """{ "noDefault": "getArgumentDefault" }""");

    [Fact]
    public void NoDefault_VariableDefaultArg() => AssertQuerySuccess("""query($arg: String = "test") { noDefault (arg: $arg) }""", """{ "noDefault": "test" }""");

    [Fact]
    public void NoDefault_VariableArg() => AssertQuerySuccess("query($arg: String) { noDefault (arg: $arg) }", """{ "noDefault": "test" }""", """{ "arg": "test" }""".ToInputs());

    [Fact]
    public void NoDefault_VariableNullArg() => AssertQuerySuccess("query($arg: String) { noDefault (arg: $arg) }", """{ "noDefault": "getArgumentDefault" }""", """{ "arg": null }""".ToInputs());

    [Fact]
    public void WithDefault_NoArg() => AssertQuerySuccess("{ withDefault }", """{ "withDefault": "fieldDefault" }""");

    [Fact]
    public void WithDefault_LiteralArg() => AssertQuerySuccess("""{ withDefault (arg: "test") }""", """{ "withDefault": "test" }""");

    [Fact]
    public void WithDefault_LiteralNullArg() => AssertQuerySuccess("{ withDefault (arg: null) }", """{ "withDefault": "getArgumentDefault" }""");

    [Fact]
    public void WithDefault_VariableDefaultUnspecifiedArg() => AssertQuerySuccess("query($arg: String) { withDefault (arg: $arg) }", """{ "withDefault": "fieldDefault" }""");

    [Fact]
    public void WithDefault_VariableDefaultNullArg() => AssertQuerySuccess("query($arg: String = null) { withDefault (arg: $arg) }", """{ "withDefault": "getArgumentDefault" }""");

    [Fact]
    public void WithDefault_VariableDefaultArg() => AssertQuerySuccess("""query($arg: String = "test") { withDefault (arg: $arg) }""", """{ "withDefault": "test" }""");

    [Fact]
    public void WithDefault_VariableArg() => AssertQuerySuccess("query($arg: String) { withDefault (arg: $arg) }", """{ "withDefault": "test" }""", """{ "arg": "test" }""".ToInputs());

    [Fact]
    public void WithDefault_VariableNullArg() => AssertQuerySuccess("query($arg: String) { withDefault (arg: $arg) }", """{ "withDefault": "getArgumentDefault" }""", """{ "arg": null }""".ToInputs());

    public class MySchema : Schema
    {
        public MySchema()
        {
            Query = new MyQuery();
        }
    }

    public class MyQuery : ObjectGraphType
    {
        public MyQuery()
        {
            Field<StringGraphType>("noDefault")
                .Resolve(ctx => ctx.GetArgument<string>("arg", "getArgumentDefault"))
                .Argument(typeof(StringGraphType), "arg");
            Field<StringGraphType>("withDefault")
                .Resolve(ctx => ctx.GetArgument<string>("arg", "getArgumentDefault"))
                .Argument(typeof(StringGraphType), "arg", arg => arg.DefaultValue = "fieldDefault");
        }
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8">

// create a parent container to enclose all divs

 List of counties and associated values


text:
package it.ninjatech.eventbus.model;

import java.io.Serializable;
import java.sql.Timestamp;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "event_bus_journal")
public class Event implements Serializable {

    private static final long serialVersionUID = -2915870084418741288L;

    @Id
    @Column(name = "id", nullable = true)
    private Integer id;
    @Column(name = "sendTimestamp", nullable = false)
    private Timestamp sendTimestamp;
    @Column(name = "receiveTimestamp", nullable = false)
    private Timestamp receiveTimestamp;
    @Column(name = "description", nullable = false)
    private String description;

    public Integer getId() {
        return this.id;
    }

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

    public Timestamp getSendTimestamp() {
        return this.sendTimestamp;
    }

    public void setSendTimestamp(Timestamp sendTimestamp) {
        this.sendTimestamp = sendTimestamp;
    }

    public Timestamp getReceiveTimestamp() {
        return this.receiveTimestamp;
    }

    public void setReceiveTimestamp(Timestamp receiveTimestamp) {
        this.receiveTimestamp = receiveTimestamp;
    }

    public String getDescription() {
        return this.description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

}


text:
package io.aeron.archiver;

import io.aeron.archiver.codecs.RecordingDescriptorDecoder;
import org.agrona.IoUtil;
import org.agrona.concurrent.EpochClock;
import org.agrona.concurrent.UnsafeBuffer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import java.io.File;
import java.io.IOException;
import java.nio.channels.FileChannel;

import static io.aeron.archiver.ArchiveUtil.loadRecordingDescriptor;
import static io.aeron.archiver.ArchiveUtil.recordingMetaFileName;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;

public class RecordingWriterTest
{

    private static final int RECORDING_ID = 1;
    private static final int TERM_BUFFER_LENGTH = 16 * 1024;
    private static final int MTU_LENGTH = 4 * 1024;
    private static final int INITIAL_TERM_ID = 3;
    private static final int JOIN_POSITION = 32;
    private static final int SESSION_ID = 1234;
    private static final int STREAM_ID = 0;
    private static final String CHANNEL = "channel";
    private static final String SOURCE = "source";
    private File archiveDir;
    private EpochClock epochClock = Mockito.mock(EpochClock.class);
    private final RecordingWriter.RecordingContext recordingContext = new RecordingWriter.RecordingContext();
    private FileChannel mockFileChannel = Mockito.mock(FileChannel.class);
    private UnsafeBuffer mockTermBuffer = Mockito.mock(UnsafeBuffer.class);

    @Before
    public void before() throws Exception
    {
        archiveDir = TestUtil.makeTempDir();
        recordingContext
            .recordingFileLength(1024 * 1024)
            .archiveDir(archiveDir)
            .epochClock(epochClock)
            .forceWrites(true);
    }

    @After
    public void after()
    {
        IoUtil.delete(archiveDir, false);
    }

    @Test
    public void shouldInitMetaData() throws IOException
    {

        when(epochClock.time()).thenReturn(42L);
        try (RecordingWriter ignored = new RecordingWriter(
            recordingContext,
            RECORDING_ID,
            TERM_BUFFER_LENGTH,
            MTU_LENGTH,
            INITIAL_TERM_ID,
            JOIN_POSITION,
            SESSION_ID,
            STREAM_ID,
            CHANNEL,
            SOURCE))
        {
            final RecordingDescriptorDecoder metaData = loadMetaData();
            assertEquals(RECORDING_ID, metaData.recordingId());
            assertEquals(TERM_BUFFER_LENGTH, metaData.termBufferLength());
            assertEquals(STREAM_ID, metaData.streamId());
            assertEquals(MTU_LENGTH, metaData.mtuLength());
            assertEquals(RecordingWriter.NULL_TIME, metaData.joinTimestamp());
            assertEquals(JOIN_POSITION, metaData.joinPosition());
            assertEquals(RecordingWriter.NULL_TIME, metaData.endTimestamp());
            assertEquals(JOIN_POSITION, metaData.endPosition());
            assertEquals(CHANNEL, metaData.channel());
            assertEquals(SOURCE, metaData.sourceIdentity());
            when(epochClock.time()).thenReturn(43L);
        }
        final RecordingDescriptorDecoder metaData = loadMetaData();
        assertEquals(RECORDING_ID, metaData.recordingId());
        assertEquals(TERM_BUFFER_LENGTH, metaData.termBufferLength());
        assertEquals(STREAM_ID, metaData.streamId());
        assertEquals(MTU_LENGTH, metaData.mtuLength());
        assertEquals(RecordingWriter.NULL_TIME, metaData.joinTimestamp());
        assertEquals(JOIN_POSITION, metaData.joinPosition());
        assertEquals(43L, metaData.endTimestamp());
        assertEquals(JOIN_POSITION, metaData.endPosition());
        assertEquals(CHANNEL, metaData.channel());
        assertEquals(SOURCE, metaData.sourceIdentity());
    }

    @Test
    public void verifyFirstWrite() throws IOException
    {
        when(epochClock.time()).thenReturn(42L);

        try (RecordingWriter writer = Mockito.spy(new RecordingWriter(
            recordingContext,
            RECORDING_ID,
            TERM_BUFFER_LENGTH,
            MTU_LENGTH,
            INITIAL_TERM_ID,
            JOIN_POSITION,
            SESSION_ID,
            STREAM_ID,
            CHANNEL,
            SOURCE)))
        {
            final RecordingDescriptorDecoder metaData = loadMetaData();
            assertEquals(RecordingWriter.NULL_TIME, metaData.joinTimestamp());

            when(mockFileChannel.transferTo(eq(0L), eq(256L), any(FileChannel.class))).then(invocation ->
            {
                final FileChannel dataFileChannel = invocation.getArgument(2);
                dataFileChannel.position(JOIN_POSITION + 256);
                return 256L;
            });
            writer.onBlock(
                mockFileChannel, 0, mockTermBuffer, JOIN_POSITION, 256, SESSION_ID, INITIAL_TERM_ID);
            when(epochClock.time()).thenReturn(43L);
            Mockito.verify(writer).forceData(any(FileChannel.class));
        }

        final RecordingDescriptorDecoder metaData = loadMetaData();
        assertEquals(42L, metaData.joinTimestamp());
        assertEquals(43L, metaData.endTimestamp());
        assertEquals(JOIN_POSITION, metaData.joinPosition());
        assertEquals(JOIN_POSITION + 256, metaData.endPosition());
    }

    private RecordingDescriptorDecoder loadMetaData() throws IOException
    {
        return loadRecordingDescriptor(new File(archiveDir, recordingMetaFileName(RECORDING_ID)));
    }
}


text:
class PyGLCanvas : public GLCanvas {
public:
    using GLCanvas::GLCanvas;
    NANOGUI_WIDGET_OVERLOADS(GLCanvas);

    void drawGL() {
        PYBIND11_OVERLOAD(void, GLCanvas, drawGL);
    }
};

void register_glcanvas(py::module &m) {
    py::class_<GLCanvas, Widget, ref<GLCanvas>, PyGLCanvas> glcanvas(m, "GLCanvas", D(GLCanvas));
    glcanvas
        .def(py::init<Widget *>(), py::arg("parent"), D(GLCanvas, GLCanvas))
        .def("backgroundColor", &GLCanvas::backgroundColor, D(GLCanvas, backgroundColor))
        .def("setBackgroundColor", &GLCanvas::setBackgroundColor, D(GLCanvas, setBackgroundColor))
        .def("drawBorder", &GLCanvas::drawBorder, D(GLCanvas, drawBorder))
        .def("setDrawBorder", &GLCanvas::setDrawBorder, D(GLCanvas, setDrawBorder))
        .def("drawGL", &GLCanvas::drawGL, D(GLCanvas, drawGL));
}

#endif


text:
<?php

namespace Symfony\Component\HttpKernel\DataCollector;

use Symfony\Component\ErrorHandler\Exception\FlattenException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 *
 * @final
 */
class ExceptionDataCollector extends DataCollector
{
    /**
     * {@inheritdoc}
     */
    public function collect(Request $request, Response $response, \Throwable $exception = null)
    {
        if (null !== $exception) {
            $this->data = [
                'exception' => FlattenException::createFromThrowable($exception),
            ];
        }
    }

    /**
     * {@inheritdoc}
     */
    public function reset()
    {
        $this->data = [];
    }

    public function hasException(): bool
    {
        return isset($this->data['exception']);
    }

    /**
     * @return \Exception|FlattenException
     */
    public function getException()
    {
        return $this->data['exception'];
    }

    public function getMessage(): string
    {
        return $this->data['exception']->getMessage();
    }

    public function getCode(): int
    {
        return $this->data['exception']->getCode();
    }

    public function getStatusCode(): int
    {
        return $this->data['exception']->getStatusCode();
    }

    public function getTrace(): array
    {
        return $this->data['exception']->getTrace();
    }

    /**
     * {@inheritdoc}
     */
    public function getName(): string
    {
        return 'exception';
    }
}