text:
This relation is a language-specific subtype of [obl]().

7 nodes (0%) are attached to their parents as `obl:agent`.

4 instances of `obl:agent` (57%) are right-to-left (child precedes parent).
Average distance between parent and child is 2.42857142857143.

The following 2 pairs of parts of speech are connected with `obl:agent`: [lt-pos/VERB]()-[lt-pos/NOUN]() (5; 71% instances), [lt-pos/VERB]()-[lt-pos/PRON]() (2; 29% instances).

~~~ conllu
# visual-style 10	bgColor:blue
# visual-style 10	fgColor:white
# visual-style 8	bgColor:blue
# visual-style 8	fgColor:white
# visual-style 8 10 obl:agent	color:blue
1	Paskutiniai	paskutinis	ADJ	JJL	Case=Nom|Definite=Ind|Degree=Pos|Gender=Masc|Number=Plur	7	amod	_	En=last
2	žemyn	žemyn	ADV	RB	Degree=Pos	3	advmod	_	En=down
3	smingančio	smigti	VERB	VBNL	Case=Gen|Definite=Ind|Gender=Masc|Number=Sing|Polarity=Pos|Reflex=No|Tense=Pres|VerbForm=Part|Voice=Act	4	amod	_	En=fall
4	Tu-154	tu-154	PROPN	NNP	Case=Gen|Gender=Masc|Number=Sing	5	nmod	_	En=Tu-154
5	kapitono	kapitonas	NOUN	NN	Case=Gen|Gender=Masc|Number=Sing	6	nmod	_	En=capitain
6	padėjėjo	padėjėjas	NOUN	NN	Case=Gen|Gender=Masc|Number=Sing	7	nmod	_	En=assistant
7	žodžiai	žodis	NOUN	NN	Case=Nom|Gender=Masc|Number=Plur	8	nsubj	_	En=word
8	fiksuoti	fiksuoti	VERB	VBNH	Case=Nom|Definite=Ind|Gender=Masc|Number=Plur|Polarity=Pos|Reflex=No|Tense=Past|VerbForm=Part|Voice=Pass	0	root	_	En=fixate
9	lietuvišku	lietuviškas	ADJ	JJL	Case=Ins|Definite=Ind|Degree=Pos|Gender=Masc|Number=Sing	10	amod	_	En=Lithianian
10	prietaisu	prietaisas	NOUN	NN	Case=Ins|Gender=Masc|Number=Sing	8	obl:agent	_	En=device

~~~

~~~ conllu
# visual-style 2	bgColor:blue
# visual-style 2	fgColor:white
# visual-style 3	bgColor:blue
# visual-style 3	fgColor:white
# visual-style 3 2 obl:agent	color:blue
1	Pasak	pasak	ADP	UH	_	4	case	_	En=according_to
2	jų	jie	PRON	PRP	Case=Gen|Number=Plur|Person=3	3	obl:agent	_	En=their
3	peršamo	piršti	VERB	VBNL	Case=Gen|Definite=Ind|Gender=Masc|Number=Sing|Polarity=Pos|Reflex=No|Tense=Pres|VerbForm=Part|Voice=Pass	4	nmod	_	En=imposed
4	mentaliteto	mentalitetas	NOUN	NN	Case=Gen|Gender=Masc|Number=Sing	9	parataxis	_	En=mentality|SpaceAfter=No
5	,	,	PUNCT	PUNCT	_	4	punct	_	En=,
6	Rusijos	Rusija	PROPN	NNP	Case=Gen|Gender=Fem|Number=Sing	7	nmod	_	En=Russia
7	interesai	interesas	NOUN	NN	Case=Nom|Gender=Masc|Number=Plur	9	nsubj	_	En=interest
8	visada	visada	ADV	RB	Degree=Pos	9	advmod	_	En=always
9	priešiški	priešiškas	ADJ	JJL	Case=Nom|Definite=Ind|Degree=Pos|Gender=Masc|Number=Plur	0	root	_	En=hostile
10	Lietuvos	Lietuva	PROPN	NNP	Case=Gen|Gender=Fem|Number=Sing	11	nmod	_	En=Lithuania
11	interesams	interesas	NOUN	NN	Case=Dat|Gender=Masc|Number=Plur	9	obj	_	En=interest|SpaceAfter=No
12	,	,	PUNCT	PUNCT	_	15	punct	_	En=,
13	ir	ir	CCONJ	CC	_	15	cc	_	En=and
14	kitaip	kitaip	ADV	RB	Degree=Pos	15	advmod	_	En=otherwise
15	negali	galėti	VERB	VBC	Mood=Ind|Number=Sing|Person=3|Polarity=Pos|Reflex=No|Tense=Pres|VerbForm=Fin|Voice=Act	9	conj	_	En=cannot
16	būti	būti	VERB	VB	Polarity=Pos|Reflex=No|VerbForm=Inf|Voice=Act	15	xcomp	_	En=be|SpaceAfter=No
17	.	.	PUNCT	PUNCT	_	9	punct	_	En=.

~~~


text:
<?php
namespace Kifs\View;

interface View
{
	/**
	 * Fetch the content of the template $templateName and returns it
	 *
	 * @param string $templateName Path to the template to fetch
	 */
	public function fetch($templateName);

	/**
	 * Registers the view helper $helper under the name $name
	 *
	 * @param string $name
	 * @param object $helper
	 */
	public function registerHelper($helper);

	/**
	 * Returns the view helper named $name if it was registered before
	 * or null otherwise
	 *
	 * @param $name $name
	 */
	public function getHelper($name);

	/**
	 * Return the content of the partial named $name. You can pass parameters
	 * to the template of the partial in $params
	 *
	 * @param string $name
	 * @param array $params
	 */
	public function partial($name, $params);
}

redpajama_set_name: RedPajamaGithub


text:
App.addChild('Explore', _.extend({
  el: 'body[data-action="index"][data-controller-name="explore"]',

  events: {
    'click .explore-toggle':'toggleCategoryList',
    'click .explore-link' : 'toggleCategoryList',
    'click #load-more' : 'loadMore'
  },

  routeFilters: {
    recent: { recent: true },
    in_funding: { in_funding: true },
    expiring: { expiring: true },
    recommended: { recommended: true },
    successful: { successful: true }
  },

  activate: function(){

    this.route('recommended');
    this.route('expiring');
    this.route('recent');
    this.route('in_funding');
    this.route('successful');
    this.route('by_category_id/:id');
    this.route('near_of/:state');

    this.setInitialFilter();
    this.setupPagination(
      this.$("#loading img"),
      this.$('#load-more'),
      this.$(".results"),
      this.$("#explore_results").data('projects-path')
    );

    if(window.location.hash == ''){
      var search_string = window.location.search.indexOf("pg_search");
      this.fetchPage();

      if(search_string == -1){
        this.toggleCategoryList();
      }
    }
  },

  toggleCategoryList: function(event) {
    this.$('#categories-wrapper').slideToggle();
  },

  selectLink: function(){
    this.$('.follow-category').hide();

    var link = this.$('a[href="' + window.location.hash + '"]')
    this.$('a.selected').removeClass('selected');

    link.addClass('selected');

    if(link.data('categoryid') || link.data('name')) {
      this.followCategory.setupFollowHeader(link);
    }
  },

  followRoute: function(route, name, params){
    this.filter = {};
    if(params.length > 0){
      this.filter[name] = params[0];
    }
    else{
      this.filter[name] = true;
    }
    this.firstPage();
    this.fetchPage();
    if(this.parent && this.parent.$search.length > 0){
      this.parent.$search.val('');
    }
    this.selectLink();
  },

  setInitialFilter: function(){
    var search = null;;
    if(this.parent && (search = this.parent.$search.val())){
      this.filter = { pg_search: search };
    }
    else{
      this.filter = {
        recommended: true,
        not_expired: true
      };
    }
  },

}, Skull.Pagination));

App.views.Explore.addChild('FollowCategory', {
  el: '.follow-category',

  setupFollowHeader: function(selectedItem) {
    var unfollow_btn = this.$('.unfollow-btn');
    var follow_btn = this.$('.follow-btn');

    this.$('.btn.btn-medium').hide();
    this.$('.category-info').html(selectedItem.data('name'));
    this.$('.following').hide();

    if(selectedItem.data('categoryid') > 0) {
      this.$('.category-follow span.count').html(selectedItem.data('totalfollowers'));

      if(selectedItem.data('totalfollowers') > 0) {
        this.$('.following').show();
      }

      if(selectedItem.data('isfollowing')) {
        unfollow_btn.prop('href', selectedItem.data('unfollowpath'))
        unfollow_btn.show();
      } else {
        follow_btn.prop('href', selectedItem.data('followpath'))
        follow_btn.show();
      }
    }

    this.$el.show();
  }

});


text:
module Test.Matrix(test) where

import Data.Matrix
import Prelude as P

import System.Exit (exitFailure)
import Test.QuickCheck(verboseCheckWithResult)
import Test.QuickCheck.Test(isSuccess,stdArgs,maxSuccess,maxSize)
import Control.Monad.Identity(runIdentity)
import qualified Data.Vector.Unboxed as V
import Data.Binary as B
import Control.DeepSeq as N

prop_splitRows :: Int -> Int -> Int -> Bool
prop_splitRows xx yy zz = (toList mm) == (concatMap toList splitted)
                       && num == (length splitted)
   where rr = abs xx + 1
         cc = abs yy + 1
         ss = abs zz + 1
         num = ceiling $ ((fromIntegral rr)::Double) / (fromIntegral ss)
         mm = fromList (rr,cc) $ P.map fromIntegral [1..(rr * cc)]
         splitted = runIdentity $ mapM d2u (splitRows ss mm)

prop_fold :: Bool
prop_fold = foldl (+) 0 (toList mm) == res
   where res = runIdentity $ fold (+) 0 mm
         mm = fromList (1,3) [1,2,3]

prop_unboxed :: Bool
prop_unboxed = (toUnboxed mm) == V.fromList [1,2,3]
   where mm = fromList (1,3) [1,2,3]

prop_binary :: Bool
prop_binary = (toList mm) == (toList $ B.decode $ B.encode $ mm)
   where mm = fromList (1,3) [1,2,3]

prop_cast :: Bool
prop_cast = (toList $ cast1 mm) == (toList $ cast2 mm)
   where mm = fromList (1,3) [1,2,3]

prop_show :: Bool
prop_show = 0 < (length $ show mm)
   where mm = fromList (1,3) [1,2,3]

prop_nfdata :: Bool
prop_nfdata = (toList mm) == (toList N.$!! mm)
   where mm = fromList (1,3) [1,2,3]

test :: IO ()
test =  do
   let check rr = if (isSuccess rr) then return () else exitFailure
       cfg = stdArgs { maxSuccess = 100, maxSize = 10 }
       runtest tst p =  do putStrLn tst; check =<< verboseCheckWithResult cfg p
   runtest "splitRows"  prop_splitRows
   runtest "fold"       prop_fold
   runtest "unboxed"    prop_unboxed
   runtest "binary"     prop_binary
   runtest "cast"       prop_cast
   runtest "show"       prop_show
   runtest "nfdata"     prop_nfdata


text:
package org.jboss.logmanager;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.text.MessageFormat;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import java.util.logging.LogRecord;

/**
 * An extended log record, which includes additional information including MDC/NDC and correct
 * caller location (even in the presence of a logging facade).
 */
public class ExtLogRecord extends LogRecord {

    private static final long serialVersionUID = -9174374711278052369L;

    /**
     * The format style to use.
     */
    public enum FormatStyle {

        /**
         * Format the message using the {@link java.text.MessageFormat} parameter style.
         */
        MESSAGE_FORMAT,
        /**
         * Format the message using the {@link java.util.Formatter} (also known as {@code printf()}) parameter style.
         */
        PRINTF,
        /**
         * Do not format the message; parameters are ignored.
         */
        NO_FORMAT,
    }

    /**
     * Construct a new instance.  Grabs the current NDC immediately.  MDC is deferred.
     *
     * @param level a logging level value
     * @param msg the raw non-localized logging message (may be null)
     * @param loggerClassName the name of the logger class
     */
    public ExtLogRecord(final java.util.logging.Level level, final String msg, final String loggerClassName) {
        this(level, msg, FormatStyle.MESSAGE_FORMAT, loggerClassName);
    }

    /**
     * Construct a new instance.  Grabs the current NDC immediately.  MDC is deferred.
     *
     * @param level a logging level value
     * @param msg the raw non-localized logging message (may be null)
     * @param formatStyle the parameter format style to use
     * @param loggerClassName the name of the logger class
     */
    public ExtLogRecord(final java.util.logging.Level level, final String msg, final FormatStyle formatStyle, final String loggerClassName) {
        super(level, msg);
        this.formatStyle = formatStyle == null ? FormatStyle.MESSAGE_FORMAT : formatStyle;
        this.loggerClassName = loggerClassName;
        ndc = NDC.get();
        threadName = Thread.currentThread().getName();
    }

    /**
     * Make a copy of a log record.
     *
     * @param original the original
     */
    public ExtLogRecord(final ExtLogRecord original) {
        super(original.getLevel(), original.getMessage());
        // LogRecord fields
        setLoggerName(original.getLoggerName());
        setMillis(original.getMillis());
        setParameters(original.getParameters());
        setResourceBundle(original.getResourceBundle());
        setResourceBundleName(original.getResourceBundleName());
        setSequenceNumber(original.getSequenceNumber());
        setThreadID(original.getThreadID());
        setThrown(original.getThrown());
        if (!original.calculateCaller) {
            setSourceClassName(original.getSourceClassName());
            setSourceMethodName(original.getSourceMethodName());
            sourceFileName = original.sourceFileName;
            sourceLineNumber = original.sourceLineNumber;
        }
        formatStyle = original.formatStyle;
        mdcCopy = original.mdcCopy;
        ndc = original.ndc;
        loggerClassName = original.loggerClassName;
        threadName = original.threadName;
        resourceKey = original.resourceKey;
        formattedMessage = original.formattedMessage;
    }

    /**
     * Wrap a JDK log record.  If the target record is already an {@code ExtLogRecord}, it is simply returned.  Otherwise
     * a wrapper record is created and returned.
     *
     * @param rec the original record
     * @return the wrapped record
     */
    public static ExtLogRecord wrap(LogRecord rec) {
        if (rec == null) {
            return null;
        } else if (rec instanceof ExtLogRecord) {
            return (ExtLogRecord) rec;
        } else {
            return new WrappedExtLogRecord(rec);
        }
    }

    private final transient String loggerClassName;
    private transient boolean calculateCaller = true;

    private String ndc;
    private FormatStyle formatStyle = FormatStyle.MESSAGE_FORMAT;
    private FastCopyHashMap<String, Object> mdcCopy;
    private int sourceLineNumber = -1;
    private String sourceFileName;
    private String resourceKey;
    private String formattedMessage;
    private String threadName;

    private void writeObject(ObjectOutputStream oos) throws IOException {
        copyAll();
        oos.defaultWriteObject();
    }

    /**
     * Disable caller calculation for this record.  If the caller has already been calculated, leave it; otherwise
     * set the caller to {@code "unknown"}.
     */
    public void disableCallerCalculation() {
        if (calculateCaller) {
            setUnknownCaller();
        }
    }

    /**
     * Copy all fields and prepare this object to be passed to another thread or to be serialized.  Calling this method
     * more than once has no additional effect and will not incur extra copies.
     */
    public void copyAll() {
        copyMdc();
        calculateCaller();
        getFormattedMessage();
    }

    /**
     * Copy the MDC.  Call this method before passing this log record to another thread.  Calling this method
     * more than once has no additional effect and will not incur extra copies.
     */
    public void copyMdc() {
        if (mdcCopy == null) {
            mdcCopy = MDC.fastCopyObject();
        }
    }

    /**
     * Get the value of an MDC property.
     *
     * @param key the property key
     * @return the property value
     */
    public String getMdc(String key) {
        final Map<String, Object> mdcCopy = this.mdcCopy;
        if (mdcCopy == null) {
            return MDC.get(key);
        }
        final Object value =  mdcCopy.get(key);
        return value == null ? null : value.toString();
    }

    /**
     * Get a copy of all the MDC properties for this log record.  If the MDC has not yet been copied, this method will copy it.
     *
     * @return a copy of the MDC map
     */
    public Map<String, String> getMdcCopy() {
        if (mdcCopy == null) {
            mdcCopy = MDC.fastCopyObject();
        }
        // Create a new map with string values
        final FastCopyHashMap<String, String> newMdc = new FastCopyHashMap<String, String>();
        for (Map.Entry<String, Object> entry : mdcCopy.entrySet()) {
            final String key = entry.getKey();
            final Object value = entry.getValue();
            newMdc.put(key, (value == null ? null : value.toString()));
        }
        return newMdc;
    }

    /**
     * Change an MDC value on this record.  If the MDC has not yet been copied, this method will copy it.
     *
     * @param key the key to set
     * @param value the value to set it to
     * @return the old value, if any
     */
    public String putMdc(String key, String value) {
        copyMdc();
        final Object oldValue = mdcCopy.put(key, value);
        return oldValue == null ? null : oldValue.toString();
    }

    /**
     * Remove an MDC value on this record.  If the MDC has not yet been copied, this method will copy it.
     *
     * @param key the key to remove
     * @return the old value, if any
     */
    public String removeMdc(String key) {
        copyMdc();
        final Object oldValue = mdcCopy.remove(key);
        return oldValue == null ? null : oldValue.toString();
    }

    /**
     * Create a new MDC using a copy of the source map.
     *
     * @param sourceMap the source man, must not be {@code null}
     */
    public void setMdc(Map<?, ?> sourceMap) {
        final FastCopyHashMap<String, Object> newMdc = new FastCopyHashMap<String, Object>();
        for (Map.Entry<?, ?> entry : sourceMap.entrySet()) {
            final Object key = entry.getKey();
            final Object value = entry.getValue();
            if (key != null && value != null) {
                newMdc.put(key.toString(), value);
            }
        }
        mdcCopy = newMdc;
    }

    /**
     * Get the NDC for this log record.
     *
     * @return the NDC
     */
    public String getNdc() {
        return ndc;
    }

    /**
     * Change the NDC for this log record.
     *
     * @param value the new NDC value
     */
    public void setNdc(String value) {
        ndc = value;
    }

    /**
     * Get the class name of the logger which created this record.
     *
     * @return the class name
     */
    public String getLoggerClassName() {
        return loggerClassName;
    }

    /**
     * Get the format style for the record.
     *
     * @return the format style
     */
    public FormatStyle getFormatStyle() {
        return formatStyle;
    }

    /**
     * Find the first stack frame below the call to the logger, and populate the log record with that information.
     */
    private void calculateCaller() {
        if (! calculateCaller) {
            return;
        }
        calculateCaller = false;
        final StackTraceElement[] stack = new Throwable().getStackTrace();
        boolean found = false;
        for (StackTraceElement element : stack) {
            final String className = element.getClassName();
            if (found) {
                if (! loggerClassName.equals(className)) {
                    setSourceClassName(className);
                    setSourceMethodName(element.getMethodName());
                    setSourceLineNumber(element.getLineNumber());
                    setSourceFileName(element.getFileName());
                    return;
                }
            } else {
                found = loggerClassName.equals(className);
            }
        }
        setUnknownCaller();
    }

    private void setUnknownCaller() {
        setSourceClassName("<unknown>");
        setSourceMethodName("<unknown>");
        setSourceLineNumber(-1);
        setSourceFileName("<unknown>");
    }

    /**
     * Get the source line number for this log record.
     *

     * Note that this line number is not verified and may be spoofed. This information may either have been
     * provided as part of the logging call, or it may have been inferred automatically by the logging framework. In the
     * latter case, the information may only be approximate and may in fact describe an earlier call on the stack frame.
     * May be -1 if no information could be obtained.
     *
     * @return the source line number
     */
    public int getSourceLineNumber() {
        calculateCaller();
        return sourceLineNumber;
    }

    /**
     * Set the source line number for this log record.
     *
     * @param sourceLineNumber the source line number
     */
    public void setSourceLineNumber(final int sourceLineNumber) {
        calculateCaller = false;
        this.sourceLineNumber = sourceLineNumber;
    }

    /**
     * Get the source file name for this log record.
     *

     * Note that this file name is not verified and may be spoofed. This information may either have been
     * provided as part of the logging call, or it may have been inferred automatically by the logging framework. In the
     * latter case, the information may only be approximate and may in fact describe an earlier call on the stack frame.
     * May be {@code null} if no information could be obtained.
     *
     * @return the source file name
     */
    public String getSourceFileName() {
        calculateCaller();
        return sourceFileName;
    }

    /**
     * Set the source file name for this log record.
     *
     * @param sourceFileName the source file name
     */
    public void setSourceFileName(final String sourceFileName) {
        calculateCaller = false;
        this.sourceFileName = sourceFileName;
    }

    /** {@inheritDoc} */
    public String getSourceClassName() {
        calculateCaller();
        return super.getSourceClassName();
    }

    /** {@inheritDoc} */
    public void setSourceClassName(final String sourceClassName) {
        calculateCaller = false;
        super.setSourceClassName(sourceClassName);
    }

    /** {@inheritDoc} */
    public String getSourceMethodName() {
        calculateCaller();
        return super.getSourceMethodName();
    }

    /** {@inheritDoc} */
    public void setSourceMethodName(final String sourceMethodName) {
        calculateCaller = false;
        super.setSourceMethodName(sourceMethodName);
    }

    /**
     * Get the fully formatted log record, with resources resolved and parameters applied.
     *
     * @return the formatted log record
     */
    public String getFormattedMessage() {
        if (formattedMessage == null) {
            formattedMessage = formatRecord();
        }
        return formattedMessage;
    }

    /**
     * Get the resource key, if any.  If the log message is not localized, then the key is {@code null}.
     *
     * @return the resource key
     */
    public String getResourceKey() {
        if (formattedMessage == null) {
            formatRecord();
        }
        return resourceKey;
    }

    private String formatRecord() {
        final ResourceBundle bundle = getResourceBundle();
        String msg = getMessage();
        if (msg == null)
            return null;
        if (bundle != null) {
            try {
                String locMsg = bundle.getString(msg);
                resourceKey = msg;
                msg = locMsg;
            } catch (MissingResourceException ex) {
                // ignore
            }
        }
        final Object[] parameters = getParameters();
        if (parameters == null || parameters.length == 0) {
            return msg;
        }
        switch (formatStyle) {
            case PRINTF: {
                return String.format(msg, parameters);
            }
            case MESSAGE_FORMAT: {
                return msg.indexOf('{') >= 0 ? MessageFormat.format(msg, parameters) : msg;
            }
        }
        // should be unreachable
        return msg;
    }

    /**
     * Get the thread name of this logging event.
     *
     * @return the thread name
     */
    public String getThreadName() {
        return threadName;
    }

    /**
     * Set the thread name of this logging event.
     *
     * @param threadName the thread name
     */
    public void setThreadName(final String threadName) {
        this.threadName = threadName;
    }

    /**
     * Set the raw message.  Any cached formatted message is discarded.  The parameter format is set to be
     * {@link java.text.MessageFormat}-style.
     *
     * @param message the new raw message
     */
    public void setMessage(final String message) {
        setMessage(message, FormatStyle.MESSAGE_FORMAT);
    }

    /**
     * Set the raw message.  Any cached formatted message is discarded.  The parameter format is set according to the
     * given argument.
     *
     * @param message the new raw message
     * @param formatStyle the format style to use
     */
    public void setMessage(final String message, final FormatStyle formatStyle) {
        this.formatStyle = formatStyle == null ? FormatStyle.MESSAGE_FORMAT : formatStyle;
        formattedMessage = null;
        super.setMessage(message);
    }

    /**
     * Set the parameters to the log message.  Any cached formatted message is discarded.
     *
     * @param parameters the log message parameters. (may be null)
     */
    public void setParameters(final Object[] parameters) {
        formattedMessage = null;
        super.setParameters(parameters);
    }

    /**
     * Set the localization resource bundle.  Any cached formatted message is discarded.
     *
     * @param bundle localization bundle (may be null)
     */
    public void setResourceBundle(final ResourceBundle bundle) {
        formattedMessage = null;
        super.setResourceBundle(bundle);
    }

    /**
     * Set the localization resource bundle name.  Any cached formatted message is discarded.
     *
     * @param name localization bundle name (may be null)
     */
    public void setResourceBundleName(final String name) {
        formattedMessage = null;
        super.setResourceBundleName(name);
    }
}


text:
import { MessageBus } from "angular2/src/web-workers/shared/message_bus";
import { Serializer } from "angular2/src/web-workers/shared/serializer";
import { Type } from "angular2/src/facade/lang";
export declare class MessageBroker {
    private _messageBus;
    protected _serializer: Serializer;
    private _pending;
    constructor(_messageBus: MessageBus, _serializer: Serializer);
    private _generateMessageId(name);
    runOnUiThread(args: UiArguments, returnType: Type): Promise<any>;
    private _handleMessage(message);
}
export declare class FnArg {
    value: any;
    type: any;
    constructor(value: any, type: any);
}
export declare class UiArguments {
    type: string;
    method: string;
    args: List<FnArg>;
    constructor(type: string, method: string, args?: List<FnArg>);
}


text:
void StructurePrinter::digStmt(Statement *s)
{
  // if this is a compound statement, traverse the elements;
  // otherwise, skip it entirely
  if (s->isS_compound()) {
    S_compound *c = s->asS_compound();
    FOREACH_ASTLIST_NC(Statement, c->stmts, iter) {
      iter.data()->traverse(*this);
    }
  }
}

bool StructurePrinter::visitTopForm(TopForm *tf)
{
  in(tf->loc);

  if (tf->isTF_func()) {
    // dig down into the body, b/c I don't want an extra level for
    // each function's body
    digStmt(tf->asTF_func()->f->body);

    out();

    // do *not* now go into the children again
    return false;
  }
  else {
    // automatically traverse children for other kinds of topforms
    return true;
  }
}

bool StructurePrinter::visitStatement(Statement *s)
{
  in(s->loc);

  ASTSWITCH(Statement, s) {
    ASTCASE(S_label, sl)
      digStmt(sl->s);

    ASTNEXT(S_case, sc)
      digStmt(sc->s);

    ASTNEXT(S_default, sd)
      digStmt(sd->s);

    ASTNEXT(S_if, si)
      digStmt(si->thenBranch);
      if (si->elseBranch->loc > si->loc) {
        digStmt(si->elseBranch);
      }
      else {
        // the else branch wasn't syntactically present
      }

    ASTNEXT(S_switch, ss)
      digStmt(ss->branches);

    ASTNEXT(S_while, sw)
      digStmt(sw->body);

    ASTNEXT(S_doWhile, sd)
      digStmt(sd->body);

    ASTNEXT(S_for, sf)
      digStmt(sf->body);

    ASTDEFAULT
      // those not listed above have their children automatically traversed
      return true;

    ASTENDCASE
  }

  // those that *are* listed above have already handled children
  out();
  return false;
}

std::ostream &StructurePrinter::ind()
{
  for (int i=0; i < depth; i++) {
    std::cout << "  ";
  }
  return std::cout;
}

bool StructurePrinter::in(SourceLoc loc)
{
  if (begin) {
    // I'm first in my parent's list
    std::cout << " {\n";
  }

  ind() << "begin=" << toString(loc);
  depth++;
  begin = true;
  return true;    // visit children
}

void StructurePrinter::out()
{
  depth--;
  if (begin) {
    // no children
    std::cout << "\n";
  }
  else {
    // finish child list
    ind() << "}\n";
  }
  begin = false;
}

void structurePrint(TranslationUnit *unit)
{
  StructurePrinter sp;
  unit->traverse(sp);
}

// EOF


text:
package org.terasology.world.generation;

import org.junit.Test;
import org.terasology.context.Context;
import org.terasology.context.internal.ContextImpl;
import org.terasology.math.Region3i;
import org.terasology.math.geom.Vector3i;
import org.terasology.world.generation.facets.base.BaseFacet3D;
import org.terasology.world.generator.plugin.WorldGeneratorPluginLibrary;

import static org.junit.Assert.assertEquals;

public class WorldBuilderTest {

    private Context context = new ContextImpl();

    @Test
    public void borderCalculation() {
        WorldBuilder worldBuilder = new WorldBuilder(context.get(WorldGeneratorPluginLibrary.class));
        worldBuilder.setSeed(12);
        worldBuilder.addProvider(new Facet1Provider());
        worldBuilder.addProvider(new Facet2Provider());

        World world = worldBuilder.build();
        Region3i regionToGenerate = Region3i.createFromCenterExtents(new Vector3i(), 1);
        Region regionData = world.getWorldData(regionToGenerate);

        Facet1 facet1 = regionData.getFacet(Facet1.class);
        assertEquals(regionToGenerate, facet1.getWorldRegion());

        Facet2 facet2 = regionData.getFacet(Facet2.class);
        assertEquals(Region3i.createFromMinAndSize(new Vector3i(-3, -1, -3), new Vector3i(7, 3, 7)), facet2.getWorldRegion());
    }

    @Test
    public void cumulativeBorderCalculation() {
        WorldBuilder worldBuilder = new WorldBuilder(context.get(WorldGeneratorPluginLibrary.class));
        worldBuilder.setSeed(12);
        worldBuilder.addProvider(new Facet1Provider());
        worldBuilder.addProvider(new Facet2Provider());
        worldBuilder.addProvider(new Facet3Provider());

        World world = worldBuilder.build();
        Region3i regionToGenerate = Region3i.createFromCenterExtents(new Vector3i(), 1);
        Region regionData = world.getWorldData(regionToGenerate);

        Facet3 facet3 = regionData.getFacet(Facet3.class);
        assertEquals(regionToGenerate, facet3.getWorldRegion());

        Facet1 facet1 = regionData.getFacet(Facet1.class);
        assertEquals(Region3i.createFromMinAndSize(new Vector3i(-2, -1, -2), new Vector3i(5, 3, 5)), facet1.getWorldRegion());

        Facet2 facet2 = regionData.getFacet(Facet2.class);
        assertEquals(Region3i.createFromMinAndSize(new Vector3i(-4, -1, -4), new Vector3i(9, 3, 9)), facet2.getWorldRegion());
    }

    @Test
    public void multiplePathsBorderCalculation() {
        WorldBuilder worldBuilder = new WorldBuilder(context.get(WorldGeneratorPluginLibrary.class));
        worldBuilder.setSeed(12);
        worldBuilder.addProvider(new Facet1Provider());
        worldBuilder.addProvider(new Facet2Provider());
        worldBuilder.addProvider(new Facet4Provider());

        World world = worldBuilder.build();
        Region3i regionToGenerate = Region3i.createFromCenterExtents(new Vector3i(), 1);
        Region regionData = world.getWorldData(regionToGenerate);

        Facet1 facet1 = regionData.getFacet(Facet1.class);
        assertEquals(regionToGenerate, facet1.getWorldRegion());

        Facet4 facet4 = regionData.getFacet(Facet4.class);
        assertEquals(regionToGenerate, facet4.getWorldRegion());

        Facet2 facet2 = regionData.getFacet(Facet2.class);
        assertEquals(Region3i.createFromMinAndSize(new Vector3i(-4, -1, -4), new Vector3i(9, 3, 9)), facet2.getWorldRegion());
    }

    public static class Facet1 extends BaseFacet3D {
        public Facet1(Region3i targetRegion, Border3D border) {
            super(targetRegion, border);
        }
    }

    public static class Facet2 extends BaseFacet3D {
        public Facet2(Region3i targetRegion, Border3D border) {
            super(targetRegion, border);
        }
    }

    public static class Facet3 extends BaseFacet3D {
        public Facet3(Region3i targetRegion, Border3D border) {
            super(targetRegion, border);
        }
    }

    public static class Facet4 extends BaseFacet3D {
        public Facet4(Region3i targetRegion, Border3D border) {
            super(targetRegion, border);
        }
    }

    @Produces(Facet1.class)
    @Requires(@Facet(value = Facet2.class, border = @FacetBorder(sides = 2)))
    public static class Facet1Provider implements FacetProvider {
        @Override
        public void setSeed(long seed) {

        }

        @Override
        public void process(GeneratingRegion region) {
            Facet1 facet = new Facet1(region.getRegion(), region.getBorderForFacet(Facet1.class));
            region.setRegionFacet(Facet1.class, facet);
        }
    }

    @Produces(Facet2.class)
    public static class Facet2Provider implements FacetProvider {
        @Override
        public void setSeed(long seed) {

        }

        @Override
        public void process(GeneratingRegion region) {
            Facet2 facet = new Facet2(region.getRegion(), region.getBorderForFacet(Facet2.class));
            region.setRegionFacet(Facet2.class, facet);
        }
    }

    @Produces(Facet3.class)
    @Requires(@Facet(value = Facet1.class, border = @FacetBorder(sides = 1)))
    public static class Facet3Provider implements FacetProvider {
        @Override
        public void setSeed(long seed) {

        }

        @Override
        public void process(GeneratingRegion region) {
            Facet3 facet = new Facet3(region.getRegion(), region.getBorderForFacet(Facet3.class));
            region.setRegionFacet(Facet3.class, facet);
        }
    }

    @Produces(Facet4.class)
    @Requires(@Facet(value = Facet2.class, border = @FacetBorder(sides = 3)))
    public static class Facet4Provider implements FacetProvider {
        @Override
        public void setSeed(long seed) {

        }

        @Override
        public void process(GeneratingRegion region) {
            Facet4 facet = new Facet4(region.getRegion(), region.getBorderForFacet(Facet4.class));
            region.setRegionFacet(Facet4.class, facet);
        }
    }
}


text:
#include "android.hpp"

#if defined(__ANDROID__)
#include <android/configuration.h>

int32_t vkx::android::screenDensity{ 0 };
android_app* vkx::android::androidApp{ nullptr };

void vkx::android::getDeviceConfig(AAssetManager* assetManager) {
    // Screen density
    AConfiguration* config = AConfiguration_new();
    AConfiguration_fromAssetManager(config, assetManager);
    vkx::android::screenDensity = AConfiguration_getDensity(config);
    AConfiguration_delete(config);
}

#endif


text:
class Http
{
public:
    Http ();
    ~Http ();

    void setUrl (const char* url);
    void setPostData (const char* postData, size_t length);

    bool send ();

    const char* getErrorMessage () const;
    const char* getData () const;

protected:

    CURL* _curl;
    std::vector<char> _data;
    char _errorMessage[CURL_ERROR_SIZE];
};


text:
.class final Ljava/util/concurrent/ForkJoinTask$AdaptedCallable;
.super Ljava/util/concurrent/ForkJoinTask;
.source "ForkJoinTask.java"

# interfaces
.implements Ljava/util/concurrent/RunnableFuture;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Ljava/util/concurrent/ForkJoinTask;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x18
    name = "AdaptedCallable"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "<T:",
        "Ljava/lang/Object;",
        ">",
        "Ljava/util/concurrent/ForkJoinTask",
        "<TT;>;",
        "Ljava/util/concurrent/RunnableFuture",
        "<TT;>;"
    }
.end annotation

# static fields
.field private static final serialVersionUID:J = 0x2763fe86dcb18e30L

# instance fields
.field final callable:Ljava/util/concurrent/Callable;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/concurrent/Callable",
            "<+TT;>;"
        }
    .end annotation
.end field

.field result:Ljava/lang/Object;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "TT;"
        }
    .end annotation
.end field

# direct methods
.method constructor <init>(Ljava/util/concurrent/Callable;)V
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/util/concurrent/Callable",
            "<+TT;>;)V"
        }
    .end annotation

    .prologue
    .line 1406
    .local p0, "this":Ljava/util/concurrent/ForkJoinTask$AdaptedCallable;, "Ljava/util/concurrent/ForkJoinTask$AdaptedCallable<TT;>;"
    .local p1, "callable":Ljava/util/concurrent/Callable;, "Ljava/util/concurrent/Callable<+TT;>;"
    invoke-direct {p0}, Ljava/util/concurrent/ForkJoinTask;-><init>()V

    .line 1407
    if-nez p1, :cond_0

    new-instance v0, Ljava/lang/NullPointerException;

    invoke-direct {v0}, Ljava/lang/NullPointerException;-><init>()V

    throw v0

    .line 1408
    :cond_0
    iput-object p1, p0, Ljava/util/concurrent/ForkJoinTask$AdaptedCallable;->callable:Ljava/util/concurrent/Callable;

    .line 1409
    return-void
.end method

# virtual methods
.method public final exec()Z
    .locals 4

    .prologue
    .line 1414
    .local p0, "this":Ljava/util/concurrent/ForkJoinTask$AdaptedCallable;, "Ljava/util/concurrent/ForkJoinTask$AdaptedCallable<TT;>;"
    :try_start_0
    iget-object v3, p0, Ljava/util/concurrent/ForkJoinTask$AdaptedCallable;->callable:Ljava/util/concurrent/Callable;

    invoke-interface {v3}, Ljava/util/concurrent/Callable;->call()Ljava/lang/Object;

    move-result-object v3

    iput-object v3, p0, Ljava/util/concurrent/ForkJoinTask$AdaptedCallable;->result:Ljava/lang/Object;
    :try_end_0
    .catch Ljava/lang/Error; {:try_start_0 .. :try_end_0} :catch_0
    .catch Ljava/lang/RuntimeException; {:try_start_0 .. :try_end_0} :catch_1
    .catch Ljava/lang/Exception; {:try_start_0 .. :try_end_0} :catch_2

    .line 1415
    const/4 v3, 0x1

    return v3

    .line 1416
    :catch_0
    move-exception v0

    .line 1417
    .local v0, "err":Ljava/lang/Error;
    throw v0

    .line 1418
    .end local v0    # "err":Ljava/lang/Error;
    :catch_1
    move-exception v2

    .line 1419
    .local v2, "rex":Ljava/lang/RuntimeException;
    throw v2

    .line 1420
    .end local v2    # "rex":Ljava/lang/RuntimeException;
    :catch_2
    move-exception v1

    .line 1421
    .local v1, "ex":Ljava/lang/Exception;
    new-instance v3, Ljava/lang/RuntimeException;

    invoke-direct {v3, v1}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/Throwable;)V

    throw v3
.end method

.method public final getRawResult()Ljava/lang/Object;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()TT;"
        }
    .end annotation

    .prologue
    .line 1410
    .local p0, "this":Ljava/util/concurrent/ForkJoinTask$AdaptedCallable;, "Ljava/util/concurrent/ForkJoinTask$AdaptedCallable<TT;>;"
    iget-object v0, p0, Ljava/util/concurrent/ForkJoinTask$AdaptedCallable;->result:Ljava/lang/Object;

    return-object v0
.end method

.method public final run()V
    .locals 0

    .prologue
    .line 1424
    .local p0, "this":Ljava/util/concurrent/ForkJoinTask$AdaptedCallable;, "Ljava/util/concurrent/ForkJoinTask$AdaptedCallable<TT;>;"
    invoke-virtual {p0}, Ljava/util/concurrent/ForkJoinTask$AdaptedCallable;->invoke()Ljava/lang/Object;

    return-void
.end method

.method public final setRawResult(Ljava/lang/Object;)V
    .locals 0
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(TT;)V"
        }
    .end annotation

    .prologue
    .line 1411
    .local p0, "this":Ljava/util/concurrent/ForkJoinTask$AdaptedCallable;, "Ljava/util/concurrent/ForkJoinTask$AdaptedCallable<TT;>;"
    .local p1, "v":Ljava/lang/Object;, "TT;"
    iput-object p1, p0, Ljava/util/concurrent/ForkJoinTask$AdaptedCallable;->result:Ljava/lang/Object;

    return-void
.end method


text:
package waffle.wafflecore.util;

import java.util.Arrays;
import java.util.Base64;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.annotation.JsonCreator;

public final class ByteArrayWrapper {
    private final byte[] data;

    public ByteArrayWrapper(byte[] data) {
        if (data == null) {
            throw new NullPointerException();
        }
        this.data = data;
    }

    @JsonCreator
    public static ByteArrayWrapper copyOf(byte[] bytes) {
        return new ByteArrayWrapper((byte[])bytes.clone());
    }

    public int size() {
        return data.length;
    }

    @JsonValue
    public byte[] getBytes() {
        return data;
    }

    @Override
    public String toString() {
        return new String(Base64.getEncoder().encode(data));
    }

    @Override
    public boolean equals(Object other) {
        if (!(other instanceof ByteArrayWrapper)) {
            return false;
        }
        return Arrays.equals(data, ((ByteArrayWrapper)other).data);
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(data);
    }
}


text:
require 'spec_helper'

describe Peribot::Processor do
  let(:bot) { instance_double(Peribot::Bot) }
  let(:task) { Peribot::Processor.new bot }

  it 'defines a default register_into that gives an error' do
    task = Class.new(Peribot::Processor)
    bot = instance_double(Peribot::Bot)

    expect { task.register_into bot }.to raise_error(NotImplementedError)
  end

  it 'provides access to the bot it was initialized with' do
    task = Class.new(Peribot::Processor) do
      def process(*)
        bot.log 'test'
      end
    end

    expect(bot).to receive(:log).with('test')
    task.new(bot).process({})
  end

  describe '.call' do
    it 'runs the processor' do
      task = Class.new(Peribot::Processor) do
        def process(message)
          bot.log 'test'
          message
        end
      end

      expect(bot).to receive(:log).with('test')

      acceptor = double('acceptor')
      expect(acceptor).to receive(:call).with(message: 'hi')

      task.call(bot, { message: 'hi' }, &acceptor.method(:call)).wait
    end

    it 'normalizes and handles advanced return formats' do
      message = { service: :x, group: 'x/1' }
      task = Class.new(Peribot::Processor) do
        def process(_)
          [nil, 'It works!']
        end
      end

      acceptor = double('acceptor')
      expect(acceptor).to receive(:call).with(service: :x, group: 'x/1',
                                              text: 'It works!')

      task.call(bot, message.merge(text: 'hi'), &acceptor.method(:call)).wait
    end

    it 'logs processor failures' do
      task = Class.new(Peribot::Processor) do
        def process(*)
          raise 'sample error'
        end
      end

      expect(bot).to receive(:log).with(/Error in/)
      task.call(bot, {}) { raise 'Should not have output' }.wait
    end
  end

  describe '#process' do
    it 'fails when not implemented' do
      msg = 'process method not implemented in Peribot::Processor'
      expect { task.process({}) }.to raise_error(msg)
    end
  end
end


text:
id: 5900f4a51000cf542c50ffb7
challengeType: 5
title: 'Problem 312: Cyclic paths on Sierpiński graphs'
videoUrl: ''
localeTitle: ''
---

## Description
undefined

## Instructions
undefined

## Tests

```yml
tests:
  - text: ''
    testString: 'assert.strictEqual(euler312(), 324681947, "<code>euler312()</code> should return 324681947.");'

```

## Challenge Seed

```js
function euler312() {
  // Good luck!
  return true;
}

euler312();

```

## Solution

```js
// solution required
```


text:
angular.module('app.services').
value('lang', {
	CLOSE:'Fechar',
	SAVE:'Salvar',
	ADD:'Adicionar',
	DELETE:'Excluir',
	NEW:'Novo',
	CODE:'Código',
	EDIT:'Editar',
	EXPORT : 'Exportar',
	MAX_CHAR:'Número máximo de caracteres',

	NO_ITEM:'Não há itens',
	ONE_ITEM:'1 item',
	MANY_ITEM:'@{}@ itens',

	NO_RESULT : 'Nada encontrado' ,
	NO_CONTENT:'Não há conteúdo',

	//folder
	FOLDER : 'Pasta',
	FOLDER_NEW : 'Nova pasta',
	FOLDER_CODE:'Código da pasta',
	FOLDER_NAME:'Nome da pasta',
	FOLDER_PREFIX:'Prefixo',
	FOLDER_NROFDIG:'Número de dígitos',

	_getLocalizationKeys: function() {
//		Returns an object that has as properties the same properties of this object.
//		The values of these properties is equal to the name of each properties.
		var keys = {};
		for (var k in this) {
			keys[k] = k;
		}
		return keys;
	}
});


text:
package org.sfm.beans;

public class Pair<T, V> {

	private T first;
	private V second;

	public T getFirst() {
		return first;
	}

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

	public V getSecond() {
		return second;
	}

	public void setSecond(V second) {
		this.second = second;
	}
}


text:
from azure.identity import DefaultAzureCredential
from azure.mgmt.cosmosdb import CosmosDBManagementClient

"""
# PREREQUISITES
    pip install azure-identity
    pip install azure-mgmt-cosmosdb
# USAGE
    python cosmos_db_gremlin_graph_throughput_update.py

    Before run the sample, please set the values of the client ID, tenant ID and client secret
    of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
    AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
    https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""

def main():
    client = CosmosDBManagementClient(
        credential=DefaultAzureCredential(),
        subscription_id="subid",
    )

    response = client.gremlin_resources.begin_update_gremlin_graph_throughput(
        resource_group_name="rg1",
        account_name="ddb1",
        database_name="databaseName",
        graph_name="graphName",
        update_throughput_parameters={
            "location": "West US",
            "properties": {"resource": {"throughput": 400}},
            "tags": {},
        },
    ).result()
    print(response)

# x-ms-original-file: specification/cosmos-db/resource-manager/Microsoft.DocumentDB/preview/2022-08-15-preview/examples/CosmosDBGremlinGraphThroughputUpdate.json
if __name__ == "__main__":
    main()


text:
package openperipheral.integration.thaumcraft;

import openperipheral.api.adapter.Asynchronous;
import openperipheral.api.adapter.IPeripheralAdapter;
import openperipheral.api.adapter.method.ReturnType;
import openperipheral.api.adapter.method.ScriptCallable;
import thaumcraft.api.nodes.INode;
import thaumcraft.api.nodes.NodeModifier;
import thaumcraft.api.nodes.NodeType;

@Asynchronous
public class AdapterNode implements IPeripheralAdapter {
	private static final String NONE = "NONE";

	@Override
	public Class<?> getTargetClass() {
		return INode.class;
	}

	@Override
	public String getSourceId() {
		return "thaumcraft_node";
	}

	@ScriptCallable(returnTypes = ReturnType.STRING, description = "Get the type of the node")
	public String getNodeType(INode node) {
		NodeType nodeType = node.getNodeType();
		return (nodeType != null? nodeType.name() : NONE);
	}

	@ScriptCallable(returnTypes = ReturnType.STRING, description = "Get the modifier of the node")
	public String getNodeModifier(INode node) {
		NodeModifier nodeModifier = node.getNodeModifier();
		return (nodeModifier != null? nodeModifier.name() : NONE);
	}
}


text:
/* $Id$ */

/*! \file */

#include <config.h>

#include <isc/app.h>
#include <isc/event.h>
#include <isc/mem.h>
#include <isc/string.h>
#include <isc/timer.h>
#include <isc/util.h>

#include <dns/result.h>

#include <isccc/alist.h>
#include <isccc/cc.h>
#include <isccc/result.h>

#include <named/control.h>
#include <named/log.h>
#include <named/os.h>
#include <named/server.h>
#ifdef HAVE_LIBSCF
#include <named/ns_smf_globals.h>
#endif

static isc_boolean_t
command_compare(const char *text, const char *command) {
	unsigned int commandlen = strlen(command);
	if (strncasecmp(text, command, commandlen) == 0 &&
	    (text[commandlen] == '\0' ||
	     text[commandlen] == ' ' ||
	     text[commandlen] == '\t'))
		return (ISC_TRUE);
	return (ISC_FALSE);
}

/*%
 * This function is called to process the incoming command
 * when a control channel message is received.
 */
isc_result_t
ns_control_docommand(isccc_sexpr_t *message, isc_buffer_t *text) {
	isccc_sexpr_t *data;
	char *command = NULL;
	isc_result_t result;
	int log_level;
#ifdef HAVE_LIBSCF
	ns_smf_want_disable = 0;
#endif

	data = isccc_alist_lookup(message, "_data");
	if (data == NULL) {
		/*
		 * No data section.
		 */
		return (ISC_R_FAILURE);
	}

	result = isccc_cc_lookupstring(data, "type", &command);
	if (result != ISC_R_SUCCESS) {
		/*
		 * We have no idea what this is.
		 */
		return (result);
	}

	/*
	 * Compare the 'command' parameter against all known control commands.
	 */
	if (command_compare(command, NS_COMMAND_NULL) ||
	    command_compare(command, NS_COMMAND_STATUS)) {
		log_level = ISC_LOG_DEBUG(1);
	} else {
		log_level = ISC_LOG_INFO;
	}
	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
		      NS_LOGMODULE_CONTROL, log_level,
		      "received control channel command '%s'",
		      command);

	if (command_compare(command, NS_COMMAND_RELOAD)) {
		result = ns_server_reloadcommand(ns_g_server, command, text);
	} else if (command_compare(command, NS_COMMAND_RECONFIG)) {
		result = ns_server_reconfigcommand(ns_g_server, command);
	} else if (command_compare(command, NS_COMMAND_REFRESH)) {
		result = ns_server_refreshcommand(ns_g_server, command, text);
	} else if (command_compare(command, NS_COMMAND_RETRANSFER)) {
		result = ns_server_retransfercommand(ns_g_server, command);
	} else if (command_compare(command, NS_COMMAND_HALT)) {
#ifdef HAVE_LIBSCF
		/*
		 * If we are managed by smf(5), AND in chroot, then
		 * we cannot connect to the smf repository, so just
		 * return with an appropriate message back to rndc.
		 */
		if (ns_smf_got_instance == 1 && ns_smf_chroot == 1) {
			result = ns_smf_add_message(text);
			return (result);
		}
		/*
		 * If we are managed by smf(5) but not in chroot,
		 * try to disable ourselves the smf way.
		 */
		if (ns_smf_got_instance == 1 && ns_smf_chroot == 0)
			ns_smf_want_disable = 1;
		/*
		 * If ns_smf_got_instance = 0, ns_smf_chroot
		 * is not relevant and we fall through to
		 * isc_app_shutdown below.
		 */
#endif
		/* Do not flush master files */
		ns_server_flushonshutdown(ns_g_server, ISC_FALSE);
		ns_os_shutdownmsg(command, text);
		isc_app_shutdown();
		result = ISC_R_SUCCESS;
	} else if (command_compare(command, NS_COMMAND_STOP)) {
		/*
		 * "stop" is the same as "halt" except it does
		 * flush master files.
		 */
#ifdef HAVE_LIBSCF
		if (ns_smf_got_instance == 1 && ns_smf_chroot == 1) {
			result = ns_smf_add_message(text);
			return (result);
		}
		if (ns_smf_got_instance == 1 && ns_smf_chroot == 0)
			ns_smf_want_disable = 1;
#endif
		ns_server_flushonshutdown(ns_g_server, ISC_TRUE);
		ns_os_shutdownmsg(command, text);
		isc_app_shutdown();
		result = ISC_R_SUCCESS;
	} else if (command_compare(command, NS_COMMAND_DUMPSTATS)) {
		result = ns_server_dumpstats(ns_g_server);
	} else if (command_compare(command, NS_COMMAND_QUERYLOG)) {
		result = ns_server_togglequerylog(ns_g_server, command);
	} else if (command_compare(command, NS_COMMAND_DUMPDB)) {
		ns_server_dumpdb(ns_g_server, command);
		result = ISC_R_SUCCESS;
	} else if (command_compare(command, NS_COMMAND_SECROOTS)) {
		result = ns_server_dumpsecroots(ns_g_server, command);
	} else if (command_compare(command, NS_COMMAND_TRACE)) {
		result = ns_server_setdebuglevel(ns_g_server, command);
	} else if (command_compare(command, NS_COMMAND_NOTRACE)) {
		ns_g_debuglevel = 0;
		isc_log_setdebuglevel(ns_g_lctx, ns_g_debuglevel);
		result = ISC_R_SUCCESS;
	} else if (command_compare(command, NS_COMMAND_FLUSH)) {
		result = ns_server_flushcache(ns_g_server, command);
	} else if (command_compare(command, NS_COMMAND_FLUSHNAME)) {
		result = ns_server_flushnode(ns_g_server, command, ISC_FALSE);
	} else if (command_compare(command, NS_COMMAND_FLUSHTREE)) {
		result = ns_server_flushnode(ns_g_server, command, ISC_TRUE);
	} else if (command_compare(command, NS_COMMAND_STATUS)) {
		result = ns_server_status(ns_g_server, text);
	} else if (command_compare(command, NS_COMMAND_TSIGLIST)) {
		result = ns_server_tsiglist(ns_g_server, text);
	} else if (command_compare(command, NS_COMMAND_TSIGDELETE)) {
		result = ns_server_tsigdelete(ns_g_server, command, text);
	} else if (command_compare(command, NS_COMMAND_FREEZE)) {
		result = ns_server_freeze(ns_g_server, ISC_TRUE, command,
					  text);
	} else if (command_compare(command, NS_COMMAND_UNFREEZE) ||
		   command_compare(command, NS_COMMAND_THAW)) {
		result = ns_server_freeze(ns_g_server, ISC_FALSE, command,
					  text);
	} else if (command_compare(command, NS_COMMAND_SYNC)) {
		result = ns_server_sync(ns_g_server, command, text);
	} else if (command_compare(command, NS_COMMAND_RECURSING)) {
		result = ns_server_dumprecursing(ns_g_server);
	} else if (command_compare(command, NS_COMMAND_TIMERPOKE)) {
		result = ISC_R_SUCCESS;
		isc_timermgr_poke(ns_g_timermgr);
	} else if (command_compare(command, NS_COMMAND_NULL)) {
		result = ISC_R_SUCCESS;
	} else if (command_compare(command, NS_COMMAND_NOTIFY)) {
		result = ns_server_notifycommand(ns_g_server, command, text);
	} else if (command_compare(command, NS_COMMAND_VALIDATION)) {
		result = ns_server_validation(ns_g_server, command);
	} else if (command_compare(command, NS_COMMAND_SIGN) ||
		   command_compare(command, NS_COMMAND_LOADKEYS)) {
		result = ns_server_rekey(ns_g_server, command);
	} else if (command_compare(command, NS_COMMAND_ADDZONE)) {
		result = ns_server_add_zone(ns_g_server, command);
	} else if (command_compare(command, NS_COMMAND_DELZONE)) {
		result = ns_server_del_zone(ns_g_server, command);
	} else if (command_compare(command, NS_COMMAND_SIGNING)) {
		result = ns_server_signing(ns_g_server, command, text);
	} else {
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_CONTROL, ISC_LOG_WARNING,
			      "unknown control channel command '%s'",
			      command);
		result = DNS_R_UNKNOWNCOMMAND;
	}

	return (result);
}


text:
/**
 * Basic http authentication provider. Uses the database to validate credentials.
 *
 */
var connect = require('connect'),
    data = require("../data"),
    utils = require("../../utils"),
    crypto = require("crypto"),
    unauthorized = connect.utils.unauthorized;

var basicDatabase = (function () {

    var module = {};

    module.authenticate = function(req, res, next) {
        if (req.method == 'GET'){
            return next();
        } else {
            var realm = 'Authorization Required';
            var authorization = req.headers.authorization;
            if (req.remoteUser) next();
            if (!authorization) return unauthorized(res, realm);

            var parts = authorization.split(' '),
                        scheme = parts[0],
                        credentials = new Buffer(parts[1], 'base64').toString().split(':');

            if ('Basic' != scheme) return next(400);

            module.validate(credentials[0], credentials[1], function(result){
                if (result) {
                    req.remoteUser = credentials[0];
                    utils.log("user authenticated: " + req.remoteUser);
                    next();
                } else {
                    unauthorized(res, realm);
                }
            });
        }
    };

    module.validate = function(username, password, c) {
        var callback = c;
        data.instance().collection("admin").list({
            email: username,
            password: crypto.createHash('md5').update(password).digest("hex") }, [],
        function(err, objs) {
             c(objs.length > 0);
        });
    };

    return module;

}());

module.exports = basicDatabase;


text:
package life.catalogue.dw.jersey.exception;

import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;

/**
 * Converts a IllegalArgumentException into a http 400 bad request.
 */
@Provider
public class IllegalArgumentExceptionMapper extends JsonExceptionMapperBase<IllegalArgumentException> {

  public IllegalArgumentExceptionMapper() {
    super(Response.Status.BAD_REQUEST, false, false);
  }
}


text:
package tv.floe.metronome.linearregression.iterativereduce;

import java.io.IOException;
import java.nio.ByteBuffer;

import tv.floe.metronome.linearregression.ParameterVector;

import com.cloudera.iterativereduce.Updateable;

public class ParameterVectorUpdateable implements
		Updateable<ParameterVector> {

	ParameterVector param_msg = null;

	public ParameterVectorUpdateable() {
	}

	public ParameterVectorUpdateable(ParameterVector g) {
		this.param_msg = g;
	}

	@Override
	public void fromBytes(ByteBuffer b) {

		b.rewind();

		try {
			this.param_msg = new ParameterVector();
			this.param_msg.Deserialize(b.array());

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public ParameterVector get() {
		return this.param_msg;
	}

	@Override
	public void set(ParameterVector t) {
		this.param_msg = t;
	}

	@Override
	public ByteBuffer toBytes() {
		byte[] bytes = null;
		try {
			bytes = this.param_msg.Serialize();
		} catch (IOException e) {
			e.printStackTrace();
		}

		ByteBuffer buf = ByteBuffer.wrap(bytes);

		return buf;
	}

	@Override
	public void fromString(String s) {

	}

}


text:
module MetaManager
  module Taggable
    extend ::ActiveSupport::Concern

    included do |base|
      has_many :meta_tags, as: :taggable, dependent: :destroy, autosave: true

      accepts_nested_attributes_for :meta_tags, reject_if: proc { |tag| tag['content'].nil? }, allow_destroy: true

      base.prepend Extension
    end

    # some required extentions
    module Extension
      def respond_to_missing?(method_sym, include_all = false)
        return true if method_sym.to_s =~ meta_match_case

        super
      end

      def method_missing(method_sym, *args)
        key = method_sym.to_s
        return read_or_update(key, args.first) if key =~ meta_match_case

        super
      end
    end

    # Save meta tags records into one hash
    def meta_tag(attr_name, options = {})
      key = normalize_meta_tag_name(attr_name)

      key = localized_key(key)

      cached_meta_tags[key] ||= find_meta(key, options[:fallback])
      cached_meta_tags[key] ||= meta_tags.build(name: key) if options[:build]

      cached_meta_tags[key]
    end

    def cached_meta_tags
      @cached_meta_tags ||= {}
    end

    private

    def find_meta(key, fallback = false)
      found = meta_tags.detect { |t| t.name == key }
      return found unless fallback

      fallback_keys(key).each do |alter_key|
        found ||= meta_tags.detect { |t| t.name == alter_key } if fallback

        break if found
      end

      found
    end

    def fallback_keys(key)
      pure_key = key.gsub(/_(#{I18n.available_locales.join('|')})$/, '')
      [
        key,
        "#{pure_key}_#{I18n.default_locale}",
        pure_key
      ].compact
    end

    def read_or_update(key, value = nil)
      attr_name = key.gsub(meta_match_case, '')
      return find_tag_content(attr_name) if value.nil? || key =~ /[^=]$/

      record = meta_tag(attr_name, build: value.present?, fallback: value.blank?)
      return if record.blank?
      return record.delete if value.blank?

      record.content = value
    end

    def normalize_meta_tag_name(value)
      value.to_s.downcase.strip.gsub('_before_type_cast', '').gsub(/=$/, '')
    end

    def meta_match_case
      /^tag_/
    end

    def localized_meta_key_case
      /^(.+?)(?:_(#{I18n.available_locales.join('|')}))?$/
    end

    def localized_key(key)
      key, locale = localized_meta_key_case.match(key)[1..2]
      [key, locale || I18n.locale].join('_')
    end

    def find_tag_content(attr_name)
      meta_tag(attr_name, fallback: true).try(:content)
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>

Configuring Atos as the Payment Gateway

How to set and configure Atos as the payment provider for your Store using the Store Admin module.

Important. Before configuring this setting, you must register for an account at http://www.sips-atos.com/fr/1/Accueil.html to obtain a Merchant ID and Merchant certificate. To test your integration with ATOS Payment Gateway, you can use the demonstration Merchant ID - Certificate file pair. To process real payments, you should change the demonstration Merchant ID into the production Merchant ID in your  configuration form and upload the production certificate file using this form.

Go to the Store Admin module.

If the Store Info page isn't displayed, click the Store Info link.

At Payment Gateway, select AtosProvider.

In the Merchant ID text box enter ID provided to you by SIPS  at the time of the registration of its shop. This ID allows the identification of a shop SIPS. It generally corresponds to the SIRET preceded by 0.

In the PathFile Folder text box, click the Load Pathfile link and upload your Merchant Certificate.

At PathFile Folder, select the file you just uploaded at Step 5.

At Bank Logo, select the logo.

               Click the Update button.


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.osanchezhuerta.eventscheduling</groupId>
  <artifactId>eventscheduling</artifactId>
  <version>0.0.0.1</version>
  <packaging>pom</packaging>
  <name>eventscheduling</name>
  <description>eventscheduling</description>
  <modules>
  	<module>eventscheduling-manager</module>
  	<module>eventscheduling-engine</module>
  </modules>
	<properties>
		<eventscheduling.version>0.0.0.1</eventscheduling.version>
		<eventscheduling-engine.version>0.0.0.1</eventscheduling-engine.version>
		<eventscheduling-engine-soa.version>0.0.0.1</eventscheduling-engine-soa.version>
		<eventscheduling-engine-web.version>0.0.0.1</eventscheduling-engine-web.version>

		<eventscheduling-motor.version>0.0.0.1</eventscheduling-motor.version>
		<eventscheduling-motor-soa.version>0.0.0.1</eventscheduling-motor-soa.version>
		<eventscheduling-motor-web.version>0.0.0.1</eventscheduling-motor-web.version>

		<slf4j.version>1.6.4</slf4j.version>
		<logback.version>1.1.3</logback.version>
	    <jcl.slf4j.version>1.7.12</jcl.slf4j.version>
		<dbh2.version>1.4.187</dbh2.version>
		<junit.version>4.8.1</junit.version>
		<aopalliance.version>1.0</aopalliance.version>
		<javax.servlet-api.version>2.5</javax.servlet-api.version>
		<spring.version>4.2.6.RELEASE</spring.version>
		<springsecurity.version>3.2.9.RELEASE</springsecurity.version>
		<jersey.version>1.18.1</jersey.version>
		<org.hsqldb.version>2.3.2</org.hsqldb.version>
		<commons-dbcp.version>1.4</commons-dbcp.version>
		<org.hibernate.version>4.3.5.Final</org.hibernate.version>
		<maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>
		<org.eclipse.jetty.jetty-maven-plugin.version>9.1.1.v20140108</org.eclipse.jetty.jetty-maven-plugin.version>
		<dozer.version>5.3.1</dozer.version>
		<aspectj.version>1.7.2</aspectj.version>
        <jodatime.version>2.2</jodatime.version>
        <jadira-usertype-core.version>3.1.0.CR1</jadira-usertype-core.version>
		<validation.version>1.0.0.GA</validation.version>
        <!-- RSS -->
        <rome.version>1.0</rome.version>
        <jsp.version>2.2</jsp.version>
        <jstl.version>1.2</jstl.version>
		<servlet.version>2.5</servlet.version>
        <javax-el.version>2.2</javax-el.version>
        <jaxb-api.version>2.2.7</jaxb-api.version>
        <jaxb-impl.version>2.2.7-b53</jaxb-impl.version>
		<maven-compiler-plugin.version>2.3.2</maven-compiler-plugin.version>
		<java.version>1.7</java.version>
		<project.encoding>UTF-8</project.encoding>
		<resources-plugin.version>2.4.3</resources-plugin.version>
		<loghome.app>/home/osanchezhuerta/loghome/eventsheduling</loghome.app>

	</properties>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>${maven-compiler-plugin.version}</version>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
					<encoding>${project.encoding}</encoding>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<version>${resources-plugin.version}</version>
				<configuration>
					<encoding>${project.encoding}</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>
  <url>https://github.com/osanchezhuerta/eventscheduling-app</url>
  <organization>
    <name>osanchezhuerta</name>
    <url>http://codefixes.blogspot.mx/</url>
  </organization>
  <licenses>
    <license>
      <name>The Apache Software License, Version 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
      <distribution>repo</distribution>
    </license>
  </licenses>
  <developers>
    <developer>
      <id>osanchezhuerta</id>
      <name>Octavio Sanchez Huerta</name>
      <email>osanchezhuerta@gmail.com</email>
    </developer>
  </developers>
  <scm>
    <connection>scm:git:git://github.com/osanchezhuerta/eventscheduling-app</connection>
    <developerConnection>scm:git:git://github.com/osanchezhuerta/eventscheduling-app</developerConnection>
    <url>https://github.com/osanchezhuerta/eventscheduling-app</url>
  </scm>

</project>


text:
package org.apache.cassandra.tools;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.PartitionPosition;
import org.apache.cassandra.db.rows.UnfilteredRowIterator;
import org.apache.cassandra.dht.AbstractBounds;
import org.apache.cassandra.dht.Bounds;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.io.sstable.Descriptor;
import org.apache.cassandra.io.sstable.ISSTableScanner;
import org.apache.cassandra.io.sstable.KeyIterator;
import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.apache.cassandra.io.sstable.metadata.MetadataComponent;
import org.apache.cassandra.io.sstable.metadata.MetadataType;
import org.apache.cassandra.schema.TableMetadataRef;
import org.apache.cassandra.utils.FBUtilities;

/**
 * Export SSTables to JSON format.
 */
public class SSTableExport
{

    private static final String KEY_OPTION = "k";
    private static final String DEBUG_OUTPUT_OPTION = "d";
    private static final String EXCLUDE_KEY_OPTION = "x";
    private static final String ENUMERATE_KEYS_OPTION = "e";
    private static final String RAW_TIMESTAMPS = "t";
    private static final String PARTITION_JSON_LINES = "l";

    private static final Options options = new Options();
    private static CommandLine cmd;

    static
    {
        DatabaseDescriptor.clientInitialization();

        Option optKey = new Option(KEY_OPTION, true, "Partition key");
        // Number of times -k <key> can be passed on the command line.
        optKey.setArgs(500);
        options.addOption(optKey);

        Option excludeKey = new Option(EXCLUDE_KEY_OPTION, true, "Excluded partition key");
        // Number of times -x <key> can be passed on the command line.
        excludeKey.setArgs(500);
        options.addOption(excludeKey);

        Option optEnumerate = new Option(ENUMERATE_KEYS_OPTION, false, "enumerate partition keys only");
        options.addOption(optEnumerate);

        Option debugOutput = new Option(DEBUG_OUTPUT_OPTION, false, "CQL row per line internal representation");
        options.addOption(debugOutput);

        Option rawTimestamps = new Option(RAW_TIMESTAMPS, false, "Print raw timestamps instead of iso8601 date strings");
        options.addOption(rawTimestamps);

        Option partitionJsonLines= new Option(PARTITION_JSON_LINES, false, "Output json lines, by partition");
        options.addOption(partitionJsonLines);
    }

    /**
     * Given arguments specifying an SSTable, and optionally an output file, export the contents of the SSTable to JSON.
     *
     * @param args
     *            command lines arguments
     * @throws ConfigurationException
     *             on configuration failure (wrong params given)
     */
    public static void main(String[] args) throws ConfigurationException
    {
        CommandLineParser parser = new PosixParser();
        try
        {
            cmd = parser.parse(options, args);
        }
        catch (ParseException e1)
        {
            System.err.println(e1.getMessage());
            printUsage();
            System.exit(1);
        }

        if (cmd.getArgs().length != 1)
        {
            System.err.println("You must supply exactly one sstable");
            printUsage();
            System.exit(1);
        }

        String[] keys = cmd.getOptionValues(KEY_OPTION);
        HashSet<String> excludes = new HashSet<>(Arrays.asList(
                cmd.getOptionValues(EXCLUDE_KEY_OPTION) == null
                        ? new String[0]
                        : cmd.getOptionValues(EXCLUDE_KEY_OPTION)));
        String ssTableFileName = new File(cmd.getArgs()[0]).getAbsolutePath();

        if (!new File(ssTableFileName).exists())
        {
            System.err.println("Cannot find file " + ssTableFileName);
            System.exit(1);
        }
        Descriptor desc = Descriptor.fromFilename(ssTableFileName);
        try
        {
            TableMetadata metadata = Util.metadataFromSSTable(desc);
            if (cmd.hasOption(ENUMERATE_KEYS_OPTION))
            {
                try (KeyIterator iter = new KeyIterator(desc, metadata))
                {
                    JsonTransformer.keysToJson(null, Util.iterToStream(iter),
                                               cmd.hasOption(RAW_TIMESTAMPS),
                                               metadata,
                                               System.out);
                }
            }
            else
            {
                SSTableReader sstable = SSTableReader.openNoValidation(desc, TableMetadataRef.forOfflineTools(metadata));
                IPartitioner partitioner = sstable.getPartitioner();
                final ISSTableScanner currentScanner;
                if ((keys != null) && (keys.length > 0))
                {
                    List<AbstractBounds<PartitionPosition>> bounds = Arrays.stream(keys)
                            .filter(key -> !excludes.contains(key))
                            .map(metadata.partitionKeyType::fromString)
                            .map(partitioner::decorateKey)
                            .sorted()
                            .map(DecoratedKey::getToken)
                            .map(token -> new Bounds<>(token.minKeyBound(), token.maxKeyBound())).collect(Collectors.toList());
                    currentScanner = sstable.getScanner(bounds.iterator());
                }
                else
                {
                    currentScanner = sstable.getScanner();
                }
                Stream<UnfilteredRowIterator> partitions = Util.iterToStream(currentScanner).filter(i ->
                    excludes.isEmpty() || !excludes.contains(metadata.partitionKeyType.getString(i.partitionKey().getKey()))
                );
                if (cmd.hasOption(DEBUG_OUTPUT_OPTION))
                {
                    AtomicLong position = new AtomicLong();
                    partitions.forEach(partition ->
                    {
                        position.set(currentScanner.getCurrentPosition());

                        if (!partition.partitionLevelDeletion().isLive())
                        {
                            System.out.println("[" + metadata.partitionKeyType.getString(partition.partitionKey().getKey()) + "]@" +
                                               position.get() + " " + partition.partitionLevelDeletion());
                        }
                        if (!partition.staticRow().isEmpty())
                        {
                            System.out.println("[" + metadata.partitionKeyType.getString(partition.partitionKey().getKey()) + "]@" +
                                               position.get() + " " + partition.staticRow().toString(metadata, true));
                        }
                        partition.forEachRemaining(row ->
                        {
                            System.out.println(
                            "[" + metadata.partitionKeyType.getString(partition.partitionKey().getKey()) + "]@"
                            + position.get() + " " + row.toString(metadata, false, true));
                            position.set(currentScanner.getCurrentPosition());
                        });
                    });
                }
                else if (cmd.hasOption(PARTITION_JSON_LINES))
                {
                    JsonTransformer.toJsonLines(currentScanner, partitions, cmd.hasOption(RAW_TIMESTAMPS), metadata, System.out);
                }
                else
                {
                    JsonTransformer.toJson(currentScanner, partitions, cmd.hasOption(RAW_TIMESTAMPS), metadata, System.out);
                }
            }
        }
        catch (IOException e)
        {
            // throwing exception outside main with broken pipe causes windows cmd to hang
            e.printStackTrace(System.err);
        }

        System.exit(0);
    }

    private static void printUsage()
    {
        String usage = String.format("sstabledump <sstable file path> <options>%n");
        String header = "Dump contents of given SSTable to standard output in JSON format.";
        new HelpFormatter().printHelp(usage, header, options, "");
    }
}


text:
from controllers import utils
class PrivacyHandler(utils.BaseHandler):
       """Handler for Privacy page."""
       def get(self):
          """Handles GET requests."""
          self.template_value['navbar'] = {'privacy': True}
          self.render('privacy.html')


text:
module KumoDockerCloud
  class Error < RuntimeError; end
  class ServiceDeployError < RuntimeError; end
  class HaproxySocketError < RuntimeError; end
  class HAProxyStateError < Error; end
  class EnvironmentApplyError < RuntimeError; end
  class StackCheckError < RuntimeError; end
  class InvalidStackError < RuntimeError; end
end


text:
//----------------------------------------------------------------------
//<Copyright company="58.com">
//      Team:SPAT
//      Blog:http://blog.58.com/spat/
//      Website:http://www.58.com
//</Copyright>
//-----------------------------------------------------------------------
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using Com.Bj58.Spat.Gaea.Serializer.Component;
using Com.Bj58.Spat.Gaea.Serializer.Component.Exceptions;

namespace Com.Bj58.Spat.Gaea.Serializer
{
    internal class DateTimeSerizlizer : SerializerBase
    {
        private readonly int BYTE_LEN = 8;
        public override void WriteObject(object obj, GaeaStream outStream)
        {
            byte[] buffer = ConvertToBinary((DateTime)obj);
            outStream.Write(buffer, 0, BYTE_LEN);
        }

        public override object ReadObject(GaeaStream inStream, Type defType)
        {
            byte[] buffer = new byte[BYTE_LEN];
            inStream.SafeRead(buffer, 0, BYTE_LEN);
            return GetDateTime(buffer);
        }
        private byte[] ConvertToBinary(DateTime dt)
        {
            return Convert.ToInt64((dt - DateTime.Parse("1970-1-1 00:00:00")).TotalMilliseconds).GetBytes();
        }
        private DateTime GetDateTime(byte[] buffer)
        {
            return DateTime.Parse("1970-1-1 00:00:00").AddMilliseconds(buffer.ToInt64(0));
        }
    }
}


text:
using System.Collections.Generic;
using Newtonsoft.Json;
using Voucherify.Core.DataModel;
using Voucherify.Core.Serialization;
using NUnit.Framework;

namespace Voucherify.Tests.Core.DataModel
{
    [TestFixture]
    public class ApiListObjectTest
    {
        [Test]
        public void ApiListObjectDeserialize()
        {
            // Arrange
            string jsonObject = "{\"object\":\"list\",\"data_ref\":\"object_list\",\"total\":1}";

            // Act
            ApiListObject jsonSerializedObject = new JsonSerializer<ApiListObject>(new List<JsonConverter>() { }).Deserialize(jsonObject);

            // Assert
            Assert.AreEqual("list", jsonSerializedObject.Object);
            Assert.AreEqual("object_list", jsonSerializedObject.DataRef);
            Assert.AreEqual(1, jsonSerializedObject.Total);
        }
    }
}


text:
namespace views {
namespace examples {

namespace {

// Time in ms per throbber frame.
const int kThrobberFrameMs = 60;

class ThrobberView : public View {
 public:
  ThrobberView() {
    throbber_ = new Throbber(kThrobberFrameMs, false);
    AddChildView(throbber_);
    throbber_->SetVisible(true);
    throbber_->Start();
  }

  virtual gfx::Size GetPreferredSize() OVERRIDE {
    return gfx::Size(width(), height());
  }

  virtual void Layout() OVERRIDE {
    View* child = child_at(0);
    gfx::Size ps = child->GetPreferredSize();
    child->SetBounds((width() - ps.width()) / 2,
                     (height() - ps.height()) / 2,
                     ps.width(), ps.height());
    SizeToPreferredSize();
  }

 private:
  Throbber* throbber_;

  DISALLOW_COPY_AND_ASSIGN(ThrobberView);
};

}  // namespace

ThrobberExample::ThrobberExample() : ExampleBase("Throbber") {
}

ThrobberExample::~ThrobberExample() {
}

void ThrobberExample::CreateExampleView(View* container) {
  container->SetLayoutManager(new FillLayout());
  container->AddChildView(new ThrobberView());
}

}  // namespace examples
}  // namespace views


text:
using System.Threading;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace Microsoft.AspNetCore.Http.Connections.Tests;

public class TestApplicationLifetime : IHostApplicationLifetime
{
    private readonly CancellationTokenSource _startedSource = new CancellationTokenSource();
    private readonly CancellationTokenSource _stoppingSource = new CancellationTokenSource();
    private readonly CancellationTokenSource _stoppedSource = new CancellationTokenSource();

    public CancellationToken ApplicationStarted => _startedSource.Token;

    public CancellationToken ApplicationStopping => _stoppingSource.Token;

    public CancellationToken ApplicationStopped => _stoppedSource.Token;

    public void StopApplication()
    {
        _stoppingSource.Cancel(throwOnFirstException: false);
    }

    public void Start()
    {
        _startedSource.Cancel(throwOnFirstException: false);
    }
}

public class EmptyApplicationLifetime : IHostApplicationLifetime
{
    public CancellationToken ApplicationStarted => CancellationToken.None;

    public CancellationToken ApplicationStopping => CancellationToken.None;

    public CancellationToken ApplicationStopped => CancellationToken.None;

    public void StopApplication()
    {
    }
}


text:
namespace c10k
{

    EventLoop::EventLoop(int max_event, const LoggerT &logger):
            logger(logger)
    {
        using detail::call_must_ok;
        epollfd = call_must_ok(epoll_create, "Create epoll fd", max_event);
        logger->debug("EPOLLFD created: {}", epollfd);
    }

    void EventLoop::loop()
    {
        using detail::make_scope_guard;
        auto in_loop_guard = make_scope_guard(
                [&]() {
                    in_loop_ = true;
                    logger->debug("Start event loop");
                },
                [&]() {
                    in_loop_ = false;
                    logger->debug("Exit event loop");
                }
        );

        epoll_event events[epoll_event_buf_size()];
        using namespace std::chrono_literals;
        TimerFD fd(25ms);

        auto fd_guard = make_scope_guard(
                [&]() {
                    add_event(fd.getfd(), EventType(EventCategory::POLLIN), EventLoop::NullEventHandler);
                },
                [&]() {
                    remove_event(fd.getfd());
                });

        for (;loop_enabled_;)
        {
            int ret = epoll_wait(epollfd, events, epoll_event_buf_size(), -1);
            if (ret >= 0)
                handle_events(events, events + ret);
            else
            {
                std::error_code ec(errno, std::system_category());
                logger->critical("Error in epoll_wait: {} epollfd={} errno={}", ec.message(), epollfd, errno);
                std::lock_guard<std::mutex> lk(map_mutex);
                for (auto &&pair : fd_to_poll_data)
                {
                    logger->debug("fd {} listening", pair.first);
                }
                throw std::system_error(ec);
            }
        }
    }

    void EventLoop::handle_events(epoll_event *st, epoll_event *ed)
    {
        std::for_each(st, ed, [&](const epoll_event &ev) {
            detail::PollData *data = static_cast<detail::PollData *>(ev.data.ptr);
            Event e;
            EventHandler handler;
            {
                std::lock_guard<std::mutex> lk(map_mutex);
                e = Event{this, data->fd, EventType(ev.events)};
                handler = data->handler;
            }
            logger->trace("Distributed to handle event {}", e);
            handler(e);
        });
    }

    void EventLoop::add_event(int fd, EventType et, EventHandler handler)
    {
        using detail::PollData;
        using detail::call_must_ok;

        std::lock_guard<std::mutex> lk(map_mutex);

        logger->debug("Add event {} to fd={}", et, fd);
        epoll_event new_event;
        new_event.events = (int)et;
        auto it = fd_to_poll_data.insert(std::make_pair(fd, std::make_unique<PollData>(fd, std::move(handler))));
        if (!it.second)
        {
            logger->error("Cannot insert fd {}: already exist",fd);
            throw std::runtime_error("Cannot insert fd into event(already exist)");
        }
        PollData *ptr = it.first->second.get();

        new_event.data.ptr = (void*) ptr;
        call_must_ok(epoll_ctl, "epoll_ctl ADD", epollfd, EPOLL_CTL_ADD, fd, &new_event);
    }

    void EventLoop::remove_event(int fd)
    {
        using detail::call_must_ok;

        std::lock_guard<std::mutex> lk(map_mutex);
        logger->debug("Remove fd={}", fd);
        call_must_ok(epoll_ctl, "epoll_ctl REMOVE", epollfd, EPOLL_CTL_DEL, fd, nullptr);
        auto it = fd_to_poll_data.find(fd);
        if (it == fd_to_poll_data.end())
        {
            logger->error("Cannot remove fd {} from map", fd);
            throw std::runtime_error("Cannot remove fd from map");
        }
        fd_to_poll_data.erase(it);
    }

    void EventLoop::modify_event(int fd, EventType et, EventHandler handler)
    {
        using detail::PollData;
        using detail::call_must_ok;

        std::lock_guard<std::mutex> lk(map_mutex);
        logger->debug("Modify event {} to fd={}", et, fd);
        epoll_event new_event;

        new_event.events = (int)et;
        auto it = fd_to_poll_data.find(fd);

        if (it == fd_to_poll_data.end())
        {
            logger->error("No old event registered with fd={}", fd);
            throw std::runtime_error("No old event registered with this fd when modifying");
        }

        it->second->fd = fd;
        it->second->handler = std::move(handler);
        new_event.data.ptr = (void*)it->second.get();

        call_must_ok(epoll_ctl, "epoll_ctl MODIFY", epollfd, EPOLL_CTL_MOD, fd, &new_event);
    }

    EventLoop::~EventLoop()
    {
        using detail::call_must_ok;
        logger->info("Closing epollfd={}", epollfd);
        call_must_ok(::close, "Close", epollfd);
    }
}


text:
TARGETS := libethdrivers.a

# Source files required to build the target
CFILES += $(patsubst $(SOURCE_DIR)/%,%,$(wildcard ${SOURCE_DIR}/src/plat/$(PLAT)/*.c))
CFILES += $(patsubst $(SOURCE_DIR)/%,%,$(wildcard ${SOURCE_DIR}/src/plat/$(PLAT)/uboot/*.c))
CFILES += $(patsubst $(SOURCE_DIR)/%,%,$(wildcard ${SOURCE_DIR}/src/*.c))

# Header files/directories this library provides
HDRFILES := \
    $(wildcard ${SOURCE_DIR}/include/*) \
    $(wildcard ${SOURCE_DIR}/plat_include/$(PLAT)/*) \
    $(wildcard ${SOURCE_DIR}/arch_include/${ARCH}/*)

include $(SEL4_COMMON)/common.mk


text:
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^get_list$', views.get_list, name='get_list'),
    url(r'^upload$', views.AjaxPhotoUploadView.as_view(), name='upload'),
]


text:
logInteractive
==============
Mathematica interactive CDF for showing how slowly log(x) grows as the base increases.


text:
package com.groupon.roboremote.roboremoteclient;

import com.android.ddmlib.NullOutputReceiver;
import com.groupon.roboremote.Constants;
import com.groupon.roboremote.roboremoteclientcommon.DebugBridge;
import com.groupon.roboremote.roboremoteclientcommon.Device;
import com.groupon.roboremote.roboremoteclientcommon.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.groupon.roboremote.roboremoteclientcommon.logging.*;

import java.io.File;
import java.lang.Exception;
import java.lang.String;
import java.lang.Thread;

public class TestBase {
    protected final Logger logger = LoggerFactory.getLogger("test");
    private static String app_package = null;
    private static String test_class = null;
    private static String test_runner = null;
    private AppThread ap = null;
    private LogcatLogger logcatLogger = null;

    public void onFailure() throws Exception {
        logger.warn("TestBase::OnFailure:: Taking screenshot");
        DebugBridge.get().getScreenShot("FAILURE.png");
        Device.storeFailurePng();
    }

    public void setUp(String testName) throws Exception {
        setUp(testName, false, true);
    }

    /**
     * This is the generic test setup function
     * @param relaunch - true if this is an app relaunch
     * @param clearAppData - true if you want app data cleared, false otherwise
     */
    public void setUp(String testName, Boolean relaunch, Boolean clearAppData) throws Exception {
        if (! relaunch) {
            logger.info("Starting test {}", testName);
            Device.setupLogDirectories(testName);

            // clear stale ports
            Utils.clearStaleADBTunnels("ROBO");

            // find a useable port
            PortSingleton.getInstance().setPort(Utils.getFreePort());

            // create adb tunnel
            Utils.addADBTunnelWithPIDFile("ROBO", PortSingleton.getInstance().getPort());
        }

        // see if a server is already listening
        boolean clientWasListening = false;
        if (Client.getInstance().isListening()) {
            clientWasListening = true;
        }

        if (clearAppData) {
            // clear app data - this has the side effect of killing a running app
            // TODO: this only works on 2.3+.. need a solution for 2.1+
            Device.clearAppData(app_package);
        }

        // wait for the client to stop listening if it was previously listening
        if (clientWasListening) {
            // wait for the server to be dead
            for (int x = 0; x < 10; x++) {
                // try to make a query.. if it doesnt work then sleep
                TestLogger.get().info("Trying to see if server is still available..");

                if (! Client.getInstance().isListening())
                    break;

                if (x == 9)
                    throw new Exception("Server is still available, but should not be");

                Thread.sleep(2000);
            }
        }

        if (! relaunch) {
            TestLogger.get().info("Starting logcat");
            if (logcatLogger == null) {
                logcatLogger = new LogcatLogger(System.getProperty("java.io.tmpdir") +
                        File.separator + "adb_robo.log");
            }
            logcatLogger.startLogListener();

            // set up event manager
            EmSingleton.get().clearEvents();
        }

        // starting test runner
        TestLogger.get().info("Starting RC Runner");

        // start app
        startApp();
    }

    // This is called in the failure method override above
    public void tearDown() throws Exception {
        try
        {
            EmSingleton.get().close();
            killApp();

            // clear stale ADB ports
            Utils.clearStaleADBTunnels("ROBO");

            // stop logcat
            TestLogger.get().info("Stopping logcat");
            logcatLogger.stopLogListener();
            logcatLogger = null;

            // store logs
            Device.storeLogs("adb_robo.log", "robo.log");

            // stop EventManager
            EmSingleton.release();
        } catch (Exception e) {

        } finally {
            DebugBridge.destroy();
        }
    }

    public static void setAppEnvironmentVariables(String appPackage, String testClass, String testRunner) {
        app_package = appPackage;
        test_class = testClass;
        test_runner = testRunner;
    }

    public static void setAppEnvironmentVariables() throws Exception {
        // get environment variables
        app_package = Utils.getEnv("ROBO_APP_PACKAGE", app_package);
        if (app_package == null) {
            throw new Exception("ROBO_APP_PACKAGE is not set");
        }

        test_class = Utils.getEnv("ROBO_TEST_CLASS", test_class);
        if (test_class == null) {
            throw new Exception("ROBO_TEST_CLASS is not set");
        }

        test_runner = Utils.getEnv("ROBO_TEST_RUNNER", test_runner);
        if (test_runner == null) {
            throw new Exception("ROBO_TEST_RUNNER is not set");
        }
    }

    public String getTestClass() {
        return test_class;
    }

    public String getTestRunner() {
        return test_runner;
    }

    public String getAppPackage() {
        return app_package;
    }

    public void startApp() throws Exception {
        ap = new AppThread();
        ap.start();

        for (int x = 0; x < 10; x++) {
            // try to make a query.. if it doesnt work then sleep
            TestLogger.get().info("Trying to ping test server..");
            if (Client.getInstance().isListening())
                break;

            if (x == 9)
                throw new Exception("Could not contact test server");

            Thread.sleep(5000);
        }
    }

    public void killApp() throws Exception {
        // try to kill just by calling exit
        try {
            Client.getInstance().map("java.lang.System", "exit", 0);
        } catch (Exception e) {
            // this will actually throw an exception since it doesnt get a response from this command
        }

        // shut down the thread
        if (ap != null) {
            ap.close();
            ap.interrupt();
            ap = null;
        }

        // wait for the server to be dead
        for (int x = 0; x < 10; x++) {
            // try to make a query.. if it doesnt work then sleep
            TestLogger.get().info("Trying to see if server is still available..");

            if (! Client.getInstance().isListening())
                break;

            if (x == 9)
                throw new Exception("Server is still available, but should not be");

            Thread.sleep(2000);
        }
    }

    /**
     * This thread contains the running RC test
     * DebugBridge does not return until the instrumentation finishes so we have to run it in its own thread
     */
    private class AppThread extends Thread {
        public void run() {
            try {
                DebugBridge.get().runShellCommand("am instrument -e port " + PortSingleton.getInstance().getPort() + " -w " + getTestRunner(), new NullOutputReceiver(), 0);
            } catch (Exception e) {

            }
        }

        public void close() {
        }
    }
}


text:
package spark.scheduler

import spark.scheduler.cluster.TaskInfo
import spark.util.Distribution
import spark.{Utils, Logging}
import spark.executor.TaskMetrics

trait SparkListener {
  /**
   * called when a stage is completed, with information on the completed stage
   */
  def onStageCompleted(stageCompleted: StageCompleted)
}

sealed trait SparkListenerEvents

case class StageCompleted(val stageInfo: StageInfo) extends SparkListenerEvents

/**
 * Simple SparkListener that logs a few summary statistics when each stage completes
 */
class StatsReportListener extends SparkListener with Logging {
  def onStageCompleted(stageCompleted: StageCompleted) {
    import spark.scheduler.StatsReportListener._
    implicit val sc = stageCompleted
    this.logInfo("Finished stage: " + stageCompleted.stageInfo)
    showMillisDistribution("task runtime:", (info, _) => Some(info.duration))

    //shuffle write
    showBytesDistribution("shuffle bytes written:",(_,metric) => metric.shuffleWriteMetrics.map{_.shuffleBytesWritten})

    //fetch & io
    showMillisDistribution("fetch wait time:",(_, metric) => metric.shuffleReadMetrics.map{_.fetchWaitTime})
    showBytesDistribution("remote bytes read:", (_, metric) => metric.shuffleReadMetrics.map{_.remoteBytesRead})
    showBytesDistribution("task result size:", (_, metric) => Some(metric.resultSize))

    //runtime breakdown
    val runtimePcts = stageCompleted.stageInfo.taskInfos.map{
      case (info, metrics) => RuntimePercentage(info.duration, metrics)
    }
    showDistribution("executor (non-fetch) time pct: ", Distribution(runtimePcts.map{_.executorPct * 100}), "%2.0f %%")
    showDistribution("fetch wait time pct: ", Distribution(runtimePcts.flatMap{_.fetchPct.map{_ * 100}}), "%2.0f %%")
    showDistribution("other time pct: ", Distribution(runtimePcts.map{_.other * 100}), "%2.0f %%")
  }

}

object StatsReportListener extends Logging {

  //for profiling, the extremes are more interesting
  val percentiles = Array[Int](0,5,10,25,50,75,90,95,100)
  val probabilities = percentiles.map{_ / 100.0}
  val percentilesHeader = "\t" + percentiles.mkString("%\t") + "%"

  def extractDoubleDistribution(stage:StageCompleted, getMetric: (TaskInfo,TaskMetrics) => Option[Double]): Option[Distribution] = {
    Distribution(stage.stageInfo.taskInfos.flatMap{
      case ((info,metric)) => getMetric(info, metric)})
  }

  //is there some way to setup the types that I can get rid of this completely?
  def extractLongDistribution(stage:StageCompleted, getMetric: (TaskInfo,TaskMetrics) => Option[Long]): Option[Distribution] = {
    extractDoubleDistribution(stage, (info, metric) => getMetric(info,metric).map{_.toDouble})
  }

  def showDistribution(heading: String, d: Distribution, formatNumber: Double => String) {
    val stats = d.statCounter
    logInfo(heading + stats)
    val quantiles = d.getQuantiles(probabilities).map{formatNumber}
    logInfo(percentilesHeader)
    logInfo("\t" + quantiles.mkString("\t"))
  }

  def showDistribution(heading: String, dOpt: Option[Distribution], formatNumber: Double => String) {
    dOpt.foreach { d => showDistribution(heading, d, formatNumber)}
  }

  def showDistribution(heading: String, dOpt: Option[Distribution], format:String) {
    def f(d:Double) = format.format(d)
    showDistribution(heading, dOpt, f _)
  }

  def showDistribution(heading:String, format: String, getMetric: (TaskInfo,TaskMetrics) => Option[Double])
    (implicit stage: StageCompleted) {
    showDistribution(heading, extractDoubleDistribution(stage, getMetric), format)
  }

  def showBytesDistribution(heading:String, getMetric: (TaskInfo,TaskMetrics) => Option[Long])
    (implicit stage: StageCompleted) {
    showBytesDistribution(heading, extractLongDistribution(stage, getMetric))
  }

  def showBytesDistribution(heading: String, dOpt: Option[Distribution]) {
    dOpt.foreach{dist => showBytesDistribution(heading, dist)}
  }

  def showBytesDistribution(heading: String, dist: Distribution) {
    showDistribution(heading, dist, (d => Utils.memoryBytesToString(d.toLong)): Double => String)
  }

  def showMillisDistribution(heading: String, dOpt: Option[Distribution]) {
    showDistribution(heading, dOpt, (d => StatsReportListener.millisToString(d.toLong)): Double => String)
  }

  def showMillisDistribution(heading: String, getMetric: (TaskInfo, TaskMetrics) => Option[Long])
    (implicit stage: StageCompleted) {
    showMillisDistribution(heading, extractLongDistribution(stage, getMetric))
  }

  val seconds = 1000L
  val minutes = seconds * 60
  val hours = minutes * 60

  /**
   * reformat a time interval in milliseconds to a prettier format for output
   */
  def millisToString(ms: Long) = {
    val (size, units) =
      if (ms > hours) {
        (ms.toDouble / hours, "hours")
      } else if (ms > minutes) {
        (ms.toDouble / minutes, "min")
      } else if (ms > seconds) {
        (ms.toDouble / seconds, "s")
      } else {
        (ms.toDouble, "ms")
      }
    "%.1f %s".format(size, units)
  }
}

case class RuntimePercentage(executorPct: Double, fetchPct: Option[Double], other: Double)
object RuntimePercentage {
  def apply(totalTime: Long, metrics: TaskMetrics): RuntimePercentage = {
    val denom = totalTime.toDouble
    val fetchTime = metrics.shuffleReadMetrics.map{_.fetchWaitTime}
    val fetch = fetchTime.map{_ / denom}
    val exec = (metrics.executorRunTime - fetchTime.getOrElse(0l)) / denom
    val other = 1.0 - (exec + fetch.getOrElse(0d))
    RuntimePercentage(exec, fetch, other)
  }
}