text:
<?php

namespace Symfony\Bundle\WebProfilerBundle\Controller;

use Symfony\Bundle\WebProfilerBundle\Profiler\TemplateManager;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Flash\AutoExpireFlashBag;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Profiler\Profiler;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig\Environment;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 */
class ProfilerController
{
    private $templateManager;
    private $generator;
    private $profiler;
    private $twig;
    private $templates;
    private $toolbarPosition;

    /**
     * @param UrlGeneratorInterface $generator       The URL Generator
     * @param Profiler              $profiler        The profiler
     * @param Environment           $twig            The twig environment
     * @param array                 $templates       The templates
     * @param string                $toolbarPosition The toolbar position (top, bottom, normal, or null -- use the configuration)
     */
    public function __construct(UrlGeneratorInterface $generator, Profiler $profiler = null, Environment $twig, array $templates, $toolbarPosition = 'bottom')
    {
        $this->generator = $generator;
        $this->profiler = $profiler;
        $this->twig = $twig;
        $this->templates = $templates;
        $this->toolbarPosition = $toolbarPosition;
    }

    /**
     * Redirects to the last profiles.
     *
     * @return RedirectResponse A RedirectResponse instance
     *
     * @throws NotFoundHttpException
     */
    public function homeAction()
    {
        if (null === $this->profiler) {
            throw new NotFoundHttpException('The profiler must be enabled.');
        }

        $this->profiler->disable();

        return new RedirectResponse($this->generator->generate('_profiler_search_results', array('token' => 'empty', 'limit' => 10)), 302, array('Content-Type' => 'text/html'));
    }

    /**
     * Renders a profiler panel for the given token.
     *
     * @param Request $request The current HTTP request
     * @param string  $token   The profiler token
     *
     * @return Response A Response instance
     *
     * @throws NotFoundHttpException
     */
    public function panelAction(Request $request, $token)
    {
        if (null === $this->profiler) {
            throw new NotFoundHttpException('The profiler must be enabled.');
        }

        $this->profiler->disable();

        $panel = $request->query->get('panel', 'request');
        $page = $request->query->get('page', 'home');

        if ('latest' === $token && $latest = current($this->profiler->find(null, null, 1, null, null, null))) {
            $token = $latest['token'];
        }

        if (!$profile = $this->profiler->loadProfile($token)) {
            return new Response($this->twig->render('@WebProfiler/Profiler/info.html.twig', array('about' => 'no_token', 'token' => $token, 'request' => $request)), 200, array('Content-Type' => 'text/html'));
        }

        if (!$profile->hasCollector($panel)) {
            throw new NotFoundHttpException(sprintf('Panel "%s" is not available for token "%s".', $panel, $token));
        }

        return new Response($this->twig->render($this->getTemplateManager()->getName($profile, $panel), array(
            'token' => $token,
            'profile' => $profile,
            'collector' => $profile->getCollector($panel),
            'panel' => $panel,
            'page' => $page,
            'request' => $request,
            'templates' => $this->getTemplateManager()->getNames($profile),
            'is_ajax' => $request->isXmlHttpRequest(),
            'profiler_markup_version' => 2, // 1 = original profiler, 2 = Symfony 2.8+ profiler
        )), 200, array('Content-Type' => 'text/html'));
    }

    /**
     * Purges all tokens.
     *
     * @return Response A Response instance
     *
     * @throws NotFoundHttpException
     */
    public function purgeAction()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);

        if (null === $this->profiler) {
            throw new NotFoundHttpException('The profiler must be enabled.');
        }

        $this->profiler->disable();
        $this->profiler->purge();

        return new RedirectResponse($this->generator->generate('_profiler_info', array('about' => 'purge')), 302, array('Content-Type' => 'text/html'));
    }

    /**
     * Displays information page.
     *
     * @param Request $request The current HTTP Request
     * @param string  $about   The about message
     *
     * @return Response A Response instance
     *
     * @throws NotFoundHttpException
     */
    public function infoAction(Request $request, $about)
    {
        if (null === $this->profiler) {
            throw new NotFoundHttpException('The profiler must be enabled.');
        }

        $this->profiler->disable();

        return new Response($this->twig->render('@WebProfiler/Profiler/info.html.twig', array(
            'about' => $about,
            'request' => $request,
        )), 200, array('Content-Type' => 'text/html'));
    }

    /**
     * Renders the Web Debug Toolbar.
     *
     * @param Request $request The current HTTP Request
     * @param string  $token   The profiler token
     *
     * @return Response A Response instance
     *
     * @throws NotFoundHttpException
     */
    public function toolbarAction(Request $request, $token)
    {
        if (null === $this->profiler) {
            throw new NotFoundHttpException('The profiler must be enabled.');
        }

        $session = $request->getSession();

        if (null !== $session && $session->isStarted() && $session->getFlashBag() instanceof AutoExpireFlashBag) {
            // keep current flashes for one more request if using AutoExpireFlashBag
            $session->getFlashBag()->setAll($session->getFlashBag()->peekAll());
        }

        if ('empty' === $token || null === $token) {
            return new Response('', 200, array('Content-Type' => 'text/html'));
        }

        $this->profiler->disable();

        if (!$profile = $this->profiler->loadProfile($token)) {
            return new Response('', 404, array('Content-Type' => 'text/html'));
        }

        // the toolbar position (top, bottom, normal, or null -- use the configuration)
        if (null === $position = $request->query->get('position')) {
            $position = $this->toolbarPosition;
        }

        $url = null;
        try {
            $url = $this->generator->generate('_profiler', array('token' => $token));
        } catch (\Exception $e) {
            // the profiler is not enabled
        }

        return new Response($this->twig->render('@WebProfiler/Profiler/toolbar.html.twig', array(
            'request' => $request,
            'position' => $position,
            'profile' => $profile,
            'templates' => $this->getTemplateManager()->getNames($profile),
            'profiler_url' => $url,
            'token' => $token,
            'profiler_markup_version' => 2, // 1 = original toolbar, 2 = Symfony 2.8+ toolbar
        )), 200, array('Content-Type' => 'text/html'));
    }

    /**
     * Renders the profiler search bar.
     *
     * @return Response A Response instance
     *
     * @throws NotFoundHttpException
     */
    public function searchBarAction(Request $request)
    {
        if (null === $this->profiler) {
            throw new NotFoundHttpException('The profiler must be enabled.');
        }

        $this->profiler->disable();

        if (null === $session = $request->getSession()) {
            $ip =
            $method =
            $url =
            $start =
            $end =
            $limit =
            $token = null;
        } else {
            $ip = $request->query->get('ip', $session->get('_profiler_search_ip'));
            $method = $request->query->get('method', $session->get('_profiler_search_method'));
            $url = $request->query->get('url', $session->get('_profiler_search_url'));
            $start = $request->query->get('start', $session->get('_profiler_search_start'));
            $end = $request->query->get('end', $session->get('_profiler_search_end'));
            $limit = $request->query->get('limit', $session->get('_profiler_search_limit'));
            $token = $request->query->get('token', $session->get('_profiler_search_token'));
        }

        return new Response(
            $this->twig->render('@WebProfiler/Profiler/search.html.twig', array(
                'token' => $token,
                'ip' => $ip,
                'method' => $method,
                'url' => $url,
                'start' => $start,
                'end' => $end,
                'limit' => $limit,
                'request' => $request,
            )),
            200,
            array('Content-Type' => 'text/html')
        );
    }

    /**
     * Renders the search results.
     *
     * @param Request $request The current HTTP Request
     * @param string  $token   The token
     *
     * @return Response A Response instance
     *
     * @throws NotFoundHttpException
     */
    public function searchResultsAction(Request $request, $token)
    {
        if (null === $this->profiler) {
            throw new NotFoundHttpException('The profiler must be enabled.');
        }

        $this->profiler->disable();

        $profile = $this->profiler->loadProfile($token);

        $ip = $request->query->get('ip');
        $method = $request->query->get('method');
        $url = $request->query->get('url');
        $start = $request->query->get('start', null);
        $end = $request->query->get('end', null);
        $limit = $request->query->get('limit');

        return new Response($this->twig->render('@WebProfiler/Profiler/results.html.twig', array(
            'request' => $request,
            'token' => $token,
            'profile' => $profile,
            'tokens' => $this->profiler->find($ip, $url, $limit, $method, $start, $end),
            'ip' => $ip,
            'method' => $method,
            'url' => $url,
            'start' => $start,
            'end' => $end,
            'limit' => $limit,
            'panel' => null,
        )), 200, array('Content-Type' => 'text/html'));
    }

    /**
     * Narrows the search bar.
     *
     * @return Response A Response instance
     *
     * @throws NotFoundHttpException
     */
    public function searchAction(Request $request)
    {
        if (null === $this->profiler) {
            throw new NotFoundHttpException('The profiler must be enabled.');
        }

        $this->profiler->disable();

        $ip = preg_replace('/[^:\d\.]/', '', $request->query->get('ip'));
        $method = $request->query->get('method');
        $url = $request->query->get('url');
        $start = $request->query->get('start', null);
        $end = $request->query->get('end', null);
        $limit = $request->query->get('limit');
        $token = $request->query->get('token');

        if (null !== $session = $request->getSession()) {
            $session->set('_profiler_search_ip', $ip);
            $session->set('_profiler_search_method', $method);
            $session->set('_profiler_search_url', $url);
            $session->set('_profiler_search_start', $start);
            $session->set('_profiler_search_end', $end);
            $session->set('_profiler_search_limit', $limit);
            $session->set('_profiler_search_token', $token);
        }

        if (!empty($token)) {
            return new RedirectResponse($this->generator->generate('_profiler', array('token' => $token)), 302, array('Content-Type' => 'text/html'));
        }

        $tokens = $this->profiler->find($ip, $url, $limit, $method, $start, $end);

        return new RedirectResponse($this->generator->generate('_profiler_search_results', array(
            'token' => $tokens ? $tokens[0]['token'] : 'empty',
            'ip' => $ip,
            'method' => $method,
            'url' => $url,
            'start' => $start,
            'end' => $end,
            'limit' => $limit,
        )), 302, array('Content-Type' => 'text/html'));
    }

    /**
     * Displays the PHP info.
     *
     * @return Response A Response instance
     *
     * @throws NotFoundHttpException
     */
    public function phpinfoAction()
    {
        if (null === $this->profiler) {
            throw new NotFoundHttpException('The profiler must be enabled.');
        }

        $this->profiler->disable();

        ob_start();
        phpinfo();
        $phpinfo = ob_get_clean();

        return new Response($phpinfo, 200, array('Content-Type' => 'text/html'));
    }

    /**
     * Gets the Template Manager.
     *
     * @return TemplateManager The Template Manager
     */
    protected function getTemplateManager()
    {
        if (null === $this->templateManager) {
            $this->templateManager = new TemplateManager($this->profiler, $this->twig, $this->templates);
        }

        return $this->templateManager;
    }
}


text:
import clsx from 'clsx'
import getHeight from 'dom-helpers/height'
import qsa from 'dom-helpers/querySelectorAll'
import PropTypes from 'prop-types'
import React from 'react'
import { findDOMNode } from 'react-dom'

import * as dates from './utils/dates'
import BackgroundCells from './BackgroundCells'
import EventRow from './EventRow'
import EventEndingRow from './EventEndingRow'
import * as DateSlotMetrics from './utils/DateSlotMetrics'

class DateContentRow extends React.Component {
  constructor(...args) {
    super(...args)

    this.slotMetrics = DateSlotMetrics.getSlotMetrics()
  }

  handleSelectSlot = slot => {
    const { range, onSelectSlot } = this.props

    onSelectSlot(range.slice(slot.start, slot.end + 1), slot)
  }

  handleShowMore = (slot, target) => {
    const { range, onShowMore } = this.props
    let metrics = this.slotMetrics(this.props)
    let row = qsa(findDOMNode(this), '.rbc-row-bg')[0]

    let cell
    if (row) cell = row.children[slot - 1]

    let events = metrics.getEventsForSlot(slot)
    onShowMore(events, range[slot - 1], cell, slot, target)
  }

  createHeadingRef = r => {
    this.headingRow = r
  }

  createEventRef = r => {
    this.eventRow = r
  }

  getContainer = () => {
    const { container } = this.props
    return container ? container() : findDOMNode(this)
  }

  getRowLimit() {
    let eventHeight = getHeight(this.eventRow)
    let headingHeight = this.headingRow ? getHeight(this.headingRow) : 0
    let eventSpace = getHeight(findDOMNode(this)) - headingHeight

    return Math.max(Math.floor(eventSpace / eventHeight), 1)
  }

  renderHeadingCell = (date, index) => {
    let { renderHeader, getNow } = this.props

    return renderHeader({
      date,
      key: `header_${index}`,
      className: clsx(
        'rbc-date-cell',
        dates.eq(date, getNow(), 'day') && 'rbc-now'
      ),
    })
  }

  renderDummy = () => {
    let { className, range, renderHeader } = this.props
    return (

          {renderHeader && (

              {range.map(this.renderHeadingCell)}

          )}

    )
  }

  render() {
    const {
      date,
      rtl,
      range,
      className,
      selected,
      selectable,
      renderForMeasure,

      accessors,
      getters,
      components,

      getNow,
      renderHeader,
      onSelect,
      localizer,
      onSelectStart,
      onSelectEnd,
      onDoubleClick,
      resourceId,
      longPressThreshold,
      isAllDay,
    } = this.props

    if (renderForMeasure) return this.renderDummy()

    let metrics = this.slotMetrics(this.props)
    let { levels, extra } = metrics

    let WeekWrapper = components.weekWrapper

    const eventRowProps = {
      selected,
      accessors,
      getters,
      localizer,
      components,
      onSelect,
      onDoubleClick,
      resourceId,
      slotMetrics: metrics,
    }

    return (

        <BackgroundCells
          date={date}
          getNow={getNow}
          rtl={rtl}
          range={range}
          selectable={selectable}
          container={this.getContainer}
          getters={getters}
          onSelectStart={onSelectStart}
          onSelectEnd={onSelectEnd}
          onSelectSlot={this.handleSelectSlot}
          components={components}
          longPressThreshold={longPressThreshold}
        />

          {renderHeader && (

              {range.map(this.renderHeadingCell)}

          )}
          <WeekWrapper isAllDay={isAllDay} {...eventRowProps}>
            {levels.map((segs, idx) => (
              <EventRow key={idx} segments={segs} {...eventRowProps} />
            ))}
            {!!extra.length && (
              <EventEndingRow
                segments={extra}
                onShowMore={this.handleShowMore}
                {...eventRowProps}
              />
            )}
          </WeekWrapper>

    )
  }
}

DateContentRow.propTypes = {
  date: PropTypes.instanceOf(Date),
  events: PropTypes.array.isRequired,
  range: PropTypes.array.isRequired,

  rtl: PropTypes.bool,
  resourceId: PropTypes.any,
  renderForMeasure: PropTypes.bool,
  renderHeader: PropTypes.func,

  container: PropTypes.func,
  selected: PropTypes.object,
  selectable: PropTypes.oneOf([true, false, 'ignoreEvents']),
  longPressThreshold: PropTypes.number,

  onShowMore: PropTypes.func,
  onSelectSlot: PropTypes.func,
  onSelect: PropTypes.func,
  onSelectEnd: PropTypes.func,
  onSelectStart: PropTypes.func,
  onDoubleClick: PropTypes.func,
  dayPropGetter: PropTypes.func,

  getNow: PropTypes.func.isRequired,
  isAllDay: PropTypes.bool,

  accessors: PropTypes.object.isRequired,
  components: PropTypes.object.isRequired,
  getters: PropTypes.object.isRequired,
  localizer: PropTypes.object.isRequired,

  minRows: PropTypes.number.isRequired,
  maxRows: PropTypes.number.isRequired,
}

DateContentRow.defaultProps = {
  minRows: 0,
  maxRows: Infinity,
}

export default DateContentRow

redpajama_set_name: RedPajamaGithub


text:
using namespace std;
#include "runner.h"

class ZhangsanRunner : public Runner{
public:
	ZhangsanRunner();
	virtual ~ZhangsanRunner();
	void Exam();
	void Swim();
	void Bike();
	void Run();
private:
	string name_;
};
#endif


text:
[![Documentation Status](https://readthedocs.org/projects/damascus/badge/?version=latest)](http://damascus.readthedocs.io/en/latest/?badge=latest)
[![Build Status](https://travis-ci.com/temken/DaMaSCUS.svg?branch=master)](https://travis-ci.com/temken/DaMaSCUS)
[![codecov](https://codecov.io/gh/temken/DaMaSCUS/branch/master/graph/badge.svg)](https://codecov.io/gh/temken/DaMaSCUS)

# DaMaSCUS

Dark Matter Simulation Code for Underground Scatterings

[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.3726878.svg)](https://doi.org/10.5281/zenodo.3726878)
[![arXiv](https://img.shields.io/badge/arXiv-1706.02249-B31B1B.svg)](https://arxiv.org/abs/1706.02249)

DaMaSCUS Version 1.1 25/03/2020

## GENERAL NOTES

For the underlying physics we refer to the paper [![arXiv](https://img.shields.io/badge/arXiv-1706.02249-B31B1B.svg)](https://arxiv.org/abs/1706.02249).

- DaMaSCUS is a MC simulator of dark matter particles as they move through the Earth and scatter on terrestrial nuclei.
- It allows to compute the local distortions of the DM phase space caused by collisions with nuclei.
- The thusly distorted distribution functions and densities are used to give precise estimates of time-dependent signal rates for direct detection experiments and diurnal modulations.
- A full, realistic model of the Earth is implemented as well as the Earth's time-dependent velocity and orientation in the galactic frame.
- DaMaSCUS is written in C++ and fully parallelized (openMPI).

## INSTALLATION AND USAGE

For installation and usage we refer to the [documentation](http://damascus.readthedocs.io/en/latest/).

## Updates
The code will be updated continuously. Here I list only important updates and major bug fixes
- `25.03.2020`: Release of v1.1
- `16.08.2017`: Release of v1.0.2: Re-structuring of the folder structure and new documentation.
- `15.06.2017`: Release of v1.0.1: major bug fix concerning mostly very high cross-sections.
- `06.06.2017`: Release of v1.0

## CITING DaMaSCUS

If you decide to use this code, please cite

>Emken, T. & Kouvaris, C., 2017, DaMaSCUS, Astrophysics Source Code Library, record [[ascl:1706.003]](https://ascl.net/1706.003)

as well as the original publication,

>Emken, T. & Kouvaris, C., DaMaSCUS: The Impact of Underground Scatterings on Direct Detection of Light Dark Matter,
[![JCAP](https://img.shields.io/badge/JCAP-1710(2017)no.10,031-255773.svg)](http://iopscience.iop.org/article/10.1088/1475-7516/2017/10/031/meta),
[![arXiv](https://img.shields.io/badge/arXiv-1706.02249-B31B1B.svg)](https://arxiv.org/abs/1706.02249)

In addition, version 1.1 of the code is archived under

> [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.3726878.svg)](https://doi.org/10.5281/zenodo.3726878)

## AUTHORS & CONTACT

The authors of DaMaSCUS are Timon Emken and Chris Kouvaris.

For questions, bug reports or other suggestions please contact Timon Emken (emken@chalmers.se).

## LICENSE

This project is licensed under the MIT License - see the LICENSE file.


text:
![Nuget](https://img.shields.io/nuget/v/Orleans.Providers.MongoDB)

> Feedback would be appreciated.

A MongoDb implementation of the Orleans Providers.

This includes

 * Membership (`IMembershipTable` & `IGatewayListProvider`)
 * Reminders (`IReminderTable`)
 * Storage (`IStoragePRovider`)

## Installation

```ps
install-package Orleans.Providers.MongoDB
```

## Setup

### Install MongoDB (BREAKING CHANGE)

From 3.1 onwards you have to register the IMongoClient in the service locator.

```csharp
### Server side

# via Silo Host Builder (ISiloHostBuilder)
var silo = new SiloHostBuilder()
    .UseMongoDBClient("mongodb://localhost")
    ...
    .Build();

# via Generic Host + Silo Builder (ISiloBuilder)
var host = Host.CreateDefaultBuilder(args)
	.UseOrleans((context, siloBuilder) => {
		siloBuilder.UseMongoDBClient("mongodb://localhost")
		...
	});

### Client side
var client = new ClientBuilder()
    .UseMongoDBClient("mongodb://localhost")
    ...
    .Build();
```

as an alternative you can also implement the IMongoClientFactory interface and override the client names with options.

There is also an overload of ```UseMongoDBClient()``` that takes a ```Func<IServiceProvider, MongoClientSettings>``` which allows you specify all MongoDB connection settings individually. This is especially useful, if you need to separate network settings and credentials into different configuration variables, or if you want to bind to an ```IOptions<T>``` configuration as shown below.

```csharp
[...]
  .UseMongoDBClient(provider =>
    {
      var cfg = provider.GetRequiredService<IOptions<MyMongoDbConfiguration>>();

      var settings = MongoClientSettings.FromConnectionString(cfg.Value.ConnectionString);
      settings.Credential = MongoCredential.CreateCredential(cfg.Value.AuthDatabase, cfg.Value.UserName, cfg.Value.Password);

      return settings;
    })
[...]
```

### Membership

Use the client builder to setup mongo db:

```csharp
var client = new ClientBuilder()
    .UseMongoDBClustering(options =>
    {
        options.DatabaseName = dbName;
        options.Strategy = MongoDBMembershipStrategy.Muiltiple
    })
    ...
    .Build();
```

and the same for the silo builder:

```csharp
var silo = new SiloHostBuilder()
     .UseMongoDBClustering(options =>
    {
        options.DatabaseName = dbName;
        options.Strategy = MongoDBMembershipStrategy.Muiltiple
    })
    ...
    .Build();
```

The provider supports three different strategies for membership management:

1. ```SingleDocument```: A single document per deployment. Fastest for small clusters.
2. ```Multiple```: One document per silo and an extra document for the table version. Needs a replica set and transaction support to work properly.
3. ```MultipleDeprecated```: One document per silo but no support for the extended membership protocol. Not recommended.

### Reminders

Just use the silo builder:

```csharp
var silo = new SiloHostBuilder()
    .UseMongoDBReminders(options =>
    {
        options.DatabaseName = dbName;
        options.CreateShardKeyForCosmos = createShardKey;
    })
    ...
    .Build();
```

### Storage

Just use the silo builder:

```csharp
var silo = new SiloHostBuilder()
    .AddMongoDBGrainStorage("grains-storage-provider-name",
    options =>
    {
        options.DatabaseName = dbName;
        options.CreateShardKeyForCosmos = createShardKey;
    })
    ...
    .Build();
```

### Storage Serializers
Mongo provider supports the following serializers:
* `JsonGrainStateSerializer (Default)`: uses Newtonsoft.JSON
* `BinaryGrainStateSerializer`: uses Orleans binary serializer
* `BsonGrainStateSerializer`: uses [BsonSerializer](https://mongodb.github.io/mongo-csharp-driver/2.18/reference/bson/serialization/)

### How to configure `JsonGrainStateSerializer`
```csharp
services.Configure<JsonGrainStateSerializerOptions>(options =>
{
    options.ConfigureJsonSerializerSettings = settings =>
    {
        settings.NullValueHandling = NullValueHandling.Include;
        settings.DefaultValueHandling = DefaultValueHandling.Populate;
        settings.ObjectCreationHandling = ObjectCreationHandling.Replace;
    });
});
```

### How to change default serializer
For example, in order to change the default from `JsonGrainStateSerializer` to `BsonGrainStateSerializer`
```csharp
services.AddSingleton<IGrainStateSerializer, BsonGrainStateSerializer>();
```

### How to configure serializer for a specific storage provider
For example in order to use binary serializer for **PubSubStore**
```csharp
services.AddSingletonNamedService<IGrainStateSerializer, BinaryGrainStateSerializer>("PubSubStore");
...
var silo = new SiloHostBuilder()
    .AddMongoDBGrainStorage("PubSubStore", options => options.DatabaseName = dbName)
    ...
    .Build();
```

## Remarks

As you can see you have to pass in the connection string to each provider. But we will only create one MongoDB client for each unique connection string to keep the number of connections to your cluster or server as low as possible.

## Building the unit tests

In order to make use of many tests already defined in [Orleans](https://github.com/dotnet/orleans/), the [unit test project of this module](https://github.com/OrleansContrib/Orleans.Providers.MongoDB/tree/master/UnitTest) depends on [TesterInternal](https://github.com/dotnet/orleans/tree/main/test/TesterInternal), which is added as a project reference from the local path [./libs](https://github.com/OrleansContrib/Orleans.Providers.MongoDB/tree/master/libs) where the whole Orleans source code is mirrored as a [git submodule](https://git-scm.com/docs/git-submodule).

This comes with two caveats:
* Depending on your git client, the submodules are sometimes not pulled automatically. If you find the ./libs subdirectory to be empty, execute ```git pull --recurse-submodules``` manually from the command shell
* some of the projects in the ./libs subfolder need F# support to be present in your VisualStudio installation, otherwise you will receive an error message about an unsupported language. This may apply to other IDEs as well


text:
.. currentmodule:: bifacial_radiance

#############
API reference
#############
.. _manualapi:

GUI
==========

.. autosummary::
   :toctree: generated/
   :caption: GUI

   gui

Classes
=======

This is a collection of classes used by bifacial_radiance for users that prefer object-oriented programming.

.. autosummary::
   :toctree: generated/
   :caption: Classes

   MetObj
   RadianceObj
   GroundObj
   ModuleObj
   SceneObj
   AnalysisObj

Sky
====

Functions and methods for dealing with weather, calculating solar position and generating the skies for the raytrace simulations.

Weather
-------

.. autosummary::
   :toctree: generated/
   :caption: Weather

   RadianceObj.getEPW
   RadianceObj.readWeatherFile

Sky Dome
--------
Functions and methods for establishing the sources or sky domes for the simulation

.. autosummary::
   :toctree: generated/
   :caption: Sky Dome

   RadianceObj.genCumSky
   RadianceObj.genCumSky1axis
   RadianceObj.gendaylit
   RadianceObj.gendaylit2manual
   RadianceObj.gendaylit1axis

Geometry
========

Modules
-------
Functions and methods to generate modules

.. autosummary::
   :toctree: generated/
   :caption: Modules

   RadianceObj.makeModule
   ModuleObj.addTorquetube
   ModuleObj.addCellModule
   ModuleObj.addFrame
   ModuleObj.addOmega
   ModuleObj.showModule
   ModuleObj.readModule
   ModuleObj.compileText
   RadianceObj.returnMaterialFiles

Scene
-----
Functions and methods to generate the scene.

.. autosummary::
   :toctree: generated/
   :caption: Scene

   RadianceObj.setGround
   RadianceObj.set1axis
   RadianceObj.makeScene
   RadianceObj.makeScene1axis
   RadianceObj.makeOct
   RadianceObj.makeOct1axis

Support methods for scene

.. autosummary::
   :toctree: generated/

   SceneObj.showScene
   RadianceObj.makeCustomObject
   RadianceObj.appendtoScene

Analysis
==========

Methods for irradiance calculations
-----------------------------------

.. autosummary::
   :toctree: generated/
   :caption: Irradiance Analysis

   AnalysisObj.moduleAnalysis
   AnalysisObj.analysis
   RadianceObj.analysis1axis

Mismatch
--------

.. autosummary::
   :toctree: generated/
   :caption: Mismatch Analysis

   mismatch.analysisIrradianceandPowerMismatch

Support
=======

Input / Output
--------------

.. autosummary::
   :toctree: generated/
   :caption: Input / Output

   load
   load.loadRadianceObj
   load.loadTrackerDict
   RadianceObj.loadtrackerdict
   load.read1Result
   load.cleanResult
   load.deepcleanResult
   RadianceObj.exportTrackerDict
   RadianceObj.save

Visualization
-------------

Functions for visualizing irradiance results

.. autosummary::
   :toctree: generated/
   :caption: Visualization

   AnalysisObj.makeFalseColor
   AnalysisObj.makeImage
   SceneObj.showScene

Others
------

.. autosummary::
   :toctree: generated/
   :caption: Other

   RadianceObj.getfilelist
   RadianceObj.getSingleTimestampTrackerAngle
   RadianceObj.returnOctFiles

ModelChain
----------

.. autosummary::
   :toctree: generated/
   :caption: ModelChain

   load.readconfigurationinputfile
   modelchain.runModelChain
   load.savedictionariestoConfigurationIniFile

Spectral Analysis
-----------------

.. autosummary::
   :toctree: generated/
   :caption: Spectral Analysis

   spectral_utils
   spectral_utils.generate_spectra


text:
title: Static properties to access the class representation
sidebar: flexberry-orm_sidebar
keywords: Flexberry ORM, data objects, performance
summary: the benefits of using static class representations in application development
toc: true
permalink: en/fo_static-view-accessors.html
lang: en
autotranslated: true
hash: 6fa8a18474617b3a75b9c4fb5f2ed011ed131516b75607a90aae955c28e1f9cb
---

When loading objects almost always need to specify a [view](fd_view-definition.html). To this may be a string name of the desired view. This involves the following challenges:

* The existence of a representation cannot be checked at compile time.
* When writing code there is no convenient way to choose representation from a list of all class representations.

For convenience, the classes of data objects added static properties to access all static [concepts class](fd_view-definition.html). For each generated service class, the nested class `Views`, and for each view is generated by a property to access this view.

It is recommended to use these properties in any work ideas class. This allows to timely detect errors associated with the deletion or renaming of PDW submissions (this error will occur at compile time and not at run time).

### Examples

Without using static properties:

``` csharp
View view = Information.GetView("КошкаL", typeof(Кошка));
```

Using static properties:

``` csharp
View view = Кошка.Views.КошкаL;
```

Example of specifying the static properties is available at [https://github.com/Flexberry/FlexberryORM-DemoApp/blob/master/FlexberryORM/CDLIB/Objects/CDDA.cs](https://github.com/Flexberry/FlexberryORM-DemoApp/blob/master/FlexberryORM/CDLIB/Objects/CDDA.cs).


text:
const { convertCommonJSToBrowserJS, genFile } = require("../cli/helpers.js");

const data = {
    js_codec: convertCommonJSToBrowserJS("lib/codec"),
    js_crypto_engine: convertCommonJSToBrowserJS("lib/cryptoEngine/cryptojsEngine"),
    js_formater: convertCommonJSToBrowserJS("lib/formater"),
};

genFile(data, "./index.html", "./scripts/index_template.html");


text:
from flask import Flask
from flask_restful import Api
from resources import UserListResource, RecordingListResource, PermissionListResource
from resources import UserResource, RecordingResource, PermissionResource

def create_app():
    app = Flask(__name__)
    api = Api(app)

    api.add_resource(UserListResource, '/users', endpoint='users')
    api.add_resource(UserResource, '/users/<string:id>', endpoint='user')

    api.add_resource(RecordingListResource, '/recordings', endpoint='recordings')
    api.add_resource(RecordingResource, '/recordings/<string:id>', endpoint='recording')

    api.add_resource(PermissionResource, '/users/<string:user_id>/permissions/<string:recording_id>',
                     endpoint='permission')
    api.add_resource(PermissionListResource, '/users/<string:user_id>/permissions', endpoint='permissions')

    return app

if __name__ == '__main__':
    create_app().run(debug=True)


text:
import os
import sys
import signal
import psutil
import logging
logging.basicConfig(filename='daemon.log', level=logging.INFO)

def stop(pgid):
    logging.info(f"Stopping pgid {pgid} by ray_daemon.")
    try:
        # SIGTERM may not kill all the children processes in the group.
        os.killpg(pgid, signal.SIGKILL)
    except Exception:
        logging.error("Cannot kill pgid: {}".format(pgid))

def manager():
    pid_to_watch = int(sys.argv[1])
    pgid_to_kill = int(sys.argv[2])
    import time
    while psutil.pid_exists(pid_to_watch):
        time.sleep(1)
    stop(pgid_to_kill)

if __name__ == "__main__":
    manager()


text:
"""
Example: Nested Sampling for Gaussian Shells
============================================

This example illustrates the usage of the contrib class NestedSampler,
which is a wrapper of `jaxns` library ([1]) to be used for NumPyro models.

Here we will replicate the Gaussian Shells demo at [2] and compare against
NUTS sampler.

**References:**

    1. jaxns library: https://github.com/Joshuaalbert/jaxns
    2. dynesty's Gaussian Shells demo:
       https://github.com/joshspeagle/dynesty/blob/master/demos/Examples%20--%20Gaussian%20Shells.ipynb
"""

import argparse

import matplotlib.pyplot as plt

from jax import random
import jax.numpy as jnp

import numpyro
from numpyro.contrib.nested_sampling import NestedSampler
import numpyro.distributions as dist
from numpyro.infer import MCMC, NUTS, DiscreteHMCGibbs

class GaussianShell(dist.Distribution):
    support = dist.constraints.real_vector

    def __init__(self, loc, radius, width):
        self.loc, self.radius, self.width = loc, radius, width
        super().__init__(batch_shape=loc.shape[:-1], event_shape=loc.shape[-1:])

    def sample(self, key, sample_shape=()):
        return jnp.zeros(
            sample_shape + self.shape()
        )  # a dummy sample to initialize the samplers

    def log_prob(self, value):
        normalizer = (-0.5) * (jnp.log(2.0 * jnp.pi) + 2.0 * jnp.log(self.width))
        d = jnp.linalg.norm(value - self.loc, axis=-1)
        return normalizer - 0.5 * ((d - self.radius) / self.width) ** 2

def model(center1, center2, radius, width, enum=False):
    z = numpyro.sample(
        "z", dist.Bernoulli(0.5), infer={"enumerate": "parallel"} if enum else {}
    )
    x = numpyro.sample("x", dist.Uniform(-6.0, 6.0).expand([2]).to_event(1))
    center = jnp.stack([center1, center2])[z]
    numpyro.sample("shell", GaussianShell(center, radius, width), obs=x)

def run_inference(args, data):
    print("=== Performing Nested Sampling ===")
    ns = NestedSampler(model)
    ns.run(random.PRNGKey(0), **data, enum=args.enum)
    ns.print_summary()
    # samples obtained from nested sampler are weighted, so
    # we need to provide random key to resample from those weighted samples
    ns_samples = ns.get_samples(random.PRNGKey(1), num_samples=args.num_samples)

    print("\n=== Performing MCMC Sampling ===")
    if args.enum:
        mcmc = MCMC(
            NUTS(model), num_warmup=args.num_warmup, num_samples=args.num_samples
        )
    else:
        mcmc = MCMC(
            DiscreteHMCGibbs(NUTS(model)),
            num_warmup=args.num_warmup,
            num_samples=args.num_samples,
        )
    mcmc.run(random.PRNGKey(2), **data, enum=args.enum)
    mcmc.print_summary()
    mcmc_samples = mcmc.get_samples()

    return ns_samples["x"], mcmc_samples["x"]

def main(args):
    data = dict(
        radius=2.0,
        width=0.1,
        center1=jnp.array([-3.5, 0.0]),
        center2=jnp.array([3.5, 0.0]),
    )
    ns_samples, mcmc_samples = run_inference(args, data)

    # plotting
    fig, (ax1, ax2) = plt.subplots(
        2, 1, sharex=True, figsize=(8, 8), constrained_layout=True
    )

    ax1.plot(mcmc_samples[:, 0], mcmc_samples[:, 1], "ro", alpha=0.2)
    ax1.set(
        xlim=(-6, 6),
        ylim=(-2.5, 2.5),
        ylabel="x[1]",
        title="Gaussian-shell samples using NUTS",
    )

    ax2.plot(ns_samples[:, 0], ns_samples[:, 1], "ro", alpha=0.2)
    ax2.set(
        xlim=(-6, 6),
        ylim=(-2.5, 2.5),
        xlabel="x[0]",
        ylabel="x[1]",
        title="Gaussian-shell samples using Nested Sampler",
    )

    plt.savefig("gaussian_shells_plot.pdf")

if __name__ == "__main__":
    assert numpyro.__version__.startswith("0.10.1")
    parser = argparse.ArgumentParser(description="Nested sampler for Gaussian shells")
    parser.add_argument("-n", "--num-samples", nargs="?", default=10000, type=int)
    parser.add_argument("--num-warmup", nargs="?", default=1000, type=int)
    parser.add_argument(
        "--enum",
        action="store_true",
        default=False,
        help="whether to enumerate over the discrete latent variable",
    )
    parser.add_argument("--device", default="cpu", type=str, help='use "cpu" or "gpu".')
    args = parser.parse_args()

    numpyro.set_platform(args.device)

    main(args)


text:
Spectra S3 Python SDK
--------------

[![Apache V2 License](http://img.shields.io/badge/license-Apache%20V2-blue.svg)](https://github.com/SpectraLogic/ds3_python_sdk/blob/master/LICENSE.md)

An SDK conforming to the Spectra S3 [specification](https://developer.spectralogic.com/doc/ds3api/1.2/wwhelp/wwhimpl/js/html/wwhelp.htm).

Contact Us
----------

Join us at our [Google Groups](https://groups.google.com/d/forum/spectralogicds3-sdks) forum to ask questions, or see frequently asked questions.

Installing
----------

Follow the instructions for installing the [ds3_c_sdk](https://github.com/SpectraLogic/ds3_c_sdk) first.  The ds3_python_sdk uses the ds3_c_sdk to communicate with a Spectra S3 endpoint, and will not function without it.

To install the ds3_python_sdk, either clone the latest code, or download a release bundle from [Releases](http://github.com/SpectraLogic/ds3_python_sdk/releases).  Once the code has been download, cd into the bundle, and install it with `sudo python setup.py install`

Once `setup.py` completes the ds3_python_sdk should be installed and available to be imported into python scripts.

Documentation
-------------
The documentation for the SDK can be found at [http://spectralogic.github.io/ds3_python_sdk/sphinx/v1.0-0/](http://spectralogic.github.io/ds3_python_sdk/sphinx/v1.0-0/)

SDK
---

The SDK provides an interface for a user to add Spectra S3 functionality to their existing or new python application.  In order to take advantage of the SDK you need to import the `ds3` python package and module.  The following is an example that creates a Spectra S3 client from environment variables, creates a bucket, and lists all the buckets that are visible to the user.

```python

from ds3 import ds3

client = ds3.createClientFromEnv()

client.putBucket("testBucket")

for bucket in client.getService():
        print bucket.name
```

Ds3Client
---------
In the ds3_python_sdk there are two ways that you can create a `Ds3Client` instance: environment variables, or manually.  `ds3.createClientFromEnv` will create a `Ds3Client` using the following environment variables:

* `DS3_ENDPOINT` - The URL to the DS3 Endpoint
* `DS3_ACCESS_KEY` - The DS3 access key
* `DS3_SECRET_KEY` - The DS3 secret key
* `http_proxy` - If set, the `Ds3Client` instance will proxy through this URL

The `Ds3Client` instance can also be created manually in code with:

```python

from ds3 import ds3

client = ds3.Ds3Client("endpoint", ds3.Credentials("access_key", "secret_key"))

```

The proxy URL can be passed in as the named parameter `proxy` to `Ds3Client()`.

Putting Data
------------

To put data to a Spectra S3 appliance you have to do it inside of the context of what is called a Bulk Job.  Bulk Jobs allow the Spectra S3 appliance to plan how data should land to cache, and subsequently get written/read to/from tape.  The basic flow of every job is:

* Generate the list of objects that will either be sent to or retrieved from Spectra S3
* Send a bulk put/get to Spectra S3 to plan the job
* The job will be split into multiple chunks.  An application must then get the available list of chunks that can be processed
* For each chunk that can be processed, sent the object (this step can be done in parallel)
* Repeat getting the list of available chunks until all chunks have been processed

[An example of the above using the Python SDK for putting data] (samples/puttingData.py)

[An example of getting data with the Python SDK] (samples/gettingData.py)

[An example of using getService and getBucket to list all accessible buckets and objects] (samples/listAll.py)

[An example of how give objects on the server a different name than what is on the filesystem, and how to delete objects by folder] (samples/renaming.py)


text:
namespace VirtualMachineScreenSaver
{
	public static class Program
	{
		public static void Main(string[] args)
		{
			new VirtualMachineGameWindow().Run();
		}
	}
}