text:
package com.jfixby.r3.fokker.core.assets;

import java.io.IOException;

import com.jfixby.r3.fokker.api.StandardPackageFormats;
import com.jfixby.rana.api.format.PackageFormat;
import com.jfixby.rana.api.loader.PackageReader;
import com.jfixby.rana.api.loader.PackageReaderInput;
import com.jfixby.scarabei.api.collections.Collection;
import com.jfixby.scarabei.api.collections.Collections;
import com.jfixby.scarabei.api.collections.List;
import com.jfixby.scarabei.api.err.Err;

public class Box2DEditorLoader implements PackageReader {

	@Override
	public Collection<PackageFormat> listAcceptablePackageFormats () {
		return null;
	}

	@Override
	public void doReadPackage (final PackageReaderInput input) throws IOException {
		Err.throwNotImplementedYet();
	}

	final List<PackageFormat> acceptablePackageFormats;

// final GdxShapesRegister register = new GdxShapesRegister();
//
	public Box2DEditorLoader () {
		this.acceptablePackageFormats = Collections.newList();
		final PackageFormat format = new PackageFormat(StandardPackageFormats.Box2DEditor.Project);
		this.acceptablePackageFormats.add(format);
	}
//
// @Override
// public Collection<PackageFormat> listAcceptablePackageFormats () {
// return this.acceptablePackageFormats;
// }
//
// @Override
// public GdxShapeEntry getAsset (final AssetID asset_id) {
// return this.register.getShapeData(asset_id);
// }
//
// @Override
// public void printAll () {
// this.register.printAll("loaded raster");
// }
//
// @Override
// public void doReadPackage (final PackageInput input) throws IOException {
// try {
// L.d("Reading " + StandardPackageFormats.Box2DEditor.Project, input.getPackageHandler().getPackageName());
// final Box2DEditorProject project = Box2DEditorProject.loadProject(input.getRootFile());
//
// for (int i = 0; i < project.size(); i++) {
// final Box2DEditorShape shape = project.getShape(i);
// final AssetID rester_id = (shape.getID());
// final Box2DEditorShapeData data = new Box2DEditorShapeData(rester_id, shape);
//
// final GdxShapeEntry entry = new GdxShapeEntry(data);
//
// this.register.registerRaster(rester_id, entry);
// AssetsManager.registerAssetContainer(rester_id, this);
// L.d(" ", rester_id);
//
// }
//
// } catch (final Throwable e) {
// throw new IOException("" + e);
// }
// }
//
// @Override
// public long readPackageTimeStamp (final AssetID assetID) {
// Err.reportNotImplementedYet();
// return 0;
// }
//
// @Override
// public long getPackageTimeStamp (final AssetID assetID) {
// Err.reportNotImplementedYet();
// return 0;
// }
//
// @Override
// public void purgeAssets (final Collection<AssetID> relatedAssets) {
// Err.reportNotImplementedYet();
//
// }

}

redpajama_set_name: RedPajamaGithub


text:
var accountSid = 'ACb90ca8a55311aff697443481e485ba09',
    authToken = '09017f12b95041004e317af8d0775893',
    twilioModule = require('twilio')(accountSid, authToken);
twilioClient = {
    client: twilioModule,
    from: "+12268871679",
    to: "",
    enabled: false
};

var func = require("./functions.js");

func.setLcd();

// call the packages we need
var express = require('express'), // call express
    app = express(), // define our app using express
    bodyParser = require('body-parser');

var port = process.env.PORT || 8080; // set our port

//API's
var light = require('./routes/light.js'),
    temperature = require('./routes/temperature.js'),
    sound = require('./routes/sound.js'),
    all = require('./routes/all.js'),
    twilio = require('./routes/twilio.js')(twilioClient),
    lcd = require('./routes/lcd.js');

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

// ROUTES FOR OUR API
// =============================================================================
app.use('/api', light);
app.use('/api', temperature);
app.use('/api', sound);
app.use('/api', all);
app.use('/api', twilio);
app.use('/api', lcd);

// START THE SERVER
// =============================================================================
app.listen(port);


text:
Chrome Extension for [OpenProxy](http://openproxy.github.io).

It allows to switch proxies directly through the OpenProxy web page.

## Installation

> Follow the same instructions if you need to update an extension.

1. Download [latest CRX](https://github.com/openproxy/openproxy-chrome-extension/releases)
2. Open "chrome://extensions" (in Chrome)
3. Drug and drop CRX package onto the Extensions page

## Development

> PREREQUISITES: [GIT](http://git-scm.com/downloads), [Node.js and NPM](https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager), [Grunt](https://github.com/gruntjs/grunt-cli)

    git clone https://github.com/openproxy/openproxy-chrome-extension.git
    cd openproxy-chrome-extension
    npm install # this will install all required dependencies

    grunt # for a "live" unpacked version
    grunt unpacked # for the unpacked version
    grunt pack # for the CRX

## License

[MIT License](http://opensource.org/licenses/mit-license.php)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/Avengers.iml" filepath="$PROJECT_DIR$/.idea/Avengers.iml" />
    </modules>
  </component>
</project>


text:
var config = {
    "shim": {
        "extjs/ext-tree": [
            "prototype"
        ],
        "extjs/ext-tree-checkbox": [
            "extjs/ext-tree",
            "extjs/defaults"
        ],
        "jquery/editableMultiselect/js/jquery.editable": [
            "jquery"
        ]
    },
    "bundles": {
        "js/theme": [
            "globalNavigation",
            "globalSearch",
            "modalPopup",
            "useDefault",
            "loadingPopup",
            "collapsable"
        ]
    },
    "map": {
        "*": {
            "translateInline":      "mage/translate-inline",
            "form":                 "mage/backend/form",
            "button":               "mage/backend/button",
            "accordion":            "mage/accordion",
            "actionLink":           "mage/backend/action-link",
            "validation":           "mage/backend/validation",
            "notification":         "mage/backend/notification",
            "loader":               "mage/loader_old",
            "loaderAjax":           "mage/loader_old",
            "floatingHeader":       "mage/backend/floating-header",
            "suggest":              "mage/backend/suggest",
            "mediabrowser":         "jquery/jstree/jquery.jstree",
            "tabs":                 "mage/backend/tabs",
            "treeSuggest":          "mage/backend/tree-suggest",
            "calendar":             "mage/calendar",
            "dropdown":             "mage/dropdown_old",
            "collapsible":          "mage/collapsible",
            "menu":                 "mage/backend/menu",
            "jstree":               "jquery/jstree/jquery.jstree",
            "details":              "jquery/jquery.details"
        }
    },
    "deps": [
        "js/theme",
        "mage/backend/bootstrap",
        "mage/adminhtml/globals"
    ],
    "paths": {
        "jquery/ui": "jquery/jquery-ui-1.9.2"
    }
};


text:
using System.Web;

namespace Umbraco.Web
{
    public interface IHttpContextAccessor
    {
        HttpContext HttpContext { get; set; }
    }
}


text:
package org.hawkular.apm.server.processor.tracecompletiontime;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import org.hawkular.apm.api.model.Constants;
import org.hawkular.apm.api.model.Property;
import org.hawkular.apm.api.model.trace.Component;
import org.hawkular.apm.api.model.trace.Consumer;
import org.hawkular.apm.api.model.trace.Producer;
import org.hawkular.apm.api.model.trace.Trace;
import org.hawkular.apm.api.utils.EndpointUtil;
import org.hawkular.apm.server.api.task.RetryAttemptException;
import org.hawkular.apm.server.processor.tracecompletiontime.TraceCompletionInformation.Communication;
import org.junit.Test;

/**
 * @author gbrown
 */
public class TraceCompletionInformationInitiatorTest {

    @Test
    public void testProcessSingleEmptyTrace() throws RetryAttemptException {
        Trace trace = new Trace();

        TraceCompletionInformationInitiator initiator = new TraceCompletionInformationInitiator();

        assertNull(initiator.processOneToOne(null, trace));
    }

    @Test
    public void testProcessSingleNotInitialFragment() throws RetryAttemptException {
        Trace trace = new Trace().setTraceId("traceId").setFragmentId("anotherId");
        Consumer c = new Consumer();
        trace.getNodes().add(c);

        TraceCompletionInformationInitiator initiator = new TraceCompletionInformationInitiator();

        assertNull(initiator.processOneToOne(null, trace));
    }

    @Test
    public void testProcessSingleInitialFragmentConsumer() throws RetryAttemptException {
        Trace trace = new Trace();
        trace.setTraceId("traceId");
        trace.setFragmentId("traceId");
        trace.setTransaction("traceName");
        trace.setTimestamp(100000);

        Consumer c = new Consumer();
        c.setUri("uri");
        c.setTimestamp(1);
        c.setDuration(200000);
        c.getProperties().add(new Property(Constants.PROP_FAULT, "myFault"));
        c.setEndpointType("HTTP");

        trace.getNodes().add(c);

        TraceCompletionInformationInitiator initiator = new TraceCompletionInformationInitiator();

        TraceCompletionInformation ci = initiator.processOneToOne(null, trace);

        assertNotNull(ci);
        assertEquals(1, ci.getCommunications().size());
        assertTrue(ci.getCommunications().get(0).getIds().contains("traceId:0"));

        assertEquals(trace.getTraceId(), ci.getCompletionTime().getId());
        assertEquals(trace.getTransaction(), ci.getCompletionTime().getTransaction());
        assertEquals(c.getEndpointType(), ci.getCompletionTime().getEndpointType());
        assertFalse(ci.getCompletionTime().isInternal());
        assertEquals(trace.getTimestamp(), ci.getCompletionTime().getTimestamp());
        assertEquals(c.getUri(), ci.getCompletionTime().getUri());
        assertEquals(200000, ci.getCompletionTime().getDuration());
        assertEquals(1, ci.getCompletionTime().getProperties(Constants.PROP_FAULT).size());
        assertEquals(c.getProperties(Constants.PROP_FAULT), ci.getCompletionTime().getProperties(Constants.PROP_FAULT));
    }

    @Test
    public void testProcessSingleInitialFragmentProducer() throws RetryAttemptException {
        Trace trace = new Trace();
        trace.setTraceId("traceId");
        trace.setFragmentId(trace.getTraceId());

        Producer p = new Producer();
        p.setUri("uri");
        p.addInteractionCorrelationId("pid");

        trace.getNodes().add(p);

        TraceCompletionInformationInitiator initiator = new TraceCompletionInformationInitiator();

        TraceCompletionInformation ci = initiator.processOneToOne(null, trace);

        assertNotNull(ci);
        assertEquals(2, ci.getCommunications().size());
        assertTrue(ci.getCommunications().get(0).getIds().contains("traceId:0"));
        assertTrue(ci.getCommunications().get(1).getIds().contains("pid"));
        assertEquals(EndpointUtil.encodeClientURI(p.getUri()), ci.getCompletionTime().getUri());
    }

    @Test
    public void testProcessSingleInitialFragmentComponent() throws RetryAttemptException {
        Trace trace = new Trace();
        trace.setTraceId("traceId");
        trace.setFragmentId("traceId");
        trace.setTransaction("traceName");
        trace.setTimestamp(100000);

        Component c = new Component();
        c.setUri("uri");
        c.setTimestamp(1);
        c.setDuration(200000);
        c.getProperties().add(new Property(Constants.PROP_FAULT, "myFault"));

        trace.getNodes().add(c);

        TraceCompletionInformationInitiator initiator = new TraceCompletionInformationInitiator();

        TraceCompletionInformation ci = initiator.processOneToOne(null, trace);

        assertNotNull(ci);
        assertEquals(1, ci.getCommunications().size());
        assertTrue(ci.getCommunications().get(0).getIds().contains("traceId:0"));

        assertEquals(trace.getTraceId(), ci.getCompletionTime().getId());
        assertEquals(trace.getTransaction(), ci.getCompletionTime().getTransaction());
        assertEquals(trace.getTimestamp(), ci.getCompletionTime().getTimestamp());
        assertEquals(c.getUri(), ci.getCompletionTime().getUri());
        assertEquals(200000, ci.getCompletionTime().getDuration());
        assertEquals(c.getProperties(Constants.PROP_FAULT), ci.getCompletionTime().getProperties(Constants.PROP_FAULT));
        assertEquals(1, ci.getCompletionTime().getProperties(Constants.PROP_FAULT).size());
    }

    @Test
    public void testProcessSingleInitialFragmentConsumerWithProducers() throws RetryAttemptException {
        Trace trace = new Trace();
        trace.setTraceId("traceId");
        trace.setFragmentId("traceId");
        trace.setTransaction("traceName");
        trace.setTimestamp(100);

        Consumer c = new Consumer();
        c.setUri("uri");

        trace.getNodes().add(c);

        Producer p1 = new Producer();
        p1.setUri("p1");
        p1.addInteractionCorrelationId("p1id");
        c.getNodes().add(p1);

        Producer p2 = new Producer();
        p2.setUri("p2");
        p2.addInteractionCorrelationId("p2id");
        c.getNodes().add(p2);

        TraceCompletionInformationInitiator initiator = new TraceCompletionInformationInitiator();

        TraceCompletionInformation ci = initiator.processOneToOne(null, trace);

        assertNotNull(ci);
        assertEquals(5, ci.getCommunications().size());

        for (Communication cm : ci.getCommunications()) {
            assertEquals(1, cm.getIds().size());
        }

        assertEquals("p1id", ci.getCommunications().get(2).getIds().get(0));
        assertEquals("p2id", ci.getCommunications().get(4).getIds().get(0));
    }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\modules\backend\modules\gallery\models\GalleryCategoriesSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'id') ?>

    <?= $form->field($model, 'title') ?>

    <?= $form->field($model, 'status') ?>

        <?= Html::submitButton(Yii::t('base', 'Search'), ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton(Yii::t('base', 'Reset'), ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
<?php

namespace Spa\BackendBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ProductType extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('description')
            ->add('file')
            ->add('productCategory')
            ->add('productCategory','entity', array(
                'class' => 'SpaBackendBundle:ProductCategory',
                'property' => 'name', 'empty_value' => 'Selecione uma linha'))
            ->add('save', 'submit', array('label' => ' Salvar'))
            ->add('save_and_publish', 'submit', array('label' => ' Salvar e Publicar' ))
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Spa\BackendBundle\Entity\Product'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'spa_backendbundle_product';
    }
}


text:
package edu.kit.ipd.crowdcontrol.objectservice.crowdworking;

/**
 * Exception if the payment request to a platform has a illegal paymentjob list
 */
public class IllegalWorkerSetException extends Exception {
    /**
     * Create the new exception
     */
    public IllegalWorkerSetException() {
        super("The list of payment Jobs need to have all workers which worked on this experiment on the given platform");
    }
}


text:
"""The **splunklib.results** module provides a streaming XML reader for Splunk
search results.

Splunk search results can be returned in a variety of formats including XML,
JSON, and CSV. To make it easier to stream search results in XML format, they
are returned as a stream of XML *fragments*, not as a single XML document. This
module supports incrementally reading one result record at a time from such a
result stream. This module also provides a friendly iterator-based interface for
accessing search results while avoiding buffering the result set, which can be
very large.

To use the reader, instantiate :class:`JSONResultsReader` on a search result stream
as follows:::

    reader = ResultsReader(result_stream)
    for item in reader:
        print(item)
    print "Results are a preview: %s" % reader.is_preview
"""

from __future__ import absolute_import

from io import BufferedReader, BytesIO

from splunklib import six

from splunklib.six import deprecated

try:
    import xml.etree.cElementTree as et
except:
    import xml.etree.ElementTree as et

from collections import OrderedDict
from json import loads as json_loads

try:
    from splunklib.six.moves import cStringIO as StringIO
except:
    from splunklib.six import StringIO

__all__ = [
    "ResultsReader",
    "Message",
    "JSONResultsReader"
]

class Message(object):
    """This class represents informational messages that Splunk interleaves in the results stream.

    ``Message`` takes two arguments: a string giving the message type (e.g., "DEBUG"), and
    a string giving the message itself.

    **Example**::

        m = Message("DEBUG", "There's something in that variable...")
    """

    def __init__(self, type_, message):
        self.type = type_
        self.message = message

    def __repr__(self):
        return "%s: %s" % (self.type, self.message)

    def __eq__(self, other):
        return (self.type, self.message) == (other.type, other.message)

    def __hash__(self):
        return hash((self.type, self.message))

class _ConcatenatedStream(object):
    """Lazily concatenate zero or more streams into a stream.

    As you read from the concatenated stream, you get characters from
    each stream passed to ``_ConcatenatedStream``, in order.

    **Example**::

        from StringIO import StringIO
        s = _ConcatenatedStream(StringIO("abc"), StringIO("def"))
        assert s.read() == "abcdef"
    """

    def __init__(self, *streams):
        self.streams = list(streams)

    def read(self, n=None):
        """Read at most *n* characters from this stream.

        If *n* is ``None``, return all available characters.
        """
        response = b""
        while len(self.streams) > 0 and (n is None or n > 0):
            txt = self.streams[0].read(n)
            response += txt
            if n is not None:
                n -= len(txt)
            if n is None or n > 0:
                del self.streams[0]
        return response

class _XMLDTDFilter(object):
    """Lazily remove all XML DTDs from a stream.

    All substrings matching the regular expression <?[^>]*> are
    removed in their entirety from the stream. No regular expressions
    are used, however, so everything still streams properly.

    **Example**::

        from StringIO import StringIO
        s = _XMLDTDFilter("<?xml abcd><element><?xml ...></element>")
        assert s.read() == "<element></element>"
    """

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

    def read(self, n=None):
        """Read at most *n* characters from this stream.

        If *n* is ``None``, return all available characters.
        """
        response = b""
        while n is None or n > 0:
            c = self.stream.read(1)
            if c == b"":
                break
            elif c == b"<":
                c += self.stream.read(1)
                if c == b"<?":
                    while True:
                        q = self.stream.read(1)
                        if q == b">":
                            break
                else:
                    response += c
                    if n is not None:
                        n -= len(c)
            else:
                response += c
                if n is not None:
                    n -= 1
        return response

@deprecated("Use the JSONResultsReader function instead in conjuction with the 'output_mode' query param set to 'json'")
class ResultsReader(object):
    """This class returns dictionaries and Splunk messages from an XML results
    stream.

    ``ResultsReader`` is iterable, and returns a ``dict`` for results, or a
    :class:`Message` object for Splunk messages. This class has one field,
    ``is_preview``, which is ``True`` when the results are a preview from a
    running search, or ``False`` when the results are from a completed search.

    This function has no network activity other than what is implicit in the
    stream it operates on.

    :param `stream`: The stream to read from (any object that supports
        ``.read()``).

    **Example**::

        import results
        response = ... # the body of an HTTP response
        reader = results.ResultsReader(response)
        for result in reader:
            if isinstance(result, dict):
                print "Result: %s" % result
            elif isinstance(result, results.Message):
                print "Message: %s" % result
        print "is_preview = %s " % reader.is_preview
    """

    # Be sure to update the docstrings of client.Jobs.oneshot,
    # client.Job.results_preview and client.Job.results to match any
    # changes made to ResultsReader.
    #
    # This wouldn't be a class, just the _parse_results function below,
    # except that you cannot get the current generator inside the
    # function creating that generator. Thus it's all wrapped up for
    # the sake of one field.
    def __init__(self, stream):
        # The search/jobs/exports endpoint, when run with
        # earliest_time=rt and latest_time=rt streams a sequence of
        # XML documents, each containing a result, as opposed to one
        # results element containing lots of results. Python's XML
        # parsers are broken, and instead of reading one full document
        # and returning the stream that follows untouched, they
        # destroy the stream and throw an error. To get around this,
        # we remove all the DTD definitions inline, then wrap the
        # fragments in a fiction <doc> element to make the parser happy.
        stream = _XMLDTDFilter(stream)
        stream = _ConcatenatedStream(BytesIO(b"<doc>"), stream, BytesIO(b"</doc>"))
        self.is_preview = None
        self._gen = self._parse_results(stream)

    def __iter__(self):
        return self

    def next(self):
        return next(self._gen)

    __next__ = next

    def _parse_results(self, stream):
        """Parse results and messages out of *stream*."""
        result = None
        values = None
        try:
            for event, elem in et.iterparse(stream, events=('start', 'end')):
                if elem.tag == 'results' and event == 'start':
                    # The wrapper element is a <results preview="0|1">. We
                    # don't care about it except to tell is whether these
                    # are preview results, or the final results from the
                    # search.
                    is_preview = elem.attrib['preview'] == '1'
                    self.is_preview = is_preview
                if elem.tag == 'result':
                    if event == 'start':
                        result = OrderedDict()
                    elif event == 'end':
                        yield result
                        result = None
                        elem.clear()

                elif elem.tag == 'field' and result is not None:
                    # We need the 'result is not None' check because
                    # 'field' is also the element name in the <meta>
                    # header that gives field order, which is not what we
                    # want at all.
                    if event == 'start':
                        values = []
                    elif event == 'end':
                        field_name = elem.attrib['k']
                        if len(values) == 1:
                            result[field_name] = values[0]
                        else:
                            result[field_name] = values
                        # Calling .clear() is necessary to let the
                        # element be garbage collected. Otherwise
                        # arbitrarily large results sets will use
                        # arbitrarily large memory intead of
                        # streaming.
                        elem.clear()

                elif elem.tag in ('text', 'v') and event == 'end':
                    try:
                        text = "".join(elem.itertext())
                    except AttributeError:
                        # Assume we're running in Python < 2.7, before itertext() was added
                        # So we'll define it here

                        def __itertext(self):
                            tag = self.tag
                            if not isinstance(tag, six.string_types) and tag is not None:
                                return
                            if self.text:
                                yield self.text
                            for e in self:
                                for s in __itertext(e):
                                    yield s
                                if e.tail:
                                    yield e.tail

                        text = "".join(__itertext(elem))
                    values.append(text)
                    elem.clear()

                elif elem.tag == 'msg':
                    if event == 'start':
                        msg_type = elem.attrib['type']
                    elif event == 'end':
                        text = elem.text if elem.text is not None else ""
                        yield Message(msg_type, text)
                        elem.clear()
        except SyntaxError as pe:
            # This is here to handle the same incorrect return from
            # splunk that is described in __init__.
            if 'no element found' in pe.msg:
                return
            else:
                raise

class JSONResultsReader(object):
    """This class returns dictionaries and Splunk messages from a JSON results
    stream.
    ``JSONResultsReader`` is iterable, and returns a ``dict`` for results, or a
    :class:`Message` object for Splunk messages. This class has one field,
    ``is_preview``, which is ``True`` when the results are a preview from a
    running search, or ``False`` when the results are from a completed search.

    This function has no network activity other than what is implicit in the
    stream it operates on.

    :param `stream`: The stream to read from (any object that supports``.read()``).

    **Example**::

        import results
        response = ... # the body of an HTTP response
        reader = results.JSONResultsReader(response)
        for result in reader:
            if isinstance(result, dict):
                print "Result: %s" % result
            elif isinstance(result, results.Message):
                print "Message: %s" % result
        print "is_preview = %s " % reader.is_preview
    """

    # Be sure to update the docstrings of client.Jobs.oneshot,
    # client.Job.results_preview and client.Job.results to match any
    # changes made to JSONResultsReader.
    #
    # This wouldn't be a class, just the _parse_results function below,
    # except that you cannot get the current generator inside the
    # function creating that generator. Thus it's all wrapped up for
    # the sake of one field.
    def __init__(self, stream):
        # The search/jobs/exports endpoint, when run with
        # earliest_time=rt and latest_time=rt, output_mode=json, streams a sequence of
        # JSON documents, each containing a result, as opposed to one
        # results element containing lots of results.
        stream = BufferedReader(stream)
        self.is_preview = None
        self._gen = self._parse_results(stream)

    def __iter__(self):
        return self

    def next(self):
        return next(self._gen)

    __next__ = next

    def _parse_results(self, stream):
        """Parse results and messages out of *stream*."""
        for line in stream.readlines():
            strip_line = line.strip()
            if strip_line.__len__() == 0: continue
            parsed_line = json_loads(strip_line)
            if "preview" in parsed_line:
                self.is_preview = parsed_line["preview"]
            if "messages" in parsed_line and parsed_line["messages"].__len__() > 0:
                for message in parsed_line["messages"]:
                    msg_type = message.get("type", "Unknown Message Type")
                    text = message.get("text")
                yield Message(msg_type, text)
            if "result" in parsed_line:
                yield parsed_line["result"]
            if "results" in parsed_line:
                for result in parsed_line["results"]:
                    yield result


text:
package info.smartkit.eip.models;

import java.util.List;

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel="company",path="company")
public interface CompanyRepository extends PagingAndSortingRepository<Company, Long> {
	List<Company> findById(@Param("id") long id);
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NClap.Metadata;
using NSubstitute;

namespace NClap.Tests.Parser
{
    [TestClass]
    public class AnswerFileParsingTests
    {
    #pragma warning disable 0649 // Field is never assigned to, and will always have its default value

        [ArgumentSet(
            Style = ArgumentSetStyle.WindowsCommandLine,
            AnswerFileArgumentPrefix = "@")]
        class Arguments
        {
            [NamedArgument(ArgumentFlags.AtMostOnce)]
            public int IntValue;

            [NamedArgument(ArgumentFlags.AtMostOnce)]
            public string StringValue;
        }

        [ArgumentSet(
            Style = ArgumentSetStyle.WindowsCommandLine,
            AnswerFileArgumentPrefix = "#!")]
        class AlternateSyntaxArguments
        {
            [NamedArgument(ArgumentFlags.AtMostOnce)]
            public string Value;
        }

    #pragma warning restore 0649

        [TestMethod]
        public void FileDoesNotExist()
        {
            var reader = CreateReaderThatThrows(new FileNotFoundException());
            var options = new CommandLineParserOptions { FileSystemReader = reader };

            TryParse(
                new[] { "@foo" },
                new Arguments(),
                options).Should().BeFalse();

            reader.Received().GetLines("foo");
        }

        [TestMethod]
        public void FileIsEmpty()
        {
            var args = new Arguments();
            var reader = CreateReaderThatReturns(Enumerable.Empty<string>());
            var options = new CommandLineParserOptions { FileSystemReader = reader };

            TryParse(
                new[] { "@foo" },
                args,
                options).Should().BeTrue();

            reader.Received().GetLines("foo");
            args.IntValue.Should().Be(0);
            args.StringValue.Should().BeNull();
        }

        [TestMethod]
        public void FileWithValidArgs()
        {
            var args = new Arguments();
            var reader = CreateReaderThatReturns(new[] { "/intvalue:17", "/stringvalue:a b" });
            var options = new CommandLineParserOptions { FileSystemReader = reader };

            TryParse(
                new[] { "@foo" },
                args,
                options).Should().BeTrue();

            reader.Received().GetLines("foo");
            args.IntValue.Should().Be(17);
            args.StringValue.Should().Be("a b");
        }

        [TestMethod]
        public void AlternateSyntax()
        {
            var args = new AlternateSyntaxArguments();
            var reader = CreateReaderThatReturns(new[] { "/value:abc" });
            var options = new CommandLineParserOptions { FileSystemReader = reader };

            TryParse(new[] { "@foo" }, args, options).Should().BeFalse();
            reader.DidNotReceive().GetLines("foo");

            TryParse(new[] { "#!foo" }, args, options).Should().BeTrue();
            reader.Received().GetLines("foo");
            args.Value.Should().Be("abc");
        }

        [TestMethod]
        public void FileWithComments()
        {
            var args = new Arguments();
            var reader = CreateReaderThatReturns(new[] { "# /intvalue:17", " #asd" });
            var options = new CommandLineParserOptions { FileSystemReader = reader };

            TryParse(
                new[] { "@foo" },
                args,
                options).Should().BeTrue();

            reader.Received().GetLines("foo");
            args.IntValue.Should().Be(0);
            args.StringValue.Should().BeNull();
        }

        [TestMethod]
        public void FileWithEmptyLine()
        {
            var args = new Arguments();
            var reader = CreateReaderThatReturns(new[] { string.Empty });
            var options = new CommandLineParserOptions { FileSystemReader = reader };

            TryParse(
                new[] { "@foo" },
                args,
                options).Should().BeTrue();

            reader.Received().GetLines("foo");
            args.IntValue.Should().Be(0);
            args.StringValue.Should().BeNull();
        }

        private static IFileSystemReader CreateReaderThatThrows(Exception exception)
        {
            var reader = Substitute.For<IFileSystemReader>();
            reader.GetLines(null).ReturnsForAnyArgs(path => { throw exception; });

            return reader;
        }

        private static IFileSystemReader CreateReaderThatReturns(IEnumerable<string> lines)
        {
            var reader = Substitute.For<IFileSystemReader>();
            reader.GetLines(null).ReturnsForAnyArgs(lines);

            return reader;
        }

        private static bool TryParse<T>(IEnumerable<string> args, T dest, CommandLineParserOptions options = null) where T : class =>
            CommandLineParser.TryParse(args, dest, options ?? new CommandLineParserOptions { DisplayUsageInfoOnError = false });
    }
}


text:
<!-- toc -->
- [Release Signoff Checklist](#release-signoff-checklist)
- [Summary](#summary)
- [Motivation](#motivation)
  - [Goals](#goals)
  - [Non-Goals](#non-goals)
- [Proposal](#proposal)
  - [User Stories (Optional)](#user-stories-optional)
    - [Story 1](#story-1)
    - [Story 2](#story-2)
  - [Risks and Mitigations](#risks-and-mitigations)
- [Design Details](#design-details)
  - [Test Plan](#test-plan)
  - [Graduation Criteria](#graduation-criteria)
    - [Alpha:](#alpha)
    - [Beta:](#beta)
    - [GA](#ga)
  - [Upgrade / Downgrade Strategy](#upgrade--downgrade-strategy)
  - [Version Skew Strategy](#version-skew-strategy)
- [Production Readiness Review Questionnaire](#production-readiness-review-questionnaire)
  - [Feature Enablement and Rollback](#feature-enablement-and-rollback)
  - [Rollout, Upgrade and Rollback Planning](#rollout-upgrade-and-rollback-planning)
  - [Monitoring Requirements](#monitoring-requirements)
  - [Dependencies](#dependencies)
  - [Scalability](#scalability)
  - [Troubleshooting](#troubleshooting)
- [Implementation History](#implementation-history)
- [Drawbacks](#drawbacks)
- [Alternatives](#alternatives)
  - [ServiceClass Resource](#serviceclass-resource)
  - [Generic Annotation](#generic-annotation)
  - [Provider-Specific Annotations](#provider-specific-annotations)
- [Infrastructure Needed (Optional)](#infrastructure-needed-optional)
<!-- /toc -->

## Release Signoff Checklist

Items marked with (R) are required *prior to targeting to a milestone / release*.

- [X] (R) Enhancement issue in release milestone, which links to KEP dir in [kubernetes/enhancements] (not the initial KEP PR)
- [X] (R) KEP approvers have approved the KEP status as `implementable`
- [X] (R) Design details are appropriately documented
- [X] (R) Test plan is in place, giving consideration to SIG Architecture and SIG Testing input
- [X] (R) Graduation criteria is in place
- [X] (R) Production readiness review completed
- [X] (R) Production readiness review approved
- [ ] "Implementation History" section is up-to-date for milestone
- [X] (R) User-facing documentation has been created in [kubernetes/website], for publication to [kubernetes.io]
- [ ] Supporting documentation—e.g., additional design documents, links to mailing list discussions/SIG meetings, relevant PRs/issues, release notes

[kubernetes.io]: https://kubernetes.io/
[kubernetes/enhancements]: https://git.k8s.io/enhancements
[kubernetes/kubernetes]: https://git.k8s.io/kubernetes
[kubernetes/website]: https://git.k8s.io/website

## Summary

When Service Type=LoadBalancer is enabled by a Kubernetes cloud provider, it is a global
configuration that applies for all Service Type=LoadBalancer resources in a given cluster.
This becomes problematic if users want to leverage multiple Service Type=LoadBalancer
implementations in a cluster.

The new [Services APIs](https://github.com/kubernetes-sigs/service-apis) addresses this already
with the GatewayClass resource. However, until Gateway/GatewayClass APIs become mature, we should
support similar functionality for Services of Type=LoadBalancer. Introducing a new resource like
`ServiceClass` is probably not worthwhile given that there are new APIs already in development.
This KEP proposes a light-weight approach for Service Type=LoadBalancer by introducing a Service
field `service.spec.loadBalancerClass`.

## Motivation

The main use-case for this feature is being able to support multiple Service Type=LoadBalancer
implementations in a cluster, as different workloads may want to leverage different loadbalancer
providers based on efficiency, availability, cost and other factors.

For example, a cluster admin may want to use a public load balancer from a cloud provider
for workloads that must be assigned a publically routable address, but they may want to
enable a lower-cost solution for workloads that are only internally accessible.

### Goals

* allow users to opt-out of the Service Type=LoadBalancer implementation by the cloud provider.
* allow multiple implementations of Service Type=LoadBalancer in a cluster.
* prevent every cloud provider from implementing a custom "opt-out" annotation for their load balancer.

### Non-Goals

* performance improvements for Service Type=LoadBalancer.
* changing any other existing behaviors for Service Type=LoadBalancer aside from being able
to disabling it from the cloud provider.

## Proposal

This KEP proposes to add a new field `spec.loadBalancerClass` in Service which allows for
multiple implementations of Service Type=LoadBalancer in a cluster.

### User Stories (Optional)

#### Story 1

As a cluster admin:
* I want to use my cloud provider's public load balancer service for applications that require
public ingress.
* I want to use my own load balancing solution for any applications that only talk internally
within my own network because I want to save costs.

#### Story 2

As an application developer:
* I MUST use a hardware-based loadbalancer for certain applications due to specific protocols
only available there.
* I want to use the cloud provider's default load balancer for any applications that do not
rely on protocols from hardware load balancers.

### Risks and Mitigations

Many cloud providers today support an "opt-out" annotation for this behavior. The annotation is specific
to the cloud provider. Introduction of the `loadBalancerClass` field at this point would mean that
cloud providers need to start accounting for both existing annotations and the new field.

## Design Details

Introduce a new field to Service `spec.loadBalancerClass`.

If the field `spec.loadBalancerClass` is not set, the existing cloud provider will assume
ownership of the Service Type=LoadBalancer resource. This is required to not break existing clusters
that assume Service Type=LoadBalancer is always managed by the cloud provider.

Required API changes:
```go
// ServiceSpec describes the attributes that a user creates on a service.
type ServiceSpec struct {
	...
	...

	// loadBalancerClass is the name of the load balancer implementation this Service belongs to.
	// This field can only be set when the Service type is 'LoadBalancer'. If not set, the default load
	// balancer implementation is used, today this is typically done through the cloud provider integration,
	// but should apply for any default implementation. If set, it is assumed that a load balancer
	// implementation is watching for Services with a matching class name. Any default load balancer
	// implementation (e.g. cloud providers) should ignore Services that set this field.
	// +optional
	LoadBalancerClass string `json:"loadBalancerClass,omitempty"`
}
```

* `loadBalancerClass` will be immutable when the Service type is `LoadBalancer`, this way existing and future implementations
do not have to worry about handling Services that change the class name. The class name is mutable only when the type is not LoadBalancer and
must be cleared when the type changes.
* `loadBalancerClass` will be validated against label-style format.
* the `loadBalancerClass` field will be feature gated. The field will be dropped during API strategy unless
the feature gate is enabled.
* all external implementations of Service LoadBalancer using a non-empty class name should use the finalizer `service.kubernetes.io/load-balancer-cleanup`
to ensure proper garbage collection of external resources.

Required updates to service controller:
* if the class field is NOT set for a Service, allow the cloud provider to reconcile the load balancer.
* if the class field IS set for a Service, skip reconciliation of the Service from the cloud provider.

### Test Plan

Unit tests:
* test that service controller does not call the cloud provider if the class field is set.
* test API strategy to ensure the `loadBalancerClass` field is dropped unless the feature gate is enabled
or an existing Service has the field set.
* test API validation for immutability.

Integration tests:
* test that the class field is properly cleared/validated when the Service type changes to and from `LoadBalancer`.

E2E tests:
* test that creating a Service with an unknown class name results in no load balancer being created for a Service.

### Graduation Criteria

#### Alpha:

* the `loadBalancerClass` field is added to Service with an alpha feature gate.
* when enabled, service controller will ignore Service LBs with a non-empty class name.
* unit tests for service controller.
* unit tests for API strategy (drop disabled fields).

#### Beta:

* Feature gate is on by default.
* E2E tests checking that default load balancer implementation ignores LoadBalancer type of Services when `loadBalancerClass` set.

#### GA

* Ensure integration/E2E tests continue to work and provide sufficient coverage.

### Upgrade / Downgrade Strategy

* Usage of `loadBalancerClass` will be off by default during the alpha stage but can handle existing Services that
has the field set already. This ensures apiserver can handle the new field on downgrade.
* On upgrade, if the feature gate is enabled, there should be no changes since the default behavior has not changed
(service controller calls the cloud provider to reconcile load balancers).

### Version Skew Strategy

Since this feature will be alpha for at least 1 release, an n-1 kube-controller-manager or cloud-controller-manager should
handle enablement of this feature if a new apiserver enabled it.

## Production Readiness Review Questionnaire

### Feature Enablement and Rollback

_This section must be completed when targeting alpha to a release._

* **How can this feature be enabled / disabled in a live cluster?**
  - [X] Feature gate (also fill in values in `kep.yaml`)
    - Feature gate name: ServiceLoadBalancerClass
    - Components depending on the feature gate: kube-apiserver, kube-controller-manager
  - [ ] Other
    - Describe the mechanism:
    - Will enabling / disabling the feature require downtime of the control
      plane?
    - Will enabling / disabling the feature require downtime or reprovisioning
      of a node? (Do not assume `Dynamic Kubelet Config` feature is enabled).

* **Does enabling the feature change any default behavior?**
  No, the default service controller in Kubernetes will continue to watch and implement
  any Services with an empty class name. Behavior is only changed when the class name is set.

* **Can the feature be disabled once it has been enabled (i.e. can we roll back
  the enablement)?**
  Yes, the feature can be disabled, but any existing Services using the new field will
  continue to have the field set. External controllers watching a specific class name
  will continue to watch and reconcile those Services.

* **What happens if we reenable the feature if it was previously rolled back?**
  New Services can continue to use the field. Existing Services with the field always had
  the field set so no behavior is changed when the feature is re-enabled.

* **Are there any tests for feature enablement/disablement?**
  Yes, there will be unit tests in Service strategy, validation and defaulting to ensure
  the field cannot be used when the feature is disabled.

### Rollout, Upgrade and Rollback Planning

_This section must be completed when targeting beta graduation to a release._

* **How can a rollout fail? Can it impact already running workloads?**

	* By default this should not impact any existing Services since we are not changing any default behaviors.
	* Enabling this feature on new clusters can impact workloads only if the user wants to use a custom load balancer implementation and sets `service.spec.loadBalancerClass`.

* **What specific metrics should inform a rollback?**
	* None, if the user doesn't want to use a custom load balancer implementation, user can simply ignore this field.

* **Were upgrade and rollback tested? Was the upgrade->downgrade->upgrade path tested?**

   * No, upgrade->downgrade->upgrade has not been tested yet. Like any new API field, on downgrade any existing Services using the field will continue to have the field set. For these LoadBalancer type of Services, any default load balancer implementation (e.g. cloud providers) would ignore them. New Services cannot use the new field unless the feature gate is enabled in the old version when the feature was alpha.

* **Is the rollout accompanied by any deprecations and/or removals of features, APIs,
fields of API types, flags, etc.?**

   * No.

### Monitoring Requirements

_This section must be completed when targeting beta graduation to a release._

* **How can an operator determine if the feature is in use by workloads?**

  * Service should have `spec.loadBalancerClass` set.

* **What are the SLIs (Service Level Indicators) an operator can use to determine
the health of the service?**

	* N/A

* **What are the reasonable SLOs (Service Level Objectives) for the above SLIs?**

   * N/A

* **Are there any missing metrics that would be useful to have to improve observability
of this feature?**

   * N/A

### Dependencies

_This section must be completed when targeting beta graduation to a release._

* **Does this feature depend on any specific services running in the cluster?**

  * This feature is dependent on the Service LoadBalancer implementation of a cluster. This feature should only be used if the user doesn't want to use default load balancer implementation.

### Scalability

_For alpha, this section is encouraged: reviewers should consider these questions
and attempt to answer them._

_For beta, this section is required: reviewers must answer these questions._

_For GA, this section is required: approvers should be able to confirm the
previous answers based on experience in the field._

* **Will enabling / using this feature result in any new API calls?**

  Introduction of this feature enables multiple implementations of Service LoadBalancer
  for a single cluster. New API calls will be introduced by new controllers operating against
  Services with a non-empty class name. This feature does not introduce new API calls from
  core Kubernetes components.

* **Will enabling / using this feature result in introducing new API types?**

  No

* **Will enabling / using this feature result in any new calls to the cloud
provider?**

  Yes, introduction of new load balancer "classes" can introduce new calls to the cloud provider.

* **Will enabling / using this feature result in increasing size or count of
the existing API objects?**

  Yes, Service will (negligibly) increase with the addition of 1 new field.

* **Will enabling / using this feature result in increasing time taken by any
operations covered by [existing SLIs/SLOs]?**

  No

* **Will enabling / using this feature result in non-negligible increase of
resource usage (CPU, RAM, disk, IO, ...) in any components?**

  This change should not impact any core Kubernetes components.

### Troubleshooting

The Troubleshooting section currently serves the `Playbook` role. We may consider
splitting it into a dedicated `Playbook` document (potentially with some monitoring
details). For now, we leave it here.

_This section must be completed when targeting beta graduation to a release._

* **How does this feature react if the API server and/or etcd is unavailable?**

   * N/A

* **What are other known failure modes?**

   * If `service.spec.loadBalancerClass` set, but there is no load balancer implementation watches the set value.

* **What steps should be taken if SLOs are not being met to determine the problem?**

   * N/A

[supported limits]: https://git.k8s.io/community//sig-scalability/configs-and-limits/thresholds.md
[existing SLIs/SLOs]: https://git.k8s.io/community/sig-scalability/slos/slos.md#kubernetes-slisslos

## Implementation History

- the `Summary`, `Motivation`, `Proposal` and `Design Details` sections was merged, signaling SIG acceptance

## Drawbacks

* Added complexity to Service.
* In **most** clusters, a single Service Type=LoadBalancer implementation from the cloud provider is sufficient.

## Alternatives

### ServiceClass Resource

Instead of a field specifying the name of the implemmentation, the class name can reference the name of a class resource
similar to GatewayClass and IngressClass. This would enable more expressive configuration per load balancer implementation.

### Generic Annotation

A generic annotation can be used to store the class name. This is avoided since there would be no way to introduce
the annotation in a safe way and we can't enforce immutability for annotations.

### Provider-Specific Annotations

Instead of a generic Kubernetes annotation read by service controller, each cloud provider could implement
their own "skip this Service"-like logic with custom annotations. Given that many cloud providers have been
asking for this feature, a generic field used across all providers may be more beneficial.

## Infrastructure Needed (Optional)

<!--
Use this section if you need things from the project/SIG. Examples include a
new subproject, repos requested, or GitHub details. Listing these here allows a
SIG to get the process for these resources started right away.
-->


text:
<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Brainstorm CTF phantom dataset tutorial — MNE 0.16.1 documentation</title>
    <link rel="stylesheet" href="../_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/gallery.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />

    <link rel="stylesheet" href="../_static/style.css " type="text/css" />
    <link rel="stylesheet" href="../_static/font-awesome.css" type="text/css" />
    <link rel="stylesheet" href="../_static/flag-icon.css" type="text/css" />

  <link rel="canonical" href="https://mne.tools/stable/index.html" />

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

        0.16.1

Install

Documentation

API

Examples

Contribute

  Site

  <button type="button" class="btn btn-primary navbar-btn dropdown-toggle" id="dropdownMenu1" data-toggle="dropdown">
    v0.16.1

  </button>

Development

v0.16 (stable)

v0.15

v0.14

v0.13

v0.12

v0.11

<form class="navbar-form navbar-right" action="../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

Brainstorm CTF phantom dataset tutorial

References

<form action="../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

Note

Click here to download the full example code

Brainstorm CTF phantom dataset tutorial¶

Here we compute the evoked from raw for the Brainstorm CTF phantom
tutorial dataset. For comparison, see [1] and:

http://neuroimage.usc.edu/brainstorm/Tutorials/PhantomCtf

References¶

<colgroup><col class="label" /><col /></colgroup>

[1]	Tadel F, Baillet S, Mosher JC, Pantazis D, Leahy RM.
Brainstorm: A User-Friendly Application for MEG/EEG Analysis.
Computational Intelligence and Neuroscience, vol. 2011, Article ID
879716, 13 pages, 2011. doi:10.1155/2011/879716

# Authors: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)

import os.path as op
import numpy as np
import matplotlib.pyplot as plt

import mne
from mne import fit_dipole
from mne.datasets.brainstorm import bst_phantom_ctf
from mne.io import read_raw_ctf

print(__doc__)

The data were collected with a CTF system at 2400 Hz.

data_path = bst_phantom_ctf.data_path()

# Switch to these to use the higher-SNR data:
# raw_path = op.join(data_path, 'phantom_200uA_20150709_01.ds')
# dip_freq = 7.
raw_path = op.join(data_path, 'phantom_20uA_20150603_03.ds')
dip_freq = 23.
erm_path = op.join(data_path, 'emptyroom_20150709_01.ds')
raw = read_raw_ctf(raw_path, preload=True)

The sinusoidal signal is generated on channel HDAC006, so we can use
that to obtain precise timing.

sinusoid, times = raw[raw.ch_names.index('HDAC006-4408')]
plt.figure()
plt.plot(times[times < 1.], sinusoid.T[times < 1.])

Let's create some events using this signal by thresholding the sinusoid.

events = np.where(np.diff(sinusoid > 0.5) > 0)[1] + raw.first_samp
events = np.vstack((events, np.zeros_like(events), np.ones_like(events))).T

The CTF software compensation works reasonably well:

raw.plot()

But here we can get slightly better noise suppression, lower localization
bias, and a better dipole goodness of fit with spatio-temporal (tSSS)
Maxwell filtering:

raw.apply_gradient_compensation(0)  # must un-do software compensation first
mf_kwargs = dict(origin=(0., 0., 0.), st_duration=10.)
raw = mne.preprocessing.maxwell_filter(raw, **mf_kwargs)
raw.plot()

Our choice of tmin and tmax should capture exactly one cycle, so
we can make the unusual choice of baselining using the entire epoch
when creating our evoked data. We also then crop to a single time point
(@t=0) because this is a peak in our signal.

tmin = -0.5 / dip_freq
tmax = -tmin
epochs = mne.Epochs(raw, events, event_id=1, tmin=tmin, tmax=tmax,
                    baseline=(None, None))
evoked = epochs.average()
evoked.plot(time_unit='s')
evoked.crop(0., 0.)

Let's use a sphere head geometry model and let's see the coordinate
alignement and the sphere location.

sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=None)

mne.viz.plot_alignment(raw.info, subject='sample',
                       meg='helmet', bem=sphere, dig=True,
                       surfaces=['brain'])
del raw, epochs

To do a dipole fit, let's use the covariance provided by the empty room
recording.

raw_erm = read_raw_ctf(erm_path).apply_gradient_compensation(0)
raw_erm = mne.preprocessing.maxwell_filter(raw_erm, coord_frame='meg',
                                           **mf_kwargs)
cov = mne.compute_raw_covariance(raw_erm)
del raw_erm

dip, residual = fit_dipole(evoked, cov, sphere)

Compare the actual position with the estimated one.

expected_pos = np.array([18., 0., 49.])
diff = np.sqrt(np.sum((dip.pos[0] * 1000 - expected_pos) ** 2))
print('Actual pos:     %s mm' % np.array_str(expected_pos, precision=1))
print('Estimated pos:  %s mm' % np.array_str(dip.pos[0] * 1000, precision=1))
print('Difference:     %0.1f mm' % diff)
print('Amplitude:      %0.1f nAm' % (1e9 * dip.amplitude[0]))
print('GOF:            %0.1f %%' % dip.gof[0])

Out:

Actual pos:     [18.  0. 49.] mm
Estimated pos:  [18.5 -2.2 44.6] mm
Difference:     4.9 mm
Amplitude:      10.0 nAm
GOF:            96.5 %

Total running time of the script: ( 0 minutes  20.210 seconds)

Download Python source code: plot_brainstorm_phantom_ctf.py

Download Jupyter notebook: plot_brainstorm_phantom_ctf.ipynb

Gallery generated by Sphinx-Gallery

GitHub

·

Mailing list

·

Gitter

·

What's new

·

Cite MNE

Back to top

© Copyright 2012-2018, MNE Developers. Last updated on 2018-06-24.


text:
#ifndef _BT848_I2C_H
#define _BT848_I2C_H

extern int bt848_i2c_attach(device_t);
extern int bt848_i2c_detach(device_t);

extern int bti2c_iic_callback(device_t, int, caddr_t *);
extern void bti2c_iic_setsda(device_t, int);
extern void bti2c_iic_setscl(device_t, int);
extern int bti2c_iic_getsda(device_t);
extern int bti2c_iic_getscl(device_t);
extern int bti2c_iic_reset(device_t, u_char, u_char, u_char *);

extern int bti2c_smb_callback(device_t, int, void *);
extern int bti2c_smb_writeb(device_t dev, u_char slave, char cmd, char byte);
extern int bti2c_smb_writew(device_t dev, u_char slave, char cmd, short word);
extern int bti2c_smb_readb(device_t dev, u_char slave, char cmd, char *byte);

#endif


text:
package com.evolveum.midpoint.web.component;

import com.evolveum.midpoint.web.component.util.TargetAcceptor;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.model.IModel;

/**
 * @author mederly
 */
public class DefaultAjaxButton extends AjaxButton {

    private final TargetAcceptor onClick;

    public DefaultAjaxButton(String id, IModel<String> label, TargetAcceptor onClick) {
        super(id, label);
        this.onClick = onClick;
    }

    @Override
    public void onClick(AjaxRequestTarget target) {
        onClick.accept(target);
    }
}


text:
require 'test_helper'

class CsvtoyTest < Test::Unit::TestCase
  should "probably rename this file and start testing for real" do
    flunk "hey buddy, you should probably rename this file and start testing for real"
  end
end


text:
package com.github.steveash.jtribespso.impl;

import com.github.steveash.jtribespso.EuclidianVector;
import com.github.steveash.jtribespso.IObjectiveFunction;
import com.github.steveash.jtribespso.rand.HyperspaceRandom;
import com.google.common.util.concurrent.ListeningExecutorService;

public class MultithreadedHypersphereSearchSpace extends MultithreadedSearchSpace<HypersphereParticle> {

    public MultithreadedHypersphereSearchSpace(ListeningExecutorService pool, IObjectiveFunction objectiveFunction,
            int workerCount) {

        super(pool, objectiveFunction, workerCount);
    }

    @Override
    protected HypersphereParticle generateParticleAtPosition(EuclidianVector position) {
        return new HypersphereParticle(this.goodnessFunction(), position, new HyperspaceRandom());
    }
}


text:
<?php namespace Modules\Translation\Importers;

use League\Csv\Reader;
use Modules\Translation\Repositories\TranslationRepository;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class TranslationsImporter
{
    /**
     * @var TranslationRepository
     */
    private $translation;

    public function __construct(TranslationRepository $translation)
    {
        $this->translation = $translation;
    }

    public function import(UploadedFile $file)
    {
        $csv = Reader::createFromPath($file->getRealPath());
        $csv->detectDelimiterList(5, [',', ';']);
        $headers = $csv->fetchOne();
        $csv->setOffset(1);

        $csv->each(function ($row) use ($headers) {
            try {
                $row = array_combine($headers, $row);
            } catch (\Exception $e) {
                return true;
            }

            $key = array_get($row, 'key');
            array_shift($row);
            $data = [];
            foreach ($row as $locale => $value) {
                $data[$locale] = ['value' => $value];
            }

            $this->translation->updateFromImport($key, $data);

            return true;
        });
    }
}


text:
'use strict';

module.exports = {
    friendlyName: "Add Volume",
    injectableName: "Task.Add.Volume",
    implementsTask: "Task.Base.Add.Volume",
    options: {
        username: null,
        password: null,
        drives: null,
        raidLevel: null,
        name: null,
        sizeInBytes: null,
        ipAddress: null
    },
    properties: {}
};


text:
using Aspose.Slides.Export;

/*
This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Slides for .NET API reference
when the project is build. Please check https://docs.nuget.org/consume/nuget-faq for more information.
If you do not wish to use NuGet, you can manually download Aspose.Slides for .NET API from http://www.aspose.com/downloads,
install it and then add its reference to this project. For any issues, questions or suggestions
please feel free to contact us using http://www.aspose.com/community/forums/default.aspx
*/

namespace Aspose.Slides.Examples.CSharp.Presentations.Conversion
{
    public class ConvertNotesSlideView
    {
        public static void Run()
        {
            //ExStart:ConvertNotesSlideView
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_Conversion();

            // Instantiate a Presentation object that represents a presentation file
            using (Presentation pres = new Presentation(dataDir + "Convert_Tiff_Default.pptx"))
            {
                // Saving the presentation to TIFF document
                pres.Save(dataDir + "Tiff_out.tiff", SaveFormat.Tiff);
            }
            //ExEnd:ConvertNotesSlideView
        }
    }
}


text:
package tree.declarations;

import java.util.LinkedList;

import tree.DefaultTreeNode;
import tree.TreeNode;
import tree.TreeNodeList;

public class TDesignatorList extends DefaultTreeNode implements TreeNodeList<TDesignator> {

	public TDesignatorList(TDesignatorList node) {
		super(node);
	}

	public LinkedList<TDesignator> getList() {
		LinkedList<TDesignator> list = new LinkedList<TDesignator>();
		for (TreeNode child : getChildren()) {
			list.add((TDesignator) child);
		}
		return list;
	}

	public TDesignatorList(TDesignator node) {
		addChild(node);
	}

	public TDesignatorList(TDesignatorList nodes, TDesignator node) {
		addChildrenOf(nodes);
		addChild(node);
	}

}


text:
module RubyJmeter
  class DSL
    def test_fragment(params={}, &block)
      node = RubyJmeter::TestFragment.new(params)
      attach_node(node, &block)
    end
  end

  class TestFragment
    attr_accessor :doc
    include Helper

    def initialize(params={})
      testname = params.kind_of?(Array) ? 'TestFragment' : (params[:name] || 'TestFragment')
      @doc = Nokogiri::XML(<<-EOS.strip_heredoc)
<TestFragmentController guiclass="TestFragmentControllerGui" testclass="TestFragmentController" testname="#{testname}" enabled="false"/>)
      EOS
      update params
      update_at_xpath params if params.is_a?(Hash) && params[:update_at_xpath]
    end
  end

end


text:
import unittest

class MlaskExampleTest(unittest.TestCase):

	def test_mlask_sum(self):
		self.assertEqual(1 + 1, 2)


text:
-- DROP TABLE cue;

CREATE TABLE cue
(

)
WITH (
  OIDS=FALSE
);
ALTER TABLE cue
  OWNER TO test;
COMMENT ON TABLE cue
  IS 'Table gathering all cues used for guidance e.g. visual, audio or textual cues. ';


text:
[__Fish Shell__](fishshell.com) config files with [__Oh-My-Fish__](https://github.com/oh-my-fish/) package manager (required)

1. Configuration file ([config.fish](https://github.com/eugenesvk/Settings-Fish/blob/master/config.fish))

2. A few custom [functions](https://github.com/eugenesvk/Settings-Fish/tree/master/Functions). Copy to `~/.config/fish/functions`

In addition, below is a screenshot of my theme [es](https://github.com/oh-my-fish/theme-es), which you can install through Oh My Fish with `omf update` then `omf install es`.

##__Git folder__

![Git folder](https://github.com/oh-my-fish/theme-es/blob/master/Fish%20Prompt%20Git-es.png?raw=true)

##__Normal folder (no Git)__

![Non-git folder](https://github.com/oh-my-fish/theme-es/blob/master/Fish%20Prompt%20NoGit-es.png?raw=true)


text:
Base d3 linegraph class

### Install

#### Node

```Shell
npm install d3-linegraph
```

#### Browser

```Shell
component install d3-linegraph
```

```Shell
bower install d3-linegraph
```

## Usage

#### d3-linegraph(opts)

```JavaScript
GreatLineGraph = Graph({

	// mandatory
	el:'#containerDiv',
	xDataKey:"year",
	yDataKey:"Prevalence Per 1,000 Animals",

	// optional
	centerGraph:true,
	gradient:true,
	fill:true,
	lineColor: 'red'
});
```

### Options

### Docs
[Yuidocs documentation here](docs/index.html)
- fire up the connect server ```$ grunt docs```
- navigate your browser to the [docs](http://localhost:9001)

## License
Copyright (c) 2013 Andrew Griffiths <mail@andrewgriffithsonline.com>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
<?php
	namespace Crystal\RumbaBundle\Controller;

	use Symfony\Bundle\FrameworkBundle\Controller\Controller;
	use Crystal\BaseBundle\Entity\ctrAccess;

	class AccessController extends Controller
	{

	    public function listAction()
	    {
	    	$access = new ctrAccess();
	    	$em = $this->getDoctrine()->getEntityManager();
			$access = $em->getRepository('CrystalBaseBundle:ctrAccess')->findAll();
			return $this->render('CrystalRumbaBundle:Access:listAccess.html.twig', array('access' => $access));
	    }

	    public function addAction()
		{
			$access = new ctrAccess();
			$em = $this->getDoctrine()->getEntityManager();

			$request = $this->getRequest();

			if($request->getMethod() == 'POST')
			{
				$_POST = $request->request;

				$access->setUser($_POST->get('txtUser'));
				$access->setPass($_POST->get('txtPass'));

				$em->persist($access);
				$em->flush();

				return $this->redirect($this->generateURL('listaAcceso'));
			}
			else
			{
				return $this->render('CrystalRumbaBundle:Access:addAccess.html.twig', array('access' => $access));
			}
		}

		public function updateAction($id)
		{

			$request = $this->getRequest();
			$em = $this->getDoctrine()->getEntityManager();
			$access = $em->getRepository('CrystalBaseBundle:ctrAccess')->find($id);

			if($request->getMethod()=='POST')
			{
				$_POST = $request->request;

				$access->setUser($_POST->get('txtUser'));
				$access->setPass($_POST->get('txtPass'));

				$em->persist($access);
				$em->flush();

				return $this->redirect($this->generateURL('listaAcceso'));

			}
			else
			{
				return $this->render('CrystalRumbaBundle:Access:updateAccess.html.twig', array('access' => $access)); //D:
			}

		}

		public function deleteAction($id)
		{
			$em = $this->getDoctrine()->getEntitymanager();
			$access = $em->getRepository('CrystalBaseBundle:ctrAccess')->find($id);

			$em->remove($access);
			$em->flush();
			return $this->redirect($this->generateURL('listaAcceso'));
		}

	}

?>


text:
@XmlSchema (
  namespace = "http://jaxws_client.enunciate.codehaus.org/draw"
)
package org.codehaus.enunciate.examples.jaxws_client.schema.draw;

import javax.xml.bind.annotation.XmlSchema;


text:
package shared

import (
	"testing"
)

func TestTrieAddNewChild(t *testing.T) {
	// expect := NewExpect(t)
	// trie := NewTrie([]byte("ted"), "somemetadata")
	// // exact nature of pathLen
	// // if pathLen is 2 for a word Hello then what happens to llo?
	// //
	// trie.Match()
}


text:
using System;
using System.Globalization;
using OpenGamingLibrary.Json.Linq;
using OpenGamingLibrary.Json.Utilities;

namespace OpenGamingLibrary.Json.Test.TestObjects
{
    public abstract class ConverterPrecedenceClassConverter : JsonConverter
    {
        public abstract string ConverterType { get; }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            ConverterPrecedenceClass c = (ConverterPrecedenceClass)value;

            JToken j = new JArray(ConverterType, c.TestValue);

            j.WriteTo(writer);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JToken j = JArray.Load(reader);

            string converter = (string)j[0];
            if (converter != ConverterType)
                throw new Exception(StringUtils.FormatWith("Serialize converter {0} and deserialize converter {1} do not match.", CultureInfo.InvariantCulture, converter, ConverterType));

            string testValue = (string)j[1];
            return new ConverterPrecedenceClass(testValue);
        }

        public override bool CanConvert(Type objectType)
        {
            return (objectType == typeof(ConverterPrecedenceClass));
        }
    }
}


text:
namespace Google.Cloud.Metastore.V1.Snippets
{
    // [START metastore_v1_generated_DataprocMetastore_GetService_sync_flattened_resourceNames]
    using Google.Cloud.Metastore.V1;

    public sealed partial class GeneratedDataprocMetastoreClientSnippets
    {
        /// <summary>Snippet for GetService</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void GetServiceResourceNames()
        {
            // Create client
            DataprocMetastoreClient dataprocMetastoreClient = DataprocMetastoreClient.Create();
            // Initialize request argument(s)
            ServiceName name = ServiceName.FromProjectLocationService("[PROJECT]", "[LOCATION]", "[SERVICE]");
            // Make the request
            Service response = dataprocMetastoreClient.GetService(name);
        }
    }
    // [END metastore_v1_generated_DataprocMetastore_GetService_sync_flattened_resourceNames]
}


text:
unsigned char BLEAttribute::_numAttributes = 0;

BLEAttribute::BLEAttribute(const char* uuid, enum BLEAttributeType type) :
  _uuid(uuid),
  _type(type)
{
  _numAttributes++;
}

const char* BLEAttribute::uuid() const {
  return this->_uuid;
}

enum BLEAttributeType BLEAttribute::type() const {
  return this->_type;
}

unsigned char BLEAttribute::numAttributes() {
  return _numAttributes;
}


text:
app.service('dataService', function($http) {
    this.headers = [];
    this.data = [];

    var that = this;

    $http.get('data/data.csv').then(function(response){
        var parseResult = $.csv.toArrays(response.data);
        that.headers = parseResult[0];
        that.data = parseResult.slice(1);
    });
});


text:
/**
    @file
    Bubble sort algorithm.

    @author Ondrej Danek <ondrej.danek@gmail.com>
    @date 2012
*/

#ifndef SAF_ALGO_SORT_BUBBLESORT_H
#define SAF_ALGO_SORT_BUBBLESORT_H

#include "../../PrimitiveTypes.h"
#include "../Swap.h"
#include "../Function/Predicate.h"

namespace Saf
{
    namespace Algo
    {
        /** Sorting algorithms. */
        namespace Sort
        {
            /** %Sort the sequence <tt>[begin, end)</tt> according to <tt>pred</tt> using
                the bubble sort algorithm.

                Properties:
                - Minimum iterator category: Forward.
                - Worst-case time complexity: \f$ \mathcal{O}(n^2) \f$
                  where \f$ n = \mathrm{Iterator::Distance(begin, end)} \f$.
                - Space complexity: \f$ \mathcal{O}(1) \f$.
                - Stable sort: Yes.

                @param[in] begin Iterator to the beginning of the sequence.
                @param[in] end Iterator to the end of the sequence.
                @param[in] pred Binary comparison predicate.
            */
            template <class FwdIter, class Pred>
            void BubbleSort(FwdIter begin, FwdIter end, Pred pred)
            {
                FwdIter sentinel = end;

                while (begin != sentinel)
                {
                    FwdIter curItem = begin;
                    FwdIter nextItem = begin;
                    FwdIter newSentinel = begin;

                    while (++nextItem != sentinel)
                    {
                        if (pred(*nextItem, *curItem))
                        {
                            Saf::Algo::Swap(*nextItem, *curItem);
                            newSentinel = nextItem;
                        }

                        ++curItem;
                    }

                    sentinel = newSentinel;
                }
            }

            /** %Sort the sequence <tt>[begin, end)</tt> from smallest to largest elements
                using the bubble sort algorithm.

                Properties:
                - Minimum iterator category: Forward.
                - Worst-case time complexity: \f$ \mathcal{O}(n^2) \f$
                  where \f$ n = \mathrm{Iterator::Distance(begin, end)} \f$.
                - Space complexity: \f$ \mathcal{O}(1) \f$.
                - Stable sort: Yes.

                @param[in] begin Iterator to the beginning of the sequence.
                @param[in] end Iterator to the end of the sequence.
            */
            template <class FwdIter>
            void BubbleSort(FwdIter begin, FwdIter end)
            {
                Function::Predicate::Less<typename Type::IteratorTraits<FwdIter>::ValueType> pred;
                BubbleSort(begin, end, pred);
            }
        }
    }
}

#endif


text:
#ifndef KFD_CRAT_H_INCLUDED
#define KFD_CRAT_H_INCLUDED

#include <linux/types.h>

#pragma pack(1)

/*
 * 4CC signature values for the CRAT and CDIT ACPI tables
 */

#define CRAT_SIGNATURE	"CRAT"
#define CDIT_SIGNATURE	"CDIT"

/*
 * Component Resource Association Table (CRAT)
 */

#define CRAT_OEMID_LENGTH	6
#define CRAT_OEMTABLEID_LENGTH	8
#define CRAT_RESERVED_LENGTH	6

#define CRAT_OEMID_64BIT_MASK ((1ULL << (CRAT_OEMID_LENGTH * 8)) - 1)

struct crat_header {
	uint32_t	signature;
	uint32_t	length;
	uint8_t		revision;
	uint8_t		checksum;
	uint8_t		oem_id[CRAT_OEMID_LENGTH];
	uint8_t		oem_table_id[CRAT_OEMTABLEID_LENGTH];
	uint32_t	oem_revision;
	uint32_t	creator_id;
	uint32_t	creator_revision;
	uint32_t	total_entries;
	uint16_t	num_domains;
	uint8_t		reserved[CRAT_RESERVED_LENGTH];
};

/*
 * The header structure is immediately followed by total_entries of the
 * data definitions
 */

/*
 * The currently defined subtype entries in the CRAT
 */
#define CRAT_SUBTYPE_COMPUTEUNIT_AFFINITY	0
#define CRAT_SUBTYPE_MEMORY_AFFINITY		1
#define CRAT_SUBTYPE_CACHE_AFFINITY		2
#define CRAT_SUBTYPE_TLB_AFFINITY		3
#define CRAT_SUBTYPE_CCOMPUTE_AFFINITY		4
#define CRAT_SUBTYPE_IOLINK_AFFINITY		5
#define CRAT_SUBTYPE_MAX			6

#define CRAT_SIBLINGMAP_SIZE	32

/*
 * ComputeUnit Affinity structure and definitions
 */
#define CRAT_CU_FLAGS_ENABLED		0x00000001
#define CRAT_CU_FLAGS_HOT_PLUGGABLE	0x00000002
#define CRAT_CU_FLAGS_CPU_PRESENT	0x00000004
#define CRAT_CU_FLAGS_GPU_PRESENT	0x00000008
#define CRAT_CU_FLAGS_IOMMU_PRESENT	0x00000010
#define CRAT_CU_FLAGS_RESERVED		0xffffffe0

#define CRAT_COMPUTEUNIT_RESERVED_LENGTH 4

struct crat_subtype_computeunit {
	uint8_t		type;
	uint8_t		length;
	uint16_t	reserved;
	uint32_t	flags;
	uint32_t	proximity_domain;
	uint32_t	processor_id_low;
	uint16_t	num_cpu_cores;
	uint16_t	num_simd_cores;
	uint16_t	max_waves_simd;
	uint16_t	io_count;
	uint16_t	hsa_capability;
	uint16_t	lds_size_in_kb;
	uint8_t		wave_front_size;
	uint8_t		num_banks;
	uint16_t	micro_engine_id;
	uint8_t		num_arrays;
	uint8_t		num_cu_per_array;
	uint8_t		num_simd_per_cu;
	uint8_t		max_slots_scatch_cu;
	uint8_t		reserved2[CRAT_COMPUTEUNIT_RESERVED_LENGTH];
};

/*
 * HSA Memory Affinity structure and definitions
 */
#define CRAT_MEM_FLAGS_ENABLED		0x00000001
#define CRAT_MEM_FLAGS_HOT_PLUGGABLE	0x00000002
#define CRAT_MEM_FLAGS_NON_VOLATILE	0x00000004
#define CRAT_MEM_FLAGS_RESERVED		0xfffffff8

#define CRAT_MEMORY_RESERVED_LENGTH 8

struct crat_subtype_memory {
	uint8_t		type;
	uint8_t		length;
	uint16_t	reserved;
	uint32_t	flags;
	uint32_t	promixity_domain;
	uint32_t	base_addr_low;
	uint32_t	base_addr_high;
	uint32_t	length_low;
	uint32_t	length_high;
	uint32_t	width;
	uint8_t		reserved2[CRAT_MEMORY_RESERVED_LENGTH];
};

/*
 * HSA Cache Affinity structure and definitions
 */
#define CRAT_CACHE_FLAGS_ENABLED	0x00000001
#define CRAT_CACHE_FLAGS_DATA_CACHE	0x00000002
#define CRAT_CACHE_FLAGS_INST_CACHE	0x00000004
#define CRAT_CACHE_FLAGS_CPU_CACHE	0x00000008
#define CRAT_CACHE_FLAGS_SIMD_CACHE	0x00000010
#define CRAT_CACHE_FLAGS_RESERVED	0xffffffe0

#define CRAT_CACHE_RESERVED_LENGTH 8

struct crat_subtype_cache {
	uint8_t		type;
	uint8_t		length;
	uint16_t	reserved;
	uint32_t	flags;
	uint32_t	processor_id_low;
	uint8_t		sibling_map[CRAT_SIBLINGMAP_SIZE];
	uint32_t	cache_size;
	uint8_t		cache_level;
	uint8_t		lines_per_tag;
	uint16_t	cache_line_size;
	uint8_t		associativity;
	uint8_t		cache_properties;
	uint16_t	cache_latency;
	uint8_t		reserved2[CRAT_CACHE_RESERVED_LENGTH];
};

/*
 * HSA TLB Affinity structure and definitions
 */
#define CRAT_TLB_FLAGS_ENABLED	0x00000001
#define CRAT_TLB_FLAGS_DATA_TLB	0x00000002
#define CRAT_TLB_FLAGS_INST_TLB	0x00000004
#define CRAT_TLB_FLAGS_CPU_TLB	0x00000008
#define CRAT_TLB_FLAGS_SIMD_TLB	0x00000010
#define CRAT_TLB_FLAGS_RESERVED	0xffffffe0

#define CRAT_TLB_RESERVED_LENGTH 4

struct crat_subtype_tlb {
	uint8_t		type;
	uint8_t		length;
	uint16_t	reserved;
	uint32_t	flags;
	uint32_t	processor_id_low;
	uint8_t		sibling_map[CRAT_SIBLINGMAP_SIZE];
	uint32_t	tlb_level;
	uint8_t		data_tlb_associativity_2mb;
	uint8_t		data_tlb_size_2mb;
	uint8_t		instruction_tlb_associativity_2mb;
	uint8_t		instruction_tlb_size_2mb;
	uint8_t		data_tlb_associativity_4k;
	uint8_t		data_tlb_size_4k;
	uint8_t		instruction_tlb_associativity_4k;
	uint8_t		instruction_tlb_size_4k;
	uint8_t		data_tlb_associativity_1gb;
	uint8_t		data_tlb_size_1gb;
	uint8_t		instruction_tlb_associativity_1gb;
	uint8_t		instruction_tlb_size_1gb;
	uint8_t		reserved2[CRAT_TLB_RESERVED_LENGTH];
};

/*
 * HSA CCompute/APU Affinity structure and definitions
 */
#define CRAT_CCOMPUTE_FLAGS_ENABLED	0x00000001
#define CRAT_CCOMPUTE_FLAGS_RESERVED	0xfffffffe

#define CRAT_CCOMPUTE_RESERVED_LENGTH 16

struct crat_subtype_ccompute {
	uint8_t		type;
	uint8_t		length;
	uint16_t	reserved;
	uint32_t	flags;
	uint32_t	processor_id_low;
	uint8_t		sibling_map[CRAT_SIBLINGMAP_SIZE];
	uint32_t	apu_size;
	uint8_t		reserved2[CRAT_CCOMPUTE_RESERVED_LENGTH];
};

/*
 * HSA IO Link Affinity structure and definitions
 */
#define CRAT_IOLINK_FLAGS_ENABLED	0x00000001
#define CRAT_IOLINK_FLAGS_COHERENCY	0x00000002
#define CRAT_IOLINK_FLAGS_RESERVED	0xfffffffc

/*
 * IO interface types
 */
#define CRAT_IOLINK_TYPE_UNDEFINED	0
#define CRAT_IOLINK_TYPE_HYPERTRANSPORT	1
#define CRAT_IOLINK_TYPE_PCIEXPRESS	2
#define CRAT_IOLINK_TYPE_OTHER		3
#define CRAT_IOLINK_TYPE_MAX		255

#define CRAT_IOLINK_RESERVED_LENGTH 24

struct crat_subtype_iolink {
	uint8_t		type;
	uint8_t		length;
	uint16_t	reserved;
	uint32_t	flags;
	uint32_t	proximity_domain_from;
	uint32_t	proximity_domain_to;
	uint8_t		io_interface_type;
	uint8_t		version_major;
	uint16_t	version_minor;
	uint32_t	minimum_latency;
	uint32_t	maximum_latency;
	uint32_t	minimum_bandwidth_mbs;
	uint32_t	maximum_bandwidth_mbs;
	uint32_t	recommended_transfer_size;
	uint8_t		reserved2[CRAT_IOLINK_RESERVED_LENGTH];
};

/*
 * HSA generic sub-type header
 */

#define CRAT_SUBTYPE_FLAGS_ENABLED 0x00000001

struct crat_subtype_generic {
	uint8_t		type;
	uint8_t		length;
	uint16_t	reserved;
	uint32_t	flags;
};

/*
 * Component Locality Distance Information Table (CDIT)
 */
#define CDIT_OEMID_LENGTH	6
#define CDIT_OEMTABLEID_LENGTH	8

struct cdit_header {
	uint32_t	signature;
	uint32_t	length;
	uint8_t		revision;
	uint8_t		checksum;
	uint8_t		oem_id[CDIT_OEMID_LENGTH];
	uint8_t		oem_table_id[CDIT_OEMTABLEID_LENGTH];
	uint32_t	oem_revision;
	uint32_t	creator_id;
	uint32_t	creator_revision;
	uint32_t	total_entries;
	uint16_t	num_domains;
	uint8_t		entry[1];
};

#pragma pack()

#endif /* KFD_CRAT_H_INCLUDED */


text:
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import { DismissButton } from '../../components/buttons/Buttons'
import { before, css, hover, media, modifier, select } from '../../styles/jss'
import * as s from '../../styles/jso'
import { dialogStyle as baseDialogStyle } from './Dialog'

const flags = {
  spam: 'Spam',
  violence: 'Violence',
  copyright: 'Copyright infringement',
  threatening: 'Threatening',
  hate_speech: 'Hate Speech',
  adult: 'Adult content that isn\'t marked NSFW*',
  offensive: 'I don\'t like it',
}

const OFFSETS = { mobile: 70, tablet: 80, desktop: 100 }

const dialogStyle = css(
  { maxWidth: 480 },
  s.colorBlack,
  s.bgcWhite,
  media(s.minBreak2, { minWidth: 480, maxWidth: 580 }),
)

const headingStyle = css(s.hv40, s.lh40, s.mb20, s.fontSize18, media(s.minBreak2, s.fontSize24))

const footnoteStyle = css(
  { margin: '20px 0 0' },
  before({ marginLeft: -10, content: '"* "' }),
)

const buttonStyle = css(
  s.hv60,
  s.lh60,
  s.fontSize14,
  s.colorWhite,
  s.bgcBlack,
  s.borderBlack,
  { transition: 'background-color 0.2s ease, border-color 0.2s ease, width 0.2s ease' },
  hover(s.bgc6, { borderColor: '#666' }),
)

const okayAndChoiceButtons = css(
  s.relative,
  s.zIndex2,
  s.block,
  s.fullWidth,
  s.py0,
  s.px20,
  s.alignLeft,
)

const okayButtonStyle = css(buttonStyle, okayAndChoiceButtons, s.center)
const choiceButtonStyle = css(
  buttonStyle,
  okayAndChoiceButtons,
  s.leftAlign,
  modifier('.isActive', { width: 'calc(100% - 140px)', borderColor: '#666' }, s.bgc6),
  select('& + &', s.mt10),
)
const flagButtonStyle = css(
  buttonStyle,
  s.absolute,
  { top: 0, right: 20, minWidth: 120 },
  s.zIndex1,
  media(s.minBreak4, { right: 40 }),
)

export default class FlagDialog extends Component {

  static propTypes = {
    deviceSize: PropTypes.string.isRequired,
    onResponse: PropTypes.func.isRequired,
    onConfirm: PropTypes.func.isRequired,
  }

  UNSAFE_componentWillMount() {
    this.state = {
      activeChoice: null,
      scene: 'renderChoicesScreen',
    }
  }

  onClickChoiceWasMade = () => {
    const { onResponse } = this.props
    const { activeChoice } = this.state
    this.setState({ scene: 'renderConfirmationScreen' })
    onResponse({ flag: activeChoice })
  }

  onClickChoice = (e) => {
    const { activeChoice } = this.state
    const dataFlag = e.target.dataset.flag
    const newChoice = dataFlag === activeChoice ? null : dataFlag
    this.setState(
      { activeChoice: newChoice },
    )
  }

  renderFlagChoices() {
    const { activeChoice } = this.state
    const buttons = []
    Object.keys(flags).forEach((choice) => {
      buttons.push(
        <button
          className={classNames({ isActive: activeChoice === choice }, `${choiceButtonStyle}`)}
          data-flag={choice}
          key={choice}
          onClick={this.onClickChoice}
        >
          {flags[choice]}
        </button>,
      )
    })
    return buttons
  }

  renderChoicesScreen() {
    const { activeChoice } = this.state
    const index = Object.keys(flags).indexOf(activeChoice)
    const top = index < 0 ? null : (70 * index) + OFFSETS[this.props.deviceSize]
    return (
      <div className={`${baseDialogStyle} ${dialogStyle}`}>

Would you like to flag this content as:

          {this.renderFlagChoices()}

          <button
            className={flagButtonStyle}
            onClick={this.onClickChoiceWasMade}
            style={top ? { top, display: 'inline-block' } : { display: 'none' }}
          >
            Submit
          </button>

          Ello allows adult content as long as it complies with our rules and is
          marked NSFW. You may temporarily still see this content. You may want
          to block or mute this user as well.

        <DismissButton />

    )
  }

  renderConfirmationScreen() {
    const { onConfirm } = this.props
    return (
      <div className={`${baseDialogStyle} ${dialogStyle}`}>

Thank you.

          You may temporarily still see this content. You may want to block or
          mute this user as well.

          <button className={okayButtonStyle} onClick={onConfirm}>Okay</button>

        <DismissButton />

    )
  }

  render() {
    const { scene } = this.state
    return this[scene]()
  }
}


text:
package at.ac.tuwien.dsg.smartcom.adapters;

import at.ac.tuwien.dsg.smartcom.adapter.exception.AdapterException;
import at.ac.tuwien.dsg.smartcom.adapters.rest.ObjectMapperProvider;
import at.ac.tuwien.dsg.smartcom.adapters.rest.RESTResource;
import at.ac.tuwien.dsg.smartcom.adapters.rest.TestSynchronizer;
import at.ac.tuwien.dsg.smartcom.model.Identifier;
import at.ac.tuwien.dsg.smartcom.model.Message;
import at.ac.tuwien.dsg.smartcom.model.PeerChannelAddress;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.Serializable;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RESTOutputAdapterTest {

    private HttpServer server;
    private ExecutorService executor;

    @Before
    public void setUp() throws Exception {
        final ResourceConfig application = new ResourceConfig(
                RESTResource.class,
                ObjectMapperProvider.class,
                JacksonFeature.class
        );

        server = GrizzlyHttpServerFactory.createHttpServer(URI.create("http://localhost:8080/"), application);
        server.start();

        executor = Executors.newFixedThreadPool(5);
    }

    @After
    public void tearDown() throws Exception {
        server.shutdown();
        executor.shutdown();
    }

    @Test(timeout = 10000l)
    public void testRESTAdapter() throws Exception {
        TestSynchronizer.initSynchronizer(20);

        final Message message = new Message.MessageBuilder()
                .setId(Identifier.message("testId"))
                .setContent("testContent")
                .setType("testType")
                .setSubtype("testSubType")
                .setSenderId(Identifier.peer("sender"))
                .setReceiverId(Identifier.peer("receiver"))
                .setConversationId("conversationId")
                .setTtl(3)
                .setLanguage("testLanguage")
                .setSecurityToken("securityToken")
                .create();

        final RESTOutputAdapter adapter = new RESTOutputAdapter();
        final List<Serializable> list = new ArrayList<>();
        list.add("http://localhost:8080/message/");

        for (int i = 0; i < 20; i++) {
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        adapter.push(message, new PeerChannelAddress(Identifier.peer("peer"), Identifier.adapter("adapter"), list));
                    } catch (AdapterException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        TestSynchronizer.await();
    }
}


text:
// Copyright 2011-2016 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.security.zynamics.binnavi.Gui.Debug.Synchronizers;

import com.google.common.base.Preconditions;
import com.google.security.zynamics.binnavi.ZyGraph.Painters.CDebuggerPainter;
import com.google.security.zynamics.binnavi.debug.debugger.interfaces.IDebugger;
import com.google.security.zynamics.binnavi.debug.models.processmanager.ProcessManagerListenerAdapter;
import com.google.security.zynamics.binnavi.debug.models.processmanager.TargetProcessThread;
import com.google.security.zynamics.binnavi.debug.models.processmanager.ThreadListenerAdapter;
import com.google.security.zynamics.binnavi.debug.models.processmanager.interfaces.ProcessManagerListener;
import com.google.security.zynamics.binnavi.disassembly.RelocatedAddress;
import com.google.security.zynamics.binnavi.yfileswrap.zygraph.ZyGraph;

/**
 * Synchronizes the GUI with events in a single thread.
 */
public final class CThreadEventSynchronizer {
  /**
   * Debugger who is synchronized with the GUI.
   */
  private final IDebugger m_debugger;

  /**
   * The graph that is synchronized with the target process.
   */
  private final ZyGraph m_graph;

  /**
   * Keeps track of threads and updates the GUI on relevant events.
   */
  private final InternalThreadListener m_internalThreadListener = new InternalThreadListener();

  /**
   * Synchronizes the GUI with changes in the process.
   */
  private final ProcessManagerListener m_processManagerListener =
      new ProcessManagerListenerAdapter() {
        @Override
        public void changedActiveThread(final TargetProcessThread oldThread, final TargetProcessThread newThread) {
          synchronizeThreads(oldThread, newThread);
        }
      };

  /**
   * Creates a new thread synchronization object.
   *
   * @param debugger Debugger who is synchronized with the GUI.
   * @param graph The graph that is synchronized with the target process.
   */
  public CThreadEventSynchronizer(final IDebugger debugger, final ZyGraph graph) {
    Preconditions.checkNotNull(debugger, "IE01514: Debugger argument can not be null");

    Preconditions.checkNotNull(graph, "IE01515: Graph argument can not be null");

    m_debugger = debugger;
    m_graph = graph;

    // m_threadListener = new CThreadSynchronizer(debugger.getProcessManager(),
    // m_internalThreadListener);

    synchronizeThreads(null, debugger.getProcessManager().getActiveThread());

    debugger.getProcessManager().addListener(m_processManagerListener);
  }

  /**
   * Paints the program counter of a given thread into the graph.
   *
   * @param thread The graph whose PC is painted into the graph.
   */
  private void paintProgramCounter(final TargetProcessThread thread) {
    if (thread == null) {
      CDebuggerPainter.clearDebuggerHighlighting(m_graph);
    } else {
      final RelocatedAddress address = thread.getCurrentAddress();

      if (address == null) {
        return;
      }
      CDebuggerPainter.updateDebuggerHighlighting(
          m_graph, m_debugger.memoryToFile(address), m_debugger.getModule(address));
    }
  }

  /**
   * Keeps listeners on the active thread.
   *
   * @param oldThread The previously active thread.
   * @param newThread The newly active thread.
   */
  private void synchronizeThreads(final TargetProcessThread oldThread, final TargetProcessThread newThread) {
    if (oldThread != null) {
      oldThread.removeListener(m_internalThreadListener);
    }

    if (newThread == null) {
      CDebuggerPainter.clearDebuggerHighlighting(m_graph);
    } else {
      newThread.addListener(m_internalThreadListener);
    }
  }

  /**
   * Frees allocated resources.
   */
  public void dispose() {
    // m_threadListener.dispose();

    synchronizeThreads(m_debugger.getProcessManager().getActiveThread(), null);
  }

  /**
   * Keeps track of threads and updates the GUI on relevant events.
   */
  private class InternalThreadListener extends ThreadListenerAdapter {
    @Override
    public void instructionPointerChanged(
        final TargetProcessThread thread, final RelocatedAddress oldAddress) {
      paintProgramCounter(thread);
    }
  }
}


text:
package net.virtualvoid.sbt.graph
package backend

import scala.language.implicitConversions
import scala.language.reflectiveCalls

import sbt._

object SbtUpdateReport {
  type OrganizationArtifactReport = {
    def modules: Seq[ModuleReport]
  }

  def fromConfigurationReport(report: ConfigurationReport, rootInfo: sbt.ModuleID): ModuleGraph = {
    implicit def id(sbtId: sbt.ModuleID): ModuleId = ModuleId(sbtId.organization, sbtId.name, sbtId.revision)

    def moduleEdges(orgArt: OrganizationArtifactReport): Seq[(Module, Seq[Edge])] = {
      val chosenVersion = orgArt.modules.find(!_.evicted).map(_.module.revision)
      orgArt.modules.map(moduleEdge(chosenVersion))
    }

    def moduleEdge(chosenVersion: Option[String])(report: ModuleReport): (Module, Seq[Edge]) = {
      val evictedByVersion = if (report.evicted) chosenVersion else None
      val jarFile = report.artifacts.find(_._1.`type` == "jar").orElse(report.artifacts.find(_._1.extension == "jar")).map(_._2)
      (
        Module(
          id = report.module,
          license = report.licenses.headOption.map(_._1),
          evictedByVersion = evictedByVersion,
          jarFile = jarFile,
          error = report.problem),
          report.callers.map(caller ⇒ Edge(caller.caller, report.module)))
    }

    val (nodes, edges) = report.details.flatMap(moduleEdges).unzip
    val root = Module(rootInfo)

    ModuleGraph(root +: nodes, edges.flatten)
  }
}