text:
parent: Code Howtos
---
# JavaFX

## FXML

The following expressions can be used in FXML attributes, according to the [official documentation](https://docs.oracle.com/javase/8/javafx/api/javafx/fxml/doc-files/introduction\_to\_fxml.html#attributes)

| Type                             | Expression                                       | Value point to                                                         | Remark                                                                                |
| -------------------------------- | ------------------------------------------------ | ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| Location                         | `@image.png`                                     | path relative to the current FXML file                                 |                                                                                |
| Resource                         | `%textToBeTranslated`                            | key in ResourceBundle                                                  |                                                                                |
| Attribute variable               | `$idOfControl` or `$variable`                    | named control or variable in controller (may be path in the namespace) | resolved only once at load time                                                                                |
| Expression binding               | `${expression}`                                  | expression, for example `textField.text`                               | changes to source are propagated                                                                                |
| Bidirectional expression binding | `#{expression}`                                  | expression                                                             | changes are propagated in both directions (not yet implemented in JavaFX, see [feature request](https://bugs.openjdk.java.net/browse/JDK-8090665)) |
| Event handler                    | `#nameOfEventHandler`                            | name of the event handler method in the controller                     |                                                                                |
| Constant                         | `<text><Strings fx:constant="MYSTRING"/></text>` | constant (here `MYSTRING` in the `Strings` class)                      |                                                                                |

## JavaFX Radio Buttons example

All radio buttons that should be grouped together need to have a ToggleGroup defined in the FXML code Example:

```markup
<VBox>
            <fx:define>
                <ToggleGroup fx:id="citeToggleGroup"/>
            </fx:define>
            <children>
                <RadioButton fx:id="inPar" minWidth="-Infinity" mnemonicParsing="false"
                             text="%Cite selected entries between parenthesis" toggleGroup="$citeToggleGroup"/>
                <RadioButton fx:id="inText" minWidth="-Infinity" mnemonicParsing="false"
                             text="%Cite selected entries with in-text citation" toggleGroup="$citeToggleGroup"/>
                <Label minWidth="-Infinity" text="%Extra information (e.g. page number)"/>
                <TextField fx:id="pageInfo"/>
            </children>
</VBox>
```

## JavaFX Dialogs

All dialogs should be displayed to the user via `DialogService` interface methods. `DialogService` provides methods to display various dialogs (including custom ones) to the user. It also ensures the displayed dialog opens on the correct window via `initOwner()` (for cases where the user has multiple screens). The following code snippet demonstrates how a custom dialog is displayed to the user:

```java
dialogService.showCustomDialog(new DocumentViewerView());
```

If an instance of `DialogService` is unavailable within current class/scope in which the dialog needs to be displayed, `DialogService` can be instantiated via the code snippet shown as follows:

```java
DialogService dialogService = Injector.instantiateModelOrService(DialogService.class);
```

## Architecture: Model - View - (Controller) - ViewModel (MV(C)VM)

The goal of the MVVM architecture is to separate the state/behavior from the appearance of the ui. This is archived by dividing JabRef into different layers, each having a clear responsibility.

* The _Model_ contains the business logic and data structures. These aspects are again encapsulated in the _logic_ and _model_ package, respectively.
* The _View_ controls the appearance and structure of the UI. It is usually defined in a _FXML_ file.
* _View model_ converts the data from logic and model in a form that is easily usable in the gui. Thus it controls the state of the View. Moreover, the ViewModel contains all the logic needed to change the current state of the UI or perform an action. These actions are usually passed down to the _logic_ package, after some data validation. The important aspect is that the ViewModel contains all the ui-related logic but does _not_ have direct access to the controls defined in the View. Hence, the ViewModel can easily be tested by unit tests.
* The _Controller_ initializes the view model and binds it to the view. In an ideal world all the binding would already be done directly in the FXML. But JavaFX's binding expressions are not yet powerful enough to accomplish this. It is important to keep in mind that the Controller should be as minimalistic as possible. Especially one should resist the temptation to validate inputs in the controller. The ViewModel should handle data validation! It is often convenient to load the FXML file directly from the controller.

The only class which access model and logic classes is the ViewModel. Controller and View have only access the ViewModel and never the backend. The ViewModel does not know the Controller or View.

More details about the MVVM pattern can be found in [an article by Microsoft](https://msdn.microsoft.com/en-us/magazine/dd419663.aspx) and in [an article focusing on the implementation with JavaFX](http://blog.buildpath.de/javafx-decouple-the-view-and-its-behavior-to-create-a-testable-ui/).

## An example

### ViewModel

* The ViewModel should derive from `AbstractViewModel`

```java
public class MyDialogViewModel extends AbstractViewModel {
}
```

* Add a (readonly) property as a private field and generate the getters according to the [JavaFX bean conventions](https://docs.oracle.com/javafx/2/binding/jfxpub-binding.htm):

```java
private final ReadOnlyStringWrapper heading = new ReadOnlyStringWrapper();

public ReadOnlyStringProperty headingProperty() {
    return heading.getReadOnlyProperty();
}

public String getHeading() {
    return heading.get();
}
```

* Create constructor which initializes the fields to their default values. Write tests to ensure that everything works as expected!

```java
public MyDialogViewModel(Dependency dependency) {
    this.dependency = Objects.requireNonNull(dependency);
    heading.set("Hello " + dependency.getUserName());
}
```

* Add methods which allow interaction. Again, don't forget to write tests!

```java
public void shutdown() {
    heading.set("Goodbye!");
}
```

### View - Controller

* The "code-behind" part of the view, which binds the `View` to the `ViewModel`.
* The usual convention is that the controller ends on the suffix `*View`. Dialogs should derive from `BaseDialog`.

```java
public class AboutDialogView extends BaseDialog<Void>
```

* You get access to nodes in the FXML file by declaring them with the `@FXML` annotation.

```java
@FXML protected Button helloButton;
@FXML protected ImageView iconImage;
```

* Dependencies can easily be injected into the controller using the `@Inject` annotation.

```java
@Inject private DialogService dialogService;
```

*   It is convenient to load the FXML-view directly from the controller class.

    The FXML file is loaded using `ViewLoader` based on the name of the class passed to `view`. To make this convention-over-configuration approach work, both the FXML file and the View class should have the same name and should be located in the same package.

    Note that fields annotated with `@FXML` or `@Inject` only become accessible after `ViewLoader.load()` is called.

    a `View` class that loads the FXML file.

```java
private Dependency dependency;

public AboutDialogView(Dependency dependency) {
        this.dependency = dependency;

        this.setTitle(Localization.lang("About JabRef"));

        ViewLoader.view(this)
                .load()
                .setAsDialogPane(this);
}
```

* Dialogs should use [setResultConverter](https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Dialog.html#setResultConverter-javafx.util.Callback-) to convert the data entered in the dialog to the desired result. This conversion should be done by the view model and not the controller.

```java
setResultConverter(button -> {
    if (button == ButtonType.OK) {
        return viewModel.getData();
    }
    return null;
});
```

* The initialize method may use data-binding to connect the ui-controls and the `ViewModel`. However, it is recommended to do as much binding as possible directly in the FXML-file.

```java
@FXML
private void initialize() {
    viewModel = new AboutDialogViewModel(dialogService, dependency, ...);

    helloLabel.textProperty().bind(viewModel.helloMessageProperty());
}
```

* calling the view model:

```java
@FXML
private void openJabrefWebsite() {
    viewModel.openJabrefWebsite();
}
```

### View - FXML

The view consists a FXML file `MyDialog.fxml` which defines the structure and the layout of the UI. Moreover, the FXML file may be accompanied by a style file that should have the same name as the FXML file but with a `css` ending, e.g., `MyDialog.css`. It is recommended to use a graphical design tools like [SceneBuilder](http://gluonhq.com/labs/scene-builder/) to edit the FXML file. The tool [Scenic View](https://github.com/JonathanGiles/scenic-view) is very helpful in debugging styling issues.

## Properties and Bindings

JabRef makes heavy use of Properties and Bindings. These are wrappers around Observables. A good explanation on the concept can be found here:
[JavaFX Bindings and Properties](https://edencoding.com/javafx-properties-and-binding-a-complete-guide/)

## Resources

* [curated list of awesome JavaFX frameworks, libraries, books and etc...](https://github.com/mhrimaz/AwesomeJavaFX)
* [ControlsFX](http://fxexperience.com/controlsfx/features/) amazing collection of controls
* [Undo manager](https://github.com/FXMisc/UndoFX)
* [Docking manager](https://github.com/alexbodogit/AnchorFX) [or](https://github.com/RobertBColton/DockFX)
* [additional bindings](https://github.com/lestard/advanced-bindings) or [EasyBind](https://github.com/TomasMikula/EasyBind)
* [Kubed](https://github.com/hudsonb/kubed): data visualization (inspired by d3)
* [Validation framework](https://github.com/sialcasa/mvvmFX/wiki/Validation)
* [mvvm framework](https://github.com/sialcasa/mvvmFX/wiki)
* [CSS Reference](http://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html)
* [JFoenix](https://github.com/jfoenixadmin/JFoenix) Material Designs look & feel
* [JavaFX Documentation project](https://fxdocs.github.io/docs/html5/index.html): Collected information on JavaFX in a central place
* [FXExperience](http://fxexperience.com) JavaFX Links of the week
* [Foojay](https://foojay.io) Java and JavaFX tutorials
* [FXTutorials](https://github.com/AlmasB/FXTutorials) A wide range of practical tutorials focusing on Java, JavaFX and FXGL

## Features missing in JavaFX

* bidirectional binding in FXML, see [official feature request](https://bugs.openjdk.java.net/browse/JDK-8090665)


text:
package com.thoughtworks.acceptance;

import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.core.JVM;
import com.thoughtworks.xstream.io.StreamException;

public class ErrorTest extends AbstractAcceptanceTest {

    public static class Thing {
        String one;
        int two;
    }

    protected void setUp() throws Exception {
        super.setUp();
        xstream.alias("thing", Thing.class);
    }

    public void testUnmarshallerThrowsExceptionWithDebuggingInfo() {
        try {
            xstream.fromXML(""
                + "<thing>\n"
                + "  <one>string 1</one>\n"
                + "  <two>another string</two>\n"
                + "</thing>");
            fail("Error expected");
        } catch (ConversionException e) {
            assertEquals("java.lang.NumberFormatException",
                    e.get("cause-exception"));
            if (JVM.is14()) {
                assertEquals("For input string: \"another string\"",
                        e.get("cause-message"));
            } else {
                assertEquals("another string",
                        e.get("cause-message"));
            }
            assertEquals(Integer.class.getName(),
                    e.get("class"));
            assertEquals("/thing/two",
                    e.get("path"));
            assertEquals("3",
                    e.get("line number"));
            assertEquals("java.lang.Integer",
                    e.get("required-type"));
            assertEquals(Thing.class.getName(),
                e.get("class[1]"));
        }
    }

    public void testInvalidXml() {
        try {
            xstream.fromXML(""
                + "<thing>\n"
                + "  <one>string 1</one>\n"
                + "  <two><<\n"
                + "</thing>");
            fail("Error expected");
        } catch (ConversionException e) {
            assertEquals(StreamException.class.getName(),
                    e.get("cause-exception"));
            assertNotNull(e.get("cause-message")); // depends on parser
            assertEquals("/thing/two",
                    e.get("path"));
            assertEquals("3",
                    e.get("line number"));
        }

    }

    public void testNonExistingMember() {
        try {
            xstream.fromXML(""
                + "<thing>\n"
                + "  <one>string 1</one>\n"
                + "  <three>3</three>\n"
                + "</thing>");
            fail("Error expected");
        } catch (ConversionException e) {
            assertEquals("three",
                    e.get("field"));
            assertEquals("/thing/three",
                    e.get("path"));
            assertEquals("3",
                    e.get("line number"));
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
// Generated from Questionnaire.g4 by ANTLR 4.2
package edu.uva.softwarecons.grammar;

import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.tree.ParseTreeVisitor;

/**
 * This interface defines a complete generic visitor for a parse tree produced
 * by {@link QuestionnaireParser}.
 *
 * @param <T> The return type of the visit operation. Use {@link Void} for
 *            operations with no return type.
 */
public interface QuestionnaireVisitor<T>
    extends ParseTreeVisitor<T>
{
    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#else}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitElse( @NotNull QuestionnaireParser.ElseContext ctx );

    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#simpleQuestion}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitSimpleQuestion( @NotNull QuestionnaireParser.SimpleQuestionContext ctx );

    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#stringType}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitStringType( @NotNull QuestionnaireParser.StringTypeContext ctx );

    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#decimalType}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitDecimalType( @NotNull QuestionnaireParser.DecimalTypeContext ctx );

    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#booleanType}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitBooleanType( @NotNull QuestionnaireParser.BooleanTypeContext ctx );

    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#computedQuestion}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitComputedQuestion( @NotNull QuestionnaireParser.ComputedQuestionContext ctx );

    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#integer}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitInteger( @NotNull QuestionnaireParser.IntegerContext ctx );

    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#or}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitOr( @NotNull QuestionnaireParser.OrContext ctx );

    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#compare}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitCompare( @NotNull QuestionnaireParser.CompareContext ctx );

    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#mulDiv}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitMulDiv( @NotNull QuestionnaireParser.MulDivContext ctx );

    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#intType}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitIntType( @NotNull QuestionnaireParser.IntTypeContext ctx );

    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#dateType}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitDateType( @NotNull QuestionnaireParser.DateTypeContext ctx );

    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#and}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitAnd( @NotNull QuestionnaireParser.AndContext ctx );

    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#id}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitId( @NotNull QuestionnaireParser.IdContext ctx );

    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#not}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitNot( @NotNull QuestionnaireParser.NotContext ctx );

    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#questionnaire}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitQuestionnaire( @NotNull QuestionnaireParser.QuestionnaireContext ctx );

    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#if}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitIf( @NotNull QuestionnaireParser.IfContext ctx );

    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#string}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitString( @NotNull QuestionnaireParser.StringContext ctx );

    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#addSub}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitAddSub( @NotNull QuestionnaireParser.AddSubContext ctx );

    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#boolean}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitBoolean( @NotNull QuestionnaireParser.BooleanContext ctx );

    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#parenthesis}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitParenthesis( @NotNull QuestionnaireParser.ParenthesisContext ctx );

    /**
     * Visit a parse tree produced by {@link QuestionnaireParser#moneyType}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    T visitMoneyType( @NotNull QuestionnaireParser.MoneyTypeContext ctx );
}


text:
// Copyright 2010-2012 RethinkDB, all rights reserved.
#include "concurrency/cross_thread_signal.hpp"

#include "arch/runtime/coroutines.hpp"

void cross_thread_signal_subscription_t::run() {
    parent_->on_signal_pulsed(keepalive_);
}

cross_thread_signal_t::cross_thread_signal_t(signal_t *source, threadnum_t dest) :
    source_thread(get_thread_id()), dest_thread(dest),
    rethreader(static_cast<signal_t *>(this), dest_thread),
    subs(this, auto_drainer_t::lock_t(&drainer)) {
    rassert(source->home_thread() == source_thread);
    subs.reset(source);
}

void cross_thread_signal_t::on_signal_pulsed(auto_drainer_t::lock_t keepalive) {
    /* We can't do anything that blocks when we're in a signal callback, so we
    have to spawn a new coroutine to do the thread switching. */
    coro_t::spawn_sometime(std::bind(&cross_thread_signal_t::deliver, this, keepalive));
}

void cross_thread_signal_t::deliver(UNUSED auto_drainer_t::lock_t keepalive) {
    on_thread_t thread_switcher(dest_thread);
    signal_t::pulse();
}


text:
<?php

namespace SimpleMon\Event;

use Symfony\Component\EventDispatcher\Event;

/**
 * Database initialize event
 *
 * @author Casey McLaughlin <caseyamcl@gmail.com>
 */
class DbInitializeEvent extends Event
{
    /**
     * @var array
     */
    private $queries;

    /**
     * DbInitializeEvent constructor.
     *
     * @param array|string[] $queries
     */
    public function __construct(array $queries)
    {
        $this->queries = $queries;
    }

    /**
     * @return array
     */
    public function getQueries()
    {
        return $this->queries;
    }
}


text:
<?php

namespace HWI\Bundle\OAuthBundle\OAuth\ResourceOwner;

use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/**
 * DailymotionResourceOwner
 *
 * @author Joseph Bielawski <stloyd@gmail.com>
 */
class DailymotionResourceOwner extends GenericOAuth2ResourceOwner
{
    /**
     * {@inheritDoc}
     */
    protected $paths = array(
        'identifier'     => 'id',
        'nickname'       => 'screenname',
        'realname'       => 'fullname', // requires 'userinfo' scope
        'email'          => 'email', // requires 'email' scope
        'profilepicture' => 'avatar_medium_url'
    );

    /**
     * {@inheritDoc}
     */
    public function getAuthorizationUrl($redirectUri, array $extraParameters = array())
    {
        return parent::getAuthorizationUrl($redirectUri, array_merge(array('display' => $this->options['display']), $extraParameters));
    }

    /**
     * {@inheritDoc}
     */
    protected function configureOptions(OptionsResolverInterface $resolver)
    {
        parent::configureOptions($resolver);

        $resolver->setDefaults(array(
            'authorization_url' => 'https://api.dailymotion.com/oauth/authorize',
            'access_token_url'  => 'https://api.dailymotion.com/oauth/token',
            'infos_url'         => 'https://api.dailymotion.com/me',

            'display'           => null,
        ));

        $resolver->setAllowedValues(array(
            // @link http://www.dailymotion.com/doc/api/authentication.html#dialog-form-factors
            'display' => array('page', 'popup', 'mobile', null),
        ));
    }
}


text:
'use strict';
//var AMQPClient = require('amqp10').Client;
var AMQPClient  = require('../lib').Client,
    Policy = require('../lib').Policy;

// Simple argument-checker, you can ignore.
function argCheck(settings, options) {
  var missing = [];
  for (var idx in options) {
    if (settings[options[idx]] === undefined) missing.push(options[idx]);
  }
  if (missing.length > 0) {
    throw new Error('Required settings ' + (missing.join(', ')) + ' missing.');
  }
}

if (process.argv.length < 3) {
  console.warn('Usage: node ' + process.argv[1] + ' <settings json file>');
} else {
  var settingsFile = process.argv[2];
  var settings = require('./' + settingsFile);
  argCheck(settings, ['serviceBusHost', 'SASKeyName', 'SASKey', 'queueName']);
  var protocol = settings.protocol || 'amqps';
  var serviceBusHost = settings.serviceBusHost + '.servicebus.windows.net';
  if (settings.serviceBusHost.indexOf(".") !== -1) {
    serviceBusHost = settings.serviceBusHost;
  }
  var sasName = settings.SASKeyName;
  var sasKey = settings.SASKey;
  var queueName = settings.queueName;

  var msgVal = Math.floor(Math.random() * 1000000);

  var uri = protocol + '://' + encodeURIComponent(sasName) + ':' + encodeURIComponent(sasKey) + '@' + serviceBusHost;

  var sender = true;
  var receiver = true;
  if (process.argv.length > 3) {
    if (process.argv[3] === 'send') receiver = false;
    else if (process.argv[3] === 'receive') sender = false;
    else throw new Error('Unknown action.');
  }

  var receiveCB = function (rx_err, message) {
    if (rx_err) {
      console.log('Error Receiving: ');
      console.log(rx_err);
    } else {
      console.log('Recv: ');
      console.log(message.body);
      if (message.annotations) {
        console.log('Annotations:');
        console.log(message.annotations);
      }
      console.log('');
      if (sender) {
        // If we aren't a sender, no value to look for.
        if (message.body.DataValue === msgVal) {
          client.disconnect().then(function () {
            console.log("Disconnected, when we saw the value we'd inserted.");
            process.exit(0);
          });
        }
      }
    }
  };

  var client = new AMQPClient(Policy.ServiceBusQueue);
  client.connect(uri).then(function () {
    if (sender) {
      client.send({"DataString": "From Node", "DataValue": msgVal}, queueName).then(function (state) {
        console.log('State: ', state);
        if (receiver) {
          client.createReceiver(queueName, receiveCB);
        } else {
          console.log('Sent message with value ' + msgVal + '.  Not receiving, so exiting');
          process.exit(0);
        }
      });
    } else {
      client.createReceiver(queueName, receiveCB);
    }
  }).catch(function (e) {
    console.warn('Error send/receive: ', e);
  });
}


text:
/*
 * puzzle.c -- Implements the puzzle accessor routines
 */

#include <puz.h>
#include <math.h>

/**
 * puz_init - initialize a puzzle
 *
 * @puz: pointer to the struct puzzle_t to init.  If NULL, one will be malloc'd for you.
 *
 * This function is used to initialize a new struct puzzle_t to sane defaults.
 *
 * Return Value: NULL on error, else a pointer to the filled-in struct
 * puzzle_t.  If puz was NULL, this is a pointer to the
 * newly-allocated structure.
 */
struct puzzle_t *puz_init(struct puzzle_t *puz) {
  unsigned char file_magic[12] = FILE_MAGIC;
  unsigned char magic_18[4] = VER_MAGIC;

 if(NULL == puz) {
    puz = (struct puzzle_t *)malloc(sizeof(struct puzzle_t));
    if(NULL == puz) {
      perror("malloc");
      return NULL;
    }
  }

  memset(puz, 0, sizeof(struct puzzle_t));

  memcpy(puz->header.magic, file_magic, 12);
  memcpy(puz->header.magic_18, magic_18, 4);
  puz->header.x_unk_30 = 0x0001;

  return puz;
}

/**
 * puz_deep_free - this frees all the pointers sitting in a puzzle,
 *   then the puzzle's memory itself.
 *
 * @puz: pointer to the struct puzzle_t to free
 *
 * This function assumes that all the pointers in a puzzle are to active
 * memory that has been malloced on the heap.  This is true if the struct
 * is built up and filled in using the other functions in this library.
 * However, if you are for some reason building up a puzzle_t using memory
 * on the stack, don't call this!
 */
void puz_deep_free (struct puzzle_t* puz) {
  if(NULL == puz)
    return;

  free(puz->solution);
  free(puz->grid);
  free(puz->title);
  free(puz->author);
  free(puz->copyright);

  if(puz->clues)
    puz_clear_clues(puz);

  free(puz->notes);
  free(puz->grbs);

  if(puz->rtbl)
    puz_clear_rtbl(puz);

  free(puz->ltim);
  free(puz->gext);

  if(puz->rusr)
    puz_clear_rusr(puz);

  free(puz);

  return;
}

/**
 * puz_size - calculate the size of a puzzle as a PUZ file
 *
 * @puz: a pointer to the struct puzzle_t to size
 *
 * This function is used to calculate the size of the PUZ file for a
 * given puzzle.
 *
 * Return value: -1 on error, a positive (non-zero) integer size on
 * success.
 */
int puz_size(struct puzzle_t *puz) {
  int i, sz;

  if(!puz)
    return -1;

  int board_size = puz_width_get(puz) * puz_height_get(puz);

  sz = 0x34; // header
  sz += board_size;
  sz += board_size;
  sz += Sstrlen(puz_title_get(puz)) + 1;  // title
  sz += Sstrlen(puz_author_get(puz)) + 1; // author
  sz += Sstrlen(puz_copyright_get(puz)) + 1; // copyright

  for(i = 0; i < puz_clue_count_get(puz); i++) {
    sz += Sstrlen(puz_clue_get(puz, i)) + 1;
  }

  if(puz->notes_sz)
    sz += puz->notes_sz;
  sz += 1; // NULL terminated

  if (puz_has_rebus(puz)) {
    sz += 4; // GRBS
    sz += 2; // board size
    sz += 2; // checksum
    sz += board_size; // rebus grid
    sz += 1; // NULL

    sz += 4; // RTBL
    sz += 2; // size
    sz += 2; // checksum

    for (i = 0; i < puz_rebus_count_get(puz); i++) {
      sz += Sstrlen(puz_rtbl_get(puz, i)) + 1;
    }
    sz += 1; // NULL
  }

  if (puz_has_timer(puz)) {
    sz += 4; //LTIM
    sz += 4; // size and checksum

    sz += Sstrlen(puz->ltim); //timer string

    sz += 1; // NULL
  }

  if (puz_has_extras(puz)) {
    sz += 4; // GEXT
    sz += 2; // size
    sz += 2; // checksum

    sz += board_size; // extras grid
    sz += 1; // NULL
  }

  if (puz_has_rusr(puz)) {
    sz += 4; // RUSR
    sz += 2; // size
    sz += 2; // checksum
    sz += puz->rusr_sz; //data
    sz++;  // NULL
  }

  return sz;
}

/**
 * puz_width_get - get the puzzle's width
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 *
 * Returns -1 on error; else a non-negative value
 */
int puz_width_get(struct puzzle_t *puz) {
  if(NULL == puz)
    return -1;

  return(puz->header.width);
}

/**
 * puz_width_set - set the puzzle's width
 *
 * @puz: a pointer to the struct puzzle_t to write to (required)
 * @val: the (positive) value to set width to (required)
 *
 * returns -1 on error, else the old value of width
 */
int puz_width_set(struct puzzle_t *puz, unsigned char val) {
  int i;

  if(NULL == puz)
    return -1;

  i = puz->header.width;

  puz->header.width = val;

  return(i);
}

/**
 * puz_height_get - get the puzzle's height
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 *
 * Returns -1 on error; else a non-negative value
 */
int puz_height_get(struct puzzle_t *puz) {
  if(NULL == puz)
    return -1;

  return(puz->header.height);
}

/**
 * puz_height_set - set the puzzle's height
 *
 * @puz: a pointer to the struct puzzle_t to write to (required)
 * @val: the (positive) value to set height to (required)
 *
 * returns -1 on error, else the old value of height
 */
int puz_height_set(struct puzzle_t *puz, unsigned char val) {
  int i;

  if(NULL == puz)
    return -1;

  i = puz->header.height;

  puz->header.height = val;

  return(i);
}

/**
 * puz_solution_get - get the puzzle's solution
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 *
 * Returns NULL on error or if field is unset.
 */
unsigned char * puz_solution_get(struct puzzle_t *puz) {
  if(NULL == puz)
    return NULL;

  return(puz->solution);
}

/**
 * puz_solution_set - set the puzzle's solution
 *
 * @puz: a pointer to the struct puzzle_t to write to (required)
 * @val: a pointer to the string to st the value to (required)
 *
 * returns NULL on error, else a pointer to the struct's copy of the string
 */
unsigned char * puz_solution_set(struct puzzle_t *puz, unsigned char *val) {
  if(NULL == puz || NULL == val)
    return NULL;

  free(puz->solution);

  puz->solution = Sstrdup(val);

  return puz->solution;
}

/**
 * puz_grid_get - get the puzzle's grid
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 *
 * Returns NULL on error or if field is unset.
 */
unsigned char * puz_grid_get(struct puzzle_t *puz) {
  if(NULL == puz)
    return NULL;

  return(puz->grid);
}

/**
 * puz_grid_set - set the puzzle's grid
 *
 * @puz: a pointer to the struct puzzle_t to write to (required)
 * @val: a pointer to the string to st the value to (required)
 *
 * returns NULL on error, else a pointer to the struct's copy of the string
 */
unsigned char * puz_grid_set(struct puzzle_t *puz, unsigned char *val) {
  if(NULL == puz || NULL == val)
    return NULL;

  free(puz->grid);

  puz->grid = Sstrdup(val);

  return puz->grid;
}

/**
 * puz_title_get - get the puzzle's title
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 *
 * Returns NULL on error or if field is unset.
 */
unsigned char * puz_title_get(struct puzzle_t *puz) {
  if(NULL == puz)
    return NULL;

  return(puz->title);
}

/**
 * puz_title_set - set the puzzle's title
 *
 * @puz: a pointer to the struct puzzle_t to write to (required)
 * @val: a pointer to the string to st the value to (required)
 *
 * returns NULL on error, else a pointer to the struct's copy of the string
 */
unsigned char * puz_title_set(struct puzzle_t *puz, unsigned char *val) {
  if(NULL == puz || NULL == val)
    return NULL;

  free(puz->title);

  puz->title = Sstrdup(val);

  return puz->title;
}

/**
 * puz_author_get - get the puzzle's author
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 *
 * Returns NULL on error or if field is unset.
 */
unsigned char * puz_author_get(struct puzzle_t *puz) {
  if(NULL == puz)
    return NULL;

  return(puz->author);
}

/**
 * puz_author_set - set the puzzle's author
 *
 * @puz: a pointer to the struct puzzle_t to write to (required)
 * @val: a pointer to the string to st the value to (required)
 *
 * returns NULL on error, else a pointer to the struct's copy of the string
 */
unsigned char * puz_author_set(struct puzzle_t *puz, unsigned char *val) {
  if(NULL == puz || NULL == val)
    return NULL;

  free(puz->author);

  puz->author = Sstrdup(val);

  return puz->author;
}

/**
 * puz_copyright_get - get the puzzle's copyright
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 *
 * Returns NULL on error or if field is unset.
 */
unsigned char * puz_copyright_get(struct puzzle_t *puz) {
  if(NULL == puz)
    return NULL;

  return(puz->copyright);
}

/**
 * puz_copyright_set - set the puzzle's copyright
 *
 * @puz: a pointer to the struct puzzle_t to write to (required)
 * @val: a pointer to the string to st the value to (required)
 *
 * returns NULL on error, else a pointer to the struct's copy of the string
 */
unsigned char * puz_copyright_set(struct puzzle_t *puz, unsigned char *val) {
  if(NULL == puz || NULL == val)
    return NULL;

  free(puz->copyright);

  puz->copyright = Sstrdup(val);

  return puz->copyright;
}

/**
 * puz_notes_get - get the puzzle's notes
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 *
 * Returns NULL on error or if field is unset.
 */
unsigned char * puz_notes_get(struct puzzle_t *puz) {
  if(NULL == puz)
    return NULL;

  return(puz->notes);
}

/**
 * puz_notes_set - set the puzzle's notes
 *
 * @puz: a pointer to the struct puzzle_t to write to (required)
 * @val: a pointer to the string to st the value to (required)
 *
 * returns NULL on error, else a pointer to the struct's copy of the string
 */
unsigned char * puz_notes_set(struct puzzle_t *puz, unsigned char *val) {
  if(NULL == puz || NULL == val)
    return NULL;

  free(puz->notes);

  puz->notes = Sstrdup(val);
  puz->notes_sz = Sstrlen(val);

  return puz->notes;
}

/**
 * puz_clue_count_get - get the puzzle's clue_count
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 *
 * Returns -1 on error; else a non-negative value
 */
int puz_clue_count_get(struct puzzle_t *puz) {
  if(NULL == puz)
    return -1;

  return(puz->header.clue_count);
}

/**
 * puz_clue_count_set - set the puzzle's clue_count
 *
 * @puz: a pointer to the struct puzzle_t to write to (required)
 * @val: the (positive) value to set clue_count to (required)
 *

 * This function can only be used to set the number of clues for a
 * blank puzzle.  If a puzzle has been filled in and you want to set
 * the number of clues to a different value, you'll need to first
 * clear the clues with puz_clear_clues(), then set the number of
 * clues, and finally fill the clues back in.
 *
 * returns -1 on error, 0 on success.
 */
int puz_clue_count_set(struct puzzle_t *puz, int val) {
  if(NULL == puz || 0 > val)
    return -1;

  if(puz->header.clue_count != 0)
    return -1;

  puz->clues = (unsigned char **)malloc(val * sizeof(unsigned char *));
  memset(puz->clues, 0, val * sizeof(unsigned char *));

  puz->header.clue_count = val;

  return(0);
}

/**
 * puz_clear_clues - clear out a puzzle's clues
 *
 * @puz: a pointer to the struct puzzle_t to clear clues from (required)
 *
 * This function clears out the clues.  Specifically, it frees all
 * clues, the clues storage, and sets the number of clues to zero.
 *
 * Note that any pointers you have to clues will become invalid after
 * calling this function.
 *
 * Returns -1 on error, 0 on success.
 */
int puz_clear_clues(struct puzzle_t *puz) {
  int i;

  if(NULL == puz || NULL == puz->clues)
    return -1;

  for(i = 0; i < puz->header.clue_count; i++)
    free(puz->clues[i]);

  free(puz->clues);

  puz->clues = NULL;
  puz->header.clue_count = 0;

  return 0;
}

/**
 * puz_clue_get -- get the nth clue of a puzzle
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 * @n: the index (between zero and n_clues) to get
 *
 * Returns NULL on error, pointer to the nth clue on success.
 */
unsigned char * puz_clue_get(struct puzzle_t *puz, int n) {
  if(NULL == puz || n < 0 || n > puz->header.clue_count)
    return NULL;

  return puz->clues[n];
}

/**
 * puz_clue_set -- set the nth clue of a puzzle
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 * @n: the index (between zero and n_clues) to get
 * @val: the value to set it to
 *
 * Returns NULL on error, pointer to the puzzle's new copy on success.
 */
unsigned char * puz_clue_set(struct puzzle_t *puz, int n, unsigned char * val) {
  if(NULL == puz || n < 0 || n > puz->header.clue_count || NULL == val)
    return NULL;

  free(puz->clues[n]);
  puz->clues[n] = Sstrdup(val);

  return puz->clues[n];
}

/**
 * puz_has_rebus -- checks if a puzzle has rebuses
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 *
 * Returns 1 if the puzzle has a rebus, 0 if not or if the puzzle is NULL
 */
int puz_has_rebus(struct puzzle_t *puz) {
  if(NULL == puz)
    return 0;

  return NULL != puz->grbs;
}

/**
 * puz_rebus_get - get the puzzle's rebus grid
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 *
 * Returns NULL on error or if field is unset.
 */
unsigned char * puz_rebus_get(struct puzzle_t *puz) {
  if(NULL == puz)
    return NULL;

  return puz->grbs;
}

/**
 * puz_rebus_set - set the puzzle's rebus grid
 *
 * @puz: a pointer to the struct puzzle_t to write to (required)
 * @val: a pointer to the string to st the value to (required)
 *
 * returns NULL on error, else a pointer to the struct's copy of the string
 */
unsigned char * puz_rebus_set(struct puzzle_t *puz, unsigned char *val) {
  if(NULL == puz || NULL == val)
    return NULL;

  free(puz->grbs);

  int size = puz_width_get(puz) * puz_height_get(puz);
  puz->grbs = calloc(size+1, sizeof (unsigned char));
  memcpy(puz->grbs, val, size);
  puz->grbs[size] = 0;

  return puz->grbs;
}

/**
 * puz_rebus_count_get - get the puzzle's rebus count
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 *
 * Returns -1 on error; else a non-negative value
 */
int puz_rebus_count_get(struct puzzle_t *puz) {
  if(NULL == puz)
    return -1;

  if (!puz_has_rebus(puz))
    return 0;

  return puz->rtbl_sz;
}

/**
 * puz_rebus_count_set - set the puzzle's clue_count
 *
 * @puz: a pointer to the struct puzzle_t to write to (required)
 * @val: the (positive) value to set rtbl_sz to (required)
 *
 * returns -1 on error, 0 on success.
 */
int puz_rebus_count_set(struct puzzle_t *puz, int val) {
  if(NULL == puz || 0 > val)
    return -1;

  puz->rtbl = (unsigned char **)malloc(val * sizeof(unsigned char *));
  // TODO should check for malloc failure
  memset(puz->rtbl, 0, val * sizeof(unsigned char *));

  puz->rtbl_sz = val;

  return(0);
}

/**
 * puz_rtbl_get -- get the nth entry of the rebus table
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 * @n: the index (between zero and rtbl_sz) to get
 *
 * Note that the numbering used here is for the list of rebus table
 * entries, and has NOTHING to do with the numeric keys in the table.
 *
 * Returns NULL on error, pointer to the nth clue on success.
 */
unsigned char * puz_rtbl_get(struct puzzle_t *puz, int n) {
  if(NULL == puz || n < 0 || !puz_has_rebus(puz) || n > puz->rtbl_sz)
    return NULL;

  return puz->rtbl[n];
}

/**
 * puz_rtbl_set -- set the nth rtbl of a puzzle
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 * @n: the index (between zero and rtbl_sz) to get
 * @val: the value to set it to
 *
 * Returns NULL on error, pointer to the puzzle's new copy on success.
 */
unsigned char * puz_rtbl_set(struct puzzle_t *puz, int n, unsigned char * val) {
  if(NULL == puz || n < 0 || n > puz->header.clue_count || NULL == val)
    return NULL;

  free(puz->rtbl[n]);
  puz->rtbl[n] = Sstrdup(val);

  return puz->rtbl[n];
}

/**
 * puz_rtblstr_get -- get the rebus table as a single string
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 *
 * Returns NULL on error, newly allocated string on success
 */
unsigned char * puz_rtblstr_get(struct puzzle_t *puz) {
  int rtbl_strsz, sz, i;
  unsigned char *rtbl_str;
  unsigned char *c;

  if (NULL == puz)
    return NULL;

  rtbl_strsz = 1; // account for NULL
  for (i = 0; i < puz->rtbl_sz; i++) {
    rtbl_strsz += Sstrlen(puz->rtbl[i]) + 1; // account for semi-colon
  }

  rtbl_str = (unsigned char *)malloc(rtbl_strsz * sizeof(unsigned char));
  if (NULL == rtbl_str) {
    perror("malloc");
    return NULL;
  }

  c = rtbl_str;
  for (i = 0; i < puz->rtbl_sz; i++) {
    sz = Sstrlen(puz->rtbl[i]);

    memcpy(c, puz->rtbl[i], sz);
    c[sz] = ';';
    c += sz+1;
  }

  rtbl_str[rtbl_strsz - 1] = '\0';

  return rtbl_str;
}

/**
 * puz_rtblstr_set -- set the rebus table as a single string
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 * @val: the rebus table as a string (required)
 *
 * Returns NULL on error, well-indexed rebus table on success
 */
unsigned char ** puz_rtblstr_set(struct puzzle_t *puz, unsigned char * val) {
  int i, sz;
  unsigned char *start;
  unsigned char *end;

  if (NULL == puz)
    return NULL;

  if (NULL != puz -> rtbl)
    puz_clear_rtbl(puz);

  sz = 0;
  for (i = 0; i < Sstrlen(val); i++) {
    if (';' == val[i])
      sz += 1;
  }
  puz_rebus_count_set(puz, sz); // allocates RTBL, sets rtbl_sz

  start = val;
  for (i = 0; i < puz->rtbl_sz; i++) {
    end = Sstrchr(start, ';'); // XXX this is fragile...bad input will hose this

    if (NULL == end) {
      printf("Appear to have run out of rebus table entries: rebuses: %d, i: %d\nPlease report\n",
             puz->rtbl_sz, i);

      return NULL; /* XXX cleanup */
    }

    puz->rtbl[i] = (unsigned char*) malloc((end - start) + 1);
    Sstrncpy(puz->rtbl[i],start,end-start);
    (puz->rtbl[i])[end-start] = 0;
    start = end+1;
  }

  return puz->rtbl;
}

/**
 * puz_clear_rtbl - clear out a puzzle's rtbl
 *
 * @puz: a pointer to the struct puzzle_t to clear rtbl from (required)
 *
 * This function clears out the rtbl.  Specifically, it frees all rtbl
 * entries, the rtbl storage, and sets the number of rtbl entries.
 *
 * Note that any pointers you have to rtbl entries will become invalid after
 * calling this function.
 *
 * Returns -1 on error, 0 on success.
 */
int puz_clear_rtbl(struct puzzle_t *puz) {
  int i;

  if (NULL == puz || NULL == puz->rtbl)
    return -1;

  for(i = 0; i < puz->rtbl_sz; i++)
    free(puz->rtbl[i]);

  free(puz->rtbl);

  puz->rtbl = NULL;
  puz->rtbl_sz = 0;
  puz->rtbl_cksum = 0;
  puz->calc_rtbl_cksum = 0;

  return 0;
}

/**
 * puz_has_timer -- checks if a puzzle has time data
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 *
 * Returns 1 if the puzzle has a timer, 0 if not or if the puzzle is NULL
 */
int puz_has_timer(struct puzzle_t *puz) {
  if (NULL == puz)
    return 0;

  return NULL != puz->ltim;
}

/**
 * puz_timer_elapsed_get - get the puzzle's elapsed time
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 *
 * Returns -1 on error or if field is unset.
 */
int puz_timer_elapsed_get(struct puzzle_t *puz) {
  int checked, elapsed;

  if(NULL == puz)
    return -1;
  if(NULL == puz->ltim)
    return -1;

  checked = sscanf((char*)puz->ltim,"%d,",&elapsed);
  if (checked == 1) {
    return elapsed;
  } else {
    printf("Puzzle has ill-formed timer section, setting time to 0\n");
    return 0;
  }
}

/**
 * puz_timer_stopped_get - get the puzzle timer's stopped value.
 * This is usually 0 if the timer if running and 1 if it is stopped.
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 *
 * Returns -1 on error or if field is unset.
 */
int puz_timer_stopped_get(struct puzzle_t *puz) {
  int checked, elapsed, stopped;

  if(NULL == puz)
    return -1;
  if(NULL == puz->ltim)
    return -1;

  checked = sscanf((char*)puz->ltim,"%d,%d",&elapsed,&stopped);
  if (checked == 2) {
    return stopped;
  } else {
    printf("Warning: puzzle has ill-formed timer section\n");
    return 1;
  }
}

/**
 * puz_timer_set - set the puzzle's extras time data
 *
 * @puz: a pointer to the struct puzzle_t to write to (required)
 * @elapsed: the number of seconds elapsed (should be non-negative) (required)
 * @stopped: 1 if the timer is stopped, 0 if it is running
 * returns NULL on error, else a pointer to the puz's copy of the timer_data
 */
unsigned char * puz_timer_set(struct puzzle_t *puz, int elapsed,
                              int stopped)
{ int size;

  if(NULL == puz)
    return NULL;

  free(puz->ltim);

  //we need to calculate the ltim's size as a string.  This is a little
  //tricky.  The int is represented as a string of ASCII digits, so we
  //use log10, but add an extra byte in case we're a little too small
  //because of floating point errors.

  size = 5+(int)(floor(log10(elapsed)));
  puz->ltim = (unsigned char*)calloc(size,sizeof(unsigned char));
  if (puz->ltim) {
    snprintf((char*)puz->ltim, size, "%d,%d", elapsed, stopped);
  }
  puz->ltim[size-1] = 0;

  return puz->ltim;
}

/**
 * puz_has_extras -- checks if a puzzle has extras
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 *
 * Returns 1 if the puzzle has a extras, 0 if not or if the puzzle is NULL
 */
int puz_has_extras(struct puzzle_t *puz) {
  if(NULL == puz)
    return 0;

  return NULL != puz->gext;
}

/**
 * puz_extras_get - get the puzzle's extras grid
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 *
 * Returns NULL on error or if field is unset.
 */
unsigned char * puz_extras_get(struct puzzle_t *puz) {
  if(NULL == puz)
    return NULL;

  return puz->gext;
}

/**
 * puz_extras_set - set the puzzle's extras grid
 *
 * @puz: a pointer to the struct puzzle_t to write to (required)
 * @val: a pointer to the string to st the value to (required)
 *
 * returns NULL on error, else a pointer to the struct's copy of the string
 */
unsigned char * puz_extras_set(struct puzzle_t *puz, unsigned char *val) {
  if(NULL == puz || NULL == val)
    return NULL;

  free(puz->gext);

  int size = puz_width_get(puz) * puz_height_get(puz);
  puz->gext = calloc(size+1, sizeof (unsigned char));
  memcpy(puz->gext, val, size);
  puz->gext[size] = 0;

  return puz->gext;
}

/**
 * puz_has_rusr -- checks if a puzzle has an rusr board
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 *
 * Returns 1 if the puzzle has an rusr board, 0 if not or if the
 * puzzle is NULL
 */
int puz_has_rusr(struct puzzle_t *puz) {
  if(NULL == puz) {
    return 0;
  }

  return (NULL != puz->rusr);
}

/**
 * puz_rusr_get - get the puzzle's rusr grid
 *
 * @puz: a pointer to the struct puzzle_t to read from (required)
 *
 * Returns NULL on error or if field is unset.
 */
unsigned char ** puz_rusr_get(struct puzzle_t *puz) {
  if(NULL == puz)
    return NULL;

  return puz->rusr;
}

/**
 * puz_rusr_set - set the puzzle's extras grid
 *
 * @puz: a pointer to the struct puzzle_t to write to (required)
 * @val: a pointer to the value (required)
 *
 * returns NULL on error, else a pointer to the struct's copy of the input
 */
unsigned char ** puz_rusr_set(struct puzzle_t *puz, unsigned char ** val) {
  if(NULL == puz || NULL == val)
    return NULL;

  if (puz->rusr)
    puz_clear_rusr(puz);

  int puz_sz = puz_width_get(puz) * puz_height_get(puz);
  unsigned char ** rusr = malloc(puz_sz * sizeof (unsigned char*));
  if(NULL == rusr) {
    return NULL;
  }

  int rusr_sz = puz_sz;
  int i;
  for(i = 0; i < puz_sz; i++) {
    if(NULL == val[i]) {
      rusr[i] = NULL;
    } else {
      rusr[i] = Sstrndup(val[i],MAX_REBUS_SIZE);
      rusr_sz += Sstrlen(rusr[i]);
    }
  }

  puz->rusr = rusr;
  puz->rusr_sz = rusr_sz;
  return puz->rusr;
}

/**
 * puz_rusrstr_get - get the binary form of the rusr
 *
 * @puz: a pointer to the struct puzzle_t
 *
 * returns a malloced string if possible, and otherwise NULL
 */
unsigned char* puz_rusrstr_get(struct puzzle_t *puz) {
  if (NULL == puz || NULL == puz->rusr)
    return NULL;

  int board_sz = puz->header.width * puz->header.height;

  unsigned char* rusrstr = malloc( (puz->rusr_sz) * sizeof(unsigned char) );

  int j,i = 0;
  for(j = 0; j < board_sz; j++) {
    if(NULL == puz->rusr[j]) {
      rusrstr[i] = 0;
    } else {
      // here we are allowed to not check length, because we did
      // that when we made the rusr board we're outputting
      Sstrcpy(rusrstr+i, (puz->rusr)[j]);
      i += Sstrlen((puz->rusr)[j]);
      rusrstr[i] = (unsigned char) 0;
    }
    i++;
  }
  return rusrstr;

}

/**
 * puz_clear_rusr - clear out a puzzle's rusr memory
 *
 * @puz: a pointer to the struct puzzle_t to clear rusr from (required)
 *
 * This function clears out the rusr memory.  Specifically, it frees
 * all rusr table entries, the rusrstorage, and sets the number of
 * rtbl entries to 0.
 *
 * Note that any pointers you have to rusr entries will become invalid
 * after calling this function.
 *
 * Returns -1 on error, 0 on success.
 */
int puz_clear_rusr(struct puzzle_t *puz) {
  int i;

  if (NULL == puz || NULL == puz->rusr)
    return -1;

  int bd_sz = puz_width_get(puz) * puz_height_get(puz);

  for(i = 0; i < bd_sz; i++)
    free(puz->rusr[i]);

  free(puz->rusr);

  puz->rusr = NULL;
  puz->rusr_sz = 0;
  puz->rusr_cksum = 0;
  puz->calc_rusr_cksum = 0;

  return 0;
}

/**
 * puz_is_locked_get - check if the puzzle's solution is scrambled
 *
 * @puz: a pointer to the struct puzzle_t to check (required)
 *
 * returns the value of the puzzle's locked flag (0 if unscrambled,
 *   nonzero if scrambled).
 */
int puz_is_locked_get (struct puzzle_t *puz) {
  if(NULL == puz)
    return 0;

  return puz->header.scrambled_tag;
}

/**
 * puz_locked_cksum_get - for puzzles that are locked, this returns
 *   the checksum of the real solution.
 *
 * @puz: a pointer to the struct puzzle_t to check against (required)
 *
 * If the puzzle is locked, this returns a short, which is the result
 * of calling:
 *     puz_cksum_region(sol, len, 0x0000);
 * where sol is the correct solution in column major order with the black
 * squares removed, and len is its length.
 *
 */
unsigned short puz_locked_cksum_get(struct puzzle_t *puz) {
  if(NULL == puz)
    return 0;

  return puz->header.scrambled_cksum;
}

/**
 * puz_lock_set - set the flags indicating whether a puzzle's solution
 *    is locked
 *
 * @puz: a pointer to the struct puzzle_t to check (required)

 * @cksum: An unsigned short.  If this is 0, the puzzle is set
 *   "unlocked". Otherwise, is should be the result of calling:
 *       puz_cksum_region(sol, len, 0x0000);
 *   when sol is the correct solution in column-major order with the
 *   black squares removed and len is its length.
 *
 * returns the input upon success.  Otherwise, -1.
 */
unsigned short puz_lock_set (struct puzzle_t *puz, unsigned short cksum) {
  if(NULL == puz)
    return -1;

  if(cksum) {
    puz->header.scrambled_tag = 4;
    puz->header.scrambled_cksum = cksum;
  } else {
    puz->header.scrambled_tag = 0;
    puz->header.scrambled_cksum = 0x0000;
  }

  return cksum;
}

/**
 * unscramble_string - an internal function used by puz_unscramble.
 *
 * Let s be a string and len be its length.  A "scrambled" version
 * of s looks like:
 *
 * [ s[len/2], s[0], s[1 + (len/2)], s[1], s[2 + (len/2)], s[2],  ...]
 *
 * This function takes such a scrambled string (inp) and unscrambles
 * it into another string (out).  inp and out had better have the same
 * length.
 *
 * return -1 on error and 0 otherwise.
 *
 */
unsigned short unscramble_string (unsigned char* inp, unsigned char* out) {
  if(NULL == inp || NULL == out)
    return -1;

  int len = Sstrlen(inp);
  int strbreak = len/2;

  int i;
  for(i = 0; i < len; i++) {
    int index;
    if (0 == i%2) {
      index = strbreak + i/2;
    } else {
      index = i/2;
    }

    out[index] = inp[i];
  }
  out[len] = 0;

  return 0;
}

/**
 * unshift_string - an internal function used by puz_unscramble.
 *
 * Given a string s and an int k, the "shifted" verison of s is created
 * by moving everything before index k to the end of the string.
 *
 * This takes such a shifted string (inp) and undoes the shifting into
 * (out).
 *
 * return -1 on error and 0 otherwise.
 */
unsigned short unshift_string(unsigned char* inp, unsigned int shift,
                              unsigned char* out) {
  if(NULL == inp || NULL == out)
    return -1;

  int len = Sstrlen(inp);

  if (len < shift)
    return -1;

  Sstrncpy(out + shift, inp, len - shift);
  Sstrncpy(out, inp + (len - shift), shift);

  out[len] = 0;

  return 0;
}

/* the scrambling functions use this impossibly unfortunate
   representation for the board.  We calculate it here.

   NULL on error
 */
unsigned char* formatted_solution(struct puzzle_t* puz) {
  if (puz == NULL)
    return NULL;

  int w = puz_width_get(puz);
  int h = puz_height_get(puz);
  int board_sz = w*h;

  unsigned char* sol = puz_solution_get(puz);

  int i,size = 0;
  for(i=0; i < board_sz; i++) {
    if(sol[i] != '.')
      size++;
  }

  unsigned char* out = calloc(size+1, sizeof(unsigned char));
  int j,index = 0;
  for(i=0; i < w; i++) {
    for(j=0; j < h; j++) {
      if (sol[j*h + i] != '.') {
        out[index] = sol[j*h + i];
        index++;
      }
    }
  }

  out[size] = 0;
  return out;
}

int unformat_unlocked_sol(struct puzzle_t* puz, unsigned char* formatted) {
  if (puz == NULL || formatted == NULL)
    return -1;

  int w = puz_width_get(puz);
  int h = puz_height_get(puz);

  unsigned char* sol = puz_solution_get(puz);

  int i,j;
  int index = 0;

  // XXX this could fail if we calculated something poorly (but shouldn't)
  for(i=0; i < w; i++) {
    for(j=0; j < h; j++) {
      if (sol[j*h + i] != '.') {
        sol[j*h + i] = formatted[index];
        index++;
      }
    }
  }

  return 0;
}

/**
 * puz_unlock_puzzle - unlock a puzzle with a key
 *
 * @puz: a pointer to the struct puzzle_t to check (required)
 * @code: an unsigned short.  This is the code for unlocking the
 *   puzzle.  It must be a number between 1111 and 9999 and have no
 *   0s.
 *
 * On success, returns 0.  Nonzero otherwise.  A few specific error codes:
 *   1 means the puzzle wasn't scrambled
 *   2 means the code didn't work
 */
int puz_unlock_solution(struct puzzle_t* puz, unsigned short code) {

  if(NULL == puz)
    return -1;

  // make sure the puzzle is actually scrambled
  if(!(puz->header.scrambled_tag)) {
    return 1;
  }

  int digits[4];
  digits[0] = (code/1000) % 10;
  digits[1] = (code/100)  % 10;
  digits[2] = (code/10)   % 10;
  digits[3] = code        % 10;

  // make sure the code is valid
  int i;
  for (i = 0; i < 4; i++) {
    if(digits[i] == 0)
      return -2;
  }

  // first we must calculate the unscrambled solution.  It's possible
  // the key passed will be wrong and we'll have to fail after we
  // calculate it.
  unsigned char* inp = formatted_solution(puz);
  int len = Sstrlen(inp);
  unsigned char* workspace1 = calloc(len+1, sizeof(unsigned char));
  unsigned char* workspace2 = calloc(len+1, sizeof(unsigned char));
  if (NULL == workspace1 || NULL == workspace2)
    return -3;

  Sstrncpy(workspace1, inp, len+1);

  int e1, e2, j;
  for(i = 3; i >= 0; i--) {
    e1 = unscramble_string(workspace1, workspace2);
    e2 = unshift_string(workspace2, digits[i], workspace1);
    if(e1 || e2)
      return -4;

    for (j = 0; j < len; j++) {
      workspace1[j] -= digits[j % 4];
      if (workspace1[j] < 65)
        workspace1[j] += 26;
    }
  }

  // Now we have to check - did this unscrambling mess actually
  // produce something with the right checksum?  The stored
  // checksum is for the solution _without_ black squares, so
  // first we create a copy without them in workspace 2.
  int index = 0;
  for(j=0; j<len; j++) {
    if(workspace1[j] != '.') {
      workspace2[index] = workspace1[j];
      index++;
    }
  }
  workspace2[j] = 0;

  unsigned short cksum = puz_cksum_region(workspace2, len, 0x0000);
  if (cksum != puz->header.scrambled_cksum) {
    return 2;
  }

  // Awesome, the unscrambled solution has the right checksum, so
  // it's almost certainly the correct board.  Copy it in as the solution
  // and fix up all the scrambled markers
  unformat_unlocked_sol(puz, workspace1);
  puz_lock_set(puz, 0x0000);

  free(workspace1);
  free(workspace2);

  return 0;
}

/**
 * puz_brute_force_unlock - unscramble a locked puzzle without the key
 *
 * @puz: a pointer to the struct puzzle_t to check (required)
 *
 * On success, returns the correct code.  Otherwise, it returns an
 * integer less than 0.
 */
int puz_brute_force_unlock(struct puzzle_t* puz) {
  // make sure we were given a puzzle that's scrambled
  if(NULL == puz)
    return -1;
  if(!(puz->header.scrambled_tag))
    return -2;

  int code = 1111;
  int great_success;
  for (; code++; code < 10000) {
    great_success = puz_unlock_solution(puz,code);
    if(!great_success) {
      break;
    }
  }

  if(great_success) {
    return -3;
  } else {
    return code;
  }
}


text:
function [signal,sample_mask] = clean_windows(signal,max_bad_channels,zthresholds,window_len,censor_cutoffs,censor_dropouts,censor_dropout_maxreject)
% Remove periods with abnormally high-power content from continuous data.
% [Signal,Mask] = clean_windows(Signal,MaxBadChannels,BadTolerances,)
%
% This function cuts segments from the data which contain high-power artifacts. Specifically,
% only windows are retained which have less than a certain fraction of "bad" channels, where a channel
% is bad in a window if its power is above or below a given upper/lower threshold (in standard
% deviations from a robust estimate of the EEG power distribution in the channel).
%
% In:
%   Signal         : Continuous data set, assumed to be appropriately high-passed (e.g. >1Hz or
%                    0.5Hz - 2.0Hz transition band)
%
%   MaxBadChannels : The maximum number or fraction of bad channels that a retained window may still
%                    contain (more than this and it is removed). Reasonable range is 0.05 (very clean
%                    output) to 0.3 (very lax cleaning of only coarse artifacts). Default: 0.1.
%
%   PowerTolerances: The minimum and maximum standard deviations within which the power of a channel
%                    must lie (relative to a robust estimate of the clean EEG power distribution in
%                    the channel) for it to be considered "not bad". Default: [-5 5].
%
%
%   The following are "specialty" parameters that usually do not have to be tuned. If you can't get
%   the function to do what you want, you might consider adapting these to your data.
%
%   WindowLength    : Window length that is used to check the data for artifact content. This is
%                     ideally as long as the expected time scale of the artifacts but not shorter
%                     than half a cycle of the high-pass filter that was used. Default: 1.
%
%   CensorCutoffs : These are robust data censoring cutoffs, in robust z scores per channel, for
%                   estimating the EEG power distribution per channel. This does not need to be
%                   tuned unless the artifact content is very unusual, e.g. lots of flat channel
%                   drop-outs or a very uncommon type of noise. Default: [-5 4].
%
%   CensorDropouts : This is an extra censoring cutoff, in robust z scores across all channels,
%                    to handle data where the majority of samples in a channel (but not all) drop out.
%                    Default: -3.
%
%   CensorDropoutMaxReject : This is the maximum fraction of windows rejected for which the dropout
%                            censoring is considered applicable (otherwise the criterion is ignored,
%                            e.g. for very low-amplitude channels). Default: 0.75
%
% Out:
%   Signal : data set with bad time periods removed.
%
%   Mask   : mask of retained samples (logical array)
%
%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                                2010-07-06

warning off stats:gevfit:IterLimit
warning off stats:gamfit:IterLimit

if ~exist('max_bad_channels','var') || isempty(max_bad_channels) max_bad_channels = 0.15; end
if ~exist('zthresholds','var') || isempty(zthresholds) zthresholds = [-5 5]; end
if ~exist('window_len','var') || isempty(window_len) window_len = 1; end
if ~exist('censor_cutoffs','var') || isempty(censor_cutoffs) censor_cutoffs = [-5 4]; end
if ~exist('censor_dropouts','var') || isempty(censor_dropouts) censor_dropouts = -3; end
if ~exist('censor_dropout_maxreject','var') || isempty(censor_dropout_maxreject) censor_dropout_maxreject = 0.75; end

coeff = [0.1314,-0.2877,-0.0104];    % coefficients that model the degrees of freedom in the EEG covariance chi^2 distribution
                                     % depending on the window length over which the covariances are calculated (these numbers
                                     % come from a fit to clean EEG)
[C,S] = size(signal.data);
N = window_len*signal.srate;
wnd = 0:N-1;
offsets = round(1:N/2:S-N);
W = length(offsets);

if max_bad_channels < 1
    max_bad_channels = round(max_bad_channels*C); end

% compute windowed power across all channels
wp = zeros(C,W);
for c = 1:C
    for o=1:W
        x = signal.data(c,offsets(o) + wnd);
        wp(c,o) = sqrt(sum(x.*x)/N);
    end
end

% find the median and median absolute deviation for that
mu_all = median(wp(:));
st_all = mad(wp(:),1);

wz = zeros(C,W);
for c = 1:C
    tmp = wp(c,:);
    % censor values that are likely temporary channel drop-outs using information from all channels
    tmp = tmp(tmp>(mu_all+st_all*censor_dropouts));
    if length(tmp)/W < (1-censor_dropout_maxreject)
        % if some channel is extremely low-amplitude, we cannot apply this criterion
        tmp = wp(c,:);
    end
    % estimate the robust mean and std. deviation for this channel
    mu_robust = median(tmp);
    st_robust = mad(tmp,1);
    % censor values that are extreme outliers for this particular channel
    tmp = tmp(tmp<(mu_robust+st_robust*censor_cutoffs(2)) & tmp>(mu_robust+st_robust*censor_cutoffs(1)));
    % fit a generalized extreme value distribution and a gamma distribution and compute the modes
    params_gam = gamfit(tmp);
    mode_gam = (params_gam(1) - 1)*params_gam(2);
    params_gev = gevfit(tmp);
    if params_gev(1) ~= 0
        mode_gev = params_gev(3) + params_gev(2)*((1+params_gev(1))^-params_gev(1) - 1)/params_gev(1);
    else
        mode_gev = params_gev(3);
    end
    % we take the smaller mode as the mean of the underlying EEG distribution (assuming that it is a Gaussian component of that distribution)
    % this is because the GEV allows right-skewed fits, which are non-physiological (in this case we fall back to the Gamma fit)
    mu_fine = min([mode_gam,mode_gev]);
    % we estimate the standard deviation dependent on the pure EEG mode -- under the assumption of a scaled Chi^2 distribution of EEG variance
    % (this depends parametrically on the window length, using a fit on clean reference EEG data)
    st_fine = mu_fine .* (coeff(1)*window_len^coeff(2) + coeff(3));
    % calculate the channel power in z scores relative to the estimated underlying EEG distribution
    wz(c,:) = (wp(c,:) - mu_fine)/st_fine;
end

% sort z scores into quantiles
swz = sort(wz);

% determine which windows to retain
retained_mask = true(1,W);
if max(zthresholds)>0
    retained_mask(swz(end-max_bad_channels,:) > max(zthresholds)) = false; end
if min(zthresholds)<0
    retained_mask(swz(1+max_bad_channels,:) < min(zthresholds)) = false; end
retained_windows = find(retained_mask);

% find retained samples
retained_samples = repmat(offsets(retained_windows)',1,length(wnd))+repmat(wnd,length(retained_windows),1);

% mask them out
sample_mask = false(1,S); sample_mask(retained_samples(:)) = true;
fprintf('Keeping %.1f%% (%.0f seconds) of the data.\n',100*(mean(sample_mask)),nnz(sample_mask)/signal.srate);
% collect into intervals
retain_data_intervals = reshape(find(diff([false sample_mask false])),2,[])';
retain_data_intervals(:,2) = retain_data_intervals(:,2)-1;

% apply selection
signal = pop_select(signal, 'point', retain_data_intervals);
if isfield(signal.etc,'clean_sample_mask')
    signal.etc.clean_sample_mask(signal.etc.clean_sample_mask) = sample_mask;
else
    signal.etc.clean_sample_mask = sample_mask;
end


text:
#if NETCOREAPP3_1
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Diagnostics;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure;
using StackExchange.Profiling.Internal;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;

namespace StackExchange.Profiling.Data
{
    /// <summary>
    /// Diagnostic listener for Microsoft.AspNetCore.Mvc.* events
    /// </summary>
    /// <remarks>
    /// See:
    /// - https://github.com/dotnet/aspnetcore/blob/v3.0.0/src/Mvc/Mvc.Core/src/MvcCoreDiagnosticListenerExtensions.cs
    /// - https://github.com/dotnet/aspnetcore/blob/v3.0.0/src/Mvc/Mvc.Core/src/Diagnostics/MvcDiagnostics.cs
    /// - https://github.com/dotnet/aspnetcore/blob/v3.0.0/src/Mvc/Mvc.Razor/src/Diagnostics/MvcDiagnostics.cs
    /// </remarks>
    public class MvcDiagnosticListener : IMiniProfilerDiagnosticListener
    {
        /// <summary>
        /// Diagnostic Listener name to handle.
        /// </summary>
        public string ListenerName => "Microsoft.AspNetCore";

        /// <summary>
        /// Notifies the observer that the provider has finished sending push-based notifications.
        /// </summary>
        public void OnCompleted()
        {
            _descriptorNameCache.Clear();
        }

        /// <summary>
        /// Notifies the observer that the provider has experienced an error condition.
        /// </summary>
        /// <param name="error">An object that provides additional information about the error.</param>
        public void OnError(Exception error) => Trace.WriteLine(error);

        // So we don't keep allocating strings for the same actions over and over
        private readonly ConcurrentDictionary<(string, string), string> _descriptorNameCache = new();
        private const string _labelSeparator = ": ";

        /// <summary>
        /// Gets a cached concatenation since this is such a hot path - don't keep allocating.
        /// </summary>
        private string GetName(string label, string name, Func<string, string> trim = null)
        {
            var key = (label, name);
            if (!_descriptorNameCache.TryGetValue(key, out var result))
            {
                name = trim?.Invoke(name) ?? name;
                result = label + _labelSeparator + name;
                _descriptorNameCache[key] = result;
            }
            return result;
        }

        private class StackTiming
        {
            public object State { get; set; }
            public Timing Timing { get; set; }
            public StackTiming Previous { get; set; }

            public StackTiming(object state, Timing timing, StackTiming previous) =>
                (State, Timing, Previous) = (state, timing, previous);
        }

        /// <summary>
        /// Stores the current timing in the tree, on each request.
        /// </summary>
        private readonly AsyncLocal<StackTiming> CurrentTiming = new();

        private object StartAction<T>(string label, T descriptor) where T : ActionDescriptor
        {
            var profiler = MiniProfiler.Current;
            var stepName = GetName(label, descriptor.DisplayName, name =>
            {
                // For the "Samples.AspNetCore.Controllers.HomeController.Index (Samples.AspNetCore3)" format,
                // ...trim off the assembly on the end.
                var assemblyNamePos = name.IndexOf(" (");
                return assemblyNamePos > 0
                        ? descriptor.DisplayName[..assemblyNamePos]
                        : descriptor.DisplayName;
            });

            CurrentTiming.Value = new StackTiming(descriptor, profiler != null ? new Timing(profiler, profiler.Head, stepName, null, null, debugStackShave: 4) : null, CurrentTiming.Value);
            return null;
        }

        private object StartActionResult<T>(T result) where T : IActionResult
        {
            var profiler = MiniProfiler.Current;
            var stepName = result switch
            {
                ViewResult vr => vr.ViewName.HasValue() ? GetName("View", vr.ViewName) : nameof(ViewResult),
                ContentResult cr => cr.ContentType.HasValue() ? GetName("Content", cr.ContentType) : nameof(ContentResult),
                ObjectResult or => or.DeclaredType != null ? GetName("Object", or.DeclaredType.Name) : nameof(ObjectResult),
                StatusCodeResult scr => scr.StatusCode > 0 ? GetName("Status Code", scr.StatusCode.ToString()) : nameof(StatusCodeResult),
                JsonResult jr => jr.ContentType.HasValue() ? GetName("JSON", jr.ContentType) : nameof(JsonResult),
                _ => GetName("Result", result.GetType().Name)
            };

            CurrentTiming.Value = new StackTiming(result, profiler != null ? new Timing(profiler, profiler.Head, stepName, null, null, debugStackShave: 4) : null, CurrentTiming.Value);
            return null;
        }

        private object StartFilter<T>(string label, T filter) where T : IFilterMetadata
        {
            var profiler = MiniProfiler.Current;
            if (profiler?.Options is MiniProfilerOptions opts && opts.EnableMvcFilterProfiling)
            {
                var stepName = GetName(label, filter.GetType().Name, name => name.EndsWith("Attribute") ? name[..^"Attribute".Length] : name);
                CurrentTiming.Value = new StackTiming(filter, new Timing(profiler, profiler.Head, stepName, opts.MvcFilterMinimumSaveMs, true, debugStackShave: 4), CurrentTiming.Value);
            }
            return null;
        }

        private object StartView<T>(T state, string label, string viewName) where T : class
        {
            var profiler = MiniProfiler.Current;
            if (profiler?.Options is MiniProfilerOptions opts && opts.EnableMvcViewProfiling)
            {
                // Trim /Views/ to / for brevity
                var stepName = GetName(label, viewName, name => name?.StartsWith("/Views/") == true ? name["/Views/".Length..] : name);
                CurrentTiming.Value = new StackTiming(state, new Timing(profiler, profiler.Head, stepName, opts.MvcViewMinimumSaveMs, true, debugStackShave: 4), CurrentTiming.Value);
            }
            return null;
        }

        private object StartHandler<T>(T state, HandlerMethodDescriptor handler) where T : class
        {
            var profiler = MiniProfiler.Current;
            var stepName = GetName("Handler", handler.Name);
            CurrentTiming.Value = new StackTiming(state, profiler != null ? new Timing(profiler, profiler.Head, stepName, null, null, debugStackShave: 4) : null, CurrentTiming.Value);
            return null;
        }

        private object Complete<T>(T state) where T : class
        {
            var top = CurrentTiming.Value;
            while (top?.Timing?.DurationMilliseconds.HasValue == true)
            {
                top = top.Previous;
            }
            if (top?.State is T currentState && currentState == state)
            {
                using (top.Timing) { }
                CurrentTiming.Value = top.Previous;
            }
            return null;
        }

        /// <summary>
        /// Provides the observer with new data.
        /// </summary>
        /// <param name="kv">The current notification information.</param>
        public void OnNext(KeyValuePair<string, object> kv)
        {
            try
            {
                _ = kv.Value switch
                {
                    // MVC Bits: https://github.com/dotnet/aspnetcore/blob/v3.0.0/src/Mvc/Mvc.Core/src/Diagnostics/MvcDiagnostics.cs
                    // ActionEvent
                    BeforeActionEventData data => StartAction("Action", data.ActionDescriptor),
                    AfterActionEventData data => Complete(data.ActionDescriptor),
                    // ControllerActionMethod
                    BeforeControllerActionMethodEventData data => StartAction("Controller Action", data.ActionContext.ActionDescriptor),
                    AfterControllerActionMethodEventData data => Complete(data.ActionContext.ActionDescriptor),
                    // ActionResultEvent
                    BeforeActionResultEventData data => StartActionResult(data.Result),
                    AfterActionResultEventData data => Complete(data.Result),

                    // AuthorizationFilterOnAuthorization
                    BeforeAuthorizationFilterOnAuthorizationEventData data => StartFilter("Auth Filter", data.Filter),
                    AfterAuthorizationFilterOnAuthorizationEventData data => Complete(data.Filter),

                    // ResourceFilterOnResourceExecution
                    BeforeResourceFilterOnResourceExecutionEventData data => StartFilter("Resource Filter (Exec)", data.Filter),
                    AfterResourceFilterOnResourceExecutionEventData data => Complete(data.Filter),
                    // ResourceFilterOnResourceExecuting
                    BeforeResourceFilterOnResourceExecutingEventData data => StartFilter("Resource Filter (Execing)", data.Filter),
                    AfterResourceFilterOnResourceExecutingEventData data => Complete(data.Filter),
                    // ResourceFilterOnResourceExecuted
                    BeforeResourceFilterOnResourceExecutedEventData data => StartFilter("Resource Filter (Execed)", data.Filter),
                    AfterResourceFilterOnResourceExecutedEventData data => Complete(data.Filter),

                    // ExceptionFilterOnException
                    BeforeExceptionFilterOnException data => StartFilter("Exception Filter", data.Filter),
                    AfterExceptionFilterOnExceptionEventData data => Complete(data.Filter),

                    // ActionFilterOnActionExecution
                    BeforeActionFilterOnActionExecutionEventData data => StartFilter("Action Filter (Exec)", data.Filter),
                    AfterActionFilterOnActionExecutionEventData data => Complete(data.Filter),
                    // ActionFilterOnActionExecuting
                    BeforeActionFilterOnActionExecutingEventData data => StartFilter("Action Filter (Execing)", data.Filter),
                    AfterActionFilterOnActionExecutingEventData data => Complete(data.Filter),
                    // ActionFilterOnActionExecuted
                    BeforeActionFilterOnActionExecutedEventData data => StartFilter("Action Filter (Execed)", data.Filter),
                    AfterActionFilterOnActionExecutedEventData data => Complete(data.Filter),

                    // ResultFilterOnResultExecution
                    BeforeResultFilterOnResultExecutionEventData data => StartFilter("Result Filter (Exec)", data.Filter),
                    AfterResultFilterOnResultExecutionEventData data => Complete(data.Filter),
                    // ResultFilterOnResultExecuting
                    BeforeResultFilterOnResultExecutingEventData data => StartFilter("Result Filter (Execing)", data.Filter),
                    AfterResultFilterOnResultExecutingEventData data => Complete(data.Filter),
                    // ResultFilterOnResultExecuted
                    BeforeResultFilterOnResultExecutedEventData data => StartFilter("Result Filter (Execed)", data.Filter),
                    AfterResultFilterOnResultExecutedEventData data => Complete(data.Filter),

                    // Razor Bits: https://github.com/dotnet/aspnetcore/blob/v3.0.0/src/Mvc/Mvc.Razor/src/Diagnostics/MvcDiagnostics.cs
                    // ViewPage
                    BeforeViewPageEventData data => StartView(data.Page, "View", data.Page.Path),
                    AfterViewPageEventData data => Complete(data.Page),

                    // ViewComponent
                    BeforeViewComponentEventData data => StartView(data.ViewComponentContext, "Component (Invoke)", data.ViewComponentContext.ViewComponentDescriptor.ShortName),
                    AfterViewComponentEventData data => Complete(data.ViewComponentContext),

                    // Intentionally not registering to slim view wrapper due to noise, accounted for in View: above.
                    //ViewComponentBeforeViewExecuteEventData data => StartView(data.ViewComponentContext, "Component (View)", data.ViewComponentContext.ViewComponentDescriptor.ShortName),
                    //ViewComponentAfterViewExecuteEventData data => Complete(data.ViewComponentContext),

                    // RazorPage Bits: https://github.com/dotnet/aspnetcore/blob/v3.0.0/src/Mvc/Mvc.RazorPages/src/Diagnostics/MvcDiagnostics.cs
                    // HandlerMethod
                    BeforeHandlerMethodEventData data => StartHandler(data.Instance, data.HandlerMethodDescriptor),
                    AfterHandlerMethodEventData data => Complete(data.Instance),

                    // PageFilterOnPageHandlerExecution
                    BeforePageFilterOnPageHandlerExecutionEventData data => StartFilter("Filter (Exec)", data.Filter),
                    AfterPageFilterOnPageHandlerExecutionEventData data => Complete(data.Filter),
                    // PageFilterOnPageHandlerExecuting
                    BeforePageFilterOnPageHandlerExecutingEventData data => StartFilter("Filter (Execing)", data.Filter),
                    AfterPageFilterOnPageHandlerExecutingEventData data => Complete(data.Filter),
                    // PageFilterOnPageHandlerExecuted
                    BeforePageFilterOnPageHandlerExecutedEventData data => StartFilter("Filter (Execed)", data.Filter),
                    AfterPageFilterOnPageHandlerExecutedEventData data => Complete(data.Filter),

                    // PageFilterOnPageHandlerSelection
                    BeforePageFilterOnPageHandlerSelectionEventData data => StartFilter("Filter (Selection)", data.Filter),
                    AfterPageFilterOnPageHandlerSelectionEventData data => Complete(data.Filter),
                    // PageFilterOnPageHandlerSelected
                    BeforePageFilterOnPageHandlerSelectedEventData data => StartFilter("Filter (Selected)", data.Filter),
                    AfterPageFilterOnPageHandlerSelectedEventData data => Complete(data.Filter),
                    _ => null
                };
            }
            catch (Exception ex)
            {
                // Don't error in profiling here, just flow it out
                MiniProfiler.DefaultOptions?.OnInternalError?.Invoke(ex);
            }
        }
    }
}
#endif


text:
import React from 'react';
import ReactDOM from 'react-dom';
import { shallow } from 'enzyme';
import { NavBar } from '../NavBar';

const props = {
  user: { uid: 'testuid', user: 'testuser' },
  logout: () => null
}

describe('NavBar Component', () => {
  it('renders without crashing', () => {
    shallow(<NavBar {...props } />)
  })
})


text:
'use babel';
'use strict';

import Setting from '../storage/models/setting';

/** A module for commands */
export default class Module {
	/**
	 * @param {Bot} bot - The bot the module is for
	 * @param {string} id - The ID for the module
	 * @param {string} [name=id] - The name of the module
	 * @param {boolean} [hide=false] - Whether or not to hide from the module list, and not allow disabling
	 * @param {Command[]} [commands] - The commands that the module contains
	 */
	constructor(bot, id, name, hide, commands) {
		if(!bot || !id) throw new Error('A bot and ID must be specified.');
		if(commands && !Array.isArray(commands)) throw new TypeError('Commands must be an array.');
		if(id !== id.toLowerCase()) throw new Error('Module ID must be lowercase.');

		/** @type {Bot} */
		this.bot = bot;
		/** @type {string} */
		this.id = id;
		/** @type {string} */
		this.name = name || id;
		/** @type {boolean} */
		this.hide = hide || false;
		/** @type {Command[]} */
		this.commands = commands || [];
	}

	/**
	 * Enables or disables the module on a guild
	 * @param {Guild|string} guild - The guild or guild ID
	 * @param {boolean} enabled - Whether the module should be enabled or disabled
	 * @see {@link Module.setEnabled}
	 */
	setEnabled(guild, enabled) {
		this.constructor.setEnabled(this.bot.storage.settings, guild, this, enabled);
	}

	/**
	 * Enables or disables a module on a guild
	 * @param {SettingStorage} settings - The setting storage to use
	 * @param {Guild|string} guild - The guild or guild ID
	 * @param {Module|string} module - The module or module ID
	 * @param {boolean} enabled - Whether the module should be enabled or disabled
	 * @see {@link Module#setEnabled}
	 */
	static setEnabled(settings, guild, module, enabled) {
		settings.save(new Setting(guild, `mod-${module.id || module}`, enabled));
	}

	/**
	 * Checks if the module is enabled on a guild
	 * @param {Guild} guild - The guild
	 * @return {boolean} Whether or not the module is enabled
	 * @see {@link Module.isEnabled}
	 */
	isEnabled(guild) {
		return this.constructor.isEnabled(this.bot.storage.settings, guild, this);
	}

	/**
	 * Checks if a module is enabled on a guild
	 * @param {SettingStorage} settings - The setting storage to use
	 * @param {Guild} guild - The guild
	 * @param {Module|string} module - The module or module ID
	 * @return {boolean} Whether or not the module is enabled
	 * @see {@link Module#isEnabled}
	 */
	static isEnabled(settings, guild, module) {
		return settings.getValue(guild, `mod-${module.id || module}`, true);
	}
}


text:
A C++ application to kill a specified process by name in a set interval.

To set the interval use /i=XXX where XXX is the interval in milliseconds. Special cases:
- Not specifying an interval will result in an error
- Any other number less or equal to 0 will result in an error
- -1 will kill the process once then terminate

To set the target name use /t=XXX where XXX is the name of the process omitting the file type, for example "MyApp" for the "MyApp.exe" process. Special cases:
- Not specifying a target will result in an error
- Leaving the target argument empty will result in an error

It should be noted that this will kill all processes with that name and it will not provide any feedback to the user except for:
- A taskbar icon with a "Exit" option
- A popup window every time it starts up

DISCLAIMER:
I am not responsible for any kind of action performed with this utility and provide it only for legal and intentional use.
Whoever does not understand the consequences of such a utility is urged not to use this application.


text:
using namespace chrono;
using namespace chrono::irrlicht;

// -----------------------------------------------------------------------------
// Callback class for contact reporting
// -----------------------------------------------------------------------------
class ContactReporter : public ChContactContainer::ReportContactCallback {
  public:
    ContactReporter(std::shared_ptr<ChBody> box1, std::shared_ptr<ChBody> box2) : m_box1(box1), m_box2(box2) {}

  private:
    virtual bool OnReportContact(const ChVector<>& pA,
                                 const ChVector<>& pB,
                                 const ChMatrix33<>& plane_coord,
                                 const double& distance,
                                 const double& eff_radius,
                                 const ChVector<>& cforce,
                                 const ChVector<>& ctorque,
                                 ChContactable* modA,
                                 ChContactable* modB) override {
        // Check if contact involves box1
        if (modA == m_box1.get()) {
            printf("  A contact on Box 1 at pos: %7.3f  %7.3f  %7.3f", pA.x(), pA.y(), pA.z());
        } else if (modB == m_box1.get()) {
            printf("  B contact on Box 1 at pos: %7.3f  %7.3f  %7.3f", pB.x(), pB.y(), pB.z());
        }

        // Check if contact involves box2
        if (modA == m_box2.get()) {
            printf("  A contact on Box 2 at pos: %7.3f  %7.3f  %7.3f", pA.x(), pA.y(), pA.z());
        } else if (modB == m_box2.get()) {
            printf("  B contact on Box 2 at pos: %7.3f  %7.3f  %7.3f", pB.x(), pB.y(), pB.z());
        }

        const ChVector<>& nrm = plane_coord.Get_A_Xaxis();
        printf("  nrm: %7.3f, %7.3f  %7.3f", nrm.x(), nrm.y(), nrm.z());
        printf("  frc: %7.3f  %7.3f  %7.3f", cforce.x(), cforce.y(), cforce.z());
        printf("  trq: %7.3f, %7.3f  %7.3f", ctorque.x(), ctorque.y(), ctorque.z());
        printf("  penetration: %8.4f   eff. radius: %7.3f\n", distance, eff_radius);

        return true;
    }

    std::shared_ptr<ChBody> m_box1;
    std::shared_ptr<ChBody> m_box2;
};

// -----------------------------------------------------------------------------
// Callback class for modifying composite material
// -----------------------------------------------------------------------------
class ContactMaterial : public ChContactContainer::AddContactCallback {
  public:
    virtual void OnAddContact(const collision::ChCollisionInfo& contactinfo,
                              ChMaterialComposite* const material) override {
        // Downcast to appropriate composite material type
        auto mat = static_cast<ChMaterialCompositeSMC* const>(material);

        // Set different friction for left/right halfs
        float friction = (contactinfo.vpA.z() > 0) ? 0.3f : 0.8f;
        mat->mu_eff = friction;
    }
};

// -----------------------------------------------------------------------------
// Class for overriding composite material laws
// -----------------------------------------------------------------------------
class CompsiteMaterial : public ChMaterialCompositionStrategy {
  public:
    virtual float CombineFriction(float a1, float a2) const { return 0.5 * (a1 + a2); }
};

// -----------------------------------------------------------------------------
// Class for overriding the default SMC contact force calculation
// -----------------------------------------------------------------------------
class ContactForce : public ChSystemSMC::ChContactForceSMC {
  public:
    // Demonstration only.
    virtual ChVector<> CalculateForce(
        const ChSystemSMC& sys,             ///< containing system
        const ChVector<>& normal_dir,       ///< normal contact direction (expressed in global frame)
        const ChVector<>& p1,               ///< most penetrated point on obj1 (expressed in global frame)
        const ChVector<>& p2,               ///< most penetrated point on obj2 (expressed in global frame)
        const ChVector<>& vel1,             ///< velocity of contact point on obj1 (expressed in global frame)
        const ChVector<>& vel2,             ///< velocity of contact point on obj2 (expressed in global frame)
        const ChMaterialCompositeSMC& mat,  ///< composite material for contact pair
        double delta,                       ///< overlap in normal direction
        double eff_radius,                  ///< effective radius of curvature at contact
        double mass1,                       ///< mass of obj1
        double mass2                        ///< mass of obj2
    ) const override {
        // Relative velocity at contact
        ChVector<> relvel = vel2 - vel1;
        double relvel_n_mag = relvel.Dot(normal_dir);
        ChVector<> relvel_n = relvel_n_mag * normal_dir;
        ChVector<> relvel_t = relvel - relvel_n;
        double relvel_t_mag = relvel_t.Length();

        // Calculate effective mass
        double eff_mass = mass1 * mass2 / (mass1 + mass2);

        // Calculate the magnitudes of the normal and tangential contact forces
        double kn = mat.kn;
        double kt = mat.kt;
        double gn = eff_mass * mat.gn;
        double gt = eff_mass * mat.gt;

        // Tangential displacement (magnitude)
        double dT = sys.GetStep();
        double delta_t = relvel_t_mag * dT;

        double forceN = kn * delta - gn * relvel_n_mag;
        double forceT = kt * delta_t + gt * relvel_t_mag;

        // Coulomb law
        forceT = std::min<double>(forceT, mat.mu_eff * std::abs(forceN));

        // Accumulate normal and tangential forces
        ChVector<> force = forceN * normal_dir;
        if (relvel_t_mag >= sys.GetSlipVelocityThreshold())
            force -= (forceT / relvel_t_mag) * relvel_t;

        return force;
    }
};

int main(int argc, char* argv[]) {
    GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n";

    // ----------------
    // Parameters
    // ----------------

    float friction = 0.6f;

    // -----------------
    // Create the system
    // -----------------

    ChSystemSMC system;
    system.Set_G_acc(ChVector<>(0, -10, 0));

    // Set solver settings
    system.SetSolverMaxIterations(100);
    system.SetSolverForceTolerance(0);

    // Change default collision effective radius of curvature
    ////collision::ChCollisionInfo::SetDefaultEffectiveCurvatureRadius(1);

    // --------------------------------------------------
    // Create a contact material, shared among all bodies
    // --------------------------------------------------

    auto material = chrono_types::make_shared<ChMaterialSurfaceSMC>();
    material->SetFriction(friction);

    // ----------
    // Add bodies
    // ----------

    auto container = std::shared_ptr<ChBody>(system.NewBody());
    system.Add(container);
    container->SetPos(ChVector<>(0, 0, 0));
    container->SetBodyFixed(true);
    container->SetIdentifier(-1);

    container->SetCollide(true);
    container->GetCollisionModel()->ClearModel();
    utils::AddBoxGeometry(container.get(), material, ChVector<>(4, 0.5, 4), ChVector<>(0, -0.5, 0));
    container->GetCollisionModel()->BuildModel();
    container->GetVisualShape(0)->SetColor(ChColor(0.4f, 0.4f, 0.4f));

    auto box1 = std::shared_ptr<ChBody>(system.NewBody());
    box1->SetMass(10);
    box1->SetInertiaXX(ChVector<>(1, 1, 1));
    box1->SetPos(ChVector<>(-1, 0.21, -1));
    box1->SetPos_dt(ChVector<>(5, 0, 0));

    box1->SetCollide(true);
    box1->GetCollisionModel()->ClearModel();
    utils::AddBoxGeometry(box1.get(), material, ChVector<>(0.4, 0.2, 0.1));
    box1->GetCollisionModel()->BuildModel();
    box1->GetVisualShape(0)->SetColor(ChColor(0.1f, 0.1f, 0.4f));

    system.AddBody(box1);

    auto box2 = std::shared_ptr<ChBody>(system.NewBody());
    box2->SetMass(10);
    box2->SetInertiaXX(ChVector<>(1, 1, 1));
    box2->SetPos(ChVector<>(-1, 0.21, +1));
    box2->SetPos_dt(ChVector<>(5, 0, 0));

    box2->SetCollide(true);
    box2->GetCollisionModel()->ClearModel();
    utils::AddBoxGeometry(box2.get(), material, ChVector<>(0.4, 0.2, 0.1));
    box2->GetCollisionModel()->BuildModel();
    box2->GetVisualShape(0)->SetColor(ChColor(0.4f, 0.1f, 0.1f));

    system.AddBody(box2);

    // -------------------------------
    // Create the visualization window
    // -------------------------------

    auto vis = chrono_types::make_shared<ChVisualSystemIrrlicht>();
    system.SetVisualSystem(vis);
    vis->SetWindowSize(800, 600);
    vis->SetWindowTitle("SMC callbacks");
    vis->Initialize();
    vis->AddLogo();
    vis->AddSkyBox();
    vis->AddCamera(ChVector<>(4, 4, -6));
    vis->AddTypicalLights();

    // ------------------------------------------------------------------------------
    // Use various user supplied callbacks to override default Chrono implementations
    // ------------------------------------------------------------------------------

    // User-defined SMC contact force calculation
    auto cforce = chrono_types::make_unique<ContactForce>();
    system.SetContactForceAlgorithm(std::move(cforce));

    // User-defined composite coefficent of friction
    auto cmat = chrono_types::make_unique<ChMaterialCompositionStrategy>();
    system.SetMaterialCompositionStrategy(std::move(cmat));

    // OVerride material properties at each new contact
    auto cmaterial = chrono_types::make_shared<ContactMaterial>();
    system.GetContactContainer()->RegisterAddContactCallback(cmaterial);

    // User-defined callback for contact reporting
    auto creporter = chrono_types::make_shared<ContactReporter>(box1, box2);

    // ---------------
    // Simulate system
    // ---------------

    while (vis->Run()) {
        vis->BeginScene();
        vis->DrawAll();
        irrlicht::tools::drawGrid(vis.get(), 0.5, 0.5, 12, 12,
                                  ChCoordsys<>(ChVector<>(0, 0, 0), Q_from_AngX(CH_C_PI_2)));
        irrlicht::tools::drawAllCOGs(vis.get(), 1.0);

        system.DoStepDynamics(1e-3);
        vis->EndScene();

        // Process contacts
        std::cout << system.GetChTime() << "  " << system.GetNcontacts() << std::endl;
        system.GetContactContainer()->ReportAllContacts(creporter);

        // Cumulative contact force and torque on boxes (as applied to COM)
        ChVector<> frc1 = box1->GetContactForce();
        ChVector<> trq1 = box1->GetContactTorque();
        printf("  Box 1 contact force at COM: %7.3f  %7.3f  %7.3f", frc1.x(), frc1.y(), frc1.z());
        printf("  contact torque at COM: %7.3f  %7.3f  %7.3f\n", trq1.x(), trq1.y(), trq1.z());
        ChVector<> frc2 = box2->GetContactForce();
        ChVector<> trq2 = box2->GetContactTorque();
        printf("  Box 2 contact force at COM: %7.3f  %7.3f  %7.3f", frc2.x(), frc2.y(), frc2.z());
        printf("  contact torque at COM: %7.3f  %7.3f  %7.3f\n", trq2.x(), trq2.y(), trq2.z());
    }

    return 0;
}


text:
define(['./baseForOwnRight', './createBaseEach'], function(baseForOwnRight, createBaseEach) {

  /**
   * The base implementation of `_.forEachRight` without support for callback
   * shorthands and `this` binding.
   *
   * @private
   * @param {Array|Object|string} collection The collection to iterate over.
   * @param {Function} iteratee The function invoked per iteration.
   * @returns {Array|Object|string} Returns `collection`.
   */
  var baseEachRight = createBaseEach(baseForOwnRight, true);

  return baseEachRight;
});


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="output:" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/output"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Read contacts\n" />
    </ScrollView>
</LinearLayout>