text:
package com.planet_ink.coffee_mud.core.intermud.packets;
import com.planet_ink.coffee_mud.core.intermud.server.*;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.Vector;

@SuppressWarnings("unchecked")
public class ChannelListen extends Packet  {
    public String channel = null;
	public String onoff="0";

	public ChannelListen()
	{
		super();
        type = ChannelPacket.CHAN_LISTEN;
	}
    public ChannelListen(Vector v) throws InvalidPacketException {
        super(v);
        try {
			type = ChannelPacket.CHAN_LISTEN;
			channel = (String)v.elementAt(6);
			onoff = (String)v.elementAt(7);
        }
        catch( ClassCastException e ) {
            throw new InvalidPacketException();
        }
    }

    public ChannelListen(int t, String chan, String setonoff) {
        super();
        type = t;
        channel = chan;
		onoff=setonoff;
    }

    public void send() throws InvalidPacketException {
        if( channel == null  ) {
            throw new InvalidPacketException();
        }
        super.send();
    }

    public String toString() {
        NameServer n = Intermud.getNameServer();
		String str=
			 "({\"channel-listen\",5,\"" + Server.getMudName() + "\",0,\""+n.name+"\",0,\"" + channel + "\"," +
               onoff + ",})";
		return str;
    }
}


text:
#!/usr/bin/env python
"""Writing for HTML pages."""

import distutils.dir_util
import json
import os
import os.path
import shutil
import sys
import xml.sax.saxutils
import urllib

import jinja2
import proc_doc
import raw_doc

def escapeForXml(s):
    """Return escaped XML of s."""
    return xml.sax.saxutils.escape(s)

def escapeName(name):
    """Escape a name such that it is safe to use for files and anchors."""
    """TODO(rmaerker): Encode special chars using urllib.quote(c.encode('utf8'))"""
    escape = '_'
    xs = []
    for c in name:
        if c.isalnum() or c in ['-']:
            xs.append(c)
        else:
            xs += [escape, str(ord(c))]
    return ''.join(xs)

def escapeAnchor(name):
    """Escape a name such that it is safe to use for anchors."""
    return name

class PathManager(object):
    """Handles the path and link generation."""

    def __init__(self, out_dir):
        self.out_dir = out_dir
        self.this_dir = os.path.dirname(os.path.realpath(__file__))

    def getTplPath(self, path):
        """Returns path to template."""
        return os.path.join(self.this_dir, 'tpl', path)

    def getEntryPath(self, entry):
        """Returns target path for page for entry."""
        path = '%s_%s.html' % (entry.kind, escapeName(entry.name))
        return os.path.join(self.out_dir, path)

    def getTopFramesetPath(self):
        """Returns target path for top frameset."""
        return os.path.join(self.out_dir, 'index.html')

    def getListPath(self):
        """Returns target path for list."""
        return os.path.join(self.out_dir, 'list.html')

    def translateDemoPath(self, path):
        """Translate demo path."""
        return path

class TextNodeToHtml(object):
    def __init__(self, text_node, skip_top_tag=None, start_heading=2, path_mgr=None):
        self.skip_top_tag = skip_top_tag
        self.text_node = text_node
        self.res = []
        self.start_heading = start_heading
        self.heading_table = {}
        self.path_mgr = path_mgr
        for i in range(0, 10):
            self.heading_table['h%d' % i] = 'h%d' % (i + start_heading - 1)

    def openTag(self, text_node, **kwargs):
        if text_node.raw_html:
            res = ['<', text_node.type]
        else:
            res = ['<', self.heading_table.get(text_node.type, text_node.type)]
        for key, value in text_node.attrs.iteritems():
            res += [' ', key, '=', '"', repr(value)[1:-1], '"']
        for key, value in kwargs.iteritems():
            res += [' ', key, '=', '"', value, '"']
        res.append('>')
        return res

    def closeTag(self, text_node):
        if text_node.raw_html:
            return ['</', text_node.type, '>']
        else:
            return ['</', self.heading_table.get(text_node.type, text_node.type), '>']

    def convertCode(self, source_code):
        # TODO(holtgrew): Interpret source type.
        try:
            import pygments, pygments.lexers, pygments.formatters
            return pygments.highlight(
                source_code, pygments.lexers.CppLexer(),
                pygments.formatters.HtmlFormatter(style='friendly'))
        except ImportError:
            return '
' + escapeForXml(source_code) + '
'
        return

    def handleTag(self, text_node):
        if text_node.type == '<text>':
            self.res.append(text_node.text)
        elif text_node.type == 'dox:code':
            target_path = text_node.attrs.get('path')
            if text_node.attrs.get('type') in ['.cpp', '.h']:
                self.res.append('
%s' %
                                (target_path, self.convertCode(text_node.children[0].text)))
                if self.path_mgr:
                    target_path = self.path_mrg.translateDemoPath(self.path_mgr)
                if text_node.attrs.get('source') == 'snippet':
                    self.res.append(
                        '
Snippet from:'
                        ' %s
' %
                        (target_path, text_node.attrs.get('path')))
                elif text_node.attrs.get('source') == 'include':
                    self.res.append(
                        '
Demo:'
                        ' %s
' %
                        (target_path, text_node.attrs.get('path')))
                self.res.append('
')
            elif text_node.attrs.get('type') in ['.console', '.stdout', '.stderr']:
                self.res.append('
%s
' %
                                (target_path, escapeForXml(text_node.children[0].text)))
            else:
                self.res.append('
%s
' %
                                (target_path, escapeForXml(text_node.children[0].text)))
        else:
            self.res += self.openTag(text_node)
            for c in text_node.children:
                self.handleTag(c)
            self.res += self.closeTag(text_node)

    def convert(self):
        if not self.text_node:
            return None
        if not self.skip_top_tag:
            self.res += self.openTag(self.text_node)
        for c in self.text_node.children:
            self.handleTag(c)
        if not self.skip_top_tag:
            self.res += self.closeTag(self.text_node)
        return ''.join(self.res)

def toDox(proc_entry, line_length=110, in_comment=False):
    """Process a ProcEntry into the dox-like format."""
    formatter = raw_doc.DoxFormatter()
    result = []
    result.append(proc_entry.raw_entry.getFormatted(formatter))
    for key, lst in proc_entry.subentries.iteritems():
        for elem in lst:
            result.append(elem.raw_entry.getFormatted(formatter))
    if in_comment:
        result = [' * ' + l for line in result for l in line.splitlines(False)]
        while result and result[-1] == ' * ':
            result.pop(-1)
        result = ['/*!'] + result + [' */']
    return '\n'.join(result)

def transTextNode(text_node, top=True, start_heading=3, path_mgr=None, **kwargs):
    #return text_node.toHtmlLike(skip_top_tag=not top)
    converter = TextNodeToHtml(text_node, skip_top_tag=not top, start_heading=start_heading, path_mgr=path_mgr)
    return converter.convert() or ''

def createTransLink(doc, path_mgr):
    link_converter = LinkConverter(doc)
    def transLink(entity_name, text=None):
        if not text:
            text = entity_name
        text_node = proc_doc.TextNode(type='a')
        text_node.attrs['href'] = 'seqan:%s' % entity_name
        text_node.children = [proc_doc.TextNode(text=text)]
        link_converter.visit(text_node)
        return transTextNode(text_node, path_mgr)
    return transLink

def createNameToPath(doc):
    path_converter = PathConverter(doc)
    def convertPath(entry_name):
        return path_converter.convert(entry_name)[0]
    return convertPath

class TemplateManager(object):
    def __init__(self, path_manager, doc):
        self.path_manager = path_manager
        self.env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.join(self.path_manager.this_dir, 'tpl')))
        def identity(x):
            return x
        self.env.filters['escape_name'] = escapeName
        self.env.filters['escape_anchor'] = escapeAnchor
        self.env.filters['url_encode'] = urllib.quote
        self.env.filters['transtext'] = transTextNode
        self.env.filters['to_dox'] = toDox
        self.env.filters['translink'] = createTransLink(doc, self)
        self.env.filters['name_to_path'] = createNameToPath(doc)
        self.env.filters['tojson'] = json.dumps
        self.tpls = {}
        for path in ['page.html', 'concept.html']:
            self.loadTemplate(path)

    def loadTemplate(self, path):
        """Load template string at path."""
        self.tpls[path] = self.env.get_template(path)

    def render(self, path, **kwargs):
        if not path in self.tpls:
            self.loadTemplate(path)
        return self.tpls[path].render(**kwargs)

class PathConverter(object):
    """Convert entry names to URL fragments (filename + anchor)."""

    def __init__(self, doc):
        self.doc = doc

    def convert(self, name):
        """Return None, None on failure path, title otherwise."""
        if self.doc.top_level_entries.get(name):
            entry = self.doc.top_level_entries.get(name)
            path = '%s_%s.html' % (entry.kind, escapeName(entry.name))
            title = None
            if entry.kind == 'page':
                title = entry.title
            return path, title, entry
        elif self.doc.entries.get(name):
            first, second = proc_doc.splitSecondLevelEntry(name)
            father = self.doc.top_level_entries.get(first)
            entry = self.doc.second_level_entries.get(name)
            path = '%s_%s.html#%s' % (father.kind, escapeName(father.name), escapeAnchor(name))
            return path, name, entry
        else:
            return None, None, None

# TODO(holtgrew): Should be doable in a simpler way than recursing ourselves here.  Visitor pattern for TextNode?
class LinkConverter(proc_doc.TextNodeVisitor):
    """Convert raw links to HTML-like links.

    Raw links are links of the form $label.
    """

    def __init__(self, doc):
        self.doc = doc
        self.path_converter = PathConverter(doc)

    def visit(self, text_node):
        if not text_node or text_node.type == '<text>':
            return
        if text_node.type == 'a':
            self._translateLink(text_node)
        else:
            for i, c in enumerate(text_node.children):
                text_node.children[i] = self._replaceNode(c)

    def _translateLink(self, a_node):
        if not a_node.attrs.get('href', '').startswith('seqan:'):
            return
        target = a_node.attrs['href'][6:]
        target_path, target_title, target_obj = self.path_converter.convert(target)
        # Shorten path title if not manually specified.
        if (a_node.children and a_node.plainText == target_title and
           self.doc.local_name_counter.get(target_title, 1) <= 1):
            short_title = proc_doc.splitSecondLevelEntry(target_title)[1]
            a_node.children = [proc_doc.TextNode(text=short_title)]
        if target_title:
            target_title = proc_doc.TextNode(text=target_title)
        else:
            target_title = proc_doc.TextNode(text=target)
        # TODO(holtgrew): Catch target_title being None, target_path not found!
        if target_path is not None:
            if target_obj:
                a_node.attrs['data-lang-entity'] = target_obj.kind
            a_node.attrs['href'] = target_path
            if not a_node.children:
                a_node.addChild(target_title)
        else:
            class_attr = a_node.attrs.get('class', '')
            if class_attr:
                class_attr += ' '
            class_attr += 'error'
            a_node.attrs['class'] = class_attr
            if a_node.attrs.get('href'):
                del a_node.attrs['href']
            #a_node.addChild(target_title)

    def _replaceNode(self, text_node):
        if text_node.type == '<text>':
            return text_node
        if text_node.type == 'a':
            self._translateLink(text_node)
        for i, c in enumerate(text_node.children):
            text_node.children[i] = self._replaceNode(c)
        return text_node

class ImagePathUpdater(proc_doc.TextNodeVisitor):
    """Update image paths to target image path."""

    def __init__(self, doc, prefix):
        self.doc = doc
        self.prefix = prefix

    def visit(self, text_node):
        if not text_node or text_node.type == '<text>':
            return
        if text_node.type == 'img':
            self._updateImagePath(text_node)
        else:
            for i, c in enumerate(text_node.children):
                text_node.children[i] = self._replaceNode(c)

    def _updateImagePath(self, img_node):
        if not img_node.attrs.get('src'):
            return  # No path.
        img_node.attrs['src'] = os.path.join(self.prefix, img_node.attrs['src'])

    def _replaceNode(self, text_node):
        if text_node.type == '<text>':
            return text_node
        if text_node.type == 'img':
            self._updateImagePath(text_node)
        for i, c in enumerate(text_node.children):
            text_node.children[i] = self._replaceNode(c)
        return text_node

class HtmlWriter(object):
    def __init__(self, doc, args, config, out_dir='html'):
        self.doc = doc
        self.out_dirs = {}
        self.args = args
        self.config = config
        # Normalize path.
        out_dir = os.path.abspath(out_dir)
        # Generate path names.
        self.out_dirs['root'] = out_dir
        self.out_dirs['css'] = os.path.join(out_dir, 'css')
        self.out_dirs['img'] = os.path.join(out_dir, 'img')
        self.out_dirs['js'] = os.path.join(out_dir, 'js')
        self.out_dirs['lib'] = os.path.join(out_dir, 'lib')
        self.out_dirs['lists'] = os.path.join(out_dir, 'lists')
        self.out_dirs['docs'] = os.path.join(out_dir, 'docs', 'seqan')
        # Create managers.
        self.path_manager = PathManager(out_dir)
        self.tpl_manager = TemplateManager(self.path_manager, doc)
        self.path_converter = PathConverter(doc)

    def generateFor(self):
        self.log('Generating HTML documentation')
        self.log('Output Directory: %s', self.out_dirs['root'])
        self.makedirs()
        self.copyStaticFiles()
        self.copyDocImages()
        self.generateTopFrameSet()
        self.generateLists(self.doc)
        self.translateLinks(self.doc)
        self.updateImagePaths(self.doc)
        self.generatePages(self.doc, self.config)
        self.generateDemoPages(self.doc)
        self.generateSearchIndex(self.doc)
        self.generateLinkData(self.doc)
        self.generateLanguageEntities()

    def makedirs(self):
        for path in self.out_dirs.values():
            if not os.path.exists(path):
                #self.log('Creating directory %s', path)
                os.makedirs(path)

    def copyStaticFiles(self):
        """Copy static files."""
        for kind in ['css', 'js', 'img', 'lib']:
            in_dir = os.path.join(self.path_manager.this_dir, 'tpl/%s' % kind)
            out_path = self.out_dirs[kind]
            self.log('  Copying %s => %s', in_dir, out_path)
            distutils.dir_util.copy_tree(in_dir, out_path, verbose=True)

    def copyDocImages(self):
        """Copy images from paths given in --image-dir parameter."""
        for image_dir in self.args.image_dirs:
            join = os.path.join  # shortcut
            files = [f for f in os.listdir(image_dir)
                     if os.path.isfile(join(image_dir, f))]
            for f in files:
                in_path = join(image_dir, f)
                out_path = os.path.join(self.out_dirs['img'], f)
                #self.log('  Copying %s => %s', in_path, out_path)
                shutil.copy(in_path, out_path)

    def generateTopFrameSet(self):
        """Generate frameset."""
        html = self.tpl_manager.render('index.html',
                                       development=self.args.development)  # TODO(holtgrew): Add title.
        with open(self.path_manager.getTopFramesetPath(), 'w') as f:
            f.write(html)

    def generateLists(self, doc):
        """Generate top level/second level/page index."""
        with open(self.path_manager.getListPath(), 'w') as f:
            f.write(self.tpl_manager.render('list.html', doc=doc, config=self.config,
                                            development=self.args.development))

    def translateLinks(self, doc):
        link_converter = LinkConverter(doc)
        for proc_entry in doc.entries.values():
            #self.log('    * %s', proc_entry.name)
            proc_entry.visitTextNodes(link_converter)

    def updateImagePaths(self, doc):
        """Appends image output directory to src attributes."""
        updater = ImagePathUpdater(doc, 'img')
        for proc_entry in doc.entries.values():
            #self.log('    * %s', proc_entry.name)
            proc_entry.visitTextNodes(updater)

    def generatePages(self, doc, config):
        """Generate pages for proc_doc.Documentation entries."""
        try:
            import pygments, pygments.lexers, pygments.formatters
            pygments_style = pygments.formatters.HtmlFormatter().get_style_defs('.highlight')
        except ImportError:
            pygments_style = ''

        for entry in doc.top_level_entries.values():
            path = self.path_manager.getEntryPath(entry)
            #self.log('Creating %s', path)
            self.generatePage(entry, path, doc, config, pygments_style)

    def generatePage(self, entry, path, doc, config, pygments_style):
        """Generate page for entry to file at path."""

        common_kwargs = {'doc': doc,
                         'config': config,
                         'development': self.args.development,
                         'pygments_style': pygments_style,
                         'entry_kind': entry.kind,
                         'entry_name': entry.name}
        if entry.kind == 'page':
            html = self.tpl_manager.render('page.html', page=entry,  **common_kwargs)
        elif entry.kind == 'concept':
            html = self.tpl_manager.render('concept.html', concept=entry,  **common_kwargs)
        elif entry.kind in ['class', 'specialization']:
            html = self.tpl_manager.render('class.html', klass=entry,  **common_kwargs)
        elif entry.kind == 'enum':
            html = self.tpl_manager.render('enum.html', enum=entry,  **common_kwargs)
        elif entry.kind == 'adaption':
            html = self.tpl_manager.render('adaption.html', adaption=entry,  **common_kwargs)
        elif entry.kind == 'shortcut':
            html = self.tpl_manager.render('shortcut.html', shortcut=entry,  **common_kwargs)
        elif entry.kind in ['global_function', 'member_function', 'interface_function']:
            html = self.tpl_manager.render('function.html', function=entry,  **common_kwargs)
        elif entry.kind in ['global_metafunction', 'interface_metafunction']:
            html = self.tpl_manager.render('metafunction.html', metafunction=entry,  **common_kwargs)
        elif entry.kind == 'group':
            html = self.tpl_manager.render('group.html', group=entry,  **common_kwargs)
        elif entry.kind == 'tag':
            html = self.tpl_manager.render('tag.html', tag=entry,  **common_kwargs)
        elif entry.kind == 'macro':
            html = self.tpl_manager.render('macro.html', macro=entry,  **common_kwargs)
        elif entry.kind == 'global_typedef':
            html = self.tpl_manager.render('typedef.html', typedef=entry,  **common_kwargs)
        elif entry.kind == 'global_variable':
            html = self.tpl_manager.render('variable.html', variable=entry,  **common_kwargs)
        elif entry.kind == 'variable':
            html = self.tpl_manager.render('variable.html', variable=entry,  **common_kwargs)
        else:
            assert False, entry.kind
        with open(self.path_manager.getEntryPath(entry), 'w') as f:
            f.write(html)

    def generateDemoPages(self, doc):
        """Copy over all demo pages."""
        file_names = set(doc.doc_processor.include_mgr.file_cache.keys() +
                         [x[0] for x in doc.doc_processor.include_mgr.snippet_cache.keys()])
        for path in sorted(file_names):
            self.generateDemoPage(path)

    def generateDemoPage(self, path):
        """Generate a demo page."""
        dirname = os.path.join(self.out_dirs['root'], os.path.dirname(path))
        if not os.path.exists(dirname):
            os.makedirs(dirname)
        in_path = self.doc.doc_processor.include_mgr.resolvePath(path)
        to_path = os.path.join(self.out_dirs['root'], path)
        #print >>sys.stderr, in_path, '=>', to_path
        shutil.copyfile(in_path, to_path)

    def generateSearchIndex(self, doc):
        """Generate the search index."""
        js = ['window.searchData = [']
        for entry in doc.top_level_entries.itervalues():
            akas, subentries = '', ''
            if hasattr(entry, 'akas'):
                akas = ','.join(entry.akas)
            if hasattr(entry, 'subentries'):
                subentries = []
                for t in entry.subentries.values():
                    for s in t:
                        sID = s.title
                        title = proc_doc.splitSecondLevelEntry(s.title)[1]
                        subentries.append({'type': s.kind, 'name': s.name, 'title': title, 'id': sID})
            js.append('  {title:%s,name:%s,text:%s,akas:%s,subentries:%s,loc:%s,langEntity:%s},' %
                      (repr(entry.title), repr(entry.name), repr(""), repr(akas), repr(subentries),
                       repr(self.path_converter.convert(entry.name)[0]),
                       repr(entry.kind)))
        js.append('];')
        with open(os.path.join(self.out_dirs['js'], 'search.data.js'), 'wb') as f:
            f.write('\n'.join(js))

    def generateLinkData(self, doc):
        """Generate the Data for top level entry links."""
        js = ['window.lookup = {']
        for entry in doc.top_level_entries.itervalues():
            js.append('    \'%(name)s\': \'%(kind)s_%(name)s\',' % { 'name': entry.name,
                                                                     'kind': entry.kind })
        js.append('};')
        with open(os.path.join(self.out_dirs['js'], 'link.data.js'), 'wb') as f:
            f.write('\n'.join(js))

    def generateLanguageEntities(self):
        """Generate language entities JavaScript file."""
        js = self.tpl_manager.render('js/lang_entities.js', config=self.config,
                                     development=self.args.development)
        with open(os.path.join(self.out_dirs['js'], 'lang_entities.js'), 'wb') as f:
            f.write(js)

    def log(self, s, *args):
        print >>sys.stderr, s % args

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE form-validation PUBLIC
    "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1//EN"
    "http://jakarta.apache.org/commons/dtds/validator_1_1.dtd">

<form-validation>

    <formset>
		<form name="articleVO">
			<field property="nttSj" depends="required, maxlength">
        		<arg0 key="comCopBbs.articleVO.regist.nttSj" />
        		<arg1 key="1200" resource="false"/>
				<var>
					<var-name>maxlength</var-name>
					<var-value>1200</var-value>
				</var>
			</field>
			<field property="nttCn" depends="required">
        		<arg0 key="comCopBbs.articleVO.regist.nttCn" />
			</field>
		</form>
    </formset>

</form-validation>


text:
<?php	 defined('C5_EXECUTE') or die("Access Denied.");?>

<?php echo Loader::helper('concrete/dashboard')->getDashboardPaneHeaderWrapper(t('Debug Level'), false, 'span6 offset3', false)?>

<form method="post" id="debug-form" action="<?php echo $this->url('/dashboard/system/environment/debug', 'update_debug')?>">

<?php echo $this->controller->token->output('update_debug')?>

	<input type="radio" name="debug_level" value="<?php echo DEBUG_DISPLAY_PRODUCTION?>" <?php  if ($debug_level == DEBUG_DISPLAY_PRODUCTION) { ?> checked <?php  } ?> /> <?php echo t('Hide errors from site visitors.')?>

	<input type="radio" name="debug_level" value="<?php echo DEBUG_DISPLAY_ERRORS?>" <?php  if ($debug_level == DEBUG_DISPLAY_ERRORS) { ?> checked <?php  } ?> /> <?php echo t('Show errors in page.')?>

	<?php
	print $interface->submit(t('Save'), 'debug-form', 'right','primary');
	?>

</form>
<?php echo Loader::helper('concrete/dashboard')->getDashboardPaneFooterWrapper(false);?>


text:
package com.baidu.inf.iis.bcs.auth;

public enum SigningAlgorithm {
	HmacSHA1, HmacSHA256;
}


text:
using namespace ocl;

//static initialisation
std::shared_ptr<oclFactory> oclFactory::instance;

std::shared_ptr<oclFactory> oclFactory::eInstance()
{
	if(!instance)
	{
		//create a new Factoryimplementation
		instance.reset(oclFactoryImpl::create());
	}
	return instance;
}


text:
/*
 *  This file is part of ngrest: http://github.com/loentar/ngrest
 */

#ifndef NGREST_UTILS_FILE_H
#define NGREST_UTILS_FILE_H

#include <list>
#include <string>
#include <stdint.h>
#include "ngrestutilsexport.h"

#ifdef WIN32
#define NGREST_PATH_SEPARATOR "\\"
#else
#define NGREST_PATH_SEPARATOR "/"
#endif

namespace ngrest {

typedef std::list<std::string> StringList; //!< list of strings

/**
 * @brief file finder
 */
class NGREST_UTILS_EXPORT File
{
public:
    /**
     * @brief file attributes
     */
    enum Attribute
    {
        AttributeNone = 0,          //!< not a file nor directory
        AttributeDirectory = 1,     //!< directory
        AttributeRegularFile = 2,   //!< regular file
        AttributeOtherFile = 4,     //!< not a regular file (symlink, pipe, socket, etc...)
        AttributeAnyFile =          //!< any file (regular, symlink, pipe, socket, etc...)
        AttributeRegularFile | AttributeOtherFile,
        AttributeAny =              //!< any file or directory
        AttributeAnyFile | AttributeDirectory
    };

public:
    /**
     * @brief constructor
     * @param path - path to the file or directory
     */
    File(const std::string& path);

    /**
     * @brief find files/directories by name
     * @param list - resulting list of files/directories
     * @param mask - file mask (shell pattern)
     * @param attrs - match by attributes
     */
    void list(StringList& list, const std::string& mask = "*", int attrs = AttributeAny);

    /**
     * @brief get file/directory attributes
     * if file does not exists returns AttributeNone
     * @return attributes
     */
    int getAttributes();

    /**
     * @brief test whether the file or directory exists
     * @return true if the file or directory exists
     */
    bool isExists();

    /**
     * @brief tests whether path is a directory
     * @return true if path is a directory
     */
    bool isDirectory();

    /**
     * @brief tests whether path is a regular file
     * @return true if path is a regular file
     */
    bool isRegularFile();

    /**
     * @brief tests whether path is not a regular file (symlink, pipe, socket, etc...)
     * @return true if path is not a regular file
     */
    bool isSystemFile();

    /**
     * @brief tests whether path is any file
     * @return true if path is any file
     */
    bool isFile();

    /**
     * @brief get file's last modification time
     * @return unix time
     */
    int64_t getTime();

    /**
     * @brief create the directory
     * @return true if the directory was created
     */
    bool mkdir();

    /**
     * @brief create the directory, including parent directories
     * @return true if the directory was created
     */
    bool mkdirs();

    /**
     * @brief is file name = "." or ".."
     * @param name - filename
     * @return true if file name = "." or ".."
     */
    static bool isDots(const char* name);

    /**
     * @brief is file name = "." or ".."
     * @param name - filename
     * @return true if file name = "." or ".."
     */
    static bool isDots(const std::string& name);

private:
    std::string path; //!< path to the file or directory
};
}

#endif // NGREST_UTILS_FILE_H


text:
package com.wordty.common.excel.eventusermodel.xlsx.handler;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

public class WorkbookXMLTable extends DefaultHandler
{
	private Map<String, Sheet> sheets = new HashMap<String, Sheet>();

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
	{
		if( "sheet".equals(qName) ){
			sheets.put(attributes.getValue("name"),
					new Sheet(attributes.getValue("name"), attributes.getValue("sheetId"), attributes.getValue("r:id")));
		}
	}

	public WorkbookXMLTable(XSSFReader xssfReader) throws Exception
	{
		XMLReader xmlReader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
		xmlReader.setContentHandler(this);
		InputStream inp = xssfReader.getWorkbookData();
		xmlReader.parse(new InputSource(inp));

		inp.close();
	}

	public String getSheetRId(String sheetName){
		Sheet sheet = sheets.get(sheetName);
		return null != sheet ? sheet.rId : null;
	}

	public static final class Sheet{
		public String name;
		public String sheetId;
		public String rId;

		public Sheet(String name, String sheetId, String rId)
		{
			super();
			this.name = name;
			this.sheetId = sheetId;
			this.rId = rId;
		}
	}
}


text:
(function() {

  describe('peculiar.filter.filterDir', function() {

    var element,
        scope;

    beforeEach(function() {
      module('src/peculiar/filter/tpls/filter.tpl.html');
      module('peculiar.filter');
    });

    beforeEach(function() {
      this.addMatchers({
        toHaveClass: function(className) {
          return this.actual.hasClass(className);
        }
      });
    });

    beforeEach(inject(['$rootScope','$compile', function($rootScope, $compile) {

      element = angular.element(
        '<pu-filter>' +
        '</pu-filter>'
      );

      scope = $rootScope;
      $compile(element)(scope);
      scope.$digest();

    }]));

    it('should add correct classes', function() {
      expect(element[0]).not.toBeNull();
      expect(element).toHaveClass('pu-filter-toggle');
    });

  });

}());


text:
package org.gsm.oneapi.responsebean.mms;

/**
 * Contains the detail of a delivery info notification response sent from the OneAPI server
 */
public class DeliveryInfoNotification implements java.io.Serializable {
	private static final long serialVersionUID = 3973280745230276281L;

	/**
	 * The inner class DeliveryInfo contains pairings of the recipient address and a textual delivery status
	 */
	public static class DeliveryInfo {
		/**
		 * The address of the recipient (normally MSISDN)
		 */
		private String address=null;
		/**
		 * Delivery status may be one of
		 * "DeliveredToTerminal", successful delivery to Terminal.
		 * "DeliveryUncertain", delivery status unknown: e.g. because it was handed off to another network.
		 * "DeliveryImpossible", unsuccessful delivery; the message could not be delivered before it expired.
		 * "MessageWaiting" , the message is still queued for delivery. This is a temporary state, pending transition to one of the preceding states.
		 * "DeliveredToNetwork", successful delivery to the network enabler responsible for routing the MMS
		 */
		private String deliveryStatus=null;

		/**
		 * return the address of the recipient (normally MSISDN)
		 */
		public String getAddress() { return address; }
		/**
		 * return the delivery status for this recipient
		 */
		public String getDeliveryStatus() { return deliveryStatus; }

		/**
		 * set the recipient address. This is called internally to set the contents according to the JSON response.
		 */
		public void setAddress(String address) { this.address=address; }
		/**
		 * set the deliveryStatus. This is called internally to set the contents according to the JSON response.
		 */
		public void setDeliveryStatus(String deliveryStatus) { this.deliveryStatus=deliveryStatus; }

		/**
		 * default constructor
		 */
		public DeliveryInfo() {

		}

		/**
		 * utility constructor to create a DeliveryInfo instance with all fields set
		 * @param address
		 * @param deliveryStatus
		 */
		public DeliveryInfo(String address, String deliveryStatus) {
			this.address=address;
			this.deliveryStatus=deliveryStatus;
		}

		/**
		 * generate a textual representation of the DeliveryInfo contents
		 */
		public String toString() {
			StringBuffer buffer=new StringBuffer();
			buffer.append("address = ");
			buffer.append(address);
			buffer.append(", deliveryStatus = ");
			buffer.append(deliveryStatus);
			return buffer.toString();
		}
	}

	/**
	 * the deliveryInfoList object contains the delivery information for each address that you asked to send the message to, in a deliveryInfo array.
	 */
	DeliveryInfo[] deliveryInfo=null;
	/**
	 * return the array of deliveryInfo pairs of address/ deliveryStatus
	 */
	public DeliveryInfo[] getDeliveryInfo() { return deliveryInfo; }
	/**
	 * set the array of deliveryInfo pairs of address/ deliveryStatus. This is called internally to set the contents according to the JSON response.
	 */
	public void setDeliveryInfo(DeliveryInfo[] deliveryInfo) { this.deliveryInfo=deliveryInfo; }

	/**
	 * details user requested data to be sent along with the callback notification
	 */
	String callbackData=null;
	/**
	 * return the user data that will be sent along with the callback notification
	 */
	public String getCallbackData() { return callbackData; }
	/**
	 * set the user data field that will be sent along with the callback notification
	 * @param callbackData
	 */
	public void setCallbackData(String callbackData) { this.callbackData=callbackData; }

	/**
	 * generate a textual representation of the DeliveryInfoList instance including nested elements and classes
	 */
	public String toString() {
		StringBuffer buffer=new StringBuffer();
		if (deliveryInfo!=null) {
			buffer.append("deliveryInfo = {");
			for (int i=0; i<deliveryInfo.length; i++) {
				buffer.append("[");
				buffer.append(i);
				buffer.append("] = {");
				if (deliveryInfo[i]!=null) buffer.append(deliveryInfo[i].toString());
				buffer.append("} ");
			}
			buffer.append("} ");
		}
		buffer.append(",callbackData = ");
		buffer.append(callbackData);
		return buffer.toString();
	}

}


text:
Title: Exercise 9
Date: 2014-11-14 10:12PM

And now for the second exericse I'm doing tonight, [exercise 9](https://learnpythonthehardway.org/book/ex9.html).

```
# Exercise 9
# https://learnpythonthehardway.org/book/ex9.html

# Here's some new strange stuff, remember type it exactly.

days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"

print "Here are the days: ", days
print "Here are the months: ", months

print """
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5 or 6.
"""
```

![Exercise 09]({filename}/images/ex09.png "Exercise 09")

`%r` prints the new lines, which is interesting because I've been using `\n` for new lines for so long, I don't remember where I learned it or what convention it follows. It turns out Python is [following Unix-style convention](https://docs.python.org/2/library/stdtypes.html#file.newlines), and Wikipedia has a [long, long entry on newlines](http://en.wikipedia.org/wiki/Newline).

Interestingly, I didn't know you could print a [docstring](https://www.python.org/dev/peps/pep-0257/#multi-line-docstrings), or even that it would print literally.

From the common student questions:

> Is it bad that my errors are always spelling mistakes?

If you've ever worked with a developer, then know that he or she will say at least once (and likely many times) when code doesn't work: "It would help if I could spell correctly."


text:
package eu.chargetime.ocpp.jsonclientimplementation.ocpphandler;

import eu.chargetime.ocpp.feature.profile.ClientCoreEventHandler;
import eu.chargetime.ocpp.model.core.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;

@TestConfiguration
@Slf4j
public class ClientCoreEventHandlerConfig {

    @Bean
    public ClientCoreEventHandler configTestClient() {
        return new ClientCoreEventHandler() {
            @Override
            public ChangeAvailabilityConfirmation handleChangeAvailabilityRequest(ChangeAvailabilityRequest request) {

                System.out.println(request);
                // ... handle event

                return new ChangeAvailabilityConfirmation(AvailabilityStatus.Accepted);
            }

            @Override
            public GetConfigurationConfirmation handleGetConfigurationRequest(GetConfigurationRequest request) {

                System.out.println(request);
                // ... handle event

                return null; // returning null means unsupported feature
            }

            @Override
            public ChangeConfigurationConfirmation handleChangeConfigurationRequest(ChangeConfigurationRequest request) {

                System.out.println(request);
                // ... handle event

                return null; // returning null means unsupported feature
            }

            @Override
            public ClearCacheConfirmation handleClearCacheRequest(ClearCacheRequest request) {

                System.out.println(request);
                // ... handle event

                return null; // returning null means unsupported feature
            }

            @Override
            public DataTransferConfirmation handleDataTransferRequest(DataTransferRequest request) {

                System.out.println(request);
                // ... handle event

                return null; // returning null means unsupported feature
            }

            @Override
            public RemoteStartTransactionConfirmation handleRemoteStartTransactionRequest(RemoteStartTransactionRequest request) {

                System.out.println(request);
                // ... handle event

                return null; // returning null means unsupported feature
            }

            @Override
            public RemoteStopTransactionConfirmation handleRemoteStopTransactionRequest(RemoteStopTransactionRequest request) {

                System.out.println(request);
                // ... handle event

                return null; // returning null means unsupported feature
            }

            @Override
            public ResetConfirmation handleResetRequest(ResetRequest request) {

                System.out.println(request);
                // ... handle event

                return null; // returning null means unsupported feature
            }

            @Override
            public UnlockConnectorConfirmation handleUnlockConnectorRequest(UnlockConnectorRequest request) {

                System.out.println(request);
                // ... handle event

                return null; // returning null means unsupported feature
            }
        };
    }
}


text:
package org.squiddev.cctweaks.api.block;

import net.minecraft.block.state.IBlockState;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
import org.squiddev.cctweaks.api.ActionResult;

import javax.annotation.Nonnull;

/**
 * A handler which attempts to rotate blocks
 */
public interface IRotationHandler {
	/**
	 * Attempt to rotate the block in a set direction
	 *
	 * @param world         The world the block is in
	 * @param pos           The position the block is in
	 * @param state         The current block state
	 * @param facing        The new direction to face
	 * @param rotatorFacing The direction the rotator is facing. Will be {@link EnumFacing#NORTH} if unknown.
	 * @return Whether rotating the block was successful
	 */
	@Nonnull
	ActionResult rotate(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull IBlockState state, @Nonnull EnumFacing facing, @Nonnull EnumFacing rotatorFacing);
}


text:
Default Value

Appears when creating a new post

Default Value

        <input type="text" class="form-control" placeholder="" value="{{ $options->defaultvalue or '' }}">


text:
#include "blis.h"

extern trsm_t* trsm_l_cntl;
extern trsm_t* trsm_r_cntl;

//
// Define object-based interface.
//
void bli_trsm( side_t  side,
               obj_t*  alpha,
               obj_t*  a,
               obj_t*  b )
{
	trsm_t* cntl;
	obj_t   a_local;
	obj_t   b_local;
	obj_t   c_local;

	// Check parameters.
	if ( bli_error_checking_is_enabled() )
		bli_trsm_check( side, alpha, a, b );

	// If alpha is zero, scale by beta and return.
	if ( bli_obj_equals( alpha, &BLIS_ZERO ) )
	{
		bli_scalm( alpha, b );
		return;
	}

	// Alias A and B so we can tweak the objects if necessary.
	bli_obj_alias_to( *a, a_local );
	bli_obj_alias_to( *b, b_local );
	bli_obj_alias_to( *b, c_local );

	// We do not explicitly implement the cases where A is transposed.
	// However, we can still handle them. Specifically, if A is marked as
	// needing a transposition, we simply induce a transposition. This
	// allows us to only explicitly implement the no-transpose cases. Once
	// the transposition is induced, the correct algorithm will be called,
	// since, for example, an algorithm over a transposed lower triangular
	// matrix A moves in the same direction (forwards) as a non-transposed
	// upper triangular matrix. And with the transposition induced, the
	// matrix now appears to be upper triangular, so the upper triangular
	// algorithm will grab the correct partitions, as if it were upper
	// triangular (with no transpose) all along.
	if ( bli_obj_has_trans( a_local ) )
	{
		bli_obj_induce_trans( a_local );
		bli_obj_set_onlytrans( BLIS_NO_TRANSPOSE, a_local );
	}

#if 0
	if ( bli_is_right( side ) )
	{
		bli_obj_induce_trans( a_local );
		bli_obj_induce_trans( b_local );
		bli_obj_induce_trans( c_local );

		bli_toggle_side( side );
	}
#endif

#if 1
	// If A is being solved against from the right, swap A and B so that
	// the matrix will actually be on the right.
	if ( bli_is_right( side ) )
	{
		bli_obj_swap( a_local, b_local );
	}

	// An optimization: If C is row-stored, transpose the entire operation
	// so as to allow the macro-kernel more favorable access patterns
	// through C. (The effect of the transposition of A and B is negligible
	// because those operands are always packed to contiguous memory.)
	if ( bli_obj_is_row_stored( c_local ) )
	{
		bli_obj_swap( a_local, b_local );

		bli_obj_induce_trans( a_local );
		bli_obj_induce_trans( b_local );
		bli_obj_induce_trans( c_local );

		bli_toggle_side( side );
	}
#endif

	// Set each alias as the root object.
	// NOTE: We MUST wait until we are done potentially swapping the objects
	// before setting the root fields!
	bli_obj_set_as_root( a_local );
	bli_obj_set_as_root( b_local );
	bli_obj_set_as_root( c_local );

	// Choose the control tree.
	if ( bli_is_left( side ) ) cntl = trsm_l_cntl;
	else                       cntl = trsm_r_cntl;

	// Invoke the internal back-end.
	bli_trsm_int( alpha,
	              &a_local,
	              &b_local,
	              &BLIS_ZERO,
	              &c_local,
	              cntl );
}

//
// Define BLAS-like interfaces with homogeneous-typed operands.
//
#undef  GENTFUNC
#define GENTFUNC( ctype, ch, opname, varname ) \
\
void PASTEMAC(ch,opname)( \
                          side_t  side, \
                          uplo_t  uploa, \
                          trans_t transa, \
                          diag_t  diaga, \
                          dim_t   m, \
                          dim_t   n, \
                          ctype*  alpha, \
                          ctype*  a, inc_t rs_a, inc_t cs_a, \
                          ctype*  b, inc_t rs_b, inc_t cs_b  \
                        ) \
{ \
	const num_t dt = PASTEMAC(ch,type); \
\
	obj_t       alphao, ao, bo; \
\
	dim_t       mn_a; \
\
	bli_set_dim_with_side( side, m, n, mn_a ); \
\
	bli_obj_create_1x1_with_attached_buffer( dt, alpha, &alphao ); \
\
	bli_obj_create_with_attached_buffer( dt, mn_a, mn_a, a, rs_a, cs_a, &ao ); \
	bli_obj_create_with_attached_buffer( dt, m,    n,    b, rs_b, cs_b, &bo ); \
\
	bli_obj_set_uplo( uploa, ao ); \
	bli_obj_set_diag( diaga, ao ); \
	bli_obj_set_conjtrans( transa, ao ); \
\
	bli_obj_set_struc( BLIS_TRIANGULAR, ao ); \
\
	PASTEMAC0(opname)( side, \
	                   &alphao, \
	                   &ao, \
	                   &bo ); \
}

INSERT_GENTFUNC_BASIC( trsm, trsm )

//
// Define BLAS-like interfaces with heterogeneous-typed operands.
//
#undef  GENTFUNC2
#define GENTFUNC2( ctype_a, ctype_b, cha, chb, opname, varname ) \
\
void PASTEMAC2(cha,chb,opname)( \
                                side_t    side, \
                                uplo_t    uploa, \
                                trans_t   transa, \
                                diag_t    diaga, \
                                dim_t     m, \
                                dim_t     n, \
                                ctype_a*  alpha, \
                                ctype_a*  a, inc_t rs_a, inc_t cs_a, \
                                ctype_b*  b, inc_t rs_b, inc_t cs_b  \
                              ) \
{ \
	bli_check_error_code( BLIS_NOT_YET_IMPLEMENTED ); \
}

INSERT_GENTFUNC2_BASIC( trsm, trsm )

#ifdef BLIS_ENABLE_MIXED_DOMAIN_SUPPORT
INSERT_GENTFUNC2_MIX_D( trsm, trsm )
#endif

#ifdef BLIS_ENABLE_MIXED_PRECISION_SUPPORT
INSERT_GENTFUNC2_MIX_P( trsm, trsm )
#endif


text:
package be.objectify.deadbolt.scala.composite

import javax.inject.{Inject, Singleton}

import be.objectify.deadbolt.scala._
import be.objectify.deadbolt.scala.composite.Operators.Operator
import be.objectify.deadbolt.scala.models.PatternType

import _root_.scala.concurrent.Future

@Singleton
class CompositeConstraints @Inject()(logic: ConstraintLogic, ecProvider: ExecutionContextProvider) {

  val ec = ecProvider.get()

  private def allow[A](request: AuthenticatedRequest[A]): Future[Boolean] = Future.successful(true)

  private def deny[A](request: AuthenticatedRequest[A]): Future[Boolean] = Future.successful(false)

  case class Restrict[A](roleGroups: RoleGroups) extends Constraint[A] {
    override def apply(authRequest: AuthenticatedRequest[A],
                       handler: DeadboltHandler): Future[Boolean] =
      logic.restrict(authRequest,
                     handler,
                     roleGroups,
                     (ar: AuthenticatedRequest[A]) => allow(ar),
                     (ar: AuthenticatedRequest[A]) => deny(ar))
  }

  case class Dynamic[A](name: String,
                        meta: Option[Any] = None) extends Constraint[A] {
    override def apply(authRequest: AuthenticatedRequest[A],
                       handler: DeadboltHandler): Future[Boolean] = {
      logic.dynamic(authRequest,
                    handler,
                    name,
                    meta,
                    (ar: AuthenticatedRequest[A]) => allow(ar),
                    (ar: AuthenticatedRequest[A]) => deny(ar))
    }
  }

  case class Pattern[A](value: String,
                        patternType: PatternType,
                        meta: Option[Any] = None,
                        invert: Boolean = false) extends Constraint[A] {
    override def apply(authRequest: AuthenticatedRequest[A],
                       handler: DeadboltHandler): Future[Boolean] =
      logic.pattern(authRequest,
                    handler,
                    value,
                    patternType,
                    meta,
                    invert,
                    (ar: AuthenticatedRequest[A]) => allow(ar),
                    (ar: AuthenticatedRequest[A]) => deny(ar))
  }

  case class SubjectPresent[A]() extends Constraint[A] {
    override def apply(authRequest: AuthenticatedRequest[A],
                       handler: DeadboltHandler): Future[Boolean] =
      logic.subjectPresent(authRequest,
                           handler,
                           (ar: AuthenticatedRequest[A]) => allow(ar),
                           (ar: AuthenticatedRequest[A]) => deny(ar))
  }

  case class SubjectNotPresent[A]() extends Constraint[A] {
    override def apply(authRequest: AuthenticatedRequest[A],
                       handler: DeadboltHandler): Future[Boolean] =
      logic.subjectPresent(authRequest,
                           handler,
                           (ar: AuthenticatedRequest[A]) => deny(ar),
                           (ar: AuthenticatedRequest[A]) => allow(ar))
  }

  private case class Deny[A]() extends Constraint[A] {
    override def apply(authRequest: AuthenticatedRequest[A],
                       handler: DeadboltHandler): Future[Boolean] = Future.successful(false)
  }

  case class ConstraintTree[A](operator: Operator[A],
                               constraints: List[Constraint[A]]) extends Constraint[A] {
    override def apply(authRequest: AuthenticatedRequest[A],
                       handler: DeadboltHandler): Future[Boolean] = {
      def combine(op: Operator[A],
                  constraint: Constraint[A],
                  remaining: List[Constraint[A]]): Constraint[A] = {
        if (remaining.isEmpty) constraint
        else combine(op, op(constraint, remaining.head), remaining.tail)
      }

      (if (constraints.isEmpty) new Deny[A]()
      else if (constraints.size == 1) constraints.head
      else combine(operator, constraints.head, constraints.tail)) (authRequest, handler)
    }
  }

}


text:
+++
date = "2014-05-16T08:35:31+08:00"
draft = true
title = "no command line tool in express 4"

+++

If you use Express 4 or higher, you need to globally install express-generator.

## Command

* `npm install -g express`
* `npm install -g express-generator`

## Reference

* <http://www.cnblogs.com/dacheng/p/nodejs.html>


text:
package com.keystone.server;

import com.keystone.server.contexts.KeystoneAppContext;
import com.keystone.server.message.http.KeystoneHttpServletRequest;
import com.keystone.server.message.http.KeystoneHttpServletResponse;
import com.keystone.server.processor.HTTPProccessor;
import com.keystone.server.processor.ServiceProccessor;
import com.keystone.share.distributed.DistributedContextFactory;
import com.keystone.share.message.keystone.KeystoneRequest;
import com.keystone.share.message.keystone.KeystoneResponse;
import com.keystone.support.common.ExceptionUtils;

public class KeystoneInvocationProccessor {

	/**
	 *
	 * @param request
	 * @return
	 */
	public static Object proccess(Object request) {
		KeystoneRequest keystoneRequest = null ; KeystoneResponse keystoneResponse = null ;
		KeystoneHttpServletRequest httpRequest = null ; KeystoneHttpServletResponse httpResponse = null ;
		if(request instanceof KeystoneRequest) {
			keystoneRequest = (KeystoneRequest) request ;
			keystoneResponse = new KeystoneResponse(keystoneRequest.getVersion(), keystoneRequest.getTicket()) ;
		} else if(request instanceof KeystoneHttpServletRequest) {
			httpRequest = (KeystoneHttpServletRequest) request ;
			httpResponse = new KeystoneHttpServletResponse() ;
		}

		ClassLoader currentClassLoader = null ;
		try
		{
			//1. found AppContext
			KeystoneAppContext appContext = foundAppContext(keystoneRequest, httpRequest) ;

			//2. is Waiting Too Long
			isWaitingTooLong(appContext, keystoneRequest, httpRequest);

			//3. switch ClassLoader
			currentClassLoader = Thread.currentThread().getContextClassLoader() ;
			Thread.currentThread().setContextClassLoader(appContext.getContextClassLoader());

			//4. proccess Request
			if(keystoneRequest!=null) {
				DistributedContextFactory.buildDistributedContext(keystoneRequest.getDistributed());
				ServiceProccessor.proccessRequest(keystoneRequest, keystoneResponse, appContext) ;
			} else if(httpRequest!=null) {
				HTTPProccessor.proccessRequest(httpRequest, httpResponse, appContext) ;
			}
		}
		catch(Throwable tw)
		{
			proccessThrowable(tw, keystoneRequest, keystoneResponse, httpRequest, httpResponse);
		}
		finally
		{
			DistributedContextFactory.clearDistributedContext();
			if(currentClassLoader!=null) Thread.currentThread().setContextClassLoader(currentClassLoader);
		}

		if(httpResponse!=null) {
			try{httpResponse.flushBuffer();}catch(Exception ignore){}
		}

		return keystoneResponse != null ? keystoneResponse : httpResponse ;
	}

	/**
	 *
	 * @param keystoneRequest
	 * @param httpRequest
	 * @return
	 */
	private static KeystoneAppContext foundAppContext(KeystoneRequest keystoneRequest, KeystoneHttpServletRequest httpRequest) {
		String contextName = keystoneRequest != null ? keystoneRequest.getContextName() : httpRequest.getContextPath() ;
		KeystoneAppContext appContext = KeystoneResourcesManager.getAppContext(contextName, true) ;
		return appContext ;
	}

	/**
	 *
	 * @param appContext
	 * @param keystoneRequest
	 * @param httpRequest
	 */
	private static void isWaitingTooLong(KeystoneAppContext appContext, KeystoneRequest keystoneRequest, KeystoneHttpServletRequest httpRequest) {
		if(appContext.getContextConfig().getWaitInQueue()<=0) return ;

		long bornTime = 0 ;
		if(keystoneRequest!=null) bornTime = keystoneRequest.getBornTime() ;
		else if(httpRequest!=null) bornTime = httpRequest.getBornTime() ;

		if(System.currentTimeMillis()-bornTime>appContext.getContextConfig().getWaitInQueue())
		{
			throw new IllegalStateException("Wait too long, server busy.");
		}
	}

	/**
	 *
	 * @param tw
	 * @param keystoneRequest
	 * @param keystoneResponse
	 * @param httpRequest
	 * @param httpResponse
	 */
	private static void proccessThrowable(Throwable tw, KeystoneRequest keystoneRequest, KeystoneResponse keystoneResponse, KeystoneHttpServletRequest httpRequest, KeystoneHttpServletResponse httpResponse) {
		try
		{
			Throwable real = ExceptionUtils.foundRealThrowable(tw) ;
			boolean print = true ;
			if(httpResponse!=null)
			{
				httpResponse.setCharacterEncoding("UTF-8");
				httpResponse.setContentType("text/plain");

				String message = real.getMessage() ;
				if(message!=null)
				{
					if(message.contains("NotFound") || message.contains("Not Found"))
					{
						httpResponse.setStatus(404);
						httpResponse.getWriter().write(message);
						print = false ;
					} else if(message.contains("Wait too long")) {
						httpResponse.setStatus(500);
						httpResponse.getWriter().write(message);
						print = false ;
					}
				}
			}

			if(print)
			{
				String cause = ExceptionUtils.formatThrowable(real) ;
				if(keystoneResponse!=null)
				{
					keystoneResponse.setThrowable(cause);
				}
				else if(httpResponse!=null)
				{
					httpResponse.setStatus(500);
					httpResponse.getWriter().write(cause);
				}
			}
			System.err.print("proccess "+(keystoneRequest!=null ? keystoneRequest : httpRequest)+ " with ex:" + ExceptionUtils.formatThrowable(real)) ;

		}
		catch(Throwable t)
		{
			t.printStackTrace();
		}
	}

}


text:
var cu = window.app.get('currentUser');
cu.setAttrs({
      "nick": "eugene",
      "timezone": "+5",
      "avatar": "eugene.trounev@gmail.com",
      "rated": ["postyui_3_17_2_1_1404866127097_19"],
      "following": ["postyui_3_17_2_1_1404866127097_19"]
    });
cu.save();
var u = window.app.get('users');
u.create({
      "sysID": "dkfndhfde83ywery",
      "nick": "eugene",
      "timezone": "+5",
      "avatar": "eugene.trounev@gmail.com"
    });
u.create({
      "sysID": "djhfjshf8324yrh",
      "nick": "sasha",
      "timezone": "+2",
      "avatar": "/images/avatar-girl.jpg"
    });

var p = window.app.get('posts');
p.create({
      "sysParentID": null,
      "sysAuthorID": "djhfjshf8324yrh",
      "dateCreated": "Wed, 09 Jul 2014 00:35:27 GMT",
      "dateModified": null,
      "tags": [
      "mim",
      "test",
      "sys-type-discussion"
    ],
      "rate": 0,
      "slug": "new-test-discussion",
      "title": "New test discussion",
      "content": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
  });


text:
package org.neo4j.ogm.domain.cineasts.annotated;

import java.net.MalformedURLException;
import java.net.URL;

import org.neo4j.ogm.typeconversion.AttributeConverter;

/**
 * @author Luanne Misquitta
 */
public class URLConverter implements AttributeConverter<URL, String> {

    @Override
    public String toGraphProperty(URL value) {
        return value == null ? null : value.toString();
    }

    @Override
    public URL toEntityAttribute(String value) {
        try {
            return value == null ? null : new URL(value);
        } catch (MalformedURLException e) {
            return null;
        }
    }
}


text:
"""
Control flow
"""

import typing
if typing.TYPE_CHECKING:
	from ._iced_x86_py import FlowControl
else:
	FlowControl = int

NEXT: FlowControl = 0 # type: ignore
"""
The next instruction that will be executed is the next instruction in the instruction stream
"""
UNCONDITIONAL_BRANCH: FlowControl = 1 # type: ignore
"""
: It's an unconditional branch instruction: ``JMP NEAR``, ``JMP FAR``
"""
INDIRECT_BRANCH: FlowControl = 2 # type: ignore
"""
: It's an unconditional indirect branch: ``JMP NEAR reg``, ``JMP NEAR [mem]``, ``JMP FAR [mem]``
"""
CONDITIONAL_BRANCH: FlowControl = 3 # type: ignore
"""
: It's a conditional branch instruction: ``Jcc SHORT``, ``Jcc NEAR``, ``LOOP``, ``LOOPcc``, ``JRCXZ``, ``JKccD SHORT``, ``JKccD NEAR``
"""
RETURN: FlowControl = 4 # type: ignore
"""
: It's a return instruction: ``RET NEAR``, ``RET FAR``, ``IRET``, ``SYSRET``, ``SYSEXIT``, ``RSM``, ``SKINIT``, ``RDM``, ``UIRET``
"""
CALL: FlowControl = 5 # type: ignore
"""
: It's a call instruction: ``CALL NEAR``, ``CALL FAR``, ``SYSCALL``, ``SYSENTER``, ``VMLAUNCH``, ``VMRESUME``, ``VMCALL``, ``VMMCALL``, ``VMGEXIT``, ``VMRUN``, ``TDCALL``, ``SEAMCALL``, ``SEAMRET``
"""
INDIRECT_CALL: FlowControl = 6 # type: ignore
"""
: It's an indirect call instruction: ``CALL NEAR reg``, ``CALL NEAR [mem]``, ``CALL FAR [mem]``
"""
INTERRUPT: FlowControl = 7 # type: ignore
"""
: It's an interrupt instruction: ``INT n``, ``INT3``, ``INT1``, ``INTO``, ``SMINT``, ``DMINT``
"""
XBEGIN_XABORT_XEND: FlowControl = 8 # type: ignore
"""
It's ``XBEGIN``
"""
EXCEPTION: FlowControl = 9 # type: ignore
"""
It's an invalid instruction, eg. :class:`iced_x86.Code.INVALID`, ``UD0``, ``UD1``, ``UD2``
"""


text:
package com.github.otrosien.yamlmerge;

import static org.assertj.core.api.Assertions.assertThat;

import java.io.StringWriter;

import org.junit.Test;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

public class YamlMapperTest {

    @Test
    public void test_roundtrip() throws Exception {
        JsonNode node1  = new YamlMapper().read(getClass().getResourceAsStream("/com/github/otrosien/yamlmerge/simple/input.yaml"));
        YamlMapper mapper = new YamlMapper();
        StringWriter writer = new StringWriter();
        mapper.write(new YAMLFactory().createGenerator(writer), node1);
        assertThat(new YamlMapper().read(writer.toString())).isEqualTo(node1);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/progress_bar"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:showIn="@layout/fragment_results_list">

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@android:style/Widget.ProgressBar.Large"
        android:layout_marginRight="5dp" />
</LinearLayout>


text:
using CBT.NuGet.Internal;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace CBT.NuGet.Tasks
{
    public sealed class NuGetList : CommandBase
    {
        private static readonly Regex MultiLineNuGetPackageIdRegex = new Regex(@"^(?<id>[^\s]+)$");
        private static readonly Regex MultiLineNuGetPackageVersionRegex = new Regex(@"^\s(?<version>\d*\.\d*\..+)$");
        private static readonly Regex SingleLineNuGetPackageRegex = new Regex(@"^(?<id>[^\s]+)\s(?<version>\d*\.\d*\..+)$");
        private readonly IList<ITaskItem> _packages = new List<ITaskItem>();

        private ITaskItem _lastTaskItem;

        public bool AllVersions { get; set; }

        public bool IncludeDelisted { get; set; }

        [Output]
        public ITaskItem[] Packages => _packages.ToArray();

        public bool Prerelease { get; set; }

        public string SearchTerms { get; set; }

        public ITaskItem[] Source { get; set; }

        protected override void GenerateCommandLineCommands(CommandLineBuilder commandLineBuilder)
        {
            commandLineBuilder.AppendSwitch("list");

            commandLineBuilder.AppendFileNameIfNotNull(SearchTerms);

            commandLineBuilder.AppendSwitchIfAny("-Source ", Source);

            commandLineBuilder.AppendSwitchIfTrue("-AllVersions", AllVersions);

            commandLineBuilder.AppendSwitchIfTrue("-Prerelease", Prerelease);

            commandLineBuilder.AppendSwitchIfTrue("-IncludeDelisted", IncludeDelisted);
        }

        protected override void LogEventsFromTextOutput(string singleLine, MessageImportance messageImportance)
        {
            if (CommandVerbosity != CommandVerbosity.Detailed)
            {
                var match = SingleLineNuGetPackageRegex.Match(singleLine);

                if (match.Success)
                {
                    _packages.Add(new TaskItem($"{match.Groups["id"].Value}.{match.Groups["version"].Value}", new Dictionary<string, string>
                    {
                        {"Id", match.Groups["id"].Value},
                        {"Version", match.Groups["version"].Value},
                    }));
                }
            }
            else
            {
                if (_lastTaskItem == null)
                {
                    var match = MultiLineNuGetPackageIdRegex.Match(singleLine);

                    if (match.Success)
                    {
                        _lastTaskItem = new TaskItem(match.Groups["id"].Value, new Dictionary<string, string>
                        {
                            {"Id", match.Groups["id"].Value}
                        });
                    }
                }
                else
                {
                    if (String.Empty.Equals(singleLine))
                    {
                        _packages.Add(_lastTaskItem);

                        _lastTaskItem = null;
                    }
                    else
                    {
                        var match = MultiLineNuGetPackageVersionRegex.Match(singleLine);

                        if (match.Success)
                        {
                            _lastTaskItem.ItemSpec = $"{_lastTaskItem.ItemSpec}.{match.Groups["version"].Value}";
                            _lastTaskItem.SetMetadata("Version", match.Groups["version"].Value);
                        }
                        else
                        {
                            _lastTaskItem.SetMetadata("Description", singleLine.Trim());
                        }
                    }
                }
            }

            base.LogEventsFromTextOutput(singleLine, messageImportance);
        }
    }
}


text:
require "language_pack/installers/ruby_installer"
require "language_pack/shell_helpers"

class LanguagePack::Installers::RbxInstaller
  include LanguagePack::ShellHelpers, LanguagePack::Installers::RubyInstaller

  BASE_URL = "https://rubinius-binaries-rubinius-com.s3.amazonaws.com/ubuntu/14.04/x86_64/"

  def initialize(stack)
    @fetcher = LanguagePack::Fetcher.new(BASE_URL)
  end

  def fetch_unpack(ruby_version, install_dir)
    file = "#{ruby_version.version_for_download}.tar.bz2"
    @fetcher.fetch_bunzip2(file)
    FileUtils.mv(Dir.glob("rubinius/#{ruby_version.engine_version}/*"), ".")
    FileUtils.rm_rf("rubinius")
  end
end


text:
def object(objname):
  return "'" + objname + "'"

def file(filename):
  return object(filename)

def dir(dirname):
  return object(dirname)

def not_exist(filename):
  return object(filename) + ' not exist'

def dir_not_exist(dirname):
  return 'directory ' + not_exist(dirname)

def file_not_exist(dirname):
  return 'file ' + not_exist(dirname)

def from_to_start(message, from_name, to):
  """Start 'from -> to' move"""
  print(
      message + ': ' + object(from_name) + '\n    -> ' + object(to) + ' ...',
      end=' '
  )

def from_to_stop():
  """Stop 'from -> to' move"""
  print('ok')


text:
angular.module('myApp').controller('TopController', ['$scope', '$rootScope', '$location', '$translate', 'Session', function ($scope, $rootScope, $location, $translate, Session) {
	$scope.serviceUriBase = $location.protocol() + '://' + $location.host() + ":" + $location.port();

	$scope.languages = [{
		id: 'en-US',
		label: 'English (US)'
	},{
		id: 'es-ES',
		label: 'Español (ES)'
	}];

	$scope.languageChanged = function(langIsoCode) {
		$rootScope.currentLanguage = langIsoCode;
		$translate.use(langIsoCode);
		$translate.refresh();
	};

	$scope.login = function() {
		$location.path('/login');
	};
	$scope.logout = function() {
		$location.path('/logout');
	};

	function init() {
		$rootScope.currentLanguage = $translate.proposedLanguage();
	}

	init();

}]);


text:
import unittest
from activity.activity_IngestToLax import activity_IngestToLax
import settings_mock
from ddt import ddt, data
from mock import patch
from classes_mock import FakeLogger

data_example = {
    "article_id": "00353",
    "update_date": "2016-10-05T10:31:54Z",
    "eif_location": "",
    "expanded_folder": "00353.1/bb2d37b8-e73c-43b3-a092-d555753316af",
    "message": None,
    "requested_action": "ingest",
    "result": "ingested",
    "run": "bb2d37b8-e73c-43b3-a092-d555753316af",
    "status": "vor",
    "version": "1"
}

@ddt
class TestIngestToLax(unittest.TestCase):
    def setUp(self):
        self.ingesttolax = activity_IngestToLax(settings_mock, None, None, None, None)

    @data(data_example)
    @patch('provider.lax_provider.prepare_action_message')
    def test_do_activity_success(self, data, fake_action_message):
        fake_action_message.return_value = {"example_message": True}

        message, queue, start_event, end_event, end_event_details, exception = self.ingesttolax.get_message_queue(data)
        self.assertEqual(queue, settings_mock.xml_info_queue)
        self.assertEqual(start_event, [settings_mock, data['article_id'], data['version'], data['run'],
                                       self.ingesttolax.pretty_name, "start",
                                       "Starting preparation of article for Lax " + data['article_id']])
        self.assertEqual(end_event, "end")
        self.assertEqual(end_event_details, [settings_mock, data['article_id'], data['version'], data['run'],
                                             self.ingesttolax.pretty_name, "end",
                                             "Finished preparation of article for Lax. "
                                             "Ingest sent to Lax" + data['article_id']])
        self.assertIsNone(exception)

    @data(data_example)
    @patch("provider.lax_provider.prepare_action_message")
    def test_do_activity_error(self, data, fake_lax_provider):
        fake_lax_provider.side_effect = Exception("Access Denied")
        self.ingesttolax = activity_IngestToLax(settings_mock, FakeLogger(), None, None, None)
        message, queue, start_event, end_event, end_event_details, exception = self.ingesttolax.get_message_queue(data)
        self.assertEqual(end_event, "error")
        self.assertEqual(exception, "Access Denied")
        self.assertListEqual(end_event_details, [settings_mock, data['article_id'], data['version'], data['run'],
                                                 self.ingesttolax.pretty_name, "error",
                                                 "Error preparing or sending message to lax" + data['article_id'] +
                                                 " message: Access Denied"])

    @data(data_example)
    def test_do_activity_not_consider_lax(self, data):

        message, queue, start_event, end_event, end_event_details, exception = self.ingesttolax.get_message_queue(data, False)
        self.assertDictEqual(message, {
                                "workflow_name": "ProcessArticleZip",
                                "workflow_data": {
                                    "run":data['run'] ,
                                    "article_id": data['article_id'],
                                    "result": "",
                                    "status": data['status'],
                                    "version": data['version'],
                                    "expanded_folder": data['expanded_folder'],
                                    "eif_location": "",
                                    "requested_action": "",
                                    "message": "",
                                    "update_date": data['update_date']
                                }
                            })
        self.assertEqual(queue, settings_mock.workflow_starter_queue)
        self.assertEqual(start_event, [settings_mock, data['article_id'], data['version'], data['run'],
                                       self.ingesttolax.pretty_name + " (Skipping)", "start",
                                       "Starting preparation of article " + data['article_id']])
        self.assertEqual(end_event, "end")
        self.assertEqual(end_event_details, [settings_mock, data['article_id'], data['version'], data['run'],
                                             self.ingesttolax.pretty_name + " (Skipping)", "end",
                                             "Lax is not being considered, this activity just triggered next "
                                             "workflow without influence from Lax."])

if __name__ == '__main__':
    unittest.main()


text:
module Jobler::ApplicationHelper
end


text:
var cheerio = require('cheerio');
var site = 'https://css-tricks.com';
var siteName = 'css-tricks.com';

var cssTricksObj = {
	siteName: siteName,
	site: site,
	url: site + '/archives/',
	transformFunc: cssTricksTrasnform,
	pages: linkToNextPage
};

module.exports = cssTricksObj;

function linkToNextPage(data) {
	var $ = cheerio.load(data);
	return $('#wp_page_numbers li').last().find('a').attr('href');
}

function cssTricksTrasnform(data) {
	var $ = cheerio.load(data);
	var resArr = [];
	$('.archive-wrap article.sitemap-article').each(function () {
		var article = $(this);
		var title = article.find('h4 .sitemap-title').text();
		var description = article.find('.sitemap-excerpt').text();
		var link = article.find('h4 .sitemap-title').attr('href');
		var date = article.find('.sitemap-meta time').text();

		resArr.push({
			siteName: siteName,
			origin: site + '/',
			title: title,
			description: description,
			link: link,
			date: date
		});
	});

	return resArr;
}


text:
const errors = require('../errors');

exports.handle = (error, req, res, next) => {
  res.status(error.statusCode || 500);
  res.send({ error: error.message.message || error.message });
};


text: <!DOCTYPE html>


text:
import cProfile
import io
import pstats
import unittest

import numpy as np

import qiskit._jobprocessor as jobprocessor
from qiskit import (qasm, unroll, QuantumProgram, QuantumJob, QuantumCircuit,
                    QuantumRegister, ClassicalRegister)
from qiskit.backends.local.unitarysimulator import UnitarySimulator
from ._random_qasm_generator import RandomQasmGenerator
from .common import QiskitTestCase

class LocalUnitarySimulatorTest(QiskitTestCase):
    """Test local unitary simulator."""

    def setUp(self):
        self.seed = 88
        self.qasm_filename = self._get_resource_path('qasm/example.qasm')
        self.qp = QuantumProgram()

    def tearDown(self):
        pass

    def test_unitary_simulator(self):
        """test generation of circuit unitary"""
        self.qp.load_qasm_file(self.qasm_filename, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm('example')).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        # strip measurements from circuit to avoid warnings
        circuit['operations'] = [op for op in circuit['operations']
                                 if op['name'] != 'measure']
        # the simulator is expecting a JSON format, so we need to convert it
        # back to JSON
        qobj = {
            'id': 'unitary',
            'config': {
                'max_credits': None,
                'shots': 1,
                'backend_name': 'local_unitary_simulator'
            },
            'circuits': [
                {
                    'name': 'test',
                    'compiled_circuit': circuit,
                    'compiled_circuit_qasm': self.qp.get_qasm('example'),
                    'config': {
                        'coupling_map': None,
                        'basis_gates': None,
                        'layout': None,
                        'seed': None
                    }
                }
            ]
        }
        # numpy.savetxt currently prints complex numbers in a way
        # loadtxt can't read. To save file do,
        # fmtstr=['% .4g%+.4gj' for i in range(numCols)]
        # np.savetxt('example_unitary_matrix.dat', numpyMatrix, fmt=fmtstr,
        # delimiter=',')
        expected = np.loadtxt(self._get_resource_path('example_unitary_matrix.dat'),
                              dtype='complex', delimiter=',')
        q_job = QuantumJob(qobj,
                           backend=UnitarySimulator(),
                           preformatted=True)

        result = UnitarySimulator().run(q_job)
        self.assertTrue(np.allclose(result.get_data('test')['unitary'],
                                    expected,
                                    rtol=1e-3))

    def test_two_unitary_simulator(self):
        """test running two circuits

        This test is similar to one in test_quantumprogram but doesn't use
        multiprocessing.
        """
        qr = QuantumRegister(2, 'q')
        cr = ClassicalRegister(1, 'c')
        qc1 = QuantumCircuit(qr, cr)
        qc2 = QuantumCircuit(qr, cr)
        qc1.h(qr)
        qc2.cx(qr[0], qr[1])
        circuits = [qc1, qc2]
        backend = UnitarySimulator()
        quantum_job = QuantumJob(circuits, do_compile=True,
                                 backend=backend)
        result = jobprocessor.run_backend(quantum_job)
        unitary1 = result[0]['data']['unitary']
        unitary2 = result[1]['data']['unitary']
        unitaryreal1 = np.array([[0.5, 0.5, 0.5, 0.5], [0.5, -0.5, 0.5, -0.5],
                                 [0.5, 0.5, -0.5, -0.5],
                                 [0.5, -0.5, -0.5, 0.5]])
        unitaryreal2 = np.array([[1, 0, 0, 0], [0, 0, 0, 1],
                                 [0., 0, 1, 0], [0, 1, 0, 0]])
        norm1 = np.trace(np.dot(np.transpose(np.conj(unitaryreal1)), unitary1))
        norm2 = np.trace(np.dot(np.transpose(np.conj(unitaryreal2)), unitary2))
        self.assertAlmostEqual(norm1, 4)
        self.assertAlmostEqual(norm2, 4)

    def profile_unitary_simulator(self):
        """Profile randomly generated circuits.

        Writes profile results to <this_module>.prof as well as recording
        to the log file.

        number of circuits = 100.
        number of operations/circuit in [1, 40]
        number of qubits in [1, 5]
        """
        n_circuits = 100
        max_depth = 40
        max_qubits = 5
        pr = cProfile.Profile()
        random_circuits = RandomQasmGenerator(seed=self.seed,
                                              max_depth=max_depth,
                                              max_qubits=max_qubits)
        random_circuits.add_circuits(n_circuits, do_measure=False)
        self.qp = random_circuits.get_program()
        pr.enable()
        self.qp.execute(self.qp.get_circuit_names(),
                        backend=UnitarySimulator())
        pr.disable()
        sout = io.StringIO()
        ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
        self.log.info('------- start profiling UnitarySimulator -----------')
        ps.print_stats()
        self.log.info(sout.getvalue())
        self.log.info('------- stop profiling UnitarySimulator -----------')
        sout.close()
        pr.dump_stats(self.moduleName + '.prof')

if __name__ == '__main__':
    unittest.main()


text:
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');

module.exports = {
    context: path.join(__dirname, "/src/js/"),
    devtool: debug ? "inline-sourcemap" : null,
    entry: {
        app: "./app.js",
        game: "./game.js",
        csgo: "./csgo.js"
    },
    resolve: {
        modulesDirectories: ["./node_modules", "./node_modules/babel"]
    },
    resolveLoader: {
        root: path.resolve(__dirname, 'node_modules')
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel-loader',
                query: {
                    presets: ['react', 'es2015', 'stage-0'],
                    plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy']
                }
            }
        ]
    },
    output: {
        path: __dirname + "/dest/js",
        filename: "[name].min.js"
    },
    plugins: debug ? [] : [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
    ]
};