text:
package com.android.test.voiceinteraction;

import android.annotation.Nullable;
import android.app.assist.AssistStructure;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import java.util.ArrayList;

public class AssistVisualizer extends View {
    static final String TAG = "AssistVisualizer";
    final Paint mFramePaint = new Paint();
    final Paint mFrameBaselinePaint = new Paint();
    final Paint mFrameNoTransformPaint = new Paint();
    final ArrayList<Matrix> mMatrixStack = new ArrayList<>();
    final ArrayList<TextEntry> mTextRects = new ArrayList<>();
    final int[] mTmpLocation = new int[2];
    AssistStructure mAssistStructure;
    public AssistVisualizer(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setWillNotDraw(false);
        mFramePaint.setColor(0xffff0000);
        mFramePaint.setStyle(Paint.Style.STROKE);
        mFramePaint.setStrokeWidth(0);
        mFrameBaselinePaint.setColor(0xa0b0b000);
        mFrameBaselinePaint.setStyle(Paint.Style.STROKE);
        mFrameBaselinePaint.setStrokeWidth(0);
        float density = getResources().getDisplayMetrics().density;
        mFramePaint.setShadowLayer(density, density, density, 0xff000000);
        mFrameNoTransformPaint.setColor(0xff0000ff);
        mFrameNoTransformPaint.setStyle(Paint.Style.STROKE);
        mFrameNoTransformPaint.setStrokeWidth(0);
        mFrameNoTransformPaint.setShadowLayer(density, density, density, 0xff000000);
    }

    public void setAssistStructure(AssistStructure as) {
        mAssistStructure = as;
        mTextRects.clear();
        final int N = as.getWindowNodeCount();
        if (N > 0) {
            for (int i = 0; i < N; i++) {
                AssistStructure.WindowNode windowNode = as.getWindowNodeAt(i);
                mMatrixStack.clear();
                Matrix matrix = new Matrix();
                matrix.setTranslate(windowNode.getLeft(), windowNode.getTop());
                mMatrixStack.add(matrix);
                buildTextRects(windowNode.getRootViewNode(), 0, windowNode.getLeft(),
                        windowNode.getTop());
            }
        }
        Log.d(TAG, "Building text rects in " + this + ": found " + mTextRects.size());
        invalidate();
    }

    public void logTree() {
/*        if (mAssistStructure != null) {
            mAssistStructure.dump();
        }*/
    }

    public void logText() {
        final int N = mTextRects.size();
        for (int i = 0; i < N; i++) {
            TextEntry te = mTextRects.get(i);
            Log.d(TAG, "View " + te.className + " " + te.bounds.toShortString()
                    + " in " + te.parentLeft + "," + te.parentTop
                    + " matrix=" + te.matrix.toShortString() + ": "
                    + te.text);
            if (te.lineCharOffsets != null && te.lineBaselines != null) {
                final int num = te.lineCharOffsets.length < te.lineBaselines.length
                        ? te.lineCharOffsets.length : te.lineBaselines.length;
                for (int j = 0; j < num; j++) {
                    Log.d(TAG, "  Line #" + j + ": offset=" + te.lineCharOffsets[j]
                            + " baseline=" + te.lineBaselines[j]);
                }
            }
        }
    }

    public void clearAssistData() {
        mAssistStructure = null;
        mTextRects.clear();
    }

    void buildTextRects(AssistStructure.ViewNode root, int matrixStackIndex,
                        int parentLeft, int parentTop) {
        if (root.getVisibility() != View.VISIBLE) {
            return;
        }
        Matrix parentMatrix = mMatrixStack.get(matrixStackIndex);
        matrixStackIndex++;
        Matrix matrix;
        if (mMatrixStack.size() > matrixStackIndex) {
            matrix = mMatrixStack.get(matrixStackIndex);
            matrix.set(parentMatrix);
        } else {
            matrix = new Matrix(parentMatrix);
            mMatrixStack.add(matrix);
        }
        matrix.preTranslate(root.getLeft(), root.getTop());
        int left = parentLeft + root.getLeft();
        int top = parentTop + root.getTop();
        Matrix transform = root.getTransformation();
        if (transform != null) {
            matrix.preConcat(transform);
        }
        if (root.getText() != null || root.getContentDescription() != null) {
            TextEntry te = new TextEntry(root, parentLeft, parentTop, matrix);
            mTextRects.add(te);
        }
        final int N = root.getChildCount();
        if (N > 0) {
            left -= root.getScrollX();
            top -= root.getScrollY();
            matrix.preTranslate(-root.getScrollX(), -root.getScrollY());
            for (int i = 0; i < N; i++) {
                AssistStructure.ViewNode child = root.getChildAt(i);
                buildTextRects(child, matrixStackIndex, left, top);
            }
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        getLocationOnScreen(mTmpLocation);
        final int N = mTextRects.size();
        Log.d(TAG, "Drawing text rects in " + this + ": found " + mTextRects.size());
        for (int i = 0; i < N; i++) {
            TextEntry te = mTextRects.get(i);
            canvas.drawRect(te.bounds.left - mTmpLocation[0], te.bounds.top - mTmpLocation[1],
                    te.bounds.right - mTmpLocation[0], te.bounds.bottom - mTmpLocation[1],
                    mFrameNoTransformPaint);
        }
        for (int i = 0; i < N; i++) {
            TextEntry te = mTextRects.get(i);
            canvas.save();
            canvas.translate(-mTmpLocation[0], -mTmpLocation[1]);
            canvas.concat(te.matrix);
            canvas.drawRect(0, 0, te.bounds.right - te.bounds.left, te.bounds.bottom - te.bounds.top,
                    mFramePaint);
            if (te.lineBaselines != null) {
                for (int j = 0; j < te.lineBaselines.length; j++) {
                    canvas.drawLine(0, te.lineBaselines[j] - te.scrollY,
                            te.bounds.right - te.bounds.left, te.lineBaselines[j] - te.scrollY,
                            mFrameBaselinePaint);
                }
            }
            canvas.restore();
        }
    }

    static class TextEntry {
        final Rect bounds;
        final int parentLeft, parentTop;
        final Matrix matrix;
        final String className;
        final CharSequence text;
        final int scrollY;
        final int[] lineCharOffsets;
        final int[] lineBaselines;

        TextEntry(AssistStructure.ViewNode node, int parentLeft, int parentTop, Matrix matrix) {
            int left = parentLeft + node.getLeft();
            int top = parentTop + node.getTop();
            bounds = new Rect(left, top, left + node.getWidth(), top + node.getHeight());
            this.parentLeft = parentLeft;
            this.parentTop = parentTop;
            this.matrix = new Matrix(matrix);
            this.className = node.getClassName();
            this.text = node.getText() != null ? node.getText() : node.getContentDescription();
            this.scrollY = node.getScrollY();
            this.lineCharOffsets = node.getTextLineCharOffsets();
            this.lineBaselines = node.getTextLineBaselines();
        }
    }
}


text:
using System;
using System.ComponentModel;
using System.IO;

namespace KugelmatikLibrary
{
    /// <summary>
    /// Stellt verschiedene Informationen über das Cluster bereit.
    /// </summary>
    public class ClusterInfo
    {
        /// <summary>
        /// Gibt die Build-Version der Firmware des Clusters zurück.
        /// </summary>
        [Category("\t\tInfo")]
        public byte BuildVersion { get; private set; }

        /// <summary>
        /// Gibt true zurück, wenn das Cluster einen Busy-Befehl ausführt.
        /// </summary>
        [Category("\t\tInfo")]
        public BusyCommand CurrentBusyCommand { get; private set; }

        /// <summary>
        /// Gibt die größte Revision des Clusters zurück.
        /// </summary>
        [Category("\tDebug")]
        public int HighestRevision { get; private set; }

        /// <summary>
        /// Gibt die Einstellungen des Clusters zurück.
        /// </summary>
        [TypeConverter(typeof(ConfigTypeConverter))]
        [Category("\t\tInfo")]
        public ClusterConfig Config { get; private set; }

        /// <summary>
        /// Gibt den letzten Fehler zurück der auf dem Cluster aufgetreten ist.
        /// </summary>
        [Category("\tDebug")]
        public ErrorCode LastError { get; private set; }

        /// <summary>
        /// Gibt den freien Speicher in Bytes auf dem Cluster zurück.
        /// </summary>
        [Category("\tDebug")]
        public ulong FreeRam { get; private set; }

        /// <summary>
        /// Bitfeld, welches angibt welche MCP ansprechbar sind.
        /// </summary>
        [Category("\tDebug")]
        public byte MCPStatus { get; private set; }

        /// <summary>
        /// Zeit die das Cluster benötigt um einen Tick auszuführen.
        /// </summary>
        [Category("Time")]
        public int LoopTime { get; private set; }

        /// <summary>
        /// Zeit die das Cluster benötigt um ein Paket zu verarbeiten.
        /// </summary>
        [Category("Time")]
        public int NetworkTime { get; private set; }

        /// <summary>
        /// Zeit die das Cluster maximal benötigt um ein Paket zu verarbeiten.
        /// </summary>
        [Category("Time")]
        public int MaxNetworkTime { get; private set; }

        /// <summary>
        /// Zeit die das Cluster benötigt um die Stepper zu aktualisieren.
        /// </summary>
        [Category("Time")]
        public int StepperTime { get; private set; }

        /// <summary>
        /// Zeit in Sekunden wie lange schon das Cluster lief.
        /// </summary>
        [Category("Time")]
        public int Uptime { get; private set; }

        public ClusterInfo(BinaryReader reader)
        {
            BuildVersion = reader.ReadByte();
            CurrentBusyCommand = (BusyCommand)reader.ReadByte();
            HighestRevision = reader.ReadInt32();

            int error = reader.ReadByte();
            if (!Enum.IsDefined(typeof(ErrorCode), error))
                LastError = ErrorCode.UnknownError;
            else
                LastError = (ErrorCode)error;

            if (BuildVersion < 20)
                FreeRam = (ulong)Math.Max((short)0, reader.ReadInt16());
            else
                FreeRam = reader.ReadUInt64();

            ushort configSize = reader.ReadUInt16();
            if (configSize != ClusterConfig.Size)
            {
                Config = new ClusterConfig();
                Log.Error("Packet config size does not match config structure size (version: {0}, size (firmware != local): {1} != {2})", BuildVersion, configSize, ClusterConfig.Size);
                reader.BaseStream.Seek(configSize, SeekOrigin.Current);
            }
            else
                Config = ClusterConfig.Read(reader);

            MCPStatus = reader.ReadByte();
            LoopTime = reader.ReadInt32();
            NetworkTime = reader.ReadInt32();
            MaxNetworkTime = reader.ReadInt32();
            StepperTime = reader.ReadInt32();
            Uptime = reader.ReadInt32();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.redhat.consulting.fusequickstarts.karaf.rest.beanvalidation.route;

import com.redhat.consulting.fusequickstarts.karaf.rest.beanvalidation.processor.MyServiceImpl;
import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.cxf.common.message.CxfConstants;

/*
 * The route for receiving requests from out cxf endpoints.
 */

public class EndpointRoute extends RouteBuilder {

    private MyServiceImpl myServiceImpl = new MyServiceImpl();

    @Override
    public void configure() throws Exception {
        // @formatter:off

        from("cxfrs:bean:rsServer?bindingStyle=SimpleConsumer")
            .routeId("restEndpointConsumer")
            .choice() //selects what to do based on the request
                .when(header(CxfConstants.OPERATION_NAME).isEqualTo("getSampleUser"))
                    .bean(myServiceImpl, "getSampleUser")
                    .log(LoggingLevel.INFO, "Request Recieved")
                .otherwise()
                    .log(LoggingLevel.WARN, "Unknown Method");

    }

}


text:
"""
Miscellaneous utility functions
"""
from __future__ import absolute_import, division, print_function

import logging

# A logger for this file
LOG = None

# Default wrapping class for an output message
HTML_DIV_CLASS = 'krn-bot'

# ----------------------------------------------------------------

def getLogger():
    global LOG
    if LOG is None:
        LOG = logging.getLogger( __name__ )
    return LOG

# ----------------------------------------------------------------

def is_collection(v):
    """
    Decide if a variable contains multiple values and therefore can be
    iterated, discarding strings (single strings can also be iterated, but
    shouldn't qualify)
    """
    # The 2nd clause is superfluous in Python 2, but (maybe) not in Python 3
    # Therefore we use 'str' instead of 'basestring'
    return hasattr(v,'__iter__') and not isinstance(v,str)

# ----------------------------------------------------------------------

def escape( x, lb=False ):
    """
    Ensure a string does not contain HTML-reserved characters (including
    double quotes)
    Optionally also insert a linebreak if the string is too long
    """
    # Insert a linebreak? Roughly around the middle of the string,
    if lb:
        l = len(x)
        if l >= 10:
            l >>= 1                     # middle of the string
            s1 = x.find( ' ', l )       # first ws to the right
            s2 = x.rfind( ' ', 0, l )   # first ws to the left
            if s2 > 0:
                s = s2 if s1<0 or l-s1 > s2-l else s1
                x = x[:s] + '\\n' + x[s+1:]
            elif s1 > 0:
                x = x[:s1] + '\\n' + x[s1+1:]
    # Escape HTML reserved characters
    return x.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """)

# ----------------------------------------------------------------------

def div( txt, *args, **kwargs ):
    """
    Create & return an HTML
 element by wrapping the passed text buffer.
      @param txt (basestring): the text buffer to use
      @param *args (list): if present, \c txt is considered a Python format
        string, and the arguments are formatted into it
      @param kwargs (dict): the \c css field can contain the CSS class for the

 element
    """
    if args:
        txt = txt.format( *args )
    css = kwargs.get('css',HTML_DIV_CLASS)
    return u'
{!s}
'.format( css, txt )

def data_msglist( msglist ):
    """
    Return a Jupyter display_data message, in both HTML & text formats, by
    joining together all passed messages.

      @param msglist (iterable): an iterable containing a list of tuples
        (message, css_style)

    Each message is either a text string, or a list. In the latter case it is
    assumed to be a format string + parameters.
    """
    txt = html = u''
    getLogger().debug( "msglist: %r", msglist )
    for msg, css in msglist:
        if is_collection(msg):
            msg = msg[0].format(*msg[1:])
        html += div( escape(msg).replace('\n','
'), css=css or 'msg' )
        txt += msg + "\n"
    return { 'data': {'text/html' : div(html),
                      'text/plain' : txt },
             'metadata' : {} }

def data_msg( msg, mtype=None ):
    """
    Return a Jupyter display_data message, in both HTML & text formats, by
    formatting a given single message.
      @param msg (str,list): a string, or a list of format string + args,
        or an iterable of (msg,mtype)
      @param mstype (str): the message type (used for the CSS class). If
        it's \c __MULTI__, then \c msg will be treated as a multi-message
    """
    if isinstance(msg,KrnlException):
        return msg() # a KrnlException knows how to format itself
    elif mtype == '_MULTI_':
        return data_msglist( msg )
    else:
        return data_msglist( [ (msg, mtype) ] )

# ----------------------------------------------------------------------

class KrnlException( Exception ):
    """
    An exception for kernel errors. Will generate a Jupyter message
    to be sent to the frontend
    """
    def __init__(self, msg, *args):
        if isinstance(msg,Exception):
            msg = repr( msg )
        elif len(msg):
            msg = msg.format(*args)
        getLogger().warn( "KrnlException: %s", msg, exc_info=1 )
        super(KrnlException,self).__init__(msg)

    def __call__(self):
        """
        When called as a function, it generates a Jupyter display data message
        """
        msg = escape(self.args[0]).replace('\n','
')
        html = div( div(u'Error: '+msg, css="error") )
        return { 'data': {'text/html' : html,
                          'text/plain' : 'Error: ' + self.args[0] },
                 'metadata' : {} }


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Blätterpilze 1: 361 (1914)

#### Original name
Agaricus imperialis Fr., 1845

### Remarks
null


text:
<!DOCTYPE html>

    <meta charset="utf-8" />

  <meta name="viewport" content="width=device-width,initial-scale=1">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="lang:clipboard.copy" content="Copy to clipboard">
  <meta name="lang:clipboard.copied" content="Copied to clipboard">
  <meta name="lang:search.language" content="en">
  <meta name="lang:search.pipeline.stopwords" content="True">
  <meta name="lang:search.pipeline.trimmer" content="True">
  <meta name="lang:search.result.none" content="No matching documents">
  <meta name="lang:search.result.one" content="1 matching document">
  <meta name="lang:search.result.other" content="# matching documents">
  <meta name="lang:search.tokenizer" content="[\s\-]+">

    <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
    <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">

  <link rel="stylesheet" href="../_static/stylesheets/application.css"/>
  <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
  <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>

  <link rel="stylesheet" href="../_static/fonts/material-icons.css"/>

  <meta name="theme-color" content="#3f51b5">

    <title>statsmodels.tsa.vector_ar.vecm.JohansenTestResult — statsmodels</title>
  <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
  <link rel="manifest" href="../_static/icons/site.webmanifest">
  <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
  <meta name="msapplication-TileColor" content="#2b5797">
  <meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
  <link rel="stylesheet" href="../_static/stylesheets/examples.css">
    <link rel="stylesheet" href="../_static/material.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />

    <link rel="shortcut icon" href="../_static/favicon.ico"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="statsmodels.tsa.vector_ar.vecm.JohansenTestResult.cvm" href="statsmodels.tsa.vector_ar.vecm.JohansenTestResult.cvm.html" />
    <link rel="prev" title="statsmodels.tsa.vector_ar.vecm.coint_johansen" href="statsmodels.tsa.vector_ar.vecm.coint_johansen.html" />

  <svg class="md-svg">
    <defs data-children-count="0">

      <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>

    </defs>
  </svg>

  <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
  <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">

   Skip to content

          statsmodels v0.11.1
           statsmodels.tsa.vector_ar.vecm.JohansenTestResult

    <form class="md-search__form" action="../search.html" method="GET" name="search">
      <input type="text" class="md-search__input" name="q" placeholder="Search"
             autocapitalize="off" autocomplete="off" spellcheck="false"
             data-md-component="query" data-md-state="active">

      <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">
        
      </button>
    </form>

            Type to start searching

      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
        <use xlink:href="#__github" width="24" height="24"></use>
      </svg>

    statsmodels

User Guide

Vector Autoregressions tsa.vector_ar

    statsmodels v0.11.1

      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
        <use xlink:href="#__github" width="24" height="24"></use>
      </svg>

    statsmodels

      Installing statsmodels

      Getting started

      User Guide

      Background

      Regression and Linear Models

      Time Series Analysis

      Time Series analysis tsa

      Time Series Analysis by State Space Methods statespace

      Vector Autoregressions tsa.vector_ar

      Other Models

      Statistics and Tools

      Data Sets

      Sandbox

      Examples

      API Reference

      About statsmodels

      Developer Page

      Release Notes

Show Source

statsmodels.tsa.vector_ar.vecm.JohansenTestResult¶

class statsmodels.tsa.vector_ar.vecm.JohansenTestResult(rkt, r0t, eig, evec, lr1, lr2, cvt, cvm, ind)[source]¶

Results class for Johansen's cointegration test

Notes

See p. 292 in [Rdb8d6a7c069c-1] for r0t and rkt

References

Rdb8d6a7c069c-1

Lütkepohl, H. 2005. New Introduction to Multiple Time Series
Analysis. Springer.

Methods

<colgroup>
<col style="width: 10%"/>
<col style="width: 90%"/>
</colgroup>

Properties

<colgroup>
<col style="width: 10%"/>
<col style="width: 90%"/>
</colgroup>

cvm

Critical values (90%, 95%, 99%) of maximum eigenvalue statistic.

cvt

Critical values (90%, 95%, 99%) of trace statistic

eig

Eigenvalues of VECM coefficient matrix

evec

Eigenvectors of VECM coefficient matrix

ind

Order of eigenvalues

lr1

Trace statistic

lr2

Maximum eigenvalue statistic

max_eig_stat

Maximum eigenvalue statistic

max_eig_stat_crit_vals

Critical values (90%, 95%, 99%) of maximum eigenvalue statistic.

meth

Test method

r0t

Residuals for \(\Delta Y\).

rkt

Residuals for \(Y_{-1}\)

trace_stat

Trace statistic

trace_stat_crit_vals

Critical values (90%, 95%, 99%) of trace statistic

                   Previous  statsmodels.tsa.vector_ar.vecm.coint_johansen

  Next  statsmodels.tsa.vector_ar.vecm.JohansenTestResult.cvm

              © Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.

            Last updated on
              Feb 21, 2020.

            Created using
            Sphinx 2.4.2.
             and
            Material for
              Sphinx


text:
require 'juli/util'
require 'juli/parser.tab'
Dir.glob(File.join(File.dirname(__FILE__), 'command/*.rb')){|sub_command_file|
  require sub_command_file
}

module Juli
  # This is a top level module for juli(1) command execution.
  # Each juli(1) command corresponds to each method here.
  module Command
    class Error < Exception; end

    # top level command execution.  command_str will be checked and
    # dispatched to each method.
    def run(command_str, opts = {})
      if command_str == 'init'
        init(opts)
      else
        Juli::Util::JuliI18n.new(conf, juli_repo)
        case command_str
        when 'gen';           gen(opts)
        when 'sitemap';       Juli::Command::Sitemap.new.run(opts)
        when 'recent_update'; Juli::Command::RecentUpdate.new.run(opts)
        when 'tag';           Juli::Command::Tag.new.run(opts)
        else
          STDERR.print "Unknown juli command: '#{command_str}'\n\n", usage, "\n"
          raise Error
        end
      end
    end

OUTPUT_TOP_COMMENT = <<EOM
# Juli-repo config file.
#
# This is YAML format.
#
# Starting '#' at each line means just comment.
# You can delete these comments.
#
# The commented-out settings shown in this file represent the default values.

# Locale(default = en)
#
#locale: en

# show_indent_toggle_button (default = true) to show/hide the toggle button
# for indented scope of the text.  NOTE: toggle action still works even
# though button is hidden.
#
#show_indent_toggle_button: true

# When set to '1st-only' (default), wikiname auto-link is applied at ONLY 1st
# occurence in a text, otherwise is applied at every occurence:
#
#link_wikiname_on:          1st-only

# Specify output top directory (default = ../html).

EOM
TEMPLATE_COMMENT = <<EOM

# Specify html template when generating (default = 'default.html', which
# means that RUBY_LIB/juli/template/default.html is used).
#
# Current available templates are under RUBY_LIB/juli/template/, where
# RUBY_LIB is the directory which juli library is installed
# (e.g. /usr/local/lib/ruby/site_ruby/1.9/).
#
# You can put your customized template under JULI_REPO/.juli/
# rather than ruby standard library directory.  For example,
# if you want to use your customized template 'blue_ocean.html',
# create it under JULI_REPO/ and specify it at config as follows:
#
#   $ cp RUBY_LIB/juli/template/default.html JULI_REPO/.juli/blue_ocean.html
#   (edit JULI_REPO/.juli/blue_ocean.html as you like)
#   (edit JULI_REPO/.juli/config as follows:
#
#   template: blue_ocean.html
#
# File extention (e.g. .html) is required in this config.
# -t option at 'juli gen' command line execution can be also supported.
#

EOM
EXT_COMMENT = <<EOM

# Generated file's extention (default = .shtml).
# The reason why '.shtml' is because to use SSI (server side include)
# for recent_update.  Of course, it depends on web-server configuration and
# you may not use SSI.  In such a case, you can change to '.html'.

EOM
    # init does:
    #
    # 1. create juli-repository at the current directory, if not yet.
    # 1. create config file under the juli-repo, if not yet.
    #    This stores juli-repo dependent information.
    # 1. if parameters are specified, store it in config file under juli-repo.
    #
    # === OPTIONS
    # -o output_top
    # -t template
    # -e ext
    def init(opts)
      if !File.directory?(Juli::REPO)
        FileUtils.mkdir(Juli::REPO)
      else
        STDERR.print "WARN: juli-repo is already created\n"
      end

      config_file = File.join(Juli::REPO, 'config')
      if !File.exist?(config_file)
        File.open(config_file, 'w') do |f|
          f.print OUTPUT_TOP_COMMENT
          write_config(f, 'output_top', opts[:o])
          f.print TEMPLATE_COMMENT
          write_config(f, 'template',   opts[:t])
          f.print EXT_COMMENT
          write_config(f, 'ext',        opts[:e])
          write_macro_conf(f)
          write_helper_conf(f)
        end
      else
        STDERR.print "WARN: config file is already created\n"
      end
    end

    # generate command
    #
    # === OPTIONS
    # -g generator::    specify generator
    # -f::              force update
    # -t template::     specify template
    # -o output_path::  specify output file path (only non-bulk-mode)
    def gen(opts)
      o = opts.dup
      o.delete(:g)
      # executes each generator's init here:
      v = visitor(opts[:g]).new(o)

      if ARGV.empty?
        print "bulk mode\n"
        if opts[:o]
          STDERR.print "ERROR: -o #{opts[:o]} is specified in bulk-mode\n"
        else
          v.run_bulk
        end
      else
        for file in ARGV do
          Juli::Parser.new.parse(file, v)
        end
      end
    end

  private
    def write_config(f, key, value)
      if value
        f.printf("%s: %s\n", key, value)
      end
    end

    # write each macro conf sample to initial .juli/conf file
    # by calling 'conf_template' method on each macro.
    def write_macro_conf(f)
      for macro_symbol in Juli::Macro.constants do
        next if macro_symbol == :Base
        macro_class = Juli::Macro.module_eval(macro_symbol.to_s)
        f.print "\n", macro_class.conf_template
      end
    end

    # write each helper conf sample to initial .juli/conf file
    # by calling 'conf_template' method on each macro.
    def write_helper_conf(f)
      for helper_symbol in Juli::Visitor::Html::Helper.constants do
        next if helper_symbol == :AbstractHelper
        helper_class = Juli::Visitor::Html::Helper.module_eval(helper_symbol.to_s)
        f.print "\n", helper_class.conf_template
      end
    end
  end
end


text:
import RegisterForm from './RegisterForm'
export default RegisterForm


text:
package com.sibisoft.data;

public interface IExpression {
	Money reduce(Bank bank, String to);
	IExpression plus(IExpression addend);
	IExpression times(Integer multiplier);
}


text:
mkdir A
mkdir B
mkdir C
mkdir D
mkdir E
mkdir F
mkdir G
mkdir H
mkdir I
mkdir J
mkdir K
mkdir L
mkdir M
mkdir N
mkdir O
mkdir P
mkdir Q
mkdir R
mkdir S
mkdir T
mkdir U
mkdir V
mkdir W
mkdir X
mkdir Y
mkdir Z
mkdir num
mkdir misc

# Must use find to do this, since "mv dir/A* otherdir/A"
# leads to an overflow on the shell command line.
echo "start A"
time find ../wiki-stripped -name 'A*' -exec mv {} A \;
time find ../wiki-stripped -name 'B*' -exec mv {} B \;
time find ../wiki-stripped -name 'C*' -exec mv {} C \;
time find ../wiki-stripped -name 'D*' -exec mv {} D \;
echo "start E"
time find ../wiki-stripped -name 'E*' -exec mv {} E \;
time find ../wiki-stripped -name 'F*' -exec mv {} F \;
time find ../wiki-stripped -name 'G*' -exec mv {} G \;
time find ../wiki-stripped -name 'H*' -exec mv {} H \;
echo "start I"
time find ../wiki-stripped -name 'I*' -exec mv {} I \;
time find ../wiki-stripped -name 'J*' -exec mv {} J \;
time find ../wiki-stripped -name 'K*' -exec mv {} K \;
time find ../wiki-stripped -name 'L*' -exec mv {} L \;
echo "start M"
time find ../wiki-stripped -name 'M*' -exec mv {} M \;
time find ../wiki-stripped -name 'N*' -exec mv {} N \;
time find ../wiki-stripped -name 'O*' -exec mv {} O \;
time find ../wiki-stripped -name 'P*' -exec mv {} P \;
time find ../wiki-stripped -name 'Q*' -exec mv {} Q \;
echo "start R"
time find ../wiki-stripped -name 'R*' -exec mv {} R \;
time find ../wiki-stripped -name 'S*' -exec mv {} S \;
echo "start T"
time find ../wiki-stripped -name 'T*' -exec mv {} T \;
time find ../wiki-stripped -name 'U*' -exec mv {} U \;
time find ../wiki-stripped -name 'V*' -exec mv {} V \;
time find ../wiki-stripped -name 'W*' -exec mv {} W \;
echo "start X"
time find ../wiki-stripped -name 'X*' -exec mv {} X \;
time find ../wiki-stripped -name 'Y*' -exec mv {} Y \;
time find ../wiki-stripped -name 'Z*' -exec mv {} Z \;
time find ../wiki-stripped -name '[०,१,२,३,४,५,६,७,८,९]*' -exec mv {} num \;
time find ../wiki-stripped -name '[૦,૧,૨,૩,૪,૫,૬,૭,૮,૯]*' -exec mv {} num \;
time find ../wiki-stripped -name '[0-9]*' -exec mv {} num \;
time find ../wiki-stripped -name '*' -type f -exec mv {} misc \;


text:
import subprocess

TYPE_WARN_MSG = 'WARNING! A string "%s" passed to a numeric variable. ' \
                'Change the variable type or the passed value.' \

class InvalidTokenError(Exception):
    pass

class InvalidConfigError(TypeError):
    pass

class UnexpectedVariableTypeError(TypeError):
    pass

class UnexpectedVariableValueTypeError(TypeError):
    pass

class MqttConnectionError(Exception):
    def __init__(self, code):
        super(MqttConnectionError, self).__init__()
        self.code = code

class NotSupportedError(Exception):
    pass

__messages = {
    KeyboardInterrupt: 'Interrupted',
    subprocess.CalledProcessError: 'Try run with sudo',
    InvalidTokenError:
        'Device token {0} is invalid. Please verify it.',
    InvalidConfigError:
        'Configuration is invalid. It must be an array.',
    UnexpectedVariableTypeError:
        ('Unexpected type for the "{0}" variable. '
         'It must be "bool", "numeric", "string" or "location".'),
    UnexpectedVariableValueTypeError:
        'Unexpected value type for variable: {0}'
}

def get_error_message(e):
    msg = getattr(e, 'message', repr(e))
    return __messages.get(type(e), 'Unexpected error: {0}').format(msg)


text:
namespace IO
{
	class IStream;
}

namespace Data
{
	class CParams;
}

namespace DEM::Sys
{
	typedef Ptr<class COSWindow> POSWindow;
}

namespace Render
{

class CGPUDriver: public Core::CObject
{
protected:

	UPTR				AdapterID = Adapter_None;
	EGPUDriverType		Type;
	EGPUFeatureLevel	FeatureLevel;	// Must be filled on init

#ifdef DEM_STATS
	UPTR				PrimitivesRendered = 0;
	UPTR				DrawsRendered = 0;
#endif

	static void					PrepareWindowAndBackBufferSize(DEM::Sys::COSWindow& Window, U32& Width, U32& Height);

public:

	CGPUDriver();
	virtual ~CGPUDriver();

	EGPUDriverType				GetType() const { return Type; }
	EGPUFeatureLevel			GetFeatureLevel() const { return FeatureLevel; }

	virtual bool				Init(UPTR AdapterNumber, EGPUDriverType DriverType) { AdapterID = AdapterNumber; OK; }
	virtual bool				CheckCaps(ECaps Cap) const = 0;
	virtual bool				SupportsShaderFormat(U32 ShaderFormatCode) const = 0;
	virtual UPTR				GetMaxVertexStreams() const = 0;
	virtual UPTR				GetMaxTextureSize(ETextureType Type) const = 0;
	virtual UPTR				GetMaxMultipleRenderTargetCount() const = 0;

	virtual int					CreateSwapChain(const CRenderTargetDesc& BackBufferDesc, const CSwapChainDesc& SwapChainDesc, DEM::Sys::COSWindow* pWindow) = 0;
	virtual bool				DestroySwapChain(UPTR SwapChainID) = 0;
	virtual bool				SwapChainExists(UPTR SwapChainID) const = 0;
	virtual bool				SwitchToFullscreen(UPTR SwapChainID, CDisplayDriver* pDisplay = nullptr, const CDisplayMode* pMode = nullptr) = 0;
	virtual bool				SwitchToWindowed(UPTR SwapChainID, const Data::CRect* pWindowRect = nullptr) = 0;
	virtual bool				ResizeSwapChain(UPTR SwapChainID, unsigned int Width, unsigned int Height) = 0;
	virtual bool				IsFullscreen(UPTR SwapChainID) const = 0;
	virtual PRenderTarget		GetSwapChainRenderTarget(UPTR SwapChainID) const = 0;
	virtual DEM::Sys::COSWindow*	GetSwapChainWindow(UPTR SwapChainID) const = 0;
	virtual PDisplayDriver		GetSwapChainDisplay(UPTR SwapChainID) const = 0;
	virtual bool				Present(UPTR SwapChainID) = 0;
	bool						PresentBlankScreen(UPTR SwapChainID, const vector4& ColorRGBA);
	virtual bool				CaptureScreenshot(UPTR SwapChainID, IO::IStream& OutStream) const = 0;

	virtual PVertexLayout		CreateVertexLayout(const CVertexComponent* pComponents, UPTR Count) = 0;
	virtual PVertexBuffer		CreateVertexBuffer(CVertexLayout& VertexLayout, UPTR VertexCount, UPTR AccessFlags, const void* pData = nullptr) = 0;
	virtual PIndexBuffer		CreateIndexBuffer(EIndexType IndexType, UPTR IndexCount, UPTR AccessFlags, const void* pData = nullptr) = 0;
	virtual PRenderState		CreateRenderState(const CRenderStateDesc& Desc) = 0;
	virtual PShader				CreateShader(IO::IStream& Stream, bool LoadParamTable = true) = 0;
	virtual PShaderParamTable   LoadShaderParamTable(uint32_t ShaderFormatCode, IO::IStream& Stream) = 0;
	virtual PConstantBuffer		CreateConstantBuffer(IConstantBufferParam& Param, UPTR AccessFlags, const CConstantBuffer* pData = nullptr) = 0;
	virtual PConstantBuffer		CreateTemporaryConstantBuffer(IConstantBufferParam& Param) = 0;
	virtual void				FreeTemporaryConstantBuffer(CConstantBuffer& Buffer) = 0;
	virtual PTexture			CreateTexture(PTextureData Data, UPTR AccessFlags) = 0;
	virtual PSampler			CreateSampler(const CSamplerDesc& Desc) = 0;
	virtual PRenderTarget		CreateRenderTarget(const CRenderTargetDesc& Desc) = 0;
	virtual PDepthStencilBuffer	CreateDepthStencilBuffer(const CRenderTargetDesc& Desc) = 0;

	virtual bool				SetViewport(UPTR Index, const CViewport* pViewport) = 0; // nullptr to reset
	virtual bool				GetViewport(UPTR Index, CViewport& OutViewport) = 0;
	virtual bool				SetScissorRect(UPTR Index, const Data::CRect* pScissorRect) = 0; // nullptr to reset
	virtual bool				GetScissorRect(UPTR Index, Data::CRect& OutScissorRect) = 0;

	virtual bool				SetVertexLayout(CVertexLayout* pVLayout) = 0;
	virtual bool				SetVertexBuffer(UPTR Index, CVertexBuffer* pVB, UPTR OffsetVertex = 0) = 0;
	virtual bool				SetIndexBuffer(CIndexBuffer* pIB) = 0;
	//virtual bool				SetInstanceBuffer(UPTR Index, CVertexBuffer* pVB, UPTR Instances, UPTR OffsetVertex = 0) = 0;
	virtual bool				SetRenderState(CRenderState* pState) = 0;
	virtual bool				SetRenderTarget(UPTR Index, CRenderTarget* pRT) = 0;
	virtual bool				SetDepthStencilBuffer(CDepthStencilBuffer* pDS) = 0;

	virtual bool				BeginFrame() = 0;
	virtual void				EndFrame() = 0;
	virtual void				Clear(UPTR Flags, const vector4& ColorRGBA, float Depth, U8 Stencil) = 0;
	virtual void				ClearRenderTarget(CRenderTarget& RT, const vector4& ColorRGBA) = 0;
	virtual void				ClearDepthStencilBuffer(CDepthStencilBuffer& DS, UPTR Flags, float Depth, U8 Stencil) = 0;
	virtual bool				Draw(const CPrimitiveGroup& PrimGroup) = 0;
	virtual bool				DrawInstanced(const CPrimitiveGroup& PrimGroup, UPTR InstanceCount) = 0;

	//!!!???need copy subresource?! (has meaning for textures only! ArraySlice, MipLevel)
	//???allow copying subresource region? to CopySubresource as optional arg
	//!!!ArraySlice is valid for cubemap faces even in D3D9, with enum consts! need proper indexing!
	//MapSubresource -> OutMappedData (pointer and 2 pitches where applicable), buffers can only return a pointer!
	//UnmapResource returns is still mapped
	//???can make these calls async? copy, map etc.
	//!!!all sync for now until I run async job manager!
	// It is a good rule of thumb to supply at least 16-byte aligned pointers to WriteToResource and ReadFromResource
	virtual bool				MapResource(void** ppOutData, const CVertexBuffer& Resource, EResourceMapMode Mode) = 0;
	virtual bool				MapResource(void** ppOutData, const CIndexBuffer& Resource, EResourceMapMode Mode) = 0;
	virtual bool				MapResource(CImageData& OutData, const CTexture& Resource, EResourceMapMode Mode, UPTR ArraySlice = 0, UPTR MipLevel = 0) = 0;
	virtual bool				UnmapResource(const CVertexBuffer& Resource) = 0;
	virtual bool				UnmapResource(const CIndexBuffer& Resource) = 0;
	virtual bool				UnmapResource(const CTexture& Resource, UPTR ArraySlice = 0, UPTR MipLevel = 0) = 0;
	virtual bool				ReadFromResource(void* pDest, const CVertexBuffer& Resource, UPTR Size = 0, UPTR Offset = 0) = 0;
	virtual bool				ReadFromResource(void* pDest, const CIndexBuffer& Resource, UPTR Size = 0, UPTR Offset = 0) = 0;
	virtual bool				ReadFromResource(const CImageData& Dest, const CTexture& Resource, UPTR ArraySlice = 0, UPTR MipLevel = 0, const Data::CBox* pRegion = nullptr) = 0;
	virtual bool				WriteToResource(CVertexBuffer& Resource, const void* pData, UPTR Size = 0, UPTR Offset = 0) = 0;
	virtual bool				WriteToResource(CIndexBuffer& Resource, const void* pData, UPTR Size = 0, UPTR Offset = 0) = 0;
	virtual bool				WriteToResource(CTexture& Resource, const CImageData& SrcData, UPTR ArraySlice = 0, UPTR MipLevel = 0, const Data::CBox* pRegion = nullptr) = 0;
	virtual bool				WriteToResource(CConstantBuffer& Resource, const void* pData, UPTR Size = 0, UPTR Offset = 0) = 0;
	//virtual PVertexBuffer		CopyResource(const CVertexBuffer& Source, UPTR NewAccessFlags) = 0;
	//virtual PIndexBuffer		CopyResource(const CIndexBuffer& Source, UPTR NewAccessFlags) = 0;
	//virtual PTexture			CopyResource(const CTexture& Source, UPTR NewAccessFlags) = 0;

	//???or auto-begin if not?!
	virtual bool				BeginShaderConstants(CConstantBuffer& Buffer) = 0;
	virtual bool				CommitShaderConstants(CConstantBuffer& Buffer) = 0;

	virtual CRenderTarget*		GetRenderTarget(UPTR Index) const = 0;
	virtual CDepthStencilBuffer* GetDepthStencilBuffer() const = 0;
};

typedef Ptr<CGPUDriver> PGPUDriver;

}


text:
Personal [Homebrew Tap](https://github.com/mxcl/homebrew/wiki/Homebrew-0.9).

To import formulas in this tap:

    brew tap cyfdecyf/homebrew-tap

After this, you can run `brew install` to install formulas in this tap. For example `brew install cow`.

If you no longer want to track this tap:

    brew untap cyfdecyf/homebrew-tap


text:
% FUNCTION ne_physio_browse: browse for physio file
function ne_physio_browse(varargin)

% Version:  v0.9b
% Build:    11050712
% Date:     Apr-10 2011, 4:52 PM EST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://neuroelf.net/

% Copyright (c) 2010, 2011, Jochen Weber
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%     * Redistributions of source code must retain the above copyright
%       notice, this list of conditions and the following disclaimer.
%     * Redistributions in binary form must reproduce the above copyright
%       notice, this list of conditions and the following disclaimer in the
%       documentation and/or other materials provided with the distribution.
%     * Neither the name of Columbia University nor the
%       names of its contributors may be used to endorse or promote products
%       derived from this software without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
% DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
% DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
% (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
% ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

% global variable
global ne_gcfg;
cc = ne_gcfg.c.physio;

% try to get handle
try
    fPhysio = xfigure(get(varargin{1}, 'Parent'));
catch ne_eo;
    neuroelf_lasterr(ne_eo);
    return;
end
ud = fPhysio.UserData;
ud.hTag.BT_physio_sf_load.Enable = 'off';

% bring up dialog
[pfile, pfolder, findex] = uigetfile(cc.filter, ...
     'Please select a file containing physiological data.', ...
     'MultiSelect', 'off');

% check selection
if isequal(pfile, 0) || ...
    isequal(pfolder, 0) || ...
    isempty(pfile)
    return;
end
if isempty(pfolder)
    pfolder = pwd;
end
pfolder = strrep(pfolder, '\', '/');
if pfolder(end) == '/'
    pfolder(end) = [];
end

% re-sort filters?
if findex > 1 && ...
    findex <= size(cc.filter, 1)
    ne_gcfg.c.physio.filter = ...
        cc.filter([findex, setdiff(1:size(cc.filter, 1), findex)], :);
end

% set in selection
ud.hTag.ED_physio_sf.String = [pfolder '/' pfile];
ud.hTag.BT_physio_sf_load.Enable = 'on';


text:
require 'spec_helper'

describe PricesUrl do
  it 'takes a fixed url as constructor argument' do
    PricesUrl.new('www.somehost.com')
  end

  it 'raises an error when no url is given' do
    expect { PricesUrl.new(nil) }.to raise_error(PricesUrl::InvalidURL, 'You must give an url, ie http://www.ns.nl/api')
  end

  let(:prices_url) { PricesUrl.new('hostname') }

  it 'uses given date' do
    expect(prices_url.url(date: Date.new(2013, 7, 12))).to eq('hostname?date=12072013')
  end

  it 'uses from' do
    expected_from = 'Amsterdam'
    expect(prices_url.url(from: 'Amsterdam')).to eq("hostname?from=#{expected_from}")
  end

  it 'uses to' do
    expected_to = 'Purmerend'
    expect(prices_url.url(to: 'Purmerend')).to eq("hostname?to=#{expected_to}")
  end

  it 'uses via' do
    expected_via = 'Zaandam'
    expect(prices_url.url(via: 'Zaandam')).to eq("hostname?via=#{expected_via}")
  end

  it 'uses any all variables for from/to/via' do
    expect(prices_url.url(from: 'Purmerend', to: 'Amsterdam', via: 'Zaandam')).to eq('hostname?from=Purmerend&to=Amsterdam&via=Zaandam')
  end

  it 'html encodes' do
    expect(prices_url.url(from: 'Purmerend', to: 'Amsterdam Centraal')).to eq('hostname?from=Purmerend&to=Amsterdam%20Centraal')
  end

  ANY_DATE = Date.new(2013, 8, 13)
  ANY_DATE_STR = '13082013'
end


text:
from __future__ import division  # so that 1/3=0.333 instead of 1/3=0
from AppKit import NSScreen
from psychopy import visual, data, core, event, monitors
from psychopy.constants import *  # things like STARTED, FINISHED
import os
from os.path import expanduser
import cPickle as pickle
import sys
sys.dont_write_bytecode = True
import vwmClasses

#########  Monitor Settings  ##################
MonitorWidth =  NSScreen.screens()[0].frame().size.width
MonitorHeight = NSScreen.screens()[0].frame().size.height
SubjDistance = 45 # distance from the screen in centimeters
MonitorWidthCM  = 27  # in cm
# set up window
mon = monitors.Monitor('')
mon.setDistance(SubjDistance) # centimeters of between monitor and subject
mon.setSizePix([MonitorWidth,MonitorHeight])
mon.setWidth(MonitorWidthCM) # width in pixels of the monitor
win = visual.Window(size=(MonitorWidth, MonitorHeight), fullscr=True, screen=1, allowGUI=False, allowStencil=False,
                    monitor=mon, units = 'deg', color=[0,0,0], colorSpace='rgb', blendMode='avg')

# behav trial run for data saving
behavRun = 'behav5'

# make filenames based on date and terminal input
date = data.getDateStr()
homeDirectory = expanduser("~")
saveDirectory = homeDirectory + os.sep + 'Google Drive/tACS_VWM_ALPHA/data'
filename = saveDirectory + os.sep + behavRun + os.sep + 's' + sys.argv[1] + os.sep + 'runData/run' + sys.argv[2] + "_" + date
pickleFilename = saveDirectory + os.sep + behavRun + os.sep + 's' + sys.argv[1] + os.sep + 'setupData/subj' + sys.argv[1] + 'run' + sys.argv[2] + '.p'

# ExperimentHandler conducts data saving
thisExp = data.ExperimentHandler(name='run', version='',
    extraInfo=None, runtimeInfo=None,
    originPath=None,
    savePickle=False, saveWideText=True,
    dataFileName=filename)

# Global Constants:
directionCueTime = 0.2
fixCrossTime = 0.1
stimArrayTime = 0.1
retentionTime = 1.0
testArrayTime = 1.0
itiTime = 0.6

# Load VWMTrials data structure from setup pickle
VWMTrials = pickle.load(open(pickleFilename, "r" ))
nTrials = len(VWMTrials)

# Define vwm class from visual.Rect()
def vwmRect(orientation, centerLoc, color):
    return visual.Rect(win=win, name=None,
    width=1, height=3, ori=orientation,
    pos=centerLoc, lineWidth=1, lineColor=color, lineColorSpace='rgb',
    fillColor=color, fillColorSpace='rgb', opacity=1, depth=-1.0, interpolate=True)

# Initialize array of all rectangles per trial
rectsPerTrial = []
for trial in VWMTrials:
    trialObjsArray = trial.Objects
    rects = []
    for obj in trialObjsArray:
        ori = obj.getOrientation()
        loc = obj.getLoc()
        color = obj.getColor()
        rect = vwmRect(ori, loc, color)
        rects.append(rect)
    rectsPerTrial.append(rects)

# Define fixation cross graphic
def makeCross():
    return visual.TextStim(win=win, ori=0,
    text=u'+',    font=u'Arial',
    pos=[0, 0], height=2.0, wrapWidth=None,
    color=u'white', colorSpace='rgb', opacity=1,
    depth=0.0)

# Initialize components for Routine "direct_cue"
direct_cueClock = core.Clock()
directionalCue = visual.TextStim(win=win, ori=0, name='text',
    text=u'\u2194',    font=u'Arial',
    pos=[0, 0], height=2.0, wrapWidth=None,
    color=u'white', colorSpace='rgb', opacity=1,
    depth=0.0)

# Initialize components for Routine "fix_cross"
fix_crossClock = core.Clock()
cross1 = makeCross()

# Initialize components for Routine "stim_array"
stim_arrayClock = core.Clock()
cross3 = makeCross()

# Initialize components for Routine "reten_time"
reten_timeClock = core.Clock()
cross2 = makeCross()

# Initialize components for Routine "test_array"
test_arrayClock = core.Clock()
cross4 = makeCross()

# Create some handy timers
globalClock = core.Clock()  # to track the time since experiment started
routineTimer = core.CountdownTimer()  # to track time remaining of each (non-slip) routine

######## Define run method ########

def oneTrial(i):
#------Prepare to start Routine "direct_cue"-------
    t = 0 # time in seconds
    direct_cueClock.reset()  # clock
    routineTimer.add(directionCueTime)
    # update component parameters for each repeat
    # keep track of which components have finished
    directionalCue.status = NOT_STARTED

    #-------Start Routine "direct_cue"-------
    continueRoutine = True
    while routineTimer.getTime() > 0:
        # get current time for data saving
        t = direct_cueClock.getTime()
        # update/draw components on each frame

        # *directionalCue* updates
        if directionalCue.status == NOT_STARTED:
            # keep track of start time for later
            directionalCue.tStart = t  # underestimates by a little under one frame
            directionalCue.setAutoDraw(True)
        if directionalCue.status == STARTED and t >= (directionCueTime-win.monitorFramePeriod*0.75): #most of one frame period left
            directionalCue.setAutoDraw(False)
            continueRoutine = False

        if continueRoutine:
            win.flip() # refreshes the screen

        # check for quit (the Esc key)
        if event.getKeys(keyList=["escape"]):
            core.quit()

    #-------Ending Routine "direct_cue"-------
    directionalCue.setAutoDraw(False)

    #------Prepare to start Routine "fix_cross"-------
    t = 0
    fix_crossClock.reset()  # clock
    routineTimer.add(fixCrossTime)
    # update component parameters for each repeat
    # keep track of which components have finished
    cross1.status = NOT_STARTED

    #-------Start Routine "fix_cross"-------
    continueRoutine = True
    while routineTimer.getTime() > 0:
        # get current time
        t = fix_crossClock.getTime()
        # update/draw components on each frame

        # *cross1* updates
        if t >= 0.0 and cross1.status == NOT_STARTED:
            # keep track of start time for later
            cross1.tStart = t  # underestimates by a little under one frame
            cross1.setAutoDraw(True)
        if cross1.status == STARTED and t >= (fixCrossTime-win.monitorFramePeriod*0.75): #most of one frame period left
            cross1.setAutoDraw(False)
            continueRoutine = False

        if continueRoutine:
            win.flip() # refreshes the screen

        # check for quit (the Esc key)
        if event.getKeys(keyList=["escape"]):
            core.quit()

    #-------Ending Routine "fix_cross"-------
    cross1.setAutoDraw(False)

    #------Prepare to start Routine "stim_array"-------
    t = 0
    stim_arrayClock.reset()  # clock
    routineTimer.add(stimArrayTime)
    # update component parameters for each repeat
    # keep track of which components have finished
    stim_arrayComponents = []
    stim_arrayComponents.append(cross3)
    for rect in rectsPerTrial[i]:
        stim_arrayComponents.append(rect)
    for thisComponent in stim_arrayComponents:
        thisComponent.status = NOT_STARTED

    #-------Start Routine "stim_array"-------
    continueRoutine = True
    while continueRoutine and routineTimer.getTime() > 0:
        # get current time
        t = stim_arrayClock.getTime()
        # update/draw components on each frame

        # *cross3* updates
        if t >= 0.0 and cross3.status == NOT_STARTED:
            # keep track of start time for later
            cross3.tStart = t  # underestimates by a little under one frame
            cross3.setAutoDraw(True)
        if cross3.status == STARTED and t >= (stimArrayTime-win.monitorFramePeriod*0.75): #most of one frame period left
            cross3.setAutoDraw(False)

        # *Rects* updates
        for rect in rectsPerTrial[i]:
            if t >= 0.0 and rect.status == NOT_STARTED:
                # keep track of start time for later
                rect.tStart = t  # underestimates by a little under one frame
                rect.setAutoDraw(True)

        if t >= (0.0 + (stimArrayTime-win.monitorFramePeriod*0.75)): #most of one frame period left
            for rect in rectsPerTrial[i]:
                rect.setAutoDraw(False)

        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in stim_arrayComponents:
            if thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished

        # check for quit (the Esc key)
        if event.getKeys(keyList=["escape"]):
            core.quit()

        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()

    #-------Ending Routine "stim_array"-------
    for thisComponent in stim_arrayComponents:
        thisComponent.setAutoDraw(False)

    #------Prepare to start Routine "reten_time"-------
    t = 0
    reten_timeClock.reset()  # clock
    routineTimer.add(retentionTime)
    # update component parameters for each repeat
    # keep track of which components have finished
    cross2.status = NOT_STARTED

    #-------Start Routine "reten_time"-------
    continueRoutine = True
    while routineTimer.getTime() > 0:
        # get current time
        t = reten_timeClock.getTime()
        # update/draw components on each frame

        # *cross2* updates
        if t >= 0.0 and cross2.status == NOT_STARTED:
            # keep track of start time for later
            cross2.tStart = t  # underestimates by a little under one frame
            cross2.setAutoDraw(True)
        if cross2.status == STARTED and t >= (retentionTime-win.monitorFramePeriod*0.75): #most of one frame period left
            cross2.setAutoDraw(False)
            continueRoutine = False

        if continueRoutine:
            win.flip() # refreshes the screen

        # check for quit (the Esc key)
        if event.getKeys(keyList=["escape"]):
            core.quit()

    #-------Ending Routine "reten_time"-------
    cross2.setAutoDraw(False)

    #------Prepare to start Routine "test_array"-------
    t = 0
    test_arrayClock.reset()  # clock
    routineTimer.add(testArrayTime + itiTime)
    # update component parameters for each repeat
    testResponse = event.BuilderKeyResponse()  # create an object of type KeyResponse
    testResponse.status = NOT_STARTED
    # keep track of which components have finished
    test_arrayComponents = []
    test_arrayComponents.append(testResponse)
    test_arrayComponents.append(cross4)
    slideRects = []
    for rect in rectsPerTrial[i]:
        test_arrayComponents.append(rect)
        slideRects.append(rect)
    if VWMTrials[i].ChangeTrial == 1:
        slideRects[VWMTrials[i].TargetChangeID].ori += VWMTrials[i].rotation
    for thisComponent in test_arrayComponents:
        thisComponent.status = NOT_STARTED

    #-------Start Routine "test_array"-------
    continueRoutine = True
    while continueRoutine and routineTimer.getTime() > 0:
        endExpNow = False
        # get current time
        t = test_arrayClock.getTime()
        # update/draw components on each frame

        # *Rects* updates
        for rect in slideRects:
            if t >= 0.0 and rect.status == NOT_STARTED:
                # keep track of start time for later
                rect.tStart = t  # underestimates by a little under one frame
                rect.setAutoDraw(True)

        if t >= (0.0 + (testArrayTime-win.monitorFramePeriod*0.75)): #most of one frame period left
            for rect in rectsPerTrial[i]:
                rect.setAutoDraw(False)

        # *cross4* updates
        if t >= 0.0 and cross4.status == NOT_STARTED:
            # keep track of start time for later
            cross4.tStart = t  # underestimates by a little under one frame
            cross4.setAutoDraw(True)
        if cross4.status == STARTED and t >= (testArrayTime - win.monitorFramePeriod*0.75): #most of one frame period left
            cross4.setAutoDraw(False)

        # *testResponse* updates
        if t >= 0.0 and testResponse.status == NOT_STARTED:
            # keep track of start time for later
            testResponse.tStart = t  # underestimates by a little under one frame
            testResponse.status = STARTED
            # keyboard checking is just starting
            win.callOnFlip(testResponse.clock.reset)  # t=0 on next screen flip
            event.clearEvents(eventType='keyboard')
        if testResponse.status == STARTED and t >= (testArrayTime + itiTime -win.monitorFramePeriod*0.75): #most of one frame period left
            testResponse.status = STOPPED
        if testResponse.status == STARTED:
            theseKeys = event.getKeys(keyList=['1','2'])

            # check for quit:
            if "escape" in theseKeys:
                endExpNow = True
            if len(theseKeys) > 0:  # at least one key was pressed
                testResponse.keys = theseKeys[-1]  # just the last key pressed
                testResponse.rt = testResponse.clock.getTime()

        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in test_arrayComponents:
            if thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished

        # check for quit (the Esc key)
        if endExpNow or event.getKeys(keyList=["escape"]):
            core.quit()

        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()

    #-------Ending Routine "test_array"-------
    for thisComponent in test_arrayComponents:
        if hasattr(thisComponent, 'setAutoDraw'):
            thisComponent.setAutoDraw(False)
    # check responses
    if testResponse.keys in ['', [], None]:  # No response was made
       testResponse.keys=None

    # record # of targets and distractors in each hemifield and where change occured
    changeTargHemi = VWMTrials[i].Objects[VWMTrials[i].TargetChangeID].getHemifield()
    leftTargCount = VWMTrials[i].leftObjectCount(objType='target')
    leftDistCount = VWMTrials[i].leftObjectCount(objType='distractor')
    rightTargCount = VWMTrials[i].rightObjectCount(objType='target')
    rightDistCount = VWMTrials[i].rightObjectCount(objType='distractor')

    # mark response
    resp = 0
    if testResponse.keys == '1':
        resp = 1
    elif testResponse.keys == '2':
        resp = 2

    #-------Store data for thisExp (ExperimentHandler)-------
    thisExp.addData('trialID', VWMTrials[i].trialID)
    thisExp.addData('Response',resp)
    if testResponse.keys != None:  # we had a response
        thisExp.addData('RT', testResponse.rt)
    thisExp.addData('ChangeTrial', VWMTrials[i].ChangeTrial)
    thisExp.addData('nDistractors', VWMTrials[i].nDistractors)
    thisExp.addData('nTargets', VWMTrials[i].nTargets)
    thisExp.addData('Cond', VWMTrials[i].condNum)
    if VWMTrials[i].ChangeTrial == 1:
        thisExp.addData('changeHemi', changeTargHemi)
    thisExp.addData('ChangeCond', VWMTrials[i].ChangeCond)
    thisExp.addData('leftTargs', leftTargCount)
    thisExp.addData('rightTargs', rightTargCount)
    thisExp.addData('leftDists', leftDistCount)
    thisExp.addData('rightDists', rightDistCount)
    thisExp.nextEntry()


text:
#pragma once

#include "MenuScreen.h"
#include "GameStateManager.h"

namespace BumbleRumble
{
    class OptionsPopUpScreen : public MenuScreen
    {
    public:
        OptionsPopUpScreen();
        virtual ~OptionsPopUpScreen();

        virtual void HandleInput() override;
        virtual void Update(float totalTime, float elapsedTime, bool otherScreenHasFocus, bool coveredByOtherScreen) override;
        virtual void Draw(float totalTime, float elapsedTime) override;
        virtual void LoadContent() override;

    protected:
        virtual void OnCancel() override;
        virtual void ComputeMenuBounds(float viewportWidth, float viewportHeight) override;

    private:
        std::shared_ptr<DX::Texture> m_backgroundTexture;
        int m_currentIndex;
    };
}


text:
using System;

namespace CQRS.Light.Contracts
{
    public interface IAggregateRepository<TAggregate> where TAggregate : IAggregateRoot
    {
        void Add(TAggregate aggregate);
        TAggregate GetById(Guid aggregateId);
        void Configure(Func<Type, object> getInstance);
    }

}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IEncryptionService.cs" company="Kephas Software SRL">
//   Copyright (c) Kephas Software SRL. All rights reserved.
//   Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
//   Declares the IEncryptionService interface.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Kephas.Cryptography
{
    using System;
    using System.IO;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;

    using Kephas.Diagnostics.Contracts;
    using Kephas.Services;
    using Kephas.Threading.Tasks;

    /// <summary>
    /// Application service contract for encryption.
    /// </summary>
    [SingletonAppServiceContract]
    public interface IEncryptionService
    {
        /// <summary>
        /// Generates a key.
        /// </summary>
        /// <param name="optionsConfig">Optional. The options configuration.</param>
        /// <returns>
        /// An array of byte.
        /// </returns>
        byte[] GenerateKey(Action<IEncryptionContext>? optionsConfig = null);

        /// <summary>
        /// Encrypts the input stream and writes the encrypted content into the output stream.
        /// </summary>
        /// <param name="input">The input stream.</param>
        /// <param name="output">The output stream.</param>
        /// <param name="optionsConfig">Optional. The options configuration.</param>
        /// <param name="cancellationToken">Optional. The cancellation token.</param>
        /// <returns>
        /// The asynchronous result.
        /// </returns>
        Task EncryptAsync(
            Stream input,
            Stream output,
            Action<IEncryptionContext>? optionsConfig = null,
            CancellationToken cancellationToken = default);

        /// <summary>
        /// Decrypts the input stream and writes the decrypted content into the output stream.
        /// </summary>
        /// <param name="input">The input stream.</param>
        /// <param name="output">The output stream.</param>
        /// <param name="optionsConfig">Optional. The options configuration.</param>
        /// <param name="cancellationToken">Optional. The cancellation token.</param>
        /// <returns>
        /// The asynchronous result.
        /// </returns>
        Task DecryptAsync(
            Stream input,
            Stream output,
            Action<IEncryptionContext>? optionsConfig = null,
            CancellationToken cancellationToken = default);

#if NETSTANDARD2_1
        /// <summary>
        /// Encrypts the input stream and writes the encrypted content into the output stream.
        /// </summary>
        /// <param name="input">The input stream.</param>
        /// <param name="output">The output stream.</param>
        /// <param name="optionsConfig">Optional. The options configuration.</param>
        void Encrypt(
            Stream input,
            Stream output,
            Action<IEncryptionContext>? optionsConfig = null)
        {
            this.EncryptAsync(input, output, optionsConfig).WaitNonLocking();
        }

        /// <summary>
        /// Decrypts the input stream and writes the decrypted content into the output stream.
        /// </summary>
        /// <param name="input">The input stream.</param>
        /// <param name="output">The output stream.</param>
        /// <param name="optionsConfig">Optional. The options configuration.</param>
        void Decrypt(
            Stream input,
            Stream output,
            Action<IEncryptionContext>? optionsConfig = null)
        {
            this.DecryptAsync(input, output, optionsConfig).WaitNonLocking();
        }
#endif
    }

#if NETSTANDARD2_1
#else
    /// <summary>
    /// Application service contract for synchronous encryption.
    /// </summary>
    public interface ISyncEncryptionService
    {
        /// <summary>
        /// Encrypts the input stream and writes the encrypted content into the output stream.
        /// </summary>
        /// <param name="input">The input stream.</param>
        /// <param name="output">The output stream.</param>
        /// <param name="optionsConfig">Optional. The options configuration.</param>
        void Encrypt(
            Stream input,
            Stream output,
            Action<IEncryptionContext>? optionsConfig = null);

        /// <summary>
        /// Decrypts the input stream and writes the decrypted content into the output stream.
        /// </summary>
        /// <param name="input">The input stream.</param>
        /// <param name="output">The output stream.</param>
        /// <param name="optionsConfig">Optional. The options configuration.</param>
        void Decrypt(
            Stream input,
            Stream output,
            Action<IEncryptionContext>? optionsConfig = null);
    }
#endif

    /// <summary>
    /// Extension methods for <see cref="IEncryptionService"/>.
    /// </summary>
    public static class EncryptionServiceExtensions
    {
#if NETSTANDARD2_1
#else
        /// <summary>
        /// Encrypts the input stream and writes the encrypted content into the output stream.
        /// </summary>
        /// <param name="encryptionService">The encryption service.</param>
        /// <param name="input">The input.</param>
        /// <param name="output">The output.</param>
        /// <param name="optionsConfig">Optional. The options configuration.</param>
        public static void Encrypt(
            this IEncryptionService encryptionService,
            Stream input,
            Stream output,
            Action<IEncryptionContext>? optionsConfig = null)
        {
            Requires.NotNull(encryptionService, nameof(encryptionService));

            if (encryptionService is ISyncEncryptionService syncEncryptionService)
            {
                syncEncryptionService.Encrypt(input, output, optionsConfig);
            }
            else
            {
                encryptionService.EncryptAsync(input, output, optionsConfig).WaitNonLocking();
            }
        }

        /// <summary>
        /// Decrypts the input stream and writes the decrypted content into the output stream.
        /// </summary>
        /// <param name="encryptionService">The encryption service.</param>
        /// <param name="input">The input stream.</param>
        /// <param name="output">The output stream.</param>
        /// <param name="optionsConfig">Optional. The options configuration.</param>
        public static void Decrypt(
            this IEncryptionService encryptionService,
            Stream input,
            Stream output,
            Action<IEncryptionContext>? optionsConfig = null)
        {
            Requires.NotNull(encryptionService, nameof(encryptionService));

            if (encryptionService is ISyncEncryptionService syncEncryptionService)
            {
                syncEncryptionService.Decrypt(input, output, optionsConfig);
            }
            else
            {
                encryptionService.DecryptAsync(input, output, optionsConfig).WaitNonLocking();
            }
        }
#endif

        /// <summary>
        /// Encrypts the input string and returns a promise of the encrypted string (Base64 encoded).
        /// </summary>
        /// <param name="encryptionService">The encryption service to act on.</param>
        /// <param name="input">The input string.</param>
        /// <param name="optionsConfig">Optional. The options configuration.</param>
        /// <param name="cancellationToken">Optional. The cancellation token.</param>
        /// <returns>
        /// A promise of the encrypted bytes (Base64 encoded).
        /// </returns>
        public static async Task<string> EncryptAsync(
            this IEncryptionService encryptionService,
            string input,
            Action<IEncryptionContext>? optionsConfig = null,
            CancellationToken cancellationToken = default)
        {
            var bytes = await EncryptAsync(encryptionService, Encoding.UTF8.GetBytes(input), optionsConfig, cancellationToken)
                            .PreserveThreadContext();
            return Convert.ToBase64String(bytes);
        }

        /// <summary>
        /// Encrypts the input bytes and returns a promise of the encrypted bytes.
        /// </summary>
        /// <param name="encryptionService">The encryption service to act on.</param>
        /// <param name="input">The input bytes.</param>
        /// <param name="optionsConfig">Optional. The options configuration.</param>
        /// <param name="cancellationToken">Optional. The cancellation token.</param>
        /// <returns>
        /// A promise of the encrypted bytes.
        /// </returns>
        public static async Task<byte[]> EncryptAsync(
            this IEncryptionService encryptionService,
            byte[] input,
            Action<IEncryptionContext>? optionsConfig = null,
            CancellationToken cancellationToken = default)
        {
            Requires.NotNull(encryptionService, nameof(encryptionService));

            using var inputStream = new MemoryStream(input);
            using var outputStream = new MemoryStream();

            await encryptionService.EncryptAsync(inputStream, outputStream, optionsConfig, cancellationToken).PreserveThreadContext();
            var outputBytes = outputStream.ToArray();
            return outputBytes;
        }

        /// <summary>
        /// Encrypts the input string and returns the encrypted string (Base64 encoded).
        /// </summary>
        /// <param name="encryptionService">The encryption service to act on.</param>
        /// <param name="input">The input string.</param>
        /// <param name="optionsConfig">Optional. The options configuration.</param>
        /// <returns>
        /// The Base64 encoded encrypted bytes.
        /// </returns>
        public static string Encrypt(
            this IEncryptionService encryptionService,
            string input,
            Action<IEncryptionContext>? optionsConfig = null)
        {
            var bytes = Encrypt(encryptionService, Encoding.UTF8.GetBytes(input), optionsConfig);
            return Convert.ToBase64String(bytes);
        }

        /// <summary>
        /// Encrypts the input bytes and returns the encrypted bytes.
        /// </summary>
        /// <param name="encryptionService">The encryption service to act on.</param>
        /// <param name="input">The input bytes.</param>
        /// <param name="optionsConfig">Optional. The options configuration.</param>
        /// <returns>
        /// The encrypted bytes.
        /// </returns>
        public static byte[] Encrypt(
            this IEncryptionService encryptionService,
            byte[] input,
            Action<IEncryptionContext>? optionsConfig = null)
        {
            Requires.NotNull(encryptionService, nameof(encryptionService));

            using var inputStream = new MemoryStream(input);
            using var outputStream = new MemoryStream();

            encryptionService.Encrypt(inputStream, outputStream, optionsConfig);
            var outputBytes = outputStream.ToArray();
            return outputBytes;
        }

        /// <summary>
        /// Decrypts the input Base64 encoded string and returns a promise of the decrypted string.
        /// </summary>
        /// <param name="encryptionService">The encryption service to act on.</param>
        /// <param name="input">The Base64 encoded input string.</param>
        /// <param name="optionsConfig">Optional. The options configuration.</param>
        /// <param name="cancellationToken">Optional. The cancellation token.</param>
        /// <returns>
        /// A promise of a decrypted string.
        /// </returns>
        public static async Task<string> DecryptAsync(
            this IEncryptionService encryptionService,
            string input,
            Action<IEncryptionContext>? optionsConfig = null,
            CancellationToken cancellationToken = default)
        {
            var bytes = await DecryptAsync(
                            encryptionService,
                            Convert.FromBase64String(input),
                            optionsConfig,
                            cancellationToken).PreserveThreadContext();

            return Encoding.UTF8.GetString(bytes);
        }

        /// <summary>
        /// Decrypts the input bytes and returns a promise of the decrypted bytes.
        /// </summary>
        /// <param name="encryptionService">The encryption service to act on.</param>
        /// <param name="input">The input bytes.</param>
        /// <param name="optionsConfig">Optional. The options configuration.</param>
        /// <param name="cancellationToken">Optional. The cancellation token.</param>
        /// <returns>
        /// A promise of a decrypted bytes.
        /// </returns>
        public static async Task<byte[]> DecryptAsync(
            this IEncryptionService encryptionService,
            byte[] input,
            Action<IEncryptionContext>? optionsConfig = null,
            CancellationToken cancellationToken = default)
        {
            Requires.NotNull(encryptionService, nameof(encryptionService));

            using var inputStream = new MemoryStream(input);
            using var outputStream = new MemoryStream();

            await encryptionService.DecryptAsync(inputStream, outputStream, optionsConfig, cancellationToken).PreserveThreadContext();
            var outputBytes = outputStream.ToArray();
            return outputBytes;
        }

        /// <summary>
        /// Decrypts the input string and returns the decrypted string.
        /// </summary>
        /// <param name="encryptionService">The encryption service to act on.</param>
        /// <param name="input">The Base64 encoded input string.</param>
        /// <param name="optionsConfig">Optional. The options configuration.</param>
        /// <returns>
        /// A promise of the decrypted string.
        /// </returns>
        public static string Decrypt(
            this IEncryptionService encryptionService,
            string input,
            Action<IEncryptionContext>? optionsConfig = null)
        {
            var bytes = Decrypt(encryptionService, Convert.FromBase64String(input), optionsConfig);
            return Encoding.UTF8.GetString(bytes);
        }

        /// <summary>
        /// Decrypts the input bytes and returns the decrypted bytes.
        /// </summary>
        /// <param name="encryptionService">The encryption service to act on.</param>
        /// <param name="input">The input bytes.</param>
        /// <param name="optionsConfig">Optional. The options configuration.</param>
        /// <returns>
        /// The decrypted bytes.
        /// </returns>
        public static byte[] Decrypt(
            this IEncryptionService encryptionService,
            byte[] input,
            Action<IEncryptionContext>? optionsConfig = null)
        {
            Requires.NotNull(encryptionService, nameof(encryptionService));

            using var inputStream = new MemoryStream(input);
            using var outputStream = new MemoryStream();

            encryptionService.Decrypt(inputStream, outputStream, optionsConfig);
            var outputBytes = outputStream.ToArray();
            return outputBytes;
        }
    }
}


text:
package org.judal.bdbj;

import java.io.Serializable;

public class DBEntityWrapper implements Serializable {

	private static final long serialVersionUID = 1L;

	private byte[] key;
	private Serializable wrapped;

	public DBEntityWrapper(byte[] key, Serializable wrapped) {
		this.key = key;
		this.wrapped = wrapped;
	}

	public byte[] getKey() {
		return key;
	}

	public Serializable getWrapped() {
		return wrapped;
	}

}


text:
from django.core.cache import get_cache
from django.conf import settings

storage = get_cache(settings.MYPAGE_STORAGE_BACKEND)


text:
package net.predictblty.machinelearning;

/**
 * Created by berkgokden on 9/9/14.
 */
public class Main {
    public static void main(String[] args) {
    }
}


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.onebitmedia.pisolipet">

    <application
        android:allowBackup="true"
        android:label="@string/app_name"
        android:icon="@drawable/ic_launcher">

    </application>

</manifest>


text:
(function (exports, io) {

  /**
   * Expose constructor.
   */

  exports.htmlfile = HTMLFile;

  /**
   * The HTMLFile transport creates a `forever iframe` based transport
   * for Internet Explorer. Regular forever iframe implementations will
   * continuously trigger the browsers buzy indicators. If the forever iframe
   * is created inside a `htmlfile` these indicators will not be trigged.
   *
   * @constructor
   * @extends {io.Transport.XHR}
   * @api public
   */

  function HTMLFile (socket) {
    io.Transport.XHR.apply(this, arguments);
  };

  /**
   * Inherits from XHR transport.
   */

  io.util.inherit(HTMLFile, io.Transport.XHR);

  /**
   * Transport name
   *
   * @api public
   */

  HTMLFile.prototype.name = 'htmlfile';

  /**
   * Creates a new ActiveX `htmlfile` with a forever loading iframe
   * that can be used to listen to messages. Inside the generated
   * `htmlfile` a reference will be made to the HTMLFile transport.
   *
   * @api private
   */

  HTMLFile.prototype.get = function () {
    this.doc = new ActiveXObject('htmlfile');
    this.doc.open();
    this.doc.write('<html></html>');
    this.doc.close();
    this.doc.parentWindow.s = this;

    var iframeC = this.doc.createElement('div');
    iframeC.className = 'socketio';

    this.doc.body.appendChild(iframeC);
    this.iframe = this.doc.createElement('iframe');

    iframeC.appendChild(this.iframe);

    var self = this
      , query = io.util.query(this.socket.options.query, 't='+ +new Date);

    this.iframe.src = this.prepareUrl() + query;

    io.util.on(window, 'unload', function () {
      self.destroy();
    });
  };

  /**
   * The Socket.IO server will write script tags inside the forever
   * iframe, this function will be used as callback for the incoming
   * information.
   *
   * @param {String} data The message
   * @param {document} doc Reference to the context
   * @api private
   */

  HTMLFile.prototype._ = function (data, doc) {
    this.onData(data);
    try {
      var script = doc.getElementsByTagName('script')[0];
      script.parentNode.removeChild(script);
    } catch (e) { }
  };

  /**
   * Destroy the established connection, iframe and `htmlfile`.
   * And calls the `CollectGarbage` function of Internet Explorer
   * to release the memory.
   *
   * @api private
   */

  HTMLFile.prototype.destroy = function () {
    if (this.iframe){
      try {
        this.iframe.src = 'about:blank';
      } catch(e){}

      this.doc = null;
      this.iframe.parentNode.removeChild(this.iframe);
      this.iframe = null;

      CollectGarbage();
    }
  };

  /**
   * Disconnects the established connection.
   *
   * @returns {Transport} Chaining.
   * @api public
   */

  HTMLFile.prototype.close = function () {
    this.destroy();
    return io.Transport.XHR.prototype.close.call(this);
  };

  /**
   * Checks if the browser supports this transport. The browser
   * must have an `ActiveXObject` implementation.
   *
   * @return {Boolean}
   * @api public
   */

  HTMLFile.check = function () {
    if (typeof window != "undefined" && 'ActiveXObject' in window){
      try {
        var a = new ActiveXObject('htmlfile');
        return a && io.Transport.XHR.check();
      } catch(e){}
    }
    return false;
  };

  /**
   * Check if cross domain requests are supported.
   *
   * @returns {Boolean}
   * @api public
   */

  HTMLFile.xdomainCheck = function () {
    // we can probably do handling for sub-domains, we should
    // test that it's cross domain but a subdomain here
    return false;
  };

  /**
   * Add the transport to your public io.transports array.
   *
   * @api private
   */

  io.transports.push('htmlfile');

})(
    'undefined' != typeof io ? io.Transport : module.exports
  , 'undefined' != typeof io ? io : module.parent.exports
);


text:
import nameFunction from "babel-helper-function-name";
import template from "babel-template";
import syntaxClassProperties from "babel-plugin-syntax-class-properties";

export default function({ types: t }) {
  const findBareSupers = {
    Super(path) {
      if (path.parentPath.isCallExpression({ callee: path.node })) {
        this.push(path.parentPath);
      }
    },
  };

  const referenceVisitor = {
    TypeAnnotation(path) {
      path.skip();
    },
    ReferencedIdentifier(path) {
      if (this.scope.hasOwnBinding(path.node.name)) {
        this.collision = true;
        path.skip();
      }
    },
  };

  const buildObjectDefineProperty = template(`
    Object.defineProperty(REF, KEY, {
      configurable: true,
      enumerable: true,
      writable: true,
      value: VALUE
    });
  `);

  const buildClassPropertySpec = (ref, { key, value, computed }, scope) =>
    buildObjectDefineProperty({
      REF: ref,
      KEY: t.isIdentifier(key) && !computed ? t.stringLiteral(key.name) : key,
      VALUE: value ? value : scope.buildUndefinedNode(),
    });

  const buildClassPropertyLoose = (ref, { key, value, computed }, scope) =>
    t.expressionStatement(
      t.assignmentExpression(
        "=",
        t.memberExpression(ref, key, computed || t.isLiteral(key)),
        value ? value : scope.buildUndefinedNode(),
      ),
    );

  return {
    inherits: syntaxClassProperties,

    visitor: {
      Class(path, state) {
        const buildClassProperty = state.opts.loose
          ? buildClassPropertyLoose
          : buildClassPropertySpec;
        const isDerived = !!path.node.superClass;
        let constructor;
        const props = [];
        const body = path.get("body");

        for (const path of body.get("body")) {
          if (path.isClassProperty()) {
            props.push(path);
          } else if (path.isClassMethod({ kind: "constructor" })) {
            constructor = path;
          }
        }

        if (!props.length) return;

        const nodes = [];
        let ref;

        if (path.isClassExpression() || !path.node.id) {
          nameFunction(path);
          ref = path.scope.generateUidIdentifier("class");
        } else {
          // path.isClassDeclaration() && path.node.id
          ref = path.node.id;
        }

        let instanceBody = [];

        for (const prop of props) {
          const propNode = prop.node;
          if (propNode.decorators && propNode.decorators.length > 0) continue;

          const isStatic = propNode.static;

          if (isStatic) {
            nodes.push(buildClassProperty(ref, propNode, path.scope));
          } else {
            instanceBody.push(
              buildClassProperty(t.thisExpression(), propNode, path.scope),
            );
          }
        }

        if (instanceBody.length) {
          if (!constructor) {
            const newConstructor = t.classMethod(
              "constructor",
              t.identifier("constructor"),
              [],
              t.blockStatement([]),
            );
            if (isDerived) {
              newConstructor.params = [t.restElement(t.identifier("args"))];
              newConstructor.body.body.push(
                t.returnStatement(
                  t.callExpression(t.super(), [
                    t.spreadElement(t.identifier("args")),
                  ]),
                ),
              );
            }
            [constructor] = body.unshiftContainer("body", newConstructor);
          }

          const collisionState = {
            collision: false,
            scope: constructor.scope,
          };

          for (const prop of props) {
            prop.traverse(referenceVisitor, collisionState);
            if (collisionState.collision) break;
          }

          if (collisionState.collision) {
            const initialisePropsRef = path.scope.generateUidIdentifier(
              "initialiseProps",
            );

            nodes.push(
              t.variableDeclaration("var", [
                t.variableDeclarator(
                  initialisePropsRef,
                  t.functionExpression(
                    null,
                    [],
                    t.blockStatement(instanceBody),
                  ),
                ),
              ]),
            );

            instanceBody = [
              t.expressionStatement(
                t.callExpression(
                  t.memberExpression(initialisePropsRef, t.identifier("call")),
                  [t.thisExpression()],
                ),
              ),
            ];
          }

          //

          if (isDerived) {
            const bareSupers = [];
            constructor.traverse(findBareSupers, bareSupers);
            for (const bareSuper of bareSupers) {
              bareSuper.insertAfter(instanceBody);
            }
          } else {
            constructor.get("body").unshiftContainer("body", instanceBody);
          }
        }

        for (const prop of props) {
          prop.remove();
        }

        if (!nodes.length) return;

        if (path.isClassExpression()) {
          path.scope.push({ id: ref });
          path.replaceWith(t.assignmentExpression("=", ref, path.node));
        } else {
          // path.isClassDeclaration()
          if (!path.node.id) {
            path.node.id = ref;
          }

          if (path.parentPath.isExportDeclaration()) {
            path = path.parentPath;
          }
        }

        path.insertAfter(nodes);
      },
      ArrowFunctionExpression(path) {
        const classExp = path.get("body");
        if (!classExp.isClassExpression()) return;

        const body = classExp.get("body");
        const members = body.get("body");
        if (members.some(member => member.isClassProperty())) {
          path.ensureBlock();
        }
      },
    },
  };
}


text:
layout: postag
title: 'NOUN'
shortdef: 'noun'
---

### Definition

Nouns are a part of speech typically denoting a person, place, thing,
animal or idea.

The `NOUN` tag is intended for common nouns only.

In Bultreebank the common nouns are annotated with the tag `Nc#`.

### Examples

- _момиче_ / _momiche_ "girl"
- _котка_ / _kotka_ "cat"
- _дърво_ / _darvo_ "tree"
- _въздух_ / _vazduh_ "air"
- _красота_ / _krasota_ "beauty"

Note that the symbol `#', used in the Universal POS section indicates a holder for arbitrary number of features, suppressed in the respective tag as irrelevant in the BulTreeBank tagset, when mapped to the Universal one.


text:
Probable issues:

 - Array.isArray

 - Promise

 - Websockets


text: roslaunch lane_detection carlane_detection_video.launch


text:
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

'''
Compat six library.  RHEL7 has python-six 1.3.0 which is too old
'''
# The following makes it easier for us to script updates of the bundled code
_BUNDLED_METADATA = { "pypi_name": "six", "version": "1.10.0" }

import os.path
import zipfile

try:
    import six as _system_six
except ImportError:
    _system_six = None

if _system_six:
    # If we need some things from even newer versions of six, then we need to
    # use our bundled copy instead

       if ( # Added in six-1.8.0
            not hasattr(_system_six.moves, 'shlex_quote') or
            # Added in six-1.4.0
            not hasattr(_system_six, 'byte2int') or
            not hasattr(_system_six, 'add_metaclass') or
            not hasattr(_system_six.moves, 'urllib')
            ):

        _system_six = False

if _system_six:
    six = _system_six
else:
    from . import _six as six

with zipfile.ZipFile(os.path.dirname(six.__file__)) as zf:
    exec(zf.read('six.py'))