text:
.. _hifive1:

SiFive HiFive1
##############

Overview
********

The HiFive1 is an Arduino-compatible development board with
an FE310 RISC-V SoC.
More information can be found on
`SiFive's website <https://www.sifive.com/boards/hifive1>`_.

.. image:: img/hifive1.jpg
   :align: center
   :alt: SiFive HiFive1 board

Programming and debugging
*************************

Building
========

Applications for the ``hifive1`` board configuration can be built as usual
(see :ref:`build_an_application`) using the corresponding board name:

.. zephyr-app-commands::
   :board: hifive1
   :goals: build

Flashing
========

In order to upload the application to the device, you'll need OpenOCD with
RISC-V support. Download the tarball for your OS from the `SiFive website
<https://www.sifive.com/boards>`_ and extract it.

The Zephyr SDK uses a bundled version of OpenOCD by default. You can
overwrite that behavior by adding the
``-DOPENOCD=<path/to/riscv-openocd/bin/openocd>`` parameter when building:

.. zephyr-app-commands::
   :board: hifive1
   :goals: build
   :gen-args: -DOPENOCD=<path/to/riscv-openocd/bin/openocd>

When using a custom toolchain it should be enough to have the downloaded
version of the binary in your ``PATH``.

Now you can flash the application as usual (see :ref:`build_an_application` and
:ref:`application_run` for more details):

.. code-block:: console

   ninja flash

Depending on your OS you might have to run the flash command as superuser.

Debugging
=========

Refer to the detailed overview about :ref:`application_debugging`.

redpajama_set_name: RedPajamaGithub


text:
%%%% making enviroment
menv;

printf("|--> loading data <<digit recognizer>> ...\n");

train = dlmread([curr_dir "/dataset/digit-recognizer/train.csv"]);
test = dlmread([curr_dir "/dataset/digit-recognizer/test.csv"]);
%%sampleSub = dlmread([curr_dir "/dataset/digit-recognizer/test.csv"]);

## elimina le intestazioni del csv
train = train(2:end,:);
labels = train(:,1:1);
train = train(:,2:end);
test = test(2:end,:);

############################################################## Normalizing naming
cross_size = 0.7;
verbose = 1;

printf("|--> performing feature scaling and normalization on train dataset and cross validation dataset ...\n");
printf("|--> splitting dataset into train set (%f) and cross validation set ...\n",cross_size);
rand_indices = randperm(size(train,1));
[Xtrain,ytrain,Xval,yval] = splitTrainValidation(train(rand_indices,:),labels(rand_indices),0.70);

[Xtrain,mu,sigma] = treatContFeatures(Xtrain,1);
[Xval,mu_val,sigma_val] = treatContFeatures(Xval,1,1,mu,sigma);

%%% TODO BETTER il feature scaling deve essere fatto unificando training set e cross validation set

##[C , gamma , epsilon , nu] = getBestParamSVM(type = 1 , solTrainXtrans , solTrainY);

probs_matrix_train = zeros(size(Xtrain,1),10);
probs_matrix_xval = zeros(size(Xval,1),10);

for label = 0:9
  [C , gamma , epsilon , nu] = getBestParamSVM(type = 1 , Xtrain , (ytrain == label) );
  if (verbose)
    fprintf("|---------------------->  [label = %i] found analitically C=%f , gamma=%f , ... \n" , label,C,gamma(2));
    fflush(stdout);
  endif

  ## training and prediction
  model = svmtrain( double(ytrain == label) , double(Xtrain), sprintf('-g %g -c %g -b 1',gamma(2),C)  );

  ##model = svmtrain(ytrain, Xtrain, ['-s 4 -t 2 -g' gamma ' -c ' C ' -n ' nu ] );
  [pred_train, accuracy_train, probs_train] = svmpredict( double(ytrain == label) , Xtrain, model , '-b 1');
  [pred_val, accuracy_xval, probs_val] = svmpredict( double(yval == label) , Xval, model , '-b 1 ');

  probs_matrix_train(:,(label+1)) = probs_train(:,2);
  probs_matrix_xval(:,(label+1)) = probs_val(:,2);

endfor

[prob_min_train , ind_train_min] = min(probs_matrix_train')';
[prob_min_xval , ind_xval_min] = min(probs_matrix_xval')';

pred_train = (ind_train_min - 1)';
pred_val = (ind_xval_min - 1)';

acc_train = mean(double(pred_train == ytrain)) * 100;
acc_val = mean(double(pred_val == yval)) * 100;
if (verbose)
  printf("*** TRAIN STATS ***\n");
  printf("|-->  Accuracy == %f \n",acc_train);
endif

if (verbose)
  printf("*** CV STATS ***\n");
  printf("|-->  Accuracy == %f \n",acc_val);
endif


text:
/* Commentary:
 *
 */

/* Change log:
 *
 */

#ifndef DTKABSTRACTDATAFACTORY_H
#define DTKABSTRACTDATAFACTORY_H

#include "dtkAbstractFactory.h"
#include <dtkCoreSupport/dtkSmartPointer>
#include <dtkCoreSupport/dtkAbstractData>
#include <dtkCoreSupport/dtkAbstractDataConverter>
#include <dtkCoreSupport/dtkAbstractDataReader>
#include <dtkCoreSupport/dtkAbstractDataWriter>
#include <dtkCoreSupport/dtkAbstractDataSerializer>
#include <dtkCoreSupport/dtkAbstractDataDeserializer>

class dtkAbstractData;
class dtkAbstractDataReader;
class dtkAbstractDataWriter;
class dtkAbstractDataConverter;
class dtkAbstractDataSerializer;
class dtkAbstractDataDeserializer;
class dtkAbstractDataFactoryPrivate;
template<class T> class dtkSmartPointer;

class DTKCORESUPPORT_EXPORT dtkAbstractDataFactory : public dtkAbstractFactory
{
    Q_OBJECT

public:
    typedef dtkAbstractData           *(*dtkAbstractDataCreator)         (void);
    typedef dtkAbstractDataReader     *(*dtkAbstractDataReaderCreator)   (void);
    typedef dtkAbstractDataWriter     *(*dtkAbstractDataWriterCreator)   (void);
    typedef dtkAbstractDataConverter  *(*dtkAbstractDataConverterCreator)(void);
    typedef dtkAbstractDataSerializer *(*dtkAbstractDataSerializerCreator)(void);
    typedef dtkAbstractDataDeserializer *(*dtkAbstractDataDeserializerCreator)(void);

public:
    typedef QMap<int, QString> dtkAbstractDataFactoryReaderPriorityMap;
    typedef QMap<int, QString> dtkAbstractDataFactoryWriterPriorityMap;
    typedef QMap<int, QString> dtkAbstractDataFactoryConverterPriorityMap;

public:
    static dtkAbstractDataFactory *instance(void);

    bool registerDataType         (const QString& type,                             dtkAbstractDataCreator          func);
    bool registerDataType         (const QString& type,                             dtkAbstractDataCreator          func, const QString& itf);
    bool registerDataReaderType   (const QString& type, const QStringList& handled, dtkAbstractDataReaderCreator    func);
    bool registerDataWriterType   (const QString& type, const QStringList& handled, dtkAbstractDataWriterCreator    func);
    bool registerDataConverterType(const QString& type, const QStringList& fromTypes, const QString& toType,  dtkAbstractDataConverterCreator func);
    bool registerDataSerializerType(const QString& type, const QStringList& handled, dtkAbstractDataSerializerCreator func);
    bool registerDataDeserializerType(const QString& type, const QStringList& handled, dtkAbstractDataDeserializerCreator func);

    unsigned int count(const QString& type) const;
    unsigned int countReaders      (const QString& type) const;
    unsigned int countWriters      (const QString& type) const;
    unsigned int countConverters   (const QString& type) const;
    unsigned int countSerializers  (const QString& type) const;
    unsigned int countDeserializers(const QString& type) const;

    QList<QString> creators(void) const;
    QList<QString> readers(void) const;
    QList<QString> writers(void) const;
    QList<QString> converters(void) const;
    QList<QString> serializers(void) const;
    QList<QString> deserializers(void) const;

public:
    void setReaderPriorities(const dtkAbstractDataFactoryReaderPriorityMap& priorities);
    void setWriterPriorities(const dtkAbstractDataFactoryWriterPriorityMap& priorities);
    void setConverterPriorities(const dtkAbstractDataFactoryConverterPriorityMap& priorities);

    const dtkAbstractDataFactoryReaderPriorityMap& readerPriorities(void) const;
    const dtkAbstractDataFactoryWriterPriorityMap& writerPriorities(void) const;
    const dtkAbstractDataFactoryConverterPriorityMap& converterPriorities(void) const;

public:
    QStringList implementations(void);
    QStringList implementations(const QString& intf);
    QStringList interfaces(void);

signals:
    void created(dtkAbstractData *data, const QString& type);

public slots:
    dtkAbstractData            *create   (const QString& type);
    dtkAbstractDataReader      *reader   (const QString& type);
    dtkAbstractDataWriter      *writer   (const QString& type);
    dtkAbstractDataConverter   *converter(const QString& type);
    dtkAbstractDataSerializer  *serializer(const QString& type);
    dtkAbstractDataDeserializer *deserializer(const QString& type);

    dtkSmartPointer<dtkAbstractData>          createSmartPointer   (const QString& type);
    dtkSmartPointer<dtkAbstractDataReader>    readerSmartPointer   (const QString& type);
    dtkSmartPointer<dtkAbstractDataWriter>    writerSmartPointer   (const QString& type);
    dtkSmartPointer<dtkAbstractDataConverter> converterSmartPointer(const QString& type);
    dtkSmartPointer<dtkAbstractDataSerializer> serializerSmartPointer(const QString& type);
    dtkSmartPointer<dtkAbstractDataDeserializer> deserializerSmartPointer(const QString& type);

protected:
     dtkAbstractDataFactory(void);
    ~dtkAbstractDataFactory(void);

private:
    static dtkAbstractDataFactory *s_instance;

private:
    dtkAbstractDataFactoryPrivate *d;
};

#endif


text:
package operations;

import java.awt.Color;

import javax.swing.JColorChooser;

import data.Collector;

public class O_SetBackgroundColor implements Operation {

	@Override
	public void run() {
		Color old = Collector.getSlides().getBackgroundColor();

		Color newColor = JColorChooser.showDialog(
                null,
                "Choose Background Color",
                old);

		if(newColor != null) {
			Collector.getSlides().setBackgroundColor(newColor);
			Collector.getWindow().updateAnimationColor();
			Collector.getWindow().updateAnimationImages();
			Collector.getWindow().repaintBoard();
		}
	}

}


text:
title: "Credits"
linkTitle: "Credits"
weight: 2
aliases:
- /credits.html
---

<!--

 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you 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

   https://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.

-->

## Apache Avro credits

### Committers

Apache Avro's active committers are:

| **username** |       **name**      |     **organization**    |       **roles**        | **timezone** |
|:-------------|:--------------------|:------------------------|:----------------------:|:------------:|
|  blue        | Ryan Blue           | Netflix                 | spec, java, ruby       |   -8 |
|  brucem      | Bruce Mitchener     | Army of Bruce           | c                      |   +7 |
|  busbey      | Sean Busbey         | Cloudera                | java, ruby             |   -6 |
|  cutting     | Doug Cutting        | Cloudera                | spec, java             |   -8 |
|  dcreager    | Douglas Creager     | RedJack, LLC            | c                      |   -5 |
|  hammer      | Jeff Hammerbacher   | Cloudera                | python                 |   -8 |
|  iemejia     | Ismaël Mejía        | Talend                  | java, docker           |   +1 |
|  kojiromike  | Michael A. Smith    | Independent             | python, docker         |   -5 |
|  massie      | Matt Massie         | UC Berkeley             | c                      |   -8 |
|  martinkl    | Martin Kleppmann    | University of Cambridge | c, ruby                |    0 |
|  mgrigorov   | Martin Grigorov     | Huawei                  | rust                   |   +2 |
|  nielsbasjes | Niels Basjes        | Bol.com                 | java, docker           |   +1 |
|  philz       | Philip Zeyliger     | Cloudera                | java                   |   -8 |
|  rskraba     | Ryan Skraba         | Talend                  | java, docker           |   +1 |
|  sbanacho    | Scott Banachowski   | Microsoft               | c++                    |   -8 |
|  scottcarey  | Scott Carey         | RichRelevance           | java                   |   -8 |
|  sekikn      | Kengo Seki          | NTT Data                | perl, interoperability |   +9 |
|  sharadag    | Sharad Agarwal      | InMobi                  | python                 | +5.5 |
|  thiru       | Thiruvalluvan M. G. | VertiCloud              | java                   | +5.5 |
|  tomwhite    | Tom White           | Cloudera                | java                   |    0 |
-------------

### Contributors
A list of Avro contributors and their contributions is available from [Jira](http://s.apache.org/AvroFixed)

### Emeriti
Contributors who are no longer active on Avro are:

* None


text:
package org.tolweb.btol.dao;

import org.tolweb.btol.Chromatogram;
import org.tolweb.btol.ChromatogramBatch;
import org.tolweb.btol.PCRReaction;
import org.tolweb.dao.ApplicationContextTestAbstract;

public class ChromatogramDAOTest extends ApplicationContextTestAbstract {
	private PCRReactionDAO reactionDAO;
	private ChromatogramBatchDAO chroDAO;
	public ChromatogramDAOTest(String name) {
		super(name);
		reactionDAO = (PCRReactionDAO) context.getBean("pcrReactionDAO");
		chroDAO = (ChromatogramBatchDAO) context.getBean("chromatogramBatchDAO");
	}

	public void testChromatograms() {
		PCRReaction reaction = new PCRReaction();
		reaction.setBtolCode("BTOL00000");
		reaction.setReactionResult(0);
		reactionDAO.saveReaction(reaction);

		Chromatogram chro = new Chromatogram();
		chro.setFilename("test.ab1");
		chroDAO.saveChromatogram(chro);

		ChromatogramBatch batch = new ChromatogramBatch();
		batch.setName("plate 1");
		batch.setDescription("1st BTOL plate");
		chroDAO.saveChromatogramBatch(batch, 1L);

		batch.addToChromatograms(chro);
		chroDAO.saveChromatogramBatch(batch, 1L);

		ChromatogramBatch otherBatch = chroDAO.getChromatogramBatchWithId(batch.getId());
		assertEquals(otherBatch.getChromatograms().size(), batch.getChromatograms().size());
		assertEquals(((Chromatogram) otherBatch.getChromatograms().iterator().next()).getId(), chro.getId());

		reaction.addToChromatograms(chro);
		reactionDAO.saveReaction(reaction);

		PCRReaction otherReaction = (PCRReaction) reactionDAO.getObjectWithId(PCRReaction.class, reaction.getId());
		assertEquals(otherReaction.getChromatograms().size(), reaction.getChromatograms().size());
		assertEquals(((Chromatogram) otherReaction.getChromatograms().iterator().next()).getId(), chro.getId());
	}
}


text:
package guiapi

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/mbertschler/blocks/html"

	"github.com/mbertschler/bunny/pkg/blocks"
	"github.com/mbertschler/bunny/pkg/data"
)

func Handlers() Handler {
	handler := Handler{
		Functions: map[string]Callable{
			"areaView":   areaViewHandler,
			"listView":   listViewHandler,
			"listSort":   listSortHandler,
			"itemNew":    itemNewHandler,
			"itemView":   itemViewHandler,
			"itemEdit":   itemEditHandler,
			"itemSave":   itemSaveHandler,
			"itemState":  itemStateHandler,
			"itemFocus":  itemFocusHandler,
			"itemDelete": itemDeleteHandler,
			"focusView":  focusViewHandler,
			"focusSort":  focusSortHandler,
		},
	}
	return handler
}

func areaViewHandler(_ json.RawMessage) (*Result, error) {
	_, things, err := data.UserArea(1, 1)
	if err != nil {
		return nil, err
	}
	res, err := replaceContainer(blocks.ViewAreaPage(things))
	if res != nil {
		args, err := json.Marshal([]interface{}{nil, "Bunny List", "/"})
		if err != nil {
			log.Println(err)
		}
		// TODO make Result API nicer
		res.JS = append(res.JS, JSCall{
			Name:      "setURL",
			Arguments: args,
		})
		res.JS = append(res.JS, JSCall{
			Name: "enableSorting",
		})
	}
	return res, err
}

func listViewHandler(_ json.RawMessage) (*Result, error) {
	list, err := data.UserItemList(1, 1)
	if err != nil {
		return nil, err
	}
	res, err := replaceContainer(blocks.ViewListPage(list))
	if res != nil {
		args, err := json.Marshal([]interface{}{nil, "Bunny List", "/"})
		if err != nil {
			log.Println(err)
		}
		// TODO make Result API nicer
		res.JS = append(res.JS, JSCall{
			Name:      "setURL",
			Arguments: args,
		})
		res.JS = append(res.JS, JSCall{
			Name: "enableSorting",
		})
	}
	return res, err
}

func focusViewHandler(_ json.RawMessage) (*Result, error) {
	focus, err := data.FocusList(1)
	if err != nil {
		log.Println(err)
	}
	res, err := replaceContainer(blocks.ViewFocusPage(focus))
	if res != nil {
		args, err := json.Marshal([]interface{}{nil, "Bunny Focus", "/focus/"})
		if err != nil {
			log.Println(err)
		}
		// TODO make Result API nicer
		res.JS = append(res.JS, JSCall{
			Name:      "setURL",
			Arguments: args,
		})
		res.JS = append(res.JS, JSCall{
			Name: "enableSorting",
		})
	}
	return res, err
}

func listSortHandler(in json.RawMessage) (*Result, error) {
	var args = struct {
		Item int
		Pos  int
	}{}
	err := json.Unmarshal(in, &args)
	if err != nil {
		return nil, err
	}
	data.SetListItemPosition(1, args.Item, args.Pos)
	return listViewHandler(nil)
}

func focusSortHandler(in json.RawMessage) (*Result, error) {
	var args = struct {
		Type string
		Old  int
		New  int
	}{}
	err := json.Unmarshal(in, &args)
	if err != nil {
		return nil, err
	}
	// var type
	// switch args.Type {
	// case "pause":
	// 	data.State = ItemOpen
	// case "later":
	// 	data.State = ItemComplete
	// 	data.Focus = FocusNone
	// case "watch":
	// 	data.State = ItemArchived
	// 	data.Focus = FocusNone
	// }
	// sortFocusItem(0, args.Old, args.New)
	return focusViewHandler(nil)
}

func itemNewHandler(in json.RawMessage) (*Result, error) {
	return replaceContainer(blocks.EditItemPage(data.Item{}, true))
}

func itemViewHandler(in json.RawMessage) (*Result, error) {
	var id int
	err := json.Unmarshal(in, &id)
	if err != nil {
		return nil, err
	}
	ui, _ := data.UserItemByID(1, id)
	res, err := replaceContainer(blocks.ViewItemPage(ui))
	if res != nil {
		args, err := json.Marshal([]interface{}{nil, "Bunny Item", fmt.Sprint("/item/", id)})
		if err != nil {
			log.Println(err)
		}
		res.JS = append(res.JS, JSCall{
			Name:      "setURL",
			Arguments: args,
		})
	}
	return res, err
}

func itemEditHandler(in json.RawMessage) (*Result, error) {
	var id int
	err := json.Unmarshal(in, &id)
	if err != nil {
		return nil, err
	}
	ui, _ := data.UserItemByID(1, id)
	return replaceContainer(blocks.EditItemPage(ui, false))
}

func itemSaveHandler(in json.RawMessage) (*Result, error) {
	var arg struct {
		ID    int
		New   bool
		Title string
		Body  string
	}
	err := json.Unmarshal(in, &arg)
	if err != nil {
		return nil, err
	}

	if arg.New {
		if len(arg.Title) == 0 {
			list, err := data.UserItemList(1, 1)
			if err != nil {
				return nil, err
			}
			return replaceContainer(blocks.ViewListPage(list))
		}
		newItem, err := data.NewItem()
		if err != nil {
			return nil, err
		}
		arg.ID = newItem.ID
	}
	d, _ := data.UserItemByID(1, arg.ID)
	if len(arg.Title) > 0 {
		d.Title = arg.Title
	}
	if len(arg.Body) > 0 {
		d.Body = arg.Body
	}
	data.SetItem(d)
	return replaceContainer(blocks.ViewItemPage(d))
}

func itemStateHandler(in json.RawMessage) (*Result, error) {
	var args = struct {
		ID    int
		State string
	}{}
	err := json.Unmarshal(in, &args)
	if err != nil {
		return nil, err
	}
	d, _ := data.UserItemByID(1, args.ID)
	switch args.State {
	case "open":
		d.State = data.ItemOpen
	case "complete":
		d.State = data.ItemComplete
	case "archived":
		d.State = data.ItemArchived
	}
	data.SetItem(d)
	return replaceContainer(blocks.ViewItemPage(d))
}

func itemFocusHandler(in json.RawMessage) (*Result, error) {
	var args = struct {
		ID    int
		Focus string
	}{}
	err := json.Unmarshal(in, &args)
	if err != nil {
		return nil, err
	}

	d, _ := data.UserItemByID(1, args.ID)
	switch args.Focus {
	case "later":
		if d.Focus == data.FocusLater {
			data.SetFocus(1, args.ID, data.FocusNone)
		} else {
			data.SetFocus(1, args.ID, data.FocusLater)
		}
	case "focus":
		if d.Focus == data.FocusNow {
			data.SetFocus(1, args.ID, data.FocusNone)
		} else {
			data.SetFocus(1, args.ID, data.FocusNow)
		}
	case "watch":
		if d.Focus == data.FocusWatch {
			data.SetFocus(1, args.ID, data.FocusNone)
		} else {
			data.SetFocus(1, args.ID, data.FocusWatch)
		}
	}
	d, _ = data.UserItemByID(1, args.ID)
	return replaceContainer(blocks.ViewItemPage(d))
}

func itemDeleteHandler(in json.RawMessage) (*Result, error) {
	var arg int
	err := json.Unmarshal(in, &arg)
	if err != nil {
		return nil, err
	}
	data.DeleteItem(arg)
	list, err := data.UserItemList(1, 1)
	if err != nil {
		return nil, err
	}
	return replaceContainer(blocks.ViewListPage(list))
}

func replaceContainer(block html.Block) (*Result, error) {
	out, err := html.RenderString(block)
	if err != nil {
		return nil, err
	}
	ret := &Result{
		HTML: []HTMLUpdate{
			{
				Operation: HTMLReplace,
				Selector:  "#container",
				Content:   out,
			},
		},
	}
	return ret, nil
}


text:
{% include "partials/head.html" %}
{% include "partials/nav.html" %}
{% include "partials/header.html" %}
{% block content %}{% endblock %}
{% include "partials/footer.html" %}


text:
{% load i18n %}
{% load sentry_api %}
{% load sentry_dsn %}
{% load sentry_assets %}
{% load sentry_features %}
{% load sentry_helpers %}
{% load sentry_react %}

{% load sentry_status %}
{% get_sentry_version %}

<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="robots" content="NONE,NOARCHIVE">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link href="{% absolute_asset_url "sentry" "images/favicon.ico" %}" rel="shortcut icon" type="image/png"/>

  <link rel="icon" href="{% absolute_asset_url "sentry" "images/icons/apple-touch-icon.png" %}">
  <link rel="apple-touch-icon" href="{% absolute_asset_url "sentry" "images/icons/apple-touch-icon.png" %}">
  <link rel="apple-touch-icon" sizes="76x76" href="{% absolute_asset_url "sentry" "images/icons/apple-touch-icon-76x76.png" %}">
  <link rel="apple-touch-icon" sizes="120x120" href="{% absolute_asset_url "sentry" "images/icons/apple-touch-icon-120x120.png" %}">
  <link rel="apple-touch-icon" sizes="152x152" href="{% absolute_asset_url "sentry" "images/icons/apple-touch-icon-152x152.png" %}">

  <link rel="mask-icon" sizes="any" href="{% absolute_asset_url "sentry" "images/icons/sentry-glyph-black.svg" %}" color="#FB4226">

  {% block css %}
  <link href="{% asset_url "sentry" "dist/sentry.css" %}" rel="stylesheet"/>
  {% endblock %}

  <title>{% block title %}Sentry{% endblock %}</title>

  {% block scripts %}

  {% locale_js_include %}

  {% include "sentry/includes/ravenjs.html" %}
  {% endblock %}

  {% block meta %}
  {% endblock %}

  {% block body %}

    {% if request.is_superuser %}
        {% show_system_status %}
    {% endif %}

    {% block alerts %}
    {% include "sentry/partial/alerts.html" %}
    {% endblock %}

    {% block header %}

        {% if request.user.is_authenticated %}
        {% block account_nav %}

                {% letter_avatar_svg request.user.get_display_name request.user.get_label %}
                {% if request.user.get_avatar_type == 'upload' %}

                {% elif request.user.get_avatar_type == 'gravatar' %}

                {% endif %}

{% trans "Account" %}

{% trans "API" %}

              {% if request.is_superuser %}

{% trans "Admin" %}

              {% endif %}

{% trans "Sign out" %}

        {% endblock %}
        {% endif %}

        {% block logo %}

        {% endblock %}

          {% block global_nav %}

{% trans "Docs" %}

          {% endblock %}

        {% if not SINGLE_ORGANIZATION and request.user.is_authenticated and organization %}
        {% block org_selector %}

              {{ organization.name }}

              {% for org in request.user|list_organizations %}

{{ org.name }}

              {% endfor %}
              {% feature organizations:create %}

New Organization

              {% endfeature %}

        {% endblock %}
        {% endif %}

    {% endblock %}

    {% if organization and ACCESS.org_read %}
    {% block sub-header %}

          {% block header_action %}{% endblock %}

            {{ organization.name }}

    {% endblock %}
    {% endif %}

      {% block above_content %}{% endblock %}

        {% block content_before %}
        {% endblock %}
        {% block content %}

            {% block sidebar %}
            {% endblock %}

            {% block main %}
            {% endblock %}

        {% endblock %}

        {% block content_after %}
        {% endblock %}

        {% block footer %}

          {% block support_link %}{% endblock %}
          {% trans "API" %}
          {% trans "Docs" %}
          {% trans "Contribute" %}
          {% if ONPREMISE %}{% trans "Migrate to SaaS" %}{% endif %}

Sentry {{ sentry_version.current }} {% if sentry_version.update_available %} {% endif %}

        {% endblock %}

  {% block selectize %}

  {% endblock %}

  {% endblock %}

  {% block scripts_bottom %}{% endblock %}


text:
from multiprocessing import Process, Queue
import random

def my_func(name, output_q):
    output_dict = {}
    output_dict[name] = []
    for i in range(0, 50000):
        print(i)
        print(output_q.full())
        output_dict[name].append(random.getrandbits(128))

    output_q.put(output_dict)
    return

def main():
    swlines = ['test1', 'test2', 'test3']
    output_q = Queue()
    procs = []
    gatherstruct = []

    for swline in swlines:
        my_proc = Process(target=my_func, args=(swline, output_q))
        my_proc.start()
        procs.append(my_proc)

    while True:
        # True if any process is still running
        still_running = any(a_proc.is_alive() for a_proc in procs)
        while not output_q.empty():
            gatherstruct.append(output_q.get())
        if not still_running:
            break

    #for a_proc in procs:
    #    while a_proc.is_alive():
    #        a_proc.join()

    while not output_q.empty():
        gatherstruct.append(output_q.get())

    print(gatherstruct)

if __name__ == "__main__":
    main()


text:
/**
 */
package CIM15.IEC61970.Informative.InfOperations;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.eclipse.emf.common.util.Enumerator;

/**
 *
 * A representation of the literals of the enumeration 'PSR Event Kind',
 * and utility methods for working with them.
 *
 * @see CIM15.IEC61970.Informative.InfOperations.InfOperationsPackage#getPSREventKind()
 * @generated
 */
public enum PSREventKind implements Enumerator {
	/**
	 * The 'Pending Remove' literal object.
	 *
	 *
	 * @see #PENDING_REMOVE_VALUE
	 * @generated
	 * @ordered
	 */
	PENDING_REMOVE(0, "pendingRemove", "pendingRemove"),

	/**
	 * The 'Pending Replace' literal object.
	 *
	 *
	 * @see #PENDING_REPLACE_VALUE
	 * @generated
	 * @ordered
	 */
	PENDING_REPLACE(1, "pendingReplace", "pendingReplace"),

	/**
	 * The 'Out Of Service' literal object.
	 *
	 *
	 * @see #OUT_OF_SERVICE_VALUE
	 * @generated
	 * @ordered
	 */
	OUT_OF_SERVICE(2, "outOfService", "outOfService"),

	/**
	 * The 'Pending Add' literal object.
	 *
	 *
	 * @see #PENDING_ADD_VALUE
	 * @generated
	 * @ordered
	 */
	PENDING_ADD(3, "pendingAdd", "pendingAdd"),

	/**
	 * The 'Unknown' literal object.
	 *
	 *
	 * @see #UNKNOWN_VALUE
	 * @generated
	 * @ordered
	 */
	UNKNOWN(4, "unknown", "unknown"),

	/**
	 * The 'In Service' literal object.
	 *
	 *
	 * @see #IN_SERVICE_VALUE
	 * @generated
	 * @ordered
	 */
	IN_SERVICE(5, "inService", "inService"),

	/**
	 * The 'Other' literal object.
	 *
	 *
	 * @see #OTHER_VALUE
	 * @generated
	 * @ordered
	 */
	OTHER(6, "other", "other");

	/**
	 * The 'Pending Remove' literal value.
	 *
	 *

	 * If the meaning of 'Pending Remove' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #PENDING_REMOVE
	 * @generated
	 * @ordered
	 */
	public static final int PENDING_REMOVE_VALUE = 0;

	/**
	 * The 'Pending Replace' literal value.
	 *
	 *

	 * If the meaning of 'Pending Replace' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #PENDING_REPLACE
	 * @generated
	 * @ordered
	 */
	public static final int PENDING_REPLACE_VALUE = 1;

	/**
	 * The 'Out Of Service' literal value.
	 *
	 *

	 * If the meaning of 'Out Of Service' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #OUT_OF_SERVICE
	 * @generated
	 * @ordered
	 */
	public static final int OUT_OF_SERVICE_VALUE = 2;

	/**
	 * The 'Pending Add' literal value.
	 *
	 *

	 * If the meaning of 'Pending Add' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #PENDING_ADD
	 * @generated
	 * @ordered
	 */
	public static final int PENDING_ADD_VALUE = 3;

	/**
	 * The 'Unknown' literal value.
	 *
	 *

	 * If the meaning of 'Unknown' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #UNKNOWN
	 * @generated
	 * @ordered
	 */
	public static final int UNKNOWN_VALUE = 4;

	/**
	 * The 'In Service' literal value.
	 *
	 *

	 * If the meaning of 'In Service' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #IN_SERVICE
	 * @generated
	 * @ordered
	 */
	public static final int IN_SERVICE_VALUE = 5;

	/**
	 * The 'Other' literal value.
	 *
	 *

	 * If the meaning of 'Other' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #OTHER
	 * @generated
	 * @ordered
	 */
	public static final int OTHER_VALUE = 6;

	/**
	 * An array of all the 'PSR Event Kind' enumerators.
	 *
	 *
	 * @generated
	 */
	private static final PSREventKind[] VALUES_ARRAY =
		new PSREventKind[] {
			PENDING_REMOVE,
			PENDING_REPLACE,
			OUT_OF_SERVICE,
			PENDING_ADD,
			UNKNOWN,
			IN_SERVICE,
			OTHER,
		};

	/**
	 * A public read-only list of all the 'PSR Event Kind' enumerators.
	 *
	 *
	 * @generated
	 */
	public static final List<PSREventKind> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));

	/**
	 * Returns the 'PSR Event Kind' literal with the specified literal value.
	 *
	 *
	 * @generated
	 */
	public static PSREventKind get(String literal) {
		for (int i = 0; i < VALUES_ARRAY.length; ++i) {
			PSREventKind result = VALUES_ARRAY[i];
			if (result.toString().equals(literal)) {
				return result;
			}
		}
		return null;
	}

	/**
	 * Returns the 'PSR Event Kind' literal with the specified name.
	 *
	 *
	 * @generated
	 */
	public static PSREventKind getByName(String name) {
		for (int i = 0; i < VALUES_ARRAY.length; ++i) {
			PSREventKind result = VALUES_ARRAY[i];
			if (result.getName().equals(name)) {
				return result;
			}
		}
		return null;
	}

	/**
	 * Returns the 'PSR Event Kind' literal with the specified integer value.
	 *
	 *
	 * @generated
	 */
	public static PSREventKind get(int value) {
		switch (value) {
			case PENDING_REMOVE_VALUE: return PENDING_REMOVE;
			case PENDING_REPLACE_VALUE: return PENDING_REPLACE;
			case OUT_OF_SERVICE_VALUE: return OUT_OF_SERVICE;
			case PENDING_ADD_VALUE: return PENDING_ADD;
			case UNKNOWN_VALUE: return UNKNOWN;
			case IN_SERVICE_VALUE: return IN_SERVICE;
			case OTHER_VALUE: return OTHER;
		}
		return null;
	}

	/**
	 *
	 *
	 * @generated
	 */
	private final int value;

	/**
	 *
	 *
	 * @generated
	 */
	private final String name;

	/**
	 *
	 *
	 * @generated
	 */
	private final String literal;

	/**
	 * Only this class can construct instances.
	 *
	 *
	 * @generated
	 */
	private PSREventKind(int value, String name, String literal) {
		this.value = value;
		this.name = name;
		this.literal = literal;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public int getValue() {
	  return value;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getName() {
	  return name;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getLiteral() {
	  return literal;
	}

	/**
	 * Returns the literal value of the enumerator, which is its string representation.
	 *
	 *
	 * @generated
	 */
	@Override
	public String toString() {
		return literal;
	}

} //PSREventKind


text:
"""
UpdateInfo - command ``yum updateinfo list -C``
===============================================
Provides a list of available advisories
"""
from insights import CommandParser, parser
from insights.parsers import parse_delimited_table, SkipException
from insights.specs import Specs

@parser(Specs.yum_updateinfo)
class YumUpdateinfo(CommandParser):
    """
    Class for parsing the output of `yum updateinfo list -C`.

    Expected output of the command is::

        RSHA-2020-0001 security       firefox-83.0-13.fc32.x86_64
        RHBA-2020-0002 bugfix         flatpak-libs-1.8.3-1.fc32.x86_64
        RHEA-2020-0003 enhancement    flatpak-selinux-1.8.3-1.fc32.noarch

    Examples:
        >>> len(updateinfo.items)
        3
        >>> updateinfo.items[0]
        {'advisory': 'RSHA-2020-0001', 'type': 'security', 'package': 'firefox-83.0-13.fc32.x86_64'}

    """

    def parse_content(self, content):
        """Parse the command output"""
        with_header = ['advisory type package'] + content
        table = parse_delimited_table(with_header)
        if not table:
            raise SkipException('No data.')
        self._items = table

    @property
    def items(self):
        """
        list: Updatable packages, along with minimal advisory metadata
        """
        return self._items


text:
namespace app { namespace Uno { namespace Content { namespace Models { struct IndexArray; } } } }
namespace app { namespace Uno { namespace Content { namespace Models { struct VertexAttributeArray; } } } }
namespace app { namespace Uno { namespace Geometry { struct Triangle; } } }

namespace app {
namespace Fuse {
namespace Entities {

struct ModelMeshCollision_Indexed;

struct ModelMeshCollision_Indexed__uType : ::app::Fuse::Entities::TriangleMeshIntersecter__uType
{
};

ModelMeshCollision_Indexed__uType* ModelMeshCollision_Indexed__typeof();

void ModelMeshCollision_Indexed___ObjInit_1(ModelMeshCollision_Indexed* __this, ::app::Uno::Content::Models::VertexAttributeArray* positions, ::app::Uno::Content::Models::IndexArray* indices, int indexCount);
::app::Uno::Geometry::Triangle ModelMeshCollision_Indexed__GetTriangle(ModelMeshCollision_Indexed* __this, int t);
ModelMeshCollision_Indexed* ModelMeshCollision_Indexed__New_1(::uStatic* __this, ::app::Uno::Content::Models::VertexAttributeArray* positions, ::app::Uno::Content::Models::IndexArray* indices, int indexCount);

struct ModelMeshCollision_Indexed : ::app::Fuse::Entities::TriangleMeshIntersecter
{
    ::uStrong< ::app::Uno::Content::Models::VertexAttributeArray*> _positions;
    ::uStrong< ::app::Uno::Content::Models::IndexArray*> _indices;

    void _ObjInit_1(::app::Uno::Content::Models::VertexAttributeArray* positions, ::app::Uno::Content::Models::IndexArray* indices, int indexCount) { ModelMeshCollision_Indexed___ObjInit_1(this, positions, indices, indexCount); }
};

}}}

#endif


text:
"""
repackage.tests.test_views
--------------------------
"""

import commonware
import os
import simplejson
#import tempfile

from mock import Mock
from nose.tools import eq_
from utils.test import TestCase

from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User

from jetpack.models import SDK
from repackage import tasks

log = commonware.log.getLogger('f.repackage')

def _del_xpi(hashtag):
    target_xpi = os.path.join(
            settings.XPI_TARGETDIR, hashtag, '.xpi')
    if os.path.isfile(target_xpi):
        os.remove(target_xpi)

class RepackageViewsTest(TestCase):
    fixtures = ['mozilla_user', 'users', 'core_sdk', 'packages']

    def setUp(self):
        settings.CELERY_ALWAYS_EAGER = True
        self.xpi_file_prefix = "file://%s" % os.path.join(
                settings.ROOT, 'apps/xpi/tests/sample_addons/')
        self.sample_addons = [
                "sample_add-on-1.0b3.xpi",
                "sample_add-on-1.0b4.xpi",
                "sample_add-on-1.0rc2.xpi"]
        self.rebuild_url = reverse('repackage_rebuild')
        self.rebuild_url_addons = reverse('repackage_rebuild_addons')

    def test_repackage_bad_request(self):
        # POST request is required
        response = self.client.get(self.rebuild_url)
        eq_(response.status_code, 405)
        # security field is required
        response = self.client.post(self.rebuild_url)
        eq_(response.status_code, 403)
        # location field is reuired
        response = self.client.post(self.rebuild_url, {
            'secret': settings.AMO_SECRET_KEY})
        eq_(response.status_code, 400)
        # invalid version format
        response = self.client.post(self.rebuild_url, {
            'location': os.path.join(
                self.xpi_file_prefix, self.sample_addons[1]),
            'secret': settings.AMO_SECRET_KEY,
            'addons': simplejson.dumps([{
                'location': os.path.join(
                    self.xpi_file_prefix, self.sample_addons[1]),
                }]),
            'version': 'invalid string'})
        eq_(response.status_code, 200)
        eq_(simplejson.loads(response.content)['status'], 'some failures')

    def test_repackage_with_download(self):
        tasks.low_rebuild.delay = Mock(return_value=None)
        get_rebuild = lambda sample: self.client.post(self.rebuild_url, {
            'location': os.path.join(self.xpi_file_prefix, sample),
            'secret': settings.AMO_SECRET_KEY})

        # test add-ons build with SDK 1.0b3
        response = get_rebuild(self.sample_addons[0])
        eq_(response.status_code, 200)
        content = simplejson.loads(response.content)
        assert 'status' in content
        eq_(content['status'], 'success')

        # test add-ons build with SDK 1.0b4
        response = get_rebuild(self.sample_addons[1])
        eq_(response.status_code, 200)
        content = simplejson.loads(response.content)
        assert 'status' in content
        eq_(content['status'], 'success')

    def test_bulk_repackage_with_download(self):
        tasks.low_rebuild.delay = Mock(return_value=None)
        response = self.client.post(self.rebuild_url, {
            'addons': simplejson.dumps([
                {'location': os.path.join(
                    self.xpi_file_prefix, self.sample_addons[0])},
                {'location': os.path.join(
                    self.xpi_file_prefix, self.sample_addons[1])},
                ]),
            'secret': settings.AMO_SECRET_KEY})

        eq_(response.status_code, 200)
        content = simplejson.loads(response.content)
        eq_(content['status'], 'success')
        eq_(tasks.low_rebuild.delay.call_count, 2)
        # is callback to the right test provided?
        assert 'callback' in tasks.low_rebuild.delay.call_args[1]
        eq_(tasks.low_rebuild.delay.call_args[1]['callback'],
            tasks.rebuild_from_location)

    def test_single_upload_and_rebuild(self):
        file_pre = os.path.join(settings.ROOT, 'apps/xpi/tests/sample_addons/')
        tasks.low_rebuild.delay = Mock(return_value=None)
        with open(os.path.join(file_pre, self.sample_addons[1])) as f:
            response = self.client.post(self.rebuild_url, {
                'upload': f,
                'secret': settings.AMO_SECRET_KEY})
        eq_(response.status_code, 200)
        content = simplejson.loads(response.content)
        eq_(content['status'], 'success')
        eq_(tasks.low_rebuild.delay.call_count, 1)
        # is callback to the right test provided?
        assert 'callback' in tasks.low_rebuild.delay.call_args[1]
        eq_(tasks.low_rebuild.delay.call_args[1]['callback'],
            tasks.rebuild_from_upload)

    def test_single_repackage_from_pk(self):
        tasks.low_rebuild.delay = Mock(return_value=None)
        response = self.client.post(self.rebuild_url, {
            'package_key': '1',
            'secret': settings.AMO_SECRET_KEY})
        eq_(response.status_code, 200)
        content = simplejson.loads(response.content)
        eq_(content['status'], 'success')
        eq_(tasks.low_rebuild.delay.call_count, 1)
        # is callback to the right test provided?
        assert 'callback' in tasks.low_rebuild.delay.call_args[1]
        eq_(tasks.low_rebuild.delay.call_args[1]['callback'],
            tasks.rebuild_addon)

    def test_bulk_repackage_from_pk(self):
        tasks.low_rebuild.delay = Mock(return_value=None)
        response = self.client.post(self.rebuild_url, {
            'addons': simplejson.dumps([
                {'package_key': '1'},
                {'package_key': '2'}]),
            'secret': settings.AMO_SECRET_KEY})
        eq_(response.status_code, 200)
        content = simplejson.loads(response.content)
        eq_(content['status'], 'success')
        eq_(tasks.low_rebuild.delay.call_count, 2)
        # is callback to the right test provided?
        assert 'callback' in tasks.low_rebuild.delay.call_args[1]
        eq_(tasks.low_rebuild.delay.call_args[1]['callback'],
            tasks.rebuild_addon)

    def test_bulk_upload_and_rebuild(self):
        file_pre = os.path.join(settings.ROOT, 'apps/xpi/tests/sample_addons/')
        tasks.low_rebuild.delay = Mock(return_value=None)
        f0 = open(os.path.join(file_pre, self.sample_addons[0]))
        f1 = open(os.path.join(file_pre, self.sample_addons[1]))
        response = self.client.post(self.rebuild_url, {
            'upload_a': f0,
            'upload_b': f1,
            'addons': simplejson.dumps([
                {'upload': 'upload_a'},
                {'upload': 'upload_b'}
                ]),
            'secret': settings.AMO_SECRET_KEY})
        eq_(response.status_code, 200)
        content = simplejson.loads(response.content)
        eq_(content['status'], 'success')
        eq_(tasks.low_rebuild.delay.call_count, 2)

    def test_repackage_with_sdk_version_suffix(self):
        file_pre = os.path.join(settings.ROOT, 'apps/xpi/tests/sample_addons/')
        tasks.low_rebuild.delay = Mock(return_value=None)
        with open(os.path.join(file_pre, self.sample_addons[1])) as f:
            response = self.client.post(self.rebuild_url, {
                'upload': f,
                'version': 'test-sdk-{sdk_version}',
                'secret': settings.AMO_SECRET_KEY})
        eq_(response.status_code, 200)
        task_args = tasks.low_rebuild.delay.call_args
        eq_(task_args[1]['package_overrides']['version'], 'test-sdk-1.0')

    def test_repackage_with_chosen_sdk(self):
        SDKVERSION = 'test'
        SDKDIR = 'not/existing/dir'
        # create new package revision for the core lib
        corelib = SDK.objects.latest('pk').core_lib
        corelib.save()
        sdk = SDK.objects.create(
                version=SDKVERSION,
                dir=SDKDIR,
                core_lib=corelib)
        file_pre = os.path.join(settings.ROOT, 'apps/xpi/tests/sample_addons/')
        tasks.low_rebuild.delay = Mock(return_value=None)
        with open(os.path.join(file_pre, self.sample_addons[1])) as f:
            response = self.client.post(self.rebuild_url, {
                'upload': f,
                'version': 'test-sdk-{sdk_version}',
                'secret': settings.AMO_SECRET_KEY,
                'sdk_version': SDKVERSION})
        eq_(response.status_code, 200)
        task_args = tasks.low_rebuild.delay.call_args
        log.critical(task_args[0])
        eq_(task_args[0][1], sdk.get_source_dir())

    def test_list_versions_api(self):
        """
        /repackage/sdk-versions/ should return a JSON list of
        all the SDK versions known to Builder
        """

        resp = self.client.get(reverse('repackage_sdk_versions'))

        num_of_versions = SDK.objects.all().count()

        eq_(200, resp.status_code)

        log.debug(resp.content)
        data = simplejson.loads(resp.content)
        eq_(num_of_versions, len(data))

    def test_bulk_repackage_addon(self):
        tasks.low_rebuild.delay = Mock(return_value=None)
        response = self.client.post(self.rebuild_url_addons, {
            'sdk_version': 'test_version',
            'addons': simplejson.dumps([
                {'package_key': 1},
                {'package_key': 2}]),
            'secret': settings.AMO_SECRET_KEY})

        eq_(response.status_code, 200)
        content = simplejson.loads(response.content)
        eq_(content['status'], 'success')
        eq_(tasks.low_rebuild.delay.call_count, 2)
        # is callback to the right test provided?
        assert 'callback' in tasks.low_rebuild.delay.call_args[1]
        # is sdk version provided?
        eq_('test_version', tasks.low_rebuild.delay.call_args[0][2])


text:
<?php

use Kisma\Core\Utility\Log;

/**
 * bootstrap.php
 * Bootstrap script for PHPUnit tests
 */
$_basePath = dirname( __DIR__ );

//	Composer
$_autoloader = require( $_basePath . '/vendor/autoload.php' );

//	Load up Yii
require_once $_basePath . '/vendor/dreamfactory/yii/framework/yii.php';

//	Yii debug settings
defined( 'YII_DEBUG' ) or define( 'YII_DEBUG', true );
defined( 'YII_TRACE_LEVEL' ) or define( 'YII_TRACE_LEVEL', 3 );

$_config = require( __DIR__ . '/config/plugin.config.php' );

//	Testing keys
if ( file_exists( __DIR__ . '/config/keys.php' ) )
{
	/** @noinspection PhpIncludeInspection */
	require_once __DIR__ . '/config/keys.php';
}

Log::setDefaultLog( __DIR__ . '/log/portal-sandbox.tests.log' );

//	Create the application but don't run (false at the end)
$_app = DreamFactory\Yii\Utility\Pii::run(
	__DIR__,
	$_autoloader,
	'DreamFactory\\Platform\\Yii\\Components\\PlatformConsoleApplication',
	$_config,
	false
);


text:
var path = require('path');

var accessoryLoader = require('hap-nodejs/lib/AccessoryLoader');

// Load up all accessories in the /accessories folder
var dir = path.join(__dirname, '../accessories');
var accessories = accessoryLoader.loadDirectory(dir);

// Publish them all separately (as opposed to BridgedCore which publishes them behind a single Bridge accessory)
accessories.forEach(function(accessory) {

    // To push Accessories separately, we'll need a few extra properties
    if (!accessory.username)
        throw new Error('Username not found on accessory "' + accessory.displayName + '". Core.js requires all accessories to define a unique "username" property.');

    if (!accessory.pincode)
        throw new Error('Pincode not found on accessory "' + accessory.displayName + '". Core.js requires all accessories to define a "pincode" property.');
});

module.exports = {
    accessories: accessories
}


text:
<?php
require 'class/Crawler.php';
require 'class/Utils.php';

$crawler = new Crawler;
$crawler->run();


text:
package util;

import java.util.Arrays;
import java.util.Optional;

import org.junit.Assert;
import org.junit.Test;

import net.imglib2.FinalInterval;
import net.imglib2.Interval;
import net.imglib2.RealPoint;
import net.imglib2.util.Intervals;

public class TestFieldOfViewUtil
{
	public static Optional<double[]> noDouble = Optional.empty();
	public static Optional<double[]> ones = Optional.of( new double[]{1,1});

	public static Optional<long[]> noLong = Optional.empty();
	public static Optional<Interval> noInterval = Optional.empty();
	public static Optional empty = Optional.empty();

	@Test
	public void testEmpty()
	{
		int nd = 2;
		FieldOfView fov = new FieldOfView( nd );
		Assert.assertNull( "return null for no parameters",
				fov.parse( nd, empty, empty,  empty,  empty, empty  ));

		Assert.assertNull( "return false for inadequate parameters",
				fov.parse( nd, empty, ones, empty, empty, ones ));
	}

	@Test
	public void testBasic()
	{
		final double delta = 1e-9;

		final double[] zero = new double[] { 0 };
		final double[] minA = new double[] { -1.0 };
		final double[] minB = new double[] { 2.0 };

		final long[] dimsA = new long[] { 5 };
		final long[] dimsB = new long[] { 10 };

		final double[] spacingA = new double[] { 1.0 };
		final double[] spacingB = new double[] { 0.5 };

		final FieldOfView fovA = new FieldOfView( minA, spacingA, dimsA );
		Assert.assertEquals( "fovA physical width", 5.0, fovA.getPhysicalWidth()[0], delta );
		Assert.assertEquals( "fovA physical min", -1, fovA.getPhysicalMin()[0], delta );
		Assert.assertEquals( "fovA physical max", 4, fovA.getPhysicalMax()[0], delta );

		final FieldOfView fovB = new FieldOfView( minB, spacingB, dimsB );
		Assert.assertEquals( "fovB physical width", 5.0, fovB.getPhysicalWidth()[0], delta );
		Assert.assertEquals( "fovB physical min", 2, fovB.getPhysicalMin()[0], delta );
		Assert.assertEquals( "fovB physical max", 7, fovB.getPhysicalMax()[0], delta );
	}

	@Test
	public void testPixelSpacing()
	{
		FieldOfView fov = FieldOfView.fromSpacingSize( new double[]{ 1.0, 1.0 }, new FinalInterval( new long[]{ 10, 10 }));
		Assert.assertArrayEquals( "pixel and spacing only simple", new double[]{ 10, 10 }, fov.getPhysicalWidth(), 1e-6 );
	}

	@Test
	public void testPhysicalPixel()
	{
		FieldOfView fov = FieldOfView.fromPhysicalPixel( new double[]{ 9.0, 9.0 }, new FinalInterval( new long[]{ 10, 10 }));
		Assert.assertArrayEquals( "from physical pixel. simple", new double[]{ 1, 1 }, fov.getSpacing(), 1e-6 );

		fov = FieldOfView.fromPhysicalPixel( new double[]{ -3, -3 }, new double[]{ 3.0, 3.0 }, new FinalInterval( new long[]{ 7, 7 }));
		Assert.assertArrayEquals( "from physical pixel. less simple", new double[]{ 1.0, 1.0 }, fov.getSpacing(), 1e-6 );

		fov = FieldOfView.fromPhysicalPixel( new double[]{ -3, -3 }, new double[]{ 3.0, 3.0 }, new FinalInterval( new long[]{ 13, 13 }));
		Assert.assertArrayEquals( "from physical pixel. even less simple", new double[]{ 0.5, 0.5 }, fov.getSpacing(), 1e-6 );
	}

	@Test
	public void testSubsetAndPinning()
	{
		double eps = 1e-6;

		double[] origMin = new double[]{ -10.0, -10.0 };
		double[] origMax = new double[]{  10.0,  10.0 };
		long[] origPixWidth = new long[]{ 21, 21 };

		double[] newSpacing = new double[]{ 1.5, 1.5 };

		double[] originA = new double[]{ 0.0, 0.0 };
		RealPoint originP = RealPoint.wrap( originA );

		double[] testA = new double[]{ 1.2, 1.2 };
		RealPoint testP = RealPoint.wrap( testA );

		FieldOfView fov = FieldOfView.fromPhysicalPixel( origMin, origMax, new FinalInterval( origPixWidth ));

		Assert.assertTrue( "origin on original grid", fov.onGrid( originP, eps ));
		Assert.assertFalse( "test not on original grid", fov.onGrid( testP, eps ));

		FieldOfView fovsubmin = fov.copy();
		fovsubmin.setSpacing( newSpacing );
		fovsubmin.updatePhysicalPinMin();

		FieldOfView fovsubmax = fov.copy();
		fovsubmax.setSpacing( newSpacing );
		fovsubmax.updatePhysicalPinMax();

		FieldOfView fovsubcenter = fov.copy();
		fovsubcenter.setSpacing( newSpacing );
		fovsubcenter.updatePhysicalPinCenter();

		System.out.println("fov: " + fov );
		System.out.println("fovsubmin: " + fovsubmin );
		System.out.println("fovsubmax: " + fovsubmax );
		System.out.println("fovsubcenter: " + fovsubcenter );

//		FieldOfView fovsub = fovsubcenter;
//		System.out.println("  fov phy w: " + Arrays.toString( fov.getPhysicalWidth() ));
//		System.out.println("  fov pix w: " + Arrays.toString( fov.getPhysicalWidthFromPixelSpacing() ));
//		System.out.println(" ");
//		System.out.println("  fovsub phy w: " + Arrays.toString( fovsub.getPhysicalWidth() ));
//		System.out.println("  fov pix w: " + Arrays.toString( fov.getPhysicalWidthFromPixelSpacing() ));
//		System.out.println(" ");

		Assert.assertArrayEquals( "check pinned min", origMin, Intervals.minAsDoubleArray( fovsubmin.getPhysical() ), 1e-6 );
		Assert.assertArrayEquals( "check pinned max", origMax, Intervals.maxAsDoubleArray( fovsubmax.getPhysical() ), 1e-6 );
	}

}


text:
class SessionsController < ApplicationController

  skip_before_filter :login_required, :only => [:new, :create]

  def new
  end

  def create
    user = User.authenticate(params[:session][:login],
                             params[:session][:password])

    respond_to do |format|
      if user
        format.html do
          reset_session
          session[:user_id] = user.id
          redirect_back_or_default root_url
        end
        format.any(:xml, :json) { head :ok }
      else
        format.html do
          flash.now[:error] = "Invalid login or password."
          render :action => :new
        end
        format.any(:xml, :json) { request_http_basic_authentication 'Web Password' }
      end
    end
  end

  def destroy
    session[:user_id] = nil
    flash[:notice] = "You've been logged out."
    redirect_to root_url
  end

end


text:
import atexit
from collections import deque
from functools import partial
import logging
import os
import socket
import sys
from threading import Lock, Thread, Event
import time
import weakref
import sys
import ssl

from six.moves import range

try:
    from weakref import WeakSet
except ImportError:
    from cassandra.util import WeakSet  # noqa

import asyncore

from cassandra.connection import Connection, ConnectionShutdown, NONBLOCKING, Timer, TimerManager

log = logging.getLogger(__name__)

_dispatcher_map = {}

def _cleanup(loop):
    if loop:
        loop._cleanup()

class WaitableTimer(Timer):
    def __init__(self, timeout, callback):
        Timer.__init__(self, timeout, callback)
        self.callback = callback
        self.event = Event()

        self.final_exception = None

    def finish(self, time_now):
        try:
            finished = Timer.finish(self, time_now)
            if finished:
                self.event.set()
                return True
            return False

        except Exception as e:
            self.final_exception = e
            self.event.set()
            return True

    def wait(self, timeout=None):
        self.event.wait(timeout)
        if self.final_exception:
            raise self.final_exception

class _PipeWrapper(object):

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

    def fileno(self):
        return self.fd

    def close(self):
        os.close(self.fd)

    def getsockopt(self, level, optname, buflen=None):
        # act like an unerrored socket for the asyncore error handling
        if level == socket.SOL_SOCKET and optname == socket.SO_ERROR and not buflen:
            return 0
        raise NotImplementedError()

class _AsyncoreDispatcher(asyncore.dispatcher):

    def __init__(self, socket):
        asyncore.dispatcher.__init__(self, map=_dispatcher_map)
        # inject after to avoid base class validation
        self.set_socket(socket)
        self._notified = False

    def writable(self):
        return False

    def validate(self):
        assert not self._notified
        self.notify_loop()
        assert self._notified
        self.loop(0.1)
        assert not self._notified

    def loop(self, timeout):
        asyncore.loop(timeout=timeout, use_poll=True, map=_dispatcher_map, count=1)

class _AsyncorePipeDispatcher(_AsyncoreDispatcher):

    def __init__(self):
        self.read_fd, self.write_fd = os.pipe()
        _AsyncoreDispatcher.__init__(self, _PipeWrapper(self.read_fd))

    def writable(self):
        return False

    def handle_read(self):
        while len(os.read(self.read_fd, 4096)) == 4096:
            pass
        self._notified = False

    def notify_loop(self):
        if not self._notified:
            self._notified = True
            os.write(self.write_fd, b'x')

class _AsyncoreUDPDispatcher(_AsyncoreDispatcher):
    """
    Experimental alternate dispatcher for avoiding busy wait in the asyncore loop. It is not used by default because
    it relies on local port binding.
    Port scanning is not implemented, so multiple clients on one host will collide. This address would need to be set per
    instance, or this could be specialized to scan until an address is found.

    To use::

        from cassandra.io.asyncorereactor import _AsyncoreUDPDispatcher, AsyncoreLoop
        AsyncoreLoop._loop_dispatch_class = _AsyncoreUDPDispatcher

    """
    bind_address = ('localhost', 10000)

    def __init__(self):
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self._socket.bind(self.bind_address)
        self._socket.setblocking(0)
        _AsyncoreDispatcher.__init__(self, self._socket)

    def handle_read(self):
        try:
            d = self._socket.recvfrom(1)
            while d and d[1]:
                d = self._socket.recvfrom(1)
        except socket.error as e:
            pass
        self._notified = False

    def notify_loop(self):
        if not self._notified:
            self._notified = True
            self._socket.sendto(b'', self.bind_address)

    def loop(self, timeout):
        asyncore.loop(timeout=timeout, use_poll=False, map=_dispatcher_map, count=1)

class _BusyWaitDispatcher(object):

    max_write_latency = 0.001
    """
    Timeout pushed down to asyncore select/poll. Dictates the amount of time it will sleep before coming back to check
    if anything is writable.
    """

    def notify_loop(self):
        pass

    def loop(self, timeout):
        if not _dispatcher_map:
            time.sleep(0.005)
        count = timeout // self.max_write_latency
        asyncore.loop(timeout=self.max_write_latency, use_poll=True, map=_dispatcher_map, count=count)

    def validate(self):
        pass

    def close(self):
        pass

class AsyncoreLoop(object):

    timer_resolution = 0.1  # used as the max interval to be in the io loop before returning to service timeouts

    _loop_dispatch_class = _AsyncorePipeDispatcher if os.name != 'nt' else _BusyWaitDispatcher

    def __init__(self):
        self._pid = os.getpid()
        self._loop_lock = Lock()
        self._started = False
        self._shutdown = False

        self._thread = None

        self._timers = TimerManager()

        try:
            dispatcher = self._loop_dispatch_class()
            dispatcher.validate()
            log.debug("Validated loop dispatch with %s", self._loop_dispatch_class)
        except Exception:
            log.exception("Failed validating loop dispatch with %s. Using busy wait execution instead.", self._loop_dispatch_class)
            dispatcher.close()
            dispatcher = _BusyWaitDispatcher()
        self._loop_dispatcher = dispatcher

    def maybe_start(self):
        should_start = False
        did_acquire = False
        try:
            did_acquire = self._loop_lock.acquire(False)
            if did_acquire and not self._started:
                self._started = True
                should_start = True
        finally:
            if did_acquire:
                self._loop_lock.release()

        if should_start:
            self._thread = Thread(target=self._run_loop, name="asyncore_cassandra_driver_event_loop")
            self._thread.daemon = True
            self._thread.start()

    def wake_loop(self):
        self._loop_dispatcher.notify_loop()

    def _run_loop(self):
        log.debug("Starting asyncore event loop")
        with self._loop_lock:
            while not self._shutdown:
                try:
                    self._loop_dispatcher.loop(self.timer_resolution)
                    self._timers.service_timeouts()
                except Exception:
                    try:
                        log.debug("Asyncore event loop stopped unexpectedly", exc_info=True)
                    except Exception:
                        # TODO: Remove when Python 2 support is removed
                        # PYTHON-1266. If our logger has disappeared, there's nothing we
                        # can do, so just log nothing.
                        pass
                    break
            self._started = False

        log.debug("Asyncore event loop ended")

    def add_timer(self, timer):
        self._timers.add_timer(timer)

        # This function is called from a different thread than the event loop
        # thread, so for this call to be thread safe, we must wake up the loop
        # in case it's stuck at a select
        self.wake_loop()

    def _cleanup(self):
        global _dispatcher_map

        self._shutdown = True
        if not self._thread:
            return

        log.debug("Waiting for event loop thread to join...")
        self._thread.join(timeout=1.0)
        if self._thread.is_alive():
            log.warning(
                "Event loop thread could not be joined, so shutdown may not be clean. "
                "Please call Cluster.shutdown() to avoid this.")

        log.debug("Event loop thread was joined")

        # Ensure all connections are closed and in-flight requests cancelled
        for conn in tuple(_dispatcher_map.values()):
            if conn is not self._loop_dispatcher:
                conn.close()
        self._timers.service_timeouts()
        # Once all the connections are closed, close the dispatcher
        self._loop_dispatcher.close()

        log.debug("Dispatchers were closed")

_global_loop = None
atexit.register(partial(_cleanup, _global_loop))

class AsyncoreConnection(Connection, asyncore.dispatcher):
    """
    An implementation of :class:`.Connection` that uses the ``asyncore``
    module in the Python standard library for its event loop.
    """

    _writable = False
    _readable = False

    @classmethod
    def initialize_reactor(cls):
        global _global_loop
        if not _global_loop:
            _global_loop = AsyncoreLoop()
        else:
            current_pid = os.getpid()
            if _global_loop._pid != current_pid:
                log.debug("Detected fork, clearing and reinitializing reactor state")
                cls.handle_fork()
                _global_loop = AsyncoreLoop()

    @classmethod
    def handle_fork(cls):
        global _dispatcher_map, _global_loop
        _dispatcher_map = {}
        if _global_loop:
            _global_loop._cleanup()
            _global_loop = None

    @classmethod
    def create_timer(cls, timeout, callback):
        timer = Timer(timeout, callback)
        _global_loop.add_timer(timer)
        return timer

    def __init__(self, *args, **kwargs):
        Connection.__init__(self, *args, **kwargs)

        self.deque = deque()
        self.deque_lock = Lock()

        self._connect_socket()

        # start the event loop if needed
        _global_loop.maybe_start()

        init_handler = WaitableTimer(
            timeout=0,
            callback=partial(asyncore.dispatcher.__init__,
                             self, self._socket, _dispatcher_map)
        )
        _global_loop.add_timer(init_handler)
        init_handler.wait(kwargs["connect_timeout"])

        self._writable = True
        self._readable = True

        self._send_options_message()

    def close(self):
        with self.lock:
            if self.is_closed:
                return
            self.is_closed = True

        log.debug("Closing connection (%s) to %s", id(self), self.endpoint)
        self._writable = False
        self._readable = False

        # We don't have to wait for this to be closed, we can just schedule it
        self.create_timer(0, partial(asyncore.dispatcher.close, self))

        log.debug("Closed socket to %s", self.endpoint)

        if not self.is_defunct:
            self.error_all_requests(
                ConnectionShutdown("Connection to %s was closed" % self.endpoint))

            #This happens when the connection is shutdown while waiting for the ReadyMessage
            if not self.connected_event.is_set():
                self.last_error = ConnectionShutdown("Connection to %s was closed" % self.endpoint)

            # don't leave in-progress operations hanging
            self.connected_event.set()

    def handle_error(self):
        self.defunct(sys.exc_info()[1])

    def handle_close(self):
        log.debug("Connection %s closed by server", self)
        self.close()

    def handle_write(self):
        while True:
            with self.deque_lock:
                try:
                    next_msg = self.deque.popleft()
                except IndexError:
                    self._writable = False
                    return

            try:
                sent = self.send(next_msg)
                self._readable = True
            except socket.error as err:
                if (err.args[0] in NONBLOCKING or
                        err.args[0] in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE)):
                    with self.deque_lock:
                        self.deque.appendleft(next_msg)
                else:
                    self.defunct(err)
                return
            else:
                if sent < len(next_msg):
                    with self.deque_lock:
                        self.deque.appendleft(next_msg[sent:])
                    if sent == 0:
                        return

    def handle_read(self):
        try:
            while True:
                buf = self.recv(self.in_buffer_size)
                self._iobuf.write(buf)
                if len(buf) < self.in_buffer_size:
                    break
        except socket.error as err:
            if isinstance(err, ssl.SSLError):
                if err.args[0] in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE):
                    if not self._iobuf.tell():
                        return
                else:
                    self.defunct(err)
                    return
            elif err.args[0] in NONBLOCKING:
                if not self._iobuf.tell():
                    return
            else:
                self.defunct(err)
                return

        if self._iobuf.tell():
            self.process_io_buffer()
            if not self._requests and not self.is_control_connection:
                self._readable = False

    def push(self, data):
        sabs = self.out_buffer_size
        if len(data) > sabs:
            chunks = []
            for i in range(0, len(data), sabs):
                chunks.append(data[i:i + sabs])
        else:
            chunks = [data]

        with self.deque_lock:
            self.deque.extend(chunks)
            self._writable = True
        _global_loop.wake_loop()

    def writable(self):
        return self._writable

    def readable(self):
        return self._readable or ((self.is_control_connection or self._continuous_paging_sessions) and not (self.is_defunct or self.is_closed))


text:
package rollout

import (
	"fmt"
	"io"

	"k8s.io/kubernetes/pkg/kubectl"
	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	"k8s.io/kubernetes/pkg/kubectl/resource"
	"k8s.io/kubernetes/pkg/util/errors"

	"github.com/spf13/cobra"
)

// HistoryOptions is the start of the data required to perform the operation.  As new fields are added, add them here instead of
// referencing the cmd.Flags()
type HistoryOptions struct {
	Filenames []string
}

const (
	history_long    = `view previous rollout revisions and configurations.`
	history_example = `# View the rollout history of a deployment
kubectl rollout history deployment/abc`
)

func NewCmdRolloutHistory(f *cmdutil.Factory, out io.Writer) *cobra.Command {
	options := &HistoryOptions{}

	cmd := &cobra.Command{
		Use:     "history (TYPE NAME | TYPE/NAME) [flags]",
		Short:   "view rollout history",
		Long:    history_long,
		Example: history_example,
		Run: func(cmd *cobra.Command, args []string) {
			cmdutil.CheckErr(RunHistory(f, cmd, out, args, options))
		},
	}

	cmd.Flags().Int64("revision", 0, "See the details, including podTemplate of the revision specified")
	usage := "Filename, directory, or URL to a file identifying the resource to get from a server."
	kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage)
	return cmd
}

func RunHistory(f *cmdutil.Factory, cmd *cobra.Command, out io.Writer, args []string, options *HistoryOptions) error {
	if len(args) == 0 && len(options.Filenames) == 0 {
		return cmdutil.UsageError(cmd, "Required resource not specified.")
	}
	revisionDetail := cmdutil.GetFlagInt64(cmd, "revision")

	mapper, typer := f.Object()

	cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
	if err != nil {
		return err
	}

	infos, err := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
		NamespaceParam(cmdNamespace).DefaultNamespace().
		FilenameParam(enforceNamespace, options.Filenames...).
		ResourceTypeOrNameArgs(true, args...).
		Latest().
		Flatten().
		Do().
		Infos()
	if err != nil {
		return err
	}

	errs := []error{}
	for _, info := range infos {
		mapping := info.ResourceMapping()
		historyViewer, err := f.HistoryViewer(mapping)
		if err != nil {
			errs = append(errs, err)
			continue
		}
		historyInfo, err := historyViewer.History(info.Namespace, info.Name)
		if err != nil {
			errs = append(errs, err)
			continue
		}

		if revisionDetail > 0 {
			// Print details of a specific revision
			template, ok := historyInfo.RevisionToTemplate[revisionDetail]
			if !ok {
				return fmt.Errorf("unable to find revision %d of %s %q", revisionDetail, mapping.Resource, info.Name)
			}
			fmt.Fprintf(out, "%s %q revision %d\n", mapping.Resource, info.Name, revisionDetail)
			kubectl.DescribePodTemplate(template, out)
		} else {
			// Print all revisions
			formattedOutput, printErr := kubectl.PrintRolloutHistory(historyInfo, mapping.Resource, info.Name)
			if printErr != nil {
				errs = append(errs, printErr)
				continue
			}
			fmt.Fprintf(out, "%s\n", formattedOutput)
		}
	}

	return errors.NewAggregate(errs)
}


text:
using io::indent;
using io::popindent;
using io::quote;

void emit_api_body_cu(std::ostream& out, APIMethod* method, bool is_point_proc, bool cv_loop = true, bool ppack=true);
void emit_procedure_body_cu(std::ostream& out, ProcedureExpression* proc);
void emit_state_read_cu(std::ostream& out, LocalVariable* local);
void emit_state_update_cu(std::ostream& out, Symbol* from, IndexedVariable* external, bool is_point_proc);

const char* index_id(Symbol *s);

struct cuprint {
    Expression* expr_;
    explicit cuprint(Expression* expr): expr_(expr) {}

    friend std::ostream& operator<<(std::ostream& out, const cuprint& w) {
        GpuPrinter printer(out);
        return w.expr_->accept(&printer), out;
    }
};

static std::string make_class_name(const std::string& n) { return "mechanism_" + n + "_gpu";}
static std::string make_ppack_name(const std::string& module_name) { return make_class_name(module_name)+"_pp_"; }
static std::string ion_field(const IonDep& ion) { return fmt::format("ion_{}",       ion.name); }
static std::string ion_index(const IonDep& ion) { return fmt::format("ion_{}_index", ion.name); }

ARB_LIBMODCC_API std::string emit_gpu_cpp_source(const Module& module_, const printer_options& opt) {
    std::string name       = module_.module_name();
    std::string class_name = make_class_name(name);
    std::string ppack_name = make_ppack_name(name);
    auto ns_components     = namespace_components(opt.cpp_namespace);
    auto vars = local_module_variables(module_);
    auto ion_deps = module_.ion_deps();

    io::pfxstringstream out;

    out << "#include <arbor/mechanism_abi.h>\n"
        << "#include <cmath>\n\n"
        << namespace_declaration_open(ns_components)
        << fmt::format("void {0}_init_(arb_mechanism_ppack*);\n"
                       "void {0}_advance_state_(arb_mechanism_ppack*);\n"
                       "void {0}_compute_currents_(arb_mechanism_ppack*);\n"
                       "void {0}_write_ions_(arb_mechanism_ppack*);\n"
                       "void {0}_apply_events_(arb_mechanism_ppack*, arb_deliverable_event_stream*);\n"
                       "void {0}_post_event_(arb_mechanism_ppack*);\n\n",
                       class_name)
        << namespace_declaration_close(ns_components)
        << "\n";

    std::stringstream ss;
    for (const auto& c: ns_components) ss << c <<"::";

    out << fmt::format(FMT_COMPILE("extern \"C\" {{\n"
                                   "  arb_mechanism_interface* make_{4}_{1}_interface_gpu() {{\n"
                                   "    static arb_mechanism_interface result;\n"
                                   "    result.backend={2};\n"
                                   "    result.partition_width=1;\n"
                                   "    result.alignment=1;\n"
                                   "    result.init_mechanism={3}{0}_init_;\n"
                                   "    result.compute_currents={3}{0}_compute_currents_;\n"
                                   "    result.apply_events={3}{0}_apply_events_;\n"
                                   "    result.advance_state={3}{0}_advance_state_;\n"
                                   "    result.write_ions={3}{0}_write_ions_;\n"
                                   "    result.post_event={3}{0}_post_event_;\n"
                                   "    return &result;\n"
                                   "  }}\n"
                                   "}};\n\n"),
                       class_name,
                       name,
                       "arb_backend_kind_gpu",
                       ss.str(),
                       std::regex_replace(opt.cpp_namespace, std::regex{"::"}, "_"));
    EXIT(out);
    return out.str();
}

ARB_LIBMODCC_API std::string emit_gpu_cu_source(const Module& module_, const printer_options& opt) {
    std::string name = module_.module_name();
    std::string class_name = make_class_name(name);

    auto ns_components = namespace_components(opt.cpp_namespace);

    const bool is_point_proc = (module_.kind() == moduleKind::point) || (module_.kind() == moduleKind::junction);

    APIMethod* net_receive_api = find_api_method(module_, "net_rec_api");
    APIMethod* post_event_api  = find_api_method(module_, "post_event_api");
    APIMethod* init_api        = find_api_method(module_, "init");
    APIMethod* state_api       = find_api_method(module_, "advance_state");
    APIMethod* current_api     = find_api_method(module_, "compute_currents");
    APIMethod* write_ions_api  = find_api_method(module_, "write_ions");

    assert_has_scope(init_api,    "init");
    assert_has_scope(state_api,   "advance_state");
    assert_has_scope(current_api, "compute_currents");

    io::pfxstringstream out;

    auto vars = local_module_variables(module_);

    out << "#include <arbor/gpu/gpu_common.hpp>\n"
           "#include <arbor/gpu/math_cu.hpp>\n"
           "#include <arbor/gpu/reduce_by_key.hpp>\n"
           "#include <arbor/mechanism_abi.h>\n";

    out << "\n" << namespace_declaration_open(ns_components) << "\n";

    out << fmt::format(FMT_COMPILE("#define PPACK_IFACE_BLOCK \\\n"
                                   "auto  {0}width             __attribute__((unused)) = params_.width;\\\n"
                                   "auto  {0}n_detectors       __attribute__((unused)) = params_.n_detectors;\\\n"
                                   "auto* {0}vec_ci            __attribute__((unused)) = params_.vec_ci;\\\n"
                                   "auto* {0}vec_di            __attribute__((unused)) = params_.vec_di;\\\n"
                                   "auto* {0}vec_t             __attribute__((unused)) = params_.vec_t;\\\n"
                                   "auto* {0}vec_dt            __attribute__((unused)) = params_.vec_dt;\\\n"
                                   "auto* {0}vec_v             __attribute__((unused)) = params_.vec_v;\\\n"
                                   "auto* {0}vec_i             __attribute__((unused)) = params_.vec_i;\\\n"
                                   "auto* {0}vec_g             __attribute__((unused)) = params_.vec_g;\\\n"
                                   "auto* {0}temperature_degC  __attribute__((unused)) = params_.temperature_degC;\\\n"
                                   "auto* {0}diam_um           __attribute__((unused)) = params_.diam_um;\\\n"
                                   "auto* {0}time_since_spike  __attribute__((unused)) = params_.time_since_spike;\\\n"
                                   "auto* {0}node_index        __attribute__((unused)) = params_.node_index;\\\n"
                                   "auto* {0}peer_index        __attribute__((unused)) = params_.peer_index;\\\n"
                                   "auto* {0}multiplicity      __attribute__((unused)) = params_.multiplicity;\\\n"
                                   "auto* {0}state_vars        __attribute__((unused)) = params_.state_vars;\\\n"
                                   "auto* {0}weight            __attribute__((unused)) = params_.weight;\\\n"
                                   "auto& {0}events            __attribute__((unused)) = params_.events;\\\n"
                                   "auto& {0}mechanism_id      __attribute__((unused)) = params_.mechanism_id;\\\n"
                                   "auto& {0}index_constraints __attribute__((unused)) = params_.index_constraints;\\\n"),
                       pp_var_pfx);

    const auto& [state_ids, global_ids, param_ids] = public_variable_ids(module_);
    const auto& assigned_ids = module_.assigned_block().parameters;

    auto global = 0;
    for (const auto& scalar: global_ids) {
        out << fmt::format("auto {}{} __attribute__((unused)) = params_.globals[{}];\\\n", pp_var_pfx, scalar.name(), global);
        global++;
    }
    auto param = 0, state = 0;
    for (const auto& array: state_ids) {
        out << fmt::format("auto* {}{} __attribute__((unused)) = params_.state_vars[{}];\\\n", pp_var_pfx, array.name(), state);
        state++;
    }
    for (const auto& array: assigned_ids) {
        out << fmt::format("auto* {}{} __attribute__((unused)) = params_.state_vars[{}];\\\n", pp_var_pfx, array.name(), state);
        state++;
    }
    for (const auto& array: param_ids) {
        out << fmt::format("auto* {}{} __attribute__((unused)) = params_.parameters[{}];\\\n", pp_var_pfx, array.name(), param);
        param++;
    }
    auto idx = 0;
    for (const auto& ion: module_.ion_deps()) {
        out << fmt::format("auto& {}{} __attribute__((unused)) = params_.ion_states[{}];\\\n",       pp_var_pfx, ion_field(ion), idx);
        out << fmt::format("auto* {}{} __attribute__((unused)) = params_.ion_states[{}].index;\\\n", pp_var_pfx, ion_index(ion), idx);
        idx++;
    }
    out << "//End of IFACEBLOCK\n\n";

    // Print the CUDA code and kernels:
    //  - first __device__ functions that implement NMODL PROCEDUREs.
    //  - then __global__ kernels that implement API methods and call the procedures.

    out << "namespace {\n\n" // place inside an anonymous namespace
        << "using ::arb::gpu::exprelr;\n"
        << "using ::arb::gpu::safeinv;\n"
        << "using ::arb::gpu::min;\n"
        << "using ::arb::gpu::max;\n\n";

    // Procedures as __device__ functions.
    auto emit_procedure_proto = [&] (ProcedureExpression* e) {
        out << fmt::format("__device__\n"
                           "void {}(arb_mechanism_ppack params_, int tid_",
                           e->name());
        for(auto& arg: e->args()) out << ", arb_value_type " << arg->is_argument()->name();
        out << ")";
    };

    auto emit_procedure_kernel = [&] (ProcedureExpression* e) {
        emit_procedure_proto(e);
        out << " {\n" << indent
            << "PPACK_IFACE_BLOCK;\n"
            << cuprint(e->body())
            << popindent << "}\n\n";
    };

    for (auto& p: module_normal_procedures(module_)) {
        emit_procedure_proto(p);
        out << ";\n\n";
    }

    for (auto& p: module_normal_procedures(module_)) {
        emit_procedure_kernel(p);
    }

    // API methods as __global__ kernels.
    auto emit_api_kernel = [&] (APIMethod* e) {
        // Only print the kernel if the method is not empty.
        if (!e->body()->statements().empty()) {
            out << "__global__\n"
                << "void " << e->name() << "(arb_mechanism_ppack params_) {\n" << indent
                << "int n_ = params_.width;\n"
                << "int tid_ = threadIdx.x + blockDim.x*blockIdx.x;\n";
            emit_api_body_cu(out, e, is_point_proc);
            out << popindent << "}\n\n";
        }
    };

    emit_api_kernel(init_api);
    if (init_api && !init_api->body()->statements().empty()) {
        out << fmt::format(FMT_COMPILE("__global__\n"
                                       "void multiply(arb_mechanism_ppack params_) {{\n"
                                       "    PPACK_IFACE_BLOCK;\n"
                                       "    auto tid_ = threadIdx.x + blockDim.x*blockIdx.x;\n"
                                       "    auto idx_ = blockIdx.y;"
                                       "    if(tid_<{0}width) {{\n"
                                       "        {0}state_vars[idx_][tid_] *= {0}multiplicity[tid_];\n"
                                       "    }}\n"
                                       "}}\n\n"),
                           pp_var_pfx);
    }
    emit_api_kernel(state_api);
    emit_api_kernel(current_api);
    emit_api_kernel(write_ions_api);

    // event delivery
    if (net_receive_api) {
        out << fmt::format(FMT_COMPILE("__global__\n"
                                       "void apply_events(arb_mechanism_ppack params_, arb_deliverable_event_stream stream) {{\n"
                                       "    PPACK_IFACE_BLOCK;\n"
                                       "    auto tid_ = threadIdx.x + blockDim.x*blockIdx.x;\n"
                                       "    if(tid_<stream.n_streams) {{\n"
                                       "        auto begin = stream.events + stream.begin[tid_];\n"
                                       "        auto end   = stream.events + stream.end[tid_];\n"
                                       "        for (auto p = begin; p<end; ++p) {{\n"
                                       "            if (p->mech_id=={1}mechanism_id) {{\n"
                                       "                auto tid_ = p->mech_index;\n"
                                       "                auto {0} = p->weight;\n"),
                           net_receive_api->args().empty() ? "weight" : net_receive_api->args().front()->is_argument()->name(),
                           pp_var_pfx);
        out << indent << indent << indent << indent;
        emit_api_body_cu(out, net_receive_api, is_point_proc, false, false);
        out << popindent << "}\n" << popindent << "}\n" << popindent << "}\n" << popindent << "}\n";
    }

    // event delivery
    if (post_event_api) {
        const std::string time_arg = post_event_api->args().empty() ? "time" : post_event_api->args().front()->is_argument()->name();
        out << fmt::format(FMT_COMPILE("__global__\n"
                                       "void post_event(arb_mechanism_ppack params_) {{\n"
                                       "    PPACK_IFACE_BLOCK;\n"
                                       "    auto tid_ = threadIdx.x + blockDim.x*blockIdx.x;\n"
                                       "    if (tid_<{1}width) {{\n"
                                       "        auto node_index_i_ = {1}node_index[tid_];\n"
                                       "        auto cid_ = {1}vec_ci[node_index_i_];\n"
                                       "        auto offset_ = {1}n_detectors * cid_;\n"
                                       "        for (unsigned c = 0; c < {1}n_detectors; c++) {{\n"
                                       "            auto {0} = {1}time_since_spike[offset_ + c];\n"
                                       "            if ({0} >= 0) {{\n"),
                           time_arg,
                           pp_var_pfx);
        out << indent << indent << indent << indent;
        emit_api_body_cu(out, post_event_api, is_point_proc, false, false);
        out << popindent << "}\n" << popindent << "}\n" << popindent << "}\n" << popindent << "}\n";
    }

    out << "} // namespace\n\n"; // close anonymous namespace

    // Write wrappers.
    auto emit_api_wrapper = [&] (APIMethod* e, const auto& width, std::string_view name="") {
        auto api_name = name.empty() ? e->name() : name;
        out << fmt::format(FMT_COMPILE("void {}_{}_(arb_mechanism_ppack* p) {{"), class_name, api_name);
        if(!e->body()->statements().empty()) {
            out << fmt::format(FMT_COMPILE("\n"
                                           "    auto n = p->{};\n"
                                           "    unsigned block_dim = 128;\n"
                                           "    unsigned grid_dim = ::arb::gpu::impl::block_count(n, block_dim);\n"
                                           "    {}<<<grid_dim, block_dim>>>(*p);\n"),
                               width,
                               api_name);
        }
        out << "}\n\n";
    };

    auto emit_empty_wrapper = [&] (std::string_view name) {
        out << fmt::format(FMT_COMPILE("void {}_{}_(arb_mechanism_ppack* p) {{}}\n"), class_name, name);
    };

    {
        auto api_name = init_api->name();
        auto n = std::count_if(vars.arrays.begin(), vars.arrays.end(),
                               [] (const auto& v) { return v->is_state(); });

        out << fmt::format(FMT_COMPILE("void {}_{}_(arb_mechanism_ppack* p) {{"), class_name, api_name);
        if(!init_api->body()->statements().empty()) {
            out << fmt::format(FMT_COMPILE("\n"
                                           "    auto n = p->{0};\n"
                                           "    unsigned block_dim = 128;\n"
                                           "    unsigned grid_dim = ::arb::gpu::impl::block_count(n, block_dim);\n"
                                           "    {1}<<<grid_dim, block_dim>>>(*p);\n"
                                           "    if (!p->multiplicity) return;\n"
                                           "    multiply<<<dim3{{grid_dim, {2}}}, block_dim>>>(*p);\n"),
                               "width",
                               api_name,
                               n);
        }
        out << "}\n\n";
    }

    emit_api_wrapper(current_api,     "width");
    emit_api_wrapper(state_api,       "width");
    emit_api_wrapper(write_ions_api,  "width");
    if (post_event_api) {
        emit_api_wrapper(post_event_api, "width", "post_event");
    } else {
        emit_empty_wrapper("post_event");
    }
    if (net_receive_api) {
        auto api_name = "apply_events";
        out << fmt::format(FMT_COMPILE("void {}_{}_(arb_mechanism_ppack* p, arb_deliverable_event_stream* stream_ptr) {{"), class_name, api_name);
        if(!net_receive_api->body()->statements().empty()) {
            out << fmt::format(FMT_COMPILE("\n"
                                           "    auto n = stream_ptr->n_streams;\n"
                                           "    unsigned block_dim = 128;\n"
                                           "    unsigned grid_dim = ::arb::gpu::impl::block_count(n, block_dim);\n"
                                           "    {}<<<grid_dim, block_dim>>>(*p, *stream_ptr);\n"),
                               api_name);
        }
        out << "}\n\n";
    } else {
        auto api_name = "apply_events";
        out << fmt::format(FMT_COMPILE("void {}_{}_(arb_mechanism_ppack* p, arb_deliverable_event_stream* events) {{}}\n\n"), class_name, api_name);
    }
    out << namespace_declaration_close(ns_components);
    return out.str();
}

static std::string index_i_name(const std::string& index_var) {
    return index_var+"i_";
}

void emit_api_body_cu(std::ostream& out, APIMethod* e, bool is_point_proc, bool cv_loop, bool ppack) {
    auto body = e->body();
    auto indexed_vars = indexed_locals(e->scope());

    struct index_prop {
        std::string source_var; // array holding the indices
        std::string index_name; // index into the array
        bool operator==(const index_prop& other) const {
            return (source_var == other.source_var) && (index_name==other.index_name);
        }
    };

    std::list<index_prop> indices;
    for (auto& sym: indexed_vars) {
        auto d = decode_indexed_variable(sym->external_variable());
        if (!d.scalar()) {
            auto nested = !d.inner_index_var().empty();
            auto outer_index_var = d.outer_index_var();
            auto inner_index_var = nested? index_i_name(d.inner_index_var()): "tid_";
            index_prop index_var = {outer_index_var, inner_index_var};
            auto it = std::find(indices.begin(), indices.end(), index_var);
            if (it == indices.end()) {
                // If an inner index is required, push the outer index_var to the end of the list
                if (nested) {
                    indices.push_back(index_var);
                }
                else {
                    indices.push_front(index_var);
                }
            }
        }
    }

    if (!body->statements().empty()) {
        if (is_point_proc) {
            // The run length information is only required if this method will
            // update an indexed variable, like current or conductance.
            // This is the case if one of the external variables "is_write".
            auto it = std::find_if(indexed_vars.begin(), indexed_vars.end(),
                      [](auto& sym){return sym->external_variable()->is_write();});
            if (it!=indexed_vars.end()) {
                out << "unsigned lane_mask_ = arb::gpu::ballot(0xffffffff, tid_<n_);\n";
            }
        }
        ppack && out << "PPACK_IFACE_BLOCK;\n";
        cv_loop && out << "if (tid_<n_) {\n" << indent;

        for (auto& index: indices) {
            out << "auto " << index_i_name(index.source_var)
                << " = " << pp_var_pfx << index.source_var << "[" << index.index_name << "];\n";
        }

        for (auto& sym: indexed_vars) {
            emit_state_read_cu(out, sym);
        }

        out << cuprint(body);

        for (auto& sym: indexed_vars) {
            emit_state_update_cu(out, sym, sym->external_variable(), is_point_proc);
        }
        cv_loop && out << popindent << "}\n";
    }
}

void emit_procedure_body_cu(std::ostream& out, ProcedureExpression* e) {
    out << cuprint(e->body());
}

namespace {
    // Convenience I/O wrapper for emitting indexed access to an external variable.

    struct deref {
        indexed_variable_info v;

        deref(indexed_variable_info v): v(v) {}
        friend std::ostream& operator<<(std::ostream& o, const deref& wrap) {
            auto index_var = wrap.v.outer_index_var();
            return o << pp_var_pfx << wrap.v.data_var << '['
                     << (wrap.v.scalar()? "0": index_i_name(index_var)) << ']';
        }
    };
}

void emit_state_read_cu(std::ostream& out, LocalVariable* local) {
    out << "arb_value_type " << cuprint(local) << " = ";

    if (local->is_read()) {
        auto d = decode_indexed_variable(local->external_variable());
        if (d.scale != 1) {
            out << as_c_double(d.scale) << "*";
        }
        out << deref(d) << ";\n";
    }
    else {
        out << "0;\n";
    }
}

void emit_state_update_cu(std::ostream& out, Symbol* from,
                          IndexedVariable* external, bool is_point_proc) {
    if (!external->is_write()) return;

    auto d = decode_indexed_variable(external);
    double coeff = 1./d.scale;

    if (d.readonly) {
        throw compiler_exception("Cannot assign to read-only external state: "+external->to_string());
    }

    if (is_point_proc && d.accumulate) {
        out << "::arb::gpu::reduce_by_key(";
        if (coeff != 1) out << as_c_double(coeff) << '*';

        out << pp_var_pfx << "weight[tid_]*" << from->name() << ',';

        auto index_var = d.outer_index_var();
        out << pp_var_pfx << d.data_var << ", " << index_i_name(index_var) << ", lane_mask_);\n";
    }
    else if (d.accumulate) {
        out << deref(d) << " = fma(";
        if (coeff != 1) out << as_c_double(coeff) << '*';

        out << pp_var_pfx << "weight[tid_], " << from->name() << ", " << deref(d) << ");\n";
    }
    else {
        out << deref(d) << " = ";
        if (coeff != 1) out << as_c_double(coeff) << '*';

        out << from->name() << ";\n";
    }
}

// CUDA Printer visitors

void GpuPrinter::visit(VariableExpression *sym) {
    out_ << pp_var_pfx << sym->name() << (sym->is_range()? "[tid_]": "");
}

void GpuPrinter::visit(CallExpression* e) {
    out_ << e->name() << "(params_, tid_";
    for (auto& arg: e->args()) {
        out_ << ", ";
        arg->accept(this);
    }
    out_ << ")";
}


text:
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.StyleSheet
       (getType, getTypeUnsafe, getTypeUnchecked, setDisabled,
        getDisabled, getOwnerNode, getParentStyleSheet, getHref,
        getHrefUnsafe, getHrefUnchecked, getTitle, getTitleUnsafe,
        getTitleUnchecked, getMedia, StyleSheet(..), gTypeStyleSheet,
        IsStyleSheet, toStyleSheet)
       where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums

-- | <https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet.type Mozilla StyleSheet.type documentation>
getType ::
        (MonadDOM m, IsStyleSheet self, FromJSString result) =>
          self -> m (Maybe result)
getType self
  = liftDOM
      (((toStyleSheet self) ^. js "type") >>= fromMaybeJSString)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet.type Mozilla StyleSheet.type documentation>
getTypeUnsafe ::
              (MonadDOM m, IsStyleSheet self, HasCallStack,
               FromJSString result) =>
                self -> m result
getTypeUnsafe self
  = liftDOM
      ((((toStyleSheet self) ^. js "type") >>= fromMaybeJSString) >>=
         maybe (Prelude.error "Nothing to return") return)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet.type Mozilla StyleSheet.type documentation>
getTypeUnchecked ::
                 (MonadDOM m, IsStyleSheet self, FromJSString result) =>
                   self -> m result
getTypeUnchecked self
  = liftDOM
      (((toStyleSheet self) ^. js "type") >>= fromJSValUnchecked)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet.disabled Mozilla StyleSheet.disabled documentation>
setDisabled ::
            (MonadDOM m, IsStyleSheet self) => self -> Bool -> m ()
setDisabled self val
  = liftDOM ((toStyleSheet self) ^. jss "disabled" (toJSVal val))

-- | <https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet.disabled Mozilla StyleSheet.disabled documentation>
getDisabled :: (MonadDOM m, IsStyleSheet self) => self -> m Bool
getDisabled self
  = liftDOM (((toStyleSheet self) ^. js "disabled") >>= valToBool)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet.ownerNode Mozilla StyleSheet.ownerNode documentation>
getOwnerNode :: (MonadDOM m, IsStyleSheet self) => self -> m Node
getOwnerNode self
  = liftDOM
      (((toStyleSheet self) ^. js "ownerNode") >>= fromJSValUnchecked)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet.parentStyleSheet Mozilla StyleSheet.parentStyleSheet documentation>
getParentStyleSheet ::
                    (MonadDOM m, IsStyleSheet self) => self -> m StyleSheet
getParentStyleSheet self
  = liftDOM
      (((toStyleSheet self) ^. js "parentStyleSheet") >>=
         fromJSValUnchecked)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet.href Mozilla StyleSheet.href documentation>
getHref ::
        (MonadDOM m, IsStyleSheet self, FromJSString result) =>
          self -> m (Maybe result)
getHref self
  = liftDOM
      (((toStyleSheet self) ^. js "href") >>= fromMaybeJSString)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet.href Mozilla StyleSheet.href documentation>
getHrefUnsafe ::
              (MonadDOM m, IsStyleSheet self, HasCallStack,
               FromJSString result) =>
                self -> m result
getHrefUnsafe self
  = liftDOM
      ((((toStyleSheet self) ^. js "href") >>= fromMaybeJSString) >>=
         maybe (Prelude.error "Nothing to return") return)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet.href Mozilla StyleSheet.href documentation>
getHrefUnchecked ::
                 (MonadDOM m, IsStyleSheet self, FromJSString result) =>
                   self -> m result
getHrefUnchecked self
  = liftDOM
      (((toStyleSheet self) ^. js "href") >>= fromJSValUnchecked)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet.title Mozilla StyleSheet.title documentation>
getTitle ::
         (MonadDOM m, IsStyleSheet self, FromJSString result) =>
           self -> m (Maybe result)
getTitle self
  = liftDOM
      (((toStyleSheet self) ^. js "title") >>= fromMaybeJSString)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet.title Mozilla StyleSheet.title documentation>
getTitleUnsafe ::
               (MonadDOM m, IsStyleSheet self, HasCallStack,
                FromJSString result) =>
                 self -> m result
getTitleUnsafe self
  = liftDOM
      ((((toStyleSheet self) ^. js "title") >>= fromMaybeJSString) >>=
         maybe (Prelude.error "Nothing to return") return)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet.title Mozilla StyleSheet.title documentation>
getTitleUnchecked ::
                  (MonadDOM m, IsStyleSheet self, FromJSString result) =>
                    self -> m result
getTitleUnchecked self
  = liftDOM
      (((toStyleSheet self) ^. js "title") >>= fromJSValUnchecked)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet.media Mozilla StyleSheet.media documentation>
getMedia :: (MonadDOM m, IsStyleSheet self) => self -> m MediaList
getMedia self
  = liftDOM
      (((toStyleSheet self) ^. js "media") >>= fromJSValUnchecked)