text:
package main

import (
	"os"

	"github.com/odedlaz/docker-registry-cli/core"
	"github.com/odedlaz/docker-registry-cli/core/cli"
	"github.com/odedlaz/docker-registry-cli/core/config"
	"github.com/odedlaz/docker-registry-cli/operations"
	"gopkg.in/alecthomas/kingpin.v2"
)

func main() {
	parsed := kingpin.MustParse(cli.App.Parse(os.Args[1:]))
	settings, err := config.Load(*cli.ConfigFilename)

	if parsed != cli.AddRegistryCommandName && parsed != cli.MigrateCommandName {
		if len((*settings).Auths) == 0 {
			cli.App.Errorf(err.Error())
			os.Exit(1)
		}
	}

	switch parsed {
	case cli.AddRegistryCommandName:
		cli.RegistrySet()
		core.Must(operations.AddRegistry(*cli.Registry, *settings))
	case cli.RemoveRegistryCommandName:
		cli.RegistrySetAndExists(settings)
		core.Must(operations.RemoveRegistry(*cli.Registry, *settings))
	case cli.ListRegistryCommandName:
		core.Must(operations.ListRegistries(*settings))
	case cli.ListRepositoriesCommandName:
		cli.RegistrySetAndExists(settings)
		core.Must(operations.ListRepositories(*cli.Registry, *settings))
	case cli.MigrateCommandName:
		core.Must(operations.Migrate(*cli.MigrateCommandConfigFilename, *cli.ConfigFilename))
	default:
		cli.App.Errorf("unknown option: %s", parsed)
	}
}


text:
"""Tests for aws module - ec2.py."""

import typing
import unittest
import mock

from libcloudforensics import errors
from libcloudforensics.providers.aws.internal import ebs
from libcloudforensics.providers.aws.internal import ec2
from tests.providers.aws import aws_mocks

class AWSInstanceTest(unittest.TestCase):
  """Test AWSInstance class."""
  # pylint: disable=line-too-long

  @typing.no_type_check
  @mock.patch('libcloudforensics.providers.aws.internal.account.AWSAccount.ResourceApi')
  @mock.patch('libcloudforensics.providers.aws.internal.account.AWSAccount.ClientApi')
  def testGetBootVolume(self, mock_ec2_api, mock_resource_api):
    """Test that the boot volume is retrieved if existing."""
    describe_volumes = mock_ec2_api.return_value.describe_volumes
    instance = mock_resource_api.return_value.Instance
    describe_volumes.return_value = aws_mocks.MOCK_DESCRIBE_VOLUMES_TAGS
    instance.return_value.root_device_name = '/dev/spf'

    boot_volume = aws_mocks.FAKE_INSTANCE.GetBootVolume()
    self.assertIsInstance(boot_volume, ebs.AWSVolume)
    self.assertEqual('fake-boot-volume-id', boot_volume.volume_id)

class EC2Test(unittest.TestCase):
  """Test the EC2 class."""
  # pylint: disable=line-too-long

  @typing.no_type_check
  @mock.patch('libcloudforensics.providers.aws.internal.account.AWSAccount.ClientApi')
  def testListInstances(self, mock_ec2_api):
    """Test that instances of an account are correctly listed."""
    describe_instances = mock_ec2_api.return_value.describe_instances
    describe_instances.return_value = aws_mocks.MOCK_DESCRIBE_INSTANCES
    instances = aws_mocks.FAKE_AWS_ACCOUNT.ec2.ListInstances()
    self.assertEqual(1, len(instances))
    self.assertIn('fake-instance-id', instances)
    self.assertEqual('fake-zone-2', instances['fake-instance-id'].region)
    self.assertEqual(
        'fake-zone-2b', instances['fake-instance-id'].availability_zone)

    describe_instances.return_value = aws_mocks.MOCK_DESCRIBE_INSTANCES_TAGS
    instances = aws_mocks.FAKE_AWS_ACCOUNT.ec2.ListInstances()
    self.assertIn('fake-instance-with-name-id', instances)
    self.assertEqual(
        'fake-instance', instances['fake-instance-with-name-id'].name)

  @typing.no_type_check
  @mock.patch('libcloudforensics.providers.aws.internal.ec2.EC2.ListInstances')
  def testGetInstanceById(self, mock_list_instances):
    """Test that an instance of an account can be found by its ID."""
    mock_list_instances.return_value = aws_mocks.MOCK_LIST_INSTANCES
    found_instance = aws_mocks.FAKE_AWS_ACCOUNT.ec2.GetInstanceById(
        aws_mocks.FAKE_INSTANCE.instance_id)
    self.assertIsInstance(found_instance, ec2.AWSInstance)
    self.assertEqual('fake-instance-id', found_instance.instance_id)
    self.assertEqual('fake-zone-2', found_instance.region)
    self.assertEqual('fake-zone-2b', found_instance.availability_zone)
    with self.assertRaises(errors.ResourceNotFoundError):
      aws_mocks.FAKE_AWS_ACCOUNT.ec2.GetInstanceById('non-existent-instance-id')

  @typing.no_type_check
  @mock.patch('libcloudforensics.providers.aws.internal.ec2.EC2.ListInstances')
  def testGetInstancesByName(self, mock_list_instances):
    """Test that an instance of an account can be found by its name."""
    mock_list_instances.return_value = aws_mocks.MOCK_LIST_INSTANCES
    found_instances = aws_mocks.FAKE_AWS_ACCOUNT.ec2.GetInstancesByName(
        aws_mocks.FAKE_INSTANCE_WITH_NAME.name)
    self.assertEqual(1, len(found_instances))
    self.assertIsInstance(found_instances[0], ec2.AWSInstance)
    self.assertEqual(
        'fake-instance-with-name-id', found_instances[0].instance_id)
    self.assertEqual('fake-zone-2', found_instances[0].region)
    self.assertEqual('fake-zone-2b', found_instances[0].availability_zone)

    found_instances = aws_mocks.FAKE_AWS_ACCOUNT.ec2.GetInstancesByName(
        'non-existent-instance-name')
    self.assertEqual(0, len(found_instances))

  @typing.no_type_check
  @mock.patch('libcloudforensics.providers.aws.internal.ec2.EC2.ListInstances')
  def testGetInstancesByNameOrId(self, mock_list_instances):
    """Test that an instance of an account can be found by its name or ID."""
    mock_list_instances.return_value = aws_mocks.MOCK_LIST_INSTANCES
    found_instances = aws_mocks.FAKE_AWS_ACCOUNT.ec2.GetInstancesByNameOrId(
        instance_id=aws_mocks.FAKE_INSTANCE.instance_id)
    self.assertEqual(1, len(found_instances))
    self.assertEqual('fake-instance-id', found_instances[0].instance_id)

    found_instances = aws_mocks.FAKE_AWS_ACCOUNT.ec2.GetInstancesByNameOrId(
        instance_name=aws_mocks.FAKE_INSTANCE_WITH_NAME.name)
    self.assertEqual(1, len(found_instances))
    self.assertEqual(
        'fake-instance-with-name-id', found_instances[0].instance_id)

    with self.assertRaises(ValueError):
      aws_mocks.FAKE_AWS_ACCOUNT.ec2.GetInstancesByNameOrId()

    with self.assertRaises(ValueError):
      aws_mocks.FAKE_AWS_ACCOUNT.ec2.GetInstancesByNameOrId(
          instance_id=aws_mocks.FAKE_INSTANCE.instance_id,
          instance_name=aws_mocks.FAKE_INSTANCE_WITH_NAME.name)

  @typing.no_type_check
  @mock.patch('libcloudforensics.scripts.utils.ReadStartupScript')
  @mock.patch('libcloudforensics.providers.aws.internal.ec2.EC2.GetInstancesByName')
  @mock.patch('libcloudforensics.providers.aws.internal.account.AWSAccount.ClientApi')
  def testGetOrCreateVm(self,
                                mock_ec2_api,
                                mock_get_instance,
                                mock_script):
    """Test that a VM is created or retrieved if it already exists."""
    mock_get_instance.return_value = [aws_mocks.FAKE_INSTANCE_WITH_NAME]
    mock_script.return_value = ''
    # GetOrCreateVm(vm_name, boot_volume_size, AMI, cpu_cores) where
    # vm_name is the name of an analysis instance that already exists.
    vm, created = aws_mocks.FAKE_AWS_ACCOUNT.ec2.GetOrCreateVm(
        aws_mocks.FAKE_INSTANCE_WITH_NAME.name, 1, 'ami-id', 2)
    mock_get_instance.assert_called_with(aws_mocks.FAKE_INSTANCE_WITH_NAME.name)
    mock_ec2_api.return_value.run_instances.assert_not_called()
    self.assertIsInstance(vm, ec2.AWSInstance)
    self.assertEqual('fake-instance', vm.name)
    self.assertFalse(created)

    # GetOrCreateVm(non_existing_vm, boot_volume_size, AMI, cpu_cores).
    # We mock the GetInstanceById() call to return an empty list, which should
    # mimic an instance that wasn't found. This should trigger run_instances
    # to be called.
    mock_get_instance.return_value = []
    vm, created = aws_mocks.FAKE_AWS_ACCOUNT.ec2.GetOrCreateVm(
        'non-existent-instance-name', 1, 'ami-id', 2)
    mock_get_instance.assert_called_with('non-existent-instance-name')
    mock_ec2_api.return_value.run_instances.assert_called()
    self.assertIsInstance(vm, ec2.AWSInstance)
    self.assertEqual('non-existent-instance-name', vm.name)
    self.assertTrue(created)

  @typing.no_type_check
  @mock.patch('libcloudforensics.providers.aws.internal.account.AWSAccount.ClientApi')
  def testGetBootVolumeConfigByAmi(self, mock_ec2_api):
    """Test that the boot volume configuration is correctly created."""
    # pylint: disable=protected-access,line-too-long
    mock_ec2_api.return_value.describe_images.return_value = aws_mocks.MOCK_DESCRIBE_AMI
    self.assertIsNone(
        aws_mocks.MOCK_DESCRIBE_AMI['Images'][0]['BlockDeviceMappings'][0]
        ['Ebs']['VolumeSize'])
    self.assertIsNone(
        aws_mocks.MOCK_DESCRIBE_AMI['Images'][0]['BlockDeviceMappings'][0]
        ['Ebs']['VolumeType'])
    config = aws_mocks.FAKE_AWS_ACCOUNT.ec2._GetBootVolumeConfigByAmi(
        'ami-id', 50, 'fake-volume-type')
    # pylint: enable=protected-access,line-too-long
    self.assertEqual(50, config['Ebs']['VolumeSize'])
    self.assertEqual('fake-volume-type', config['Ebs']['VolumeType'])

  @typing.no_type_check
  @mock.patch('libcloudforensics.providers.aws.internal.account.AWSAccount.ClientApi')
  def testListImages(self, mock_ec2_api):
    """Test that AMI images are correctly listed."""
    describe_images = mock_ec2_api.return_value.describe_images
    describe_images.return_value = aws_mocks.MOCK_DESCRIBE_IMAGES
    images = aws_mocks.FAKE_AWS_ACCOUNT.ec2.ListImages()
    self.assertEqual(2, len(images))
    self.assertIn('Name', images[0])

redpajama_set_name: RedPajamaGithub


text:
struct neighbour;
struct babel_route;
struct xroute;

#define LOCAL_FLUSH 0
#define LOCAL_ADD 1
#define LOCAL_CHANGE 2

#ifndef MAX_LOCAL_SOCKETS
#define MAX_LOCAL_SOCKETS 4
#endif

#define LOCAL_BUFSIZE 1024

struct local_socket {
    int fd;
    char *buf;
    int n;
    int monitor;
};

extern int local_server_socket;
extern struct local_socket local_sockets[MAX_LOCAL_SOCKETS];
extern int num_local_sockets;
extern int local_server_port;
extern char *local_server_path;

void local_notify_interface(struct interface *ifp, int kind);
void local_notify_neighbour(struct neighbour *neigh, int kind);
void local_notify_xroute(struct xroute *xroute, int kind);
void local_notify_route(struct babel_route *route, int kind);
int local_read(struct local_socket *s);
int local_header(struct local_socket *s);
struct local_socket *local_socket_create(int fd);
void local_socket_destroy(int i);


text:
typedef NS_ENUM(NSInteger, AVAudioQuality) { AVAudioQualityMin = 0, AVAudioQualityLow = 0x20, AVAudioQualityMedium = 0x40, AVAudioQualityHigh = 0x60, AVAudioQualityMax = 0x7F };

struct AVAudio3DPoint {
    float x;
    float y;
    float z;
};
typedef struct AVAudio3DPoint AVAudio3DVector;

struct AVAudio3DVectorOrientation {
    AVAudio3DVector forward;
    AVAudio3DVector up;
};

struct AVAudio3DAngularOrientation {
    float yaw;
    float pitch;
    float roll;
};

typedef int64_t AVAudioFramePosition;
typedef uint32_t AVAudioFrameCount;
typedef uint32_t AVAudioChannelCount;
typedef void (^AVAudioNodeCompletionBlock)(void);
typedef NSUInteger AVAudioNodeBus;
typedef struct AVAudio3DPoint AVAudio3DPoint;
typedef struct AVAudio3DVectorOrientation AVAudio3DVectorOrientation;
typedef struct AVAudio3DAngularOrientation AVAudio3DAngularOrientation;

typedef enum : NSInteger {
    AVCaptureVideoOrientationPortrait = 1,
    AVCaptureVideoOrientationPortraitUpsideDown,
    AVCaptureVideoOrientationLandscapeRight,
    AVCaptureVideoOrientationLandscapeLeft,
} AVCaptureVideoOrientation;

AVFOUNDATION_EXPORT CGRect AVMakeRectWithAspectRatioInsideRect(CGSize aspectRatio, CGRect boundingRect) STUB_METHOD;


text:
👍🎉 First off, thanks for taking the time to contribute! 🎉👍

These contribution guidelines are mostly just that - guidelines, not rules. This is what we've found to work best over the years, but if you choose to ignore them, we still love you! 💖 Use your best judgement, and feel free to propose changes to this document in a pull request.

## Coding not your thing? Or want more ways to contribute?

This document covers contributing to the codebase of the CMS but [the community site has plenty of inspiration for other ways to get involved.][get involved]

If you don't feel you'd like to make code changes here, you can visit our [documentation repository][docs repo] and use your experience to contribute to making the docs we have, even better.

We also encourage community members to feel free to comment on others' pull requests and issues - the expertise we have is not limited to the Core Collaborators and HQ. So, if you see something on the issue tracker or pull requests you feel you can add to, please don't be shy.

## Table of contents

- [Before you start](#before-you-start)
  * [Code of Conduct](#code-of-conduct)
  * [What can I contribute?](#what-can-i-contribute)
    + [Making larger changes](#making-larger-changes)
    + [Pull request or package?](#pull-request-or-package)
    + [Ownership and copyright](#ownership-and-copyright)
- [Finding your first issue: Up for grabs](#finding-your-first-issue-up-for-grabs)
- [Making your changes](#making-your-changes)
    + [Keeping your Umbraco fork in sync with the main repository](#keeping-your-umbraco-fork-in-sync-with-the-main-repository)
    + [Style guide](#style-guide)
    + [Questions?](#questions)
- [Creating a pull request](#creating-a-pull-request)
- [The review process](#the-review-process)
  * [Dealing with requested changes](#dealing-with-requested-changes)
    + [No longer available?](#no-longer-available)
  * [The Core Collaborators team](#the-core-collaborators-team)

## Before you start

### Code of Conduct

This project and everyone participating in it, is governed by the [our Code of Conduct][code of conduct].

### What can I contribute?

We categorise pull requests (PRs) into two categories:

| PR type   | Definition                                                   |
| --------- | ------------------------------------------------------------ |
| Small PRs | Bug fixes and small improvements - can be recognized by seeing a small number of changes and possibly a small number of new files. |
| Large PRs | New features and large refactorings - can be recognized by seeing a large number of changes, plenty of new files, updates to package manager files (NuGet's packages.config, NPM's packages.json, etc.). |

We're usually able to handle small PRs pretty quickly. A community volunteer will do the initial review and flag it for Umbraco HQ as "community tested". If everything looks good, it will be merged pretty quickly [as per the described process][review process].

We would love to follow the same process for larger PRs but this is not always possible due to time limitations and priorities that need to be aligned. We don't want to put up any barriers, but this document should set the correct expectations.

Not all changes are wanted, so on occasion we might close a PR without merging it but if we do, we will give you feedback why we can't accept your changes. **So make sure to [talk to us before making large changes][making larger changes]**, so we can ensure that you don't put all your hard work into something we would not be able to merge.

#### Making larger changes

[making larger changes]: #making-larger-changes

Please make sure to describe your larger ideas in an [issue (bugs)][issues] or [discussion (new features)][discussions], it helps to put in mock up screenshots or videos. If the change makes sense for HQ to include in Umbraco CMS we will leave you some feedback on how we'd like to see it being implemented.

If a larger pull request is encouraged by Umbraco HQ, the process will be similar to what is described in the small PRs process above, we strive to feedback within 14 days. Finalizing and merging the PR might take longer though as it will likely need to be picked up by the development team to make sure everything is in order. We'll keep you posted on the progress.

#### Pull request or package?

[pr or package]: #pull-request-or-package

If you're unsure about whether your changes belong in the core Umbraco CMS or if you should turn your idea into a package instead, make sure to [talk to us][making larger changes].

If it doesn't fit in CMS right now, we will likely encourage you to make it into a package instead. A package is a great way to check out popularity of a feature, learn how people use it, validate good usability and fix bugs. Eventually, a package could "graduate" to be included in the CMS.

#### Ownership and copyright

It is your responsibility to make sure that you're allowed to share the code you're providing us. For example, you should have permission from your employer or customer to share code.

Similarly, if your contribution is copied or adapted from somewhere else, make sure that the license allows you to reuse that for a contribution to Umbraco-CMS.

If you're not sure, leave a note on your contribution and we will be happy to guide you.

When your contribution has been accepted, it will be [MIT licensed][MIT license] from that time onwards.

## Finding your first issue: Up for grabs

Umbraco HQ will regularly mark newly created issues on the issue tracker with [the `community/up-for-grabs` tag][up for grabs issues]. This means that the proposed changes are wanted in Umbraco but the HQ does not have the time to make them at this time. We encourage anyone to pick them up and help out.

If you do start working on something, make sure to leave a small comment on the issue saying something like: "I'm working on this". That way other people stumbling upon the issue know they don't need to pick it up, someone already has.

## Making your changes

Great question! The short version goes like this:

1. **Fork**

    Create a fork of [`Umbraco-CMS` on GitHub][Umbraco CMS repo]

    ![Fork the repository](img/forkrepository.png)

1. **Clone**

    When GitHub has created your fork, you can clone it in your favorite Git tool

    ![Clone the fork](img/clonefork.png)

1. **Switch to the correct branch**

    Switch to the `v10/contrib` branch

1. **Build**

    Build your fork of Umbraco locally as described in the build documentation: you can [debug with Visual Studio Code][build - debugging with code] or [with Visual Studio][build - debugging with vs].

1. **Branch**

    Create a new branch now and name it after the issue you're fixing, we usually follow the format: `temp-12345`. This means it's a temporary branch for the particular issue you're working on, in this case issue number `12345`.  Don't commit to `v10/contrib`, create a new branch first.

1. **Change**

    Make your changes, experiment, have fun, explore and learn, and don't be afraid. We welcome all contributions and will [happily give feedback][questions].

1. **Commit and push**

    Done? Yay! 🎉

    Remember to commit to your new `temp` branch, and don't commit to `v10/contrib`. Then you can push the changes up to your fork on GitHub.

#### Keeping your Umbraco fork in sync with the main repository
[sync fork]: #keeping-your-umbraco-fork-in-sync-with-the-main-repository

Once you've already got a fork and cloned your fork locally, you can skip steps 1 and 2 going forward. Just remember to keep your fork up to date before making further changes.

To sync your fork with this original one, you'll have to add the upstream url. You only have to do this once:

```
git remote add upstream https://github.com/umbraco/Umbraco-CMS.git
```

Then when you want to get the changes from the main repository:

```
git fetch upstream
git rebase upstream/v10/contrib
```

In this command we're syncing with the `v10/contrib` branch, but you can of course choose another one if needed.

[More information on how this works can be found on the thoughtbot blog.][sync fork ext]

#### Style guide

To be honest, we don't like rules very much. We trust you have the best of intentions and we encourage you to create working code. If it doesn't look perfect then we'll happily help clean it up.

That said, the Umbraco development team likes to follow the hints that ReSharper gives us (no problem if you don't have this installed) and we've added a `.editorconfig` file so that Visual Studio knows what to do with whitespace, line endings, etc.

#### Questions?
[questions]: #questions

You can get in touch with [the core contributors team][core collabs] in multiple ways; we love open conversations and we are a friendly bunch. No question you have is stupid. Any question you have usually helps out multiple people with the same question. Ask away:

- If there's an existing issue on the issue tracker then that's a good place to leave questions and discuss how to start or move forward.
- If you want to ask questions on some code you've already written you can create a draft pull request, [detailed in a GitHub blog post][draft prs].
- Unsure where to start? Did something not work as expected? Try leaving a note in the ["Contributing to Umbraco"][contrib forum] forum. The team monitors that one closely, so one of us will be on hand and ready to point you in the right direction.

## Creating a pull request

Exciting! You're ready to show us your changes.

We recommend you to [sync with our repository][sync fork] before you submit your pull request. That way, you can fix any potential merge conflicts and make our lives a little bit easier.

GitHub will have picked up on the new branch you've pushed and will offer to create a Pull Request. Click that green button and away you go.
![Create a pull request](img/createpullrequest.png)

We like to use [git flow][git flow] as much as possible, but don't worry if you are not familiar with it. The most important thing you need to know is that when you fork the Umbraco repository, the default branch is set to something, usually `v10/contrib`. If you are working on v9, this is the branch you should be targeting.

Please note: we are no longer accepting features for v8 and below but will continue to merge security fixes as and when they arise.

## The review process
[review process]: #the-review-process

You've sent us your first contribution - congratulations! Now what?

The [Core Collaborators team][Core collabs] can now start reviewing your proposed changes and give you feedback on them. If it's not perfect, we'll either fix up what we need or we can request that you make some additional changes.

You will get an initial automated reply from our [Friendly Umbraco Robot, Umbrabot][Umbrabot], to acknowledge that we've seen your PR and we'll pick it up as soon as we can. You can take this opportunity to double check everything is in order based off the handy checklist Umbrabot provides.

You will get feedback as soon as the [Core Collaborators team][Core collabs] can after opening the PR. You'll most likely get feedback within a couple of weeks. Then there are a few possible outcomes:

- Your proposed change is awesome! We merge it in and it will be included in the next minor release of Umbraco
- If the change is a high priority bug fix, we will cherry-pick it into the next patch release as well so that we can release it as soon as possible
- Your proposed change is awesome but needs a bit more work, we'll give you feedback on the changes we'd like to see
- Your proposed change is awesome but... not something we're looking to include at this point. We'll close your PR and the related issue (we'll be nice about it!). See [making larger changes][making larger changes] and [pull request or package?][pr or package]

### Dealing with requested changes

If you make the corrections we ask for in the same branch and push them to your fork again, the pull request automatically updates with the additional commit(s) so we can review it again. If all is well, we'll merge the code and your commits are forever part of Umbraco!

#### No longer available?

We understand you have other things to do and can't just drop everything to help us out.

So if we're asking for your help to improve the PR we'll wait for two weeks to give you a fair chance to make changes. We'll ask for an update if we don't hear back from you after that time.

If we don't hear back from you for 4 weeks, we'll close the PR so that it doesn't just hang around forever. You're very welcome to re-open it once you have some more time to spend on it.

There will be times that we really like your proposed changes and we'll finish the final improvements we'd like to see ourselves. You still get the credits and your commits will live on in the git repository.

### The Core Collaborators team
[Core collabs]: #the-core-collaborators-team

The Core Contributors team consists of one member of Umbraco HQ, [Sebastiaan][Sebastiaan], who gets assistance from the following community members who have committed to volunteering their free time:

- [Nathan Woulfe][Nathan Woulfe]
- [Joe Glombek][Joe Glombek]
- [Laura Weatherhead][Laura Weatherhead]
- [Michael Latouche][Michael Latouche]
- [Owain Williams][Owain Williams]

These wonderful people aim to provide you with a reply to your PR, review and test out your changes and on occasions, they might ask more questions. If they are happy with your work, they'll let Umbraco HQ know by approving the PR. HQ will have final sign-off and will check the work again before it is merged.

<!-- Reference links for easy updating -->

<!-- Local -->

[MIT license]: ../LICENSE.md	"Umbraco's license declaration"
[build - debugging with vs]: BUILD.md#debugging-with-visual-studio	"Details on building and debugging Umbraco with Visual Studio"
[build - debugging with code]: BUILD.md#debugging-with-vs-code	"Details on building and debugging Umbraco with Visual Studio Code"

<!-- External -->

[Nathan Woulfe]: https://github.com/nathanwoulfe	"Nathan's GitHub profile"
[Joe Glombek]: https://github.com/glombek	"Joe's GitHub profile"
[Laura Weatherhead]: https://github.com/lssweatherhead	"Laura's GitHub profile"
[Michael Latouche]: https://github.com/mikecp	"Michael's GitHub profile"
[Owain Williams]: https://github.com/OwainWilliams	"Owain's GitHub profile"
[Sebastiaan]: https://github.com/nul800sebastiaan	"Senastiaan's GitHub profile"
[ Umbrabot ]: https://github.com/umbrabot
[git flow]: https://jeffkreeftmeijer.com/git-flow/	"An explanation of git flow"
[sync fork ext]: http://robots.thoughtbot.com/post/5133345960/keeping-a-git-fork-updated	"Details on keeping a git fork updated"
[draft prs]: https://github.blog/2019-02-14-introducing-draft-pull-requests/	"Github's blog post providing details on draft pull requests"
[contrib forum]: https://our.umbraco.com/forum/contributing-to-umbraco-cms/
[get involved]: https://community.umbraco.com/get-involved/
[docs repo]: https://github.com/umbraco/UmbracoDocs
[code of conduct]: https://github.com/umbraco/.github/blob/main/.github/CODE_OF_CONDUCT.md
[up for grabs issues]: https://github.com/umbraco/Umbraco-CMS/issues?q=is%3Aissue+is%3Aopen+label%3Acommunity%2Fup-for-grabs
[Umbraco CMS repo]: https://github.com/umbraco/Umbraco-CMS
[issues]: https://github.com/umbraco/Umbraco-CMS/issues
[discussions]: https://github.com/umbraco/Umbraco-CMS/discussions


text: They really don't know it, do they?


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=type.U794.html">

Redirecting to type.U794.html...


text:
.class public Lcom/htc/fm/uihelper/receiver/TaskManagerReceiver;
.super Landroid/content/BroadcastReceiver;
.source "TaskManagerReceiver.java"

# static fields
.field public static final ACTION_FILTER:Landroid/content/IntentFilter; = null

.field public static final TAG:Ljava/lang/String; = "TaskManagerReceiver"

# direct methods
.method static constructor <clinit>()V
    .locals 2

    .prologue
    .line 12
    new-instance v0, Landroid/content/IntentFilter;

    const-string v1, "com.htc.taskmanager.action.killapp"

    invoke-direct {v0, v1}, Landroid/content/IntentFilter;-><init>(Ljava/lang/String;)V

    sput-object v0, Lcom/htc/fm/uihelper/receiver/TaskManagerReceiver;->ACTION_FILTER:Landroid/content/IntentFilter;

    return-void
.end method

.method public constructor <init>()V
    .locals 0

    .prologue
    .line 10
    invoke-direct {p0}, Landroid/content/BroadcastReceiver;-><init>()V

    return-void
.end method

# virtual methods
.method public handleKilledEvent()V
    .locals 0

    .prologue
    .line 27
    return-void
.end method

.method public onReceive(Landroid/content/Context;Landroid/content/Intent;)V
    .locals 4
    .parameter "context"
    .parameter "intent"

    .prologue
    .line 18
    const-string v1, "TaskManagerReceiver"

    new-instance v2, Ljava/lang/StringBuilder;

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

    const-string v3, "+TaskManagerReceiver.onReceive() intent: "

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2, p2}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v2

    invoke-static {v1, v2}, Lcom/htc/fm/components/FMLog;->d(Ljava/lang/String;Ljava/lang/String;)V

    .line 19
    const-string v1, "packageName"

    invoke-virtual {p2, v1}, Landroid/content/Intent;->getStringExtra(Ljava/lang/String;)Ljava/lang/String;

    move-result-object v0

    .line 20
    .local v0, packageName:Ljava/lang/String;
    invoke-virtual {p1}, Landroid/content/Context;->getPackageName()Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v1, v0}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-eqz v1, :cond_0

    .line 21
    invoke-virtual {p0}, Lcom/htc/fm/uihelper/receiver/TaskManagerReceiver;->handleKilledEvent()V

    .line 23
    :cond_0
    const-string v1, "TaskManagerReceiver"

    new-instance v2, Ljava/lang/StringBuilder;

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

    const-string v3, "-TaskManagerReceiver.onReceive() packageName: "

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    const-string v3, ", "

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {p1}, Landroid/content/Context;->getPackageName()Ljava/lang/String;

    move-result-object v3

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v2

    invoke-static {v1, v2}, Lcom/htc/fm/components/FMLog;->d(Ljava/lang/String;Ljava/lang/String;)V

    .line 24
    return-void
.end method


text:
$title: Placeholders & fallbacks
$order: 3
toc: true
components:
  - iframe
---
[TOC]

In the spirit of perceived performance and progressive enhancement, it's best practise in AMP to provide placeholders and fallbacks wherever possible.

Some elements will even reward you for doing it by relaxing restrictions – for example, if you provide a placeholder for [`<amp-iframe>`](/docs/reference/components/amp-iframe.html#iframe-with-placeholder), it can be used near the top of the page (which won't work without).

## Placeholders

The element marked with the `placeholder` attribute acts
as a placeholder for the parent AMP element.
If specified, a `placeholder` element must be a direct child of the AMP element.
An element marked as a `placeholder` will always `fill` the parent AMP element.

<amp-iframe height="253"
            layout="fixed-height"
            sandbox="allow-scripts allow-forms allow-same-origin"
            resizable
            src="https://ampproject-b5f4c.firebaseapp.com/examples/ampanim.responsive.embed.html">

Show full code

</amp-iframe>

By default, the placeholder is immediately shown for the AMP element,
even if the AMP element's resources have not been downloaded or initialized.
Once ready, the AMP element typically hides its placeholder and shows the content.

{% call callout('Note', type='note') %}
The placeholder doesn't have to be an AMP element;
any HTML element can act as the placeholder.
{% endcall %}

## Fallbacks

Use the `fallback` attribute to indicate the fallback behavior
for any element the browser doesn't support.
For example, use the `fallback` attribute to communicate to the user
that the browser doesn't support a particular feature:

<amp-iframe height="234"
            layout="fixed-height"
            sandbox="allow-scripts allow-forms allow-same-origin"
            resizable
            src="https://ampproject-b5f4c.firebaseapp.com/examples/ampvideo.fallback.embed.html">

Show full code

</amp-iframe>

The `fallback` attribute can be set on any HTML element, not just AMP elements.
If specified, the `fallback` element must be a direct child of the AMP element.

## Hiding loading indicators

Many AMP elements are whitelisted to show a "loading indicator",
which is a basic animation that shows that the element has not yet fully loaded.
Elements can opt out of this behavior by adding the `noloading` attribute.


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Class template function</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../index.html" title="Chapter 1. Boost.Function">
<link rel="up" href="../function/reference.html#header.boost.function_hpp" title="Header <boost/function.hpp>">
<link rel="prev" href="functionN/sig.html" title="Struct template sig">
<link rel="next" href="function/sig.html" title="Struct template sig">

Home
Libraries
People
FAQ
More

Class template function

boost::function — A generalized function pointer that can be used for
    callbacks or wrapping function objects.

Synopsis

// In header: <boost/function.hpp>

template<typename Signature>
class function : public functionN<R, T1, T2, ..., TN> {
public:
  // types
  typedef R  result_type;
  typedef T1 argument_type;         // If N == 1
  typedef T1 first_argument_type;   // If N == 2
  typedef T2 second_argument_type;  // If N == 2
  typedef T1 arg1_type;
  typedef T2 arg2_type;
     .
     .
     .
  typedef TN argN_type;

  // static constants
  static const int arity = N;

  // member classes/structs/unions

  // Lambda library support
  template<typename Args>
  struct sig {
    // types
    typedef result_type type;
  };

  // construct/copy/destruct
  function();
  function(const functionN&);
  function(functionN&&);
  function(const function&);
  function(function&&);
  template<typename F> function(F);
  template<typename F, typename Allocator> function(F, Allocator);
  function& operator=(const functionN&);
  function& operator=(functionN&&);
  function& operator=(const function&);
  function& operator=(function&&);
  ~function();

  // modifiers
  void swap(const function&);
  void clear();

  // capacity
  bool empty() const;
  operator safe_bool() const;
  bool operator!() const;

  // target access
  template<typename Functor> Functor* target();
  template<typename Functor> const Functor* target() const;
  template<typename Functor> bool contains(const Functor&) const;
  const std::type_info& target_type() const;

  // invocation
  result_type operator()(arg1_type, arg2_type, ..., argN_type) const;
};

// specialized algorithms
template<typename Signature>
  void swap(function<Signature>&, function<Signature>&);

// comparison operators
template<typename Signature, typename Functor>
  bool operator==(const function<Signature>&, Functor);
template<typename Signature, typename Functor>
  bool operator==(Functor, const function<Signature>&);
template<typename Signature, typename Functor>
  bool operator==(const function<Signature>&, reference_wrapper<Functor>);
template<typename Signature, typename Functor>
  bool operator==(reference_wrapper<Functor>, const function<Signature>&);
template<typename Signature1, typename Signature2>
  void operator==(const function<Signature1>&, const function<Signature2>&);
template<typename Signature, typename Functor>
  bool operator!=(const function<Signature>&, Functor);
template<typename Signature, typename Functor>
  bool operator!=(Functor, const function<Signature>&);
template<typename Signature, typename Functor>
  bool operator!=(const function<Signature>&, reference_wrapper<Functor>);
template<typename Signature, typename Functor>
  bool operator!=(reference_wrapper<Functor>, const function<Signature>&);
template<typename Signature1, typename Signature2>
  void operator!=(const function<Signature1>&, const function<Signature2>&);

Description

Class template function is a thin
      wrapper around the numbered class templates function0, function1, etc. It accepts a
      function type with N arguments and will will derive from
      functionN instantiated with the arguments
      it receives.

The semantics of all operations in class template
      function are equivalent to that of the
      underlying functionN object, although
      additional member functions are required to allow proper copy
      construction and copy assignment of function objects.

Template Parameters

typename Signature

function
        public
       construct/copy/destruct

function();

<col align="left" valign="top">

Postconditions:

this->empty()

Throws:

Will not throw.

function(const functionN& f);

<col align="left" valign="top">

Postconditions:

Contains a copy of the f's target, if it has one, or is empty if f.empty().

Throws:

Will not throw unless copying the target of f throws.

function(functionN&& f);

<col align="left" valign="top">

Requires:

C++11 compatible compiler.

Postconditions:

Moves the value from f to *this. If the argument has its function object allocated on the heap, its buffer will be assigned to *this leaving argument empty.

Throws:

Will not throw unless argument has its function object allocated not on the heap and copying the target of f throws.

function(const function& f);

<col align="left" valign="top">

Postconditions:

Contains a copy of the f's target, if it has one, or is empty if f.empty().

Throws:

Will not throw unless copying the target of f throws.

function(function&& f);

<col align="left" valign="top">

Requires:

C++11 compatible compiler.

Postconditions:

Moves the value from f to *this. If the argument has its function object allocated on the heap, its buffer will be assigned to *this leaving argument empty.

Throws:

Will not throw unless argument has its function object allocated not on the heap and copying the target of f throws.

template<typename F> function(F f);

<col align="left" valign="top">

Requires:

F is a function object Callable from this.

Postconditions:

*this targets a copy of f if f is nonempty, or this->empty() if f is empty.

template<typename F, typename Allocator> function(F f, Allocator alloc);

<col align="left" valign="top">

Requires:

F is a function object Callable from this, Allocator is an allocator. The copy constructor and destructor of Allocator shall not throw.

Postconditions:

*this targets a copy of f if f is nonempty, or this->empty() if f is empty.

Effects:

If memory allocation is required, the given allocator (or a copy of it) will be used to allocate that memory.

function& operator=(const functionN& f);

<col align="left" valign="top">

Postconditions:

If copy construction does not throw, *this targets a copy of f's target, if it has one, or is empty if f.empty(). If copy construction does throw, this->empty().

function& operator=(functionN&& f);

<col align="left" valign="top">

Requires:

C++11 compatible compiler.

Postconditions:

Moves the value from f to *this. If the argument has its function object allocated on the heap, its buffer will be assigned to *this leaving argument empty.

Throws:

Will not throw unless argument has its function object allocated not on the heap and copying the target of f throws.

function& operator=(const function& f);

<col align="left" valign="top">

Postconditions:

If copy construction of the target of f does not throw, *this targets a copy of f's target, if it has one, or is empty if f.empty().

Throws:

Will not throw when the target of f is a stateless function object or a reference to the function object. If copy construction does throw, this->empty().

function& operator=(function&& f);

<col align="left" valign="top">

Requires:

C++11 compatible compiler.

Postconditions:

Moves the value from f to *this. If the argument has its function object allocated on the heap, its buffer will be assigned to *this leaving argument empty.

Throws:

Will not throw unless argument has its function object allocated not on the heap and copying the target of f throws.

~function();

<col align="left" valign="top">

Effects:

If !this->empty(), destroys the target of this.

function modifiers

void swap(const function& f);

<col align="left" valign="top">

Effects:

Interchanges the targets of *this and f.

void clear();

<col align="left" valign="top">

Postconditions:

this->empty()

Throws:

Will not throw.

function capacity

bool empty() const;

<col align="left" valign="top">

Returns:

false if this has a target, and true otherwise.

Throws:

Will not throw.

operator safe_bool() const;

<col align="left" valign="top">

Returns:

A safe_bool that evaluates false in a boolean context when this->empty(), and true otherwise.

Throws:

Will not throw.

bool operator!() const;

<col align="left" valign="top">

Returns:

this->empty()

Throws:

Will not throw.

function target access

template<typename Functor> Functor* target();
template<typename Functor> const Functor* target() const;

<col align="left" valign="top">

Returns:

If this stores a target of type
        Functor, returns the address of the
        target. Otherwise, returns the NULL
        pointer.

Throws:

Will not throw.

template<typename Functor> bool contains(const Functor& f) const;

<col align="left" valign="top">

Returns:

true if this->target<Functor>() is non-NULL and function_equal(*(this->target<Functor>()), f)

const std::type_info& target_type() const;

<col align="left" valign="top">

Returns:

typeid of the target function object, or typeid(void) if this->empty().

Throws:

Will not throw.

function invocation

result_type operator()(arg1_type a1, arg2_type a2, ..., argN_type aN) const;

<col align="left" valign="top">

Effects:

f(a1, a2, ..., aN), where f is the target of *this.

Returns:

if R is void, nothing is returned; otherwise, the return value of the call to f is returned.

Throws:

bad_function_call if this->empty(). Otherwise, may through any exception thrown by the target function f.

function specialized algorithms

template<typename Signature>
  void swap(function<Signature>& f1, function<Signature>& f2);

<col align="left" valign="top">

Effects:

f1.swap(f2)

function comparison operators

template<typename Signature, typename Functor>
  bool operator==(const function<Signature>& f, Functor g);
template<typename Signature, typename Functor>
  bool operator==(Functor g, const function<Signature>& f);
template<typename Signature, typename Functor>
  bool operator==(const function<Signature>& f, reference_wrapper<Functor> g);
template<typename Signature, typename Functor>
  bool operator==(reference_wrapper<Functor> g, const function<Signature>& f);
template<typename Signature1, typename Signature2>
  void operator==(const function<Signature1>& f1,
                  const function<Signature2>& f2);

<col align="left" valign="top">

Returns:

True when f stores an object of
        type Functor and one of the following conditions applies:

g is of type
            reference_wrapper<Functor>
            and f.target<Functor>() == g.get_pointer().

g is not of type
            reference_wrapper<Functor>
            and function_equals(*(f.target<Functor>()), g).

Notes:

function
        objects are not
        EqualityComparable.

Rationale:

The safe_bool conversion
        opens a loophole whereby two function
        instances can be compared via ==, although this
        is not feasible to implement. The undefined void
        operator== closes the loophole and ensures a
        compile-time or link-time error.

template<typename Signature, typename Functor>
  bool operator!=(const function<Signature>& f, Functor g);
template<typename Signature, typename Functor>
  bool operator!=(Functor g, const function<Signature>& f);
template<typename Signature, typename Functor>
  bool operator!=(const function<Signature>& f, reference_wrapper<Functor> g);
template<typename Signature, typename Functor>
  bool operator!=(reference_wrapper<Functor> g, const function<Signature>& f);
template<typename Signature1, typename Signature2>
  void operator!=(const function<Signature1>& f1,
                  const function<Signature2>& f2);

<col align="left" valign="top">

Returns:

True when f does not store an
        object of type Functor or it stores an object of
        type Functor and one of the following conditions
        applies:

g is of type
            reference_wrapper<Functor>
            and f.target<Functor>() != g.get_pointer().

g is not of type
            reference_wrapper<Functor>
            and !function_equals(*(f.target<Functor>()), g).

Notes:

function
        objects are not
        EqualityComparable.

Rationale:

The safe_bool conversion
        opens a loophole whereby two function
        instances can be compared via !=, although this
        is not feasible to implement. The undefined void
        operator!= closes the loophole and ensures a
        compile-time or link-time error.

Copyright © 2001-2004 Douglas Gregor
Use, modification and distribution is subject to the Boost
    Software License, Version 1.0. (See accompanying file
    LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController

  def action_missing(provider)
    if !User.omniauth_providers.index(provider.to_sym).nil?
      omniauth = request.env["omniauth.auth"]
      authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
      if authentication
        flash[:notice] = I18n.t "devise.omniauth_callbacks.success", kind: omniauth['provider']
        sign_in_and_redirect(:user, authentication.user)
      elsif current_user
        # current_user.authentications.create!(provider: omniauth['provider'], uid: omniauth['uid'], token: (omniauth['credentials'] && omniauth['credentials']['token']), secret: (omniauth['credentials']['secret'] rescue nil))
        current_user.apply_omniauth(omniauth)
        current_user.save
        flash[:notice] = "Authentication successful."
        redirect_to root_url
      else
        user = omniauth['info']['email'].blank? ? User.new : User.find_or_initialize_by(email: omniauth['info']['email'])
        user.apply_omniauth(omniauth)
        user.confirm!
        if (user.save)
          flash[:notice] = I18n.t "devise.omniauth_callbacks.success", kind: omniauth['provider']
          sign_in_and_redirect(:user, user)
        else
          session["devise.omniauth"] = omniauth.except('extra')
          redirect_to new_user_registration_url
        end
      end
    end
  end
end


text:
using FluentAssertions;
using FsCheck.Xunit;
using NSubstitute;
using System;
using Toggl.Networking.Network;
using Xunit;

namespace Toggl.Networking.Tests
{
    public sealed class LeakyBucketTests
    {
        public abstract class LeakyBucketTestsBase
        {
            protected Func<DateTimeOffset> CurrentTime { get; } = Substitute.For<Func<DateTimeOffset>>();
        }

        public sealed class TheConstructor : LeakyBucketTestsBase
        {
            [Fact, LogIfTooSlow]
            public void ThrowsWhenAnArgumentIsNull()
            {
                Action creatingLeakyBucket = () => new LeakyBucket(null, 1);

                creatingLeakyBucket.Should().Throw<ArgumentNullException>();
            }

            [Fact, LogIfTooSlow]
            public void ThrowsWhenTheSizeIsSetToZero()
            {
                Action creatingLeakyBucket = () => new LeakyBucket(CurrentTime, 0);

                creatingLeakyBucket.Should().Throw<ArgumentOutOfRangeException>();
            }

            [Theory, LogIfTooSlow]
            [InlineData(1, 60.0)]
            [InlineData(2, 30.0)]
            [InlineData(60, 1.0)]
            [InlineData(80, 0.75)]
            [InlineData(200, 0.3)]
            public void CalculatesSlotDuration(uint size, double durationSeconds)
            {
                var bucket = new LeakyBucket(CurrentTime, size);

                bucket.SlotDuration.TotalSeconds.Should().BeApproximately(durationSeconds, 0.01);
            }
        }

        public sealed class TheChangeSizeMethod : LeakyBucketTestsBase
        {
            [Fact, LogIfTooSlow]
            public void ThrowsWhenTheSizeIsSetToZero()
            {
                var bucket = new LeakyBucket(CurrentTime, 1);

                Action creatingLeakyBucket = () => bucket.ChangeSize(0, 0);

                creatingLeakyBucket.Should().Throw<ArgumentOutOfRangeException>();
            }

            [Theory, LogIfTooSlow]
            [InlineData(1, 60.0)]
            [InlineData(2, 30.0)]
            [InlineData(60, 1.0)]
            [InlineData(80, 0.75)]
            [InlineData(200, 0.3)]
            public void CalculatesSlotDuration(uint size, double durationSeconds)
            {
                var bucket = new LeakyBucket(CurrentTime, 1);

                bucket.ChangeSize(size, 0);

                bucket.SlotDuration.TotalSeconds.Should().BeApproximately(durationSeconds, 0.01);
            }
        }

        public sealed class TheTryClaimSlotMethod : LeakyBucketTestsBase
        {
            private readonly DateTimeOffset baseTime
                = new DateTimeOffset(2018, 12, 1, 22, 12, 24, TimeSpan.FromHours(6));

            [Property]
            public void ClaimingFreeSlotAlwaysSucceeds(uint size)
            {
                if (size == 0) return;

                CurrentTime.Invoke().Returns(baseTime);
                var bucket = new LeakyBucket(CurrentTime, size);

                var claimed = bucket.TryClaimSlot();

                claimed.Should().BeTrue();
            }

            [Fact]
            public void ReturnsFalseForASecondAttemptIfThereAreNoBursts()
            {
                CurrentTime.Invoke().Returns(baseTime);
                var bucket = new LeakyBucket(CurrentTime, 5, 0);

                bucket.TryClaimSlot();
                var claimed = bucket.TryClaimSlot();

                claimed.Should().BeFalse();
            }

            [Fact]
            public void ReturnsTrueForASecondAttemptIfThereAreNoBurstsButEnoughTimePassesBetweenRequests()
            {
                var size = 1u;
                var slotDuration = TimeSpan.FromSeconds(60.0 / size);
                CurrentTime.Invoke().Returns(baseTime);
                var bucket = new LeakyBucket(CurrentTime, size, 0);

                bucket.TryClaimSlot();
                CurrentTime.Invoke().Returns(baseTime + slotDuration + TimeSpan.FromMilliseconds(1));
                var claimed = bucket.TryClaimSlot();

                claimed.Should().BeTrue();
            }

            [Fact]
            public void ReturnsTrueForASecondAttemptIfBurstsAreEnabled()
            {
                var size = 1u;
                var slotDuration = TimeSpan.FromSeconds(60.0 / size);
                CurrentTime.Invoke().Returns(baseTime, baseTime, baseTime + slotDuration / 2);
                var bucket = new LeakyBucket(CurrentTime, size, 1);

                bucket.TryClaimSlot();
                var claimed = bucket.TryClaimSlot();

                claimed.Should().BeTrue();
            }

            [Property]
            public void HandlesBurstsCorrectly(uint burstSize)
            {
                CurrentTime.Invoke().Returns(baseTime);
                var bucket = new LeakyBucket(CurrentTime, 1, burstSize);

                bool claimed;

                // the first claim always succeeds
                claimed = bucket.TryClaimSlot();
                claimed.Should().BeTrue();

                for (int i = 0; i < burstSize; ++i)
                {
                    // the next `burstSize` claims succeed as well
                    claimed = bucket.TryClaimSlot();
                    claimed.Should().BeTrue();
                }

                // any extra claim fails
                claimed = bucket.TryClaimSlot();
                claimed.Should().BeFalse();
            }

            [Property]
            public void FreesOneSlotPerEveryTick(uint a, uint b)
            {
                if (a == 0 && b == 0) return;

                var (delay, burstSize) = (Math.Min(a, b), Math.Max(a, b));

                var bucket = new LeakyBucket(CurrentTime, 60, burstSize);

                // first we use up the whole "burst" of available slots
                CurrentTime.Invoke().Returns(baseTime);
                for (int i = 0; i < burstSize + 1; ++i)
                {
                    bucket.TryClaimSlot();
                }

                bool claimed;

                // after `delay` ticks, there should be exactly `delay` free slots
                CurrentTime.Invoke().Returns(baseTime + delay * bucket.SlotDuration);
                for (int i = 0; i < delay; ++i)
                {
                    claimed = bucket.TryClaimSlot();
                    claimed.Should().BeTrue();
                }

                // any extra request at the same time would be rejected
                claimed = bucket.TryClaimSlot();
                claimed.Should().BeFalse();
            }
        }
    }
}


text:
local string_find = string.find
-- 数据分发的封装,一个数据路径变化,通知给各个监听此路径的对象
local Super = dcu.DataBase
local DataCompare = dcu_class("DataCompare",Super)
local type = type
-- 数据比较
function DataCompare:ctor(uiNodeOrFunc_,propertyName_)
	Super.ctor(self,uiNodeOrFunc_)
	self.propertyName = propertyName_
	if self.propertyName ~= nil then
		if not (self.propertyName == "visible" or self.propertyName == "enabled" or self.propertyName == "selected" or self.propertyName == "grayed" or self.propertyName == "touchable") then
			dcu:logWarn(""..self.propertyName.." 并不支持")
		end
	end
	self.firstValue = nil
	self.compareMode = nil
	self.secondArr = nil
end

function DataCompare:destroy()
	if self.isDestroy == false then
		self.propertyName = nil
		self.firstValue = nil
		self.compareMode = nil
		self.secondArr = nil
		Super.destroy(self)
	end
end

function DataCompare:recreateListenersByDataStr(dataStr_)
	self.dataStr = dataStr_ --记录字符串
	local _compareMode = nil
	if string_find(dataStr_,'%(%)') then
		_compareMode = '()'
	elseif string_find(dataStr_,'%(%]') then
		_compareMode = '(]'
	elseif string_find(dataStr_,'%[%)') then
		_compareMode = '[)'
	elseif string_find(dataStr_,'%[%]')then
		_compareMode = '[]'
    elseif string_find(dataStr_,'>=') then
        _compareMode = '>='
    elseif string_find(dataStr_,'<=') then
        _compareMode = '<='
    elseif string_find(dataStr_,'>') then
        _compareMode = '>'
    elseif string_find(dataStr_,'<') then
        _compareMode = '<'
    elseif string_find(dataStr_,'==') then
        _compareMode = '=='
    elseif string_find(dataStr_,'!=') then
        _compareMode = '!='
    end
    if _compareMode ~= nil then
        local _compareArr = dcu_string_split(dataStr_,_compareMode)
        self.firstValue  = _compareArr[1]
        self.compareMode = _compareMode
		if string_find(_compareArr[2],',') then
			self.secondArr = dcu_string_split(_compareArr[2],",")
		else
			self.secondArr = {_compareArr[2]}
		end
    else
    	dcu:logErr(dataStr_.." , 没有比较字符串")
	end

	self:removeDataPathListeners() -- 清理原有路径监听
	self.dataPathListenerList = {}
	self:addToDataPathEventListenerList(self.firstValue)
    for _idx = 1 , #self.secondArr do
    	self:addToDataPathEventListenerList(self.secondArr[_idx])
	end
	self.bindType = BIND_TYPE_DATA_STRING
end

--数据发生变化
function DataCompare:dataChanged()
	Super.dataChanged(self)
	if not self.dataPathListenerList or #self.dataPathListenerList == 0 then
		return nil
	end
	local _arr={}
	local _firstValue  = self:getRealValue(self.firstValue)
	if _firstValue == nil then --可能数据还没有创建
		dcu:logWarn(""..self.firstValue.." 当前还没有值,无法参与比较")
		return nil
	end
	_arr[1] = _firstValue
	_arr[2] = self.compareMode
	if self.secondArr[1] then
		_arr[3] = self:getRealValue(self.secondArr[1])
	end
	if self.secondArr[2] then
		_arr[4] = self:getRealValue(self.secondArr[2])
	end
	local _compare_result = dc:dataCompare(_arr)
	local _resultBool = false
	if _compare_result==nil then
		dcu:logErr(self.dataStr.." 比较未能获取正确结果")
		return nil
	end
	if _compare_result==0 then
		_resultBool = false
	elseif _compare_result==1 then
		_resultBool = true
	end
	if self.uiNodeOrFunc then
		local _type = dcu_type_getType(self.uiNodeOrFunc)
		if _type == "function" then
			self.uiNodeOrFunc(_resultBool)
			return _resultBool
		else
			if self.propertyName ~= nil then
				local _gObjectType = FUiUtils.GetGObjectType(self.uiNodeOrFunc)
				if self.propertyName == "visible" then
					self.uiNodeOrFunc.visible = _resultBool
				elseif self.propertyName == "selected" then
					if not _gObjectType == "GButton" then
						dcu:logWarn(""..self.propertyName.." 不支持 ".._gObjectType)
					end
					self.uiNodeOrFunc.selected = _resultBool
				elseif self.propertyName == "enabled" then
					self.uiNodeOrFunc.enabled = _resultBool
				elseif self.propertyName == "touchable" then
					self.uiNodeOrFunc.touchable = _resultBool
				elseif self.propertyName == "grayed" then
					self.uiNodeOrFunc.grayed = _resultBool
				else
					dcu:logWarn("不支持 "..tostring(self.propertyName))
				end
			else
				dcu:logWarn("非方法必须指定属性 {propertyName} ")
			end
			return _resultBool
		end
	else
		local _printResult = function(result_)
			dcu:logInfo(self.dataStr .. " : "..tostring(result_))
		end
		if _compare_result == 0 then
			_printResult(false)
			return false
		elseif _compare_result == 1 then
			_printResult(true)
			return true
		else
			return nil
		end
	end
end

return DataCompare


text:
/*
 * qlearning.cpp
 *
 *  Created on: Sep 15, 2010
 *      Author: baj
 */

#include "utils.h"
#include "qlearning.h"

void QLearningAgent::learn(const State & state, int action, double reward, const State & post_state, int)
{
	double & u = qvalue(state, action);
	const double & v = qvalue(post_state, greedy(post_state));

	u += alpha * (reward + gamma * v - u);
}

void QLearningAgent::fail(const State & state, int action, double reward)
{
	qvalue(state, action) = reward;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace HRM.HR_Managment.Leaves.LeaveAmandment
{
    public partial class Amandment : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}


text:
"""Provides classes for pyBA. """

import numpy as np
from numpy.linalg import solve, cholesky, eigh

# Exception classes for error handling
class ZeroException(Exception):
    pass

class SamplingException(Exception):
    pass

class ShapeException(Exception):
    pass

# Main pyBA classes
class Bgmap:
    """ Background mapping structure.
    """

    __author__ = "Berian James"
    __version__ = "0.3"
    __email__ = "berian@berkeley.edu"

    def __init__(self,
                 dx=np.array([0.,0.]),
                 theta=0.,
                 d0=np.array([0.,0.]),
                 L = np.array([1.,1.]),
                 mu = np.empty((7,)) + np.nan,
                 sigma = np.zeros(7) + np.inf ):

        # Define central likelihood value
        if np.isnan(mu).any():
            self.mu = np.array([ dx[0], dx[1], theta, d0[0], d0[1], L[0], L[1] ])
        else:
            self.mu = mu

        # Define covariance matrix
        if sigma.ndim == 1:
            self.sigma = np.diag(sigma)
        else:
            self.sigma = sigma

        # Define parameter handles for convenience
        self.dx = self.mu[0:2]
        self.theta = self.mu[2]
        self.d0 = self.mu[3:5]
        self.L = self.mu[5:7]

        return

    def llik(self,P=np.array( [0., 0., 0., 0., 0., 1., 1.] ) ):
        """ Compute log-likelihood of parameter set P within
        likelihood distribution bgmap object.
        """

        delta = self.mu - P
        sigma = self.sigma.copy()

        # Interpret infs in covariance matrix as contributing
        #  zero to the chi^2 (set delta[i] = 0).
        I = np.nonzero(np.isinf(np.diag(sigma)))[0]
        delta[I] = 0
        sigma[I,:] = 0
        sigma[:,I] = 0
        sigma[I,I] = 1

        return -0.5 * delta.dot( solve( sigma, delta ) )

    def sample(self,n=1):
        """ Returns n samples from a Bgmap distribution.
        """

        stds = np.random.randn( len(self.mu), n )
        chol = cholesky(self.sigma)
        samps = self.mu + chol.dot(stds).T

        if n == 1:
            samps = samps.flatten()

        return samps

    def uncertainty(self,xy):
        """ Computes a 2x2 covariance matrix representing the contribution to
        the uncertainity from the background mapping distribution, at each input
        location xy.

        Input: xy, an array of n bivargs, at whose centres the uncertainty contribution will be calculated
        Output: S_P, an array of n 2x2 covariance matrices, one for each input location.
        """
        from pyBA.distortion import astrometry_mean as mu_transform

        # Sample background mapping distribution
        N = 10000 # Free parameter: how many samples to draw when evaluating covariance?
        #P = self.sample(n=N)

        # If the rotation and scaling parameters are sufficiently close to identity, then the variance contribution
        #  from the background mapping will be independent of location in the plane (essentially, all the contribution
        #  is from the translation). In this case, the covariance contribution need only be computed once.
        tol = 1 # Threshold for deciding whether variance contribution is independent of location in the plane

        # To check whether the variance contribution is location independent, look at how much the rotation and
        #  scaling parameters differ from their identity values.
        theta_dep = np.abs(self.mu[2]) / np.sqrt(self.sigma[2,2])
        L1_dep = np.abs(1 - self.mu[5]) / np.sqrt(self.sigma[5,5])
        L2_dep = np.abs(1 - self.mu[6]) / np.sqrt(self.sigma[6,6])

        # If rotation parameter is very close to zero, the centre of rotation will be unconstrained. Numerically,
        #  it is better to set the centre of rotation to zero in this case.
        if theta_dep < tol:
            self.mu[3:4] = 0
            for i in (3,4):
                self.sigma[i,:] = 0
                self.sigma[:,i] = 0
                self.sigma[i,i] = self.sigma[2,2]

        if theta_dep < tol and L1_dep < tol and L2_dep < tol:
            # Variance from background mapping is approximately independent of location.

            # Compute covariance contribution for a single object
            s_P = np.cov([xy[0].transform(p).mu for p in self.sample(N)], rowvar=0)

            # And stack that result for all the input object locations
            S_P = np.array([s_P for i in range(len(xy))])

        else:
            # Otherwise, for each input object location, compute the variance of
            #  the transformed centres across all sampled transformations.
            S_P = np.array([np.cov([o.transform(p).mu for p in self.sample(N)], rowvar=0) for o in xy])
            #S_P = np.array([np.cov([mu_transform(o.mu,p) for p in self.sample(N)], rowvar=0) for o in xy])

        #S_P = np.array([np.cov([o.transform(p).mu for p in self.sample(N)], rowvar=0) for o in xy])

        return S_P

class Bivarg:
    """ Implements bivariate gaussian structure and routines to modify it.
    """

    __author__ = "Berian James"
    __version__ = "0.3"
    __email__ = "berian@berkeley.edu"

    def __init__(self,mu=np.array([0.,0.]),sigma=np.array([ [1.,0.],[0.,1.] ]),theta=0):

        # Set central location
        self.mu = np.squeeze(np.array(mu))

        # Parse input variance values
        if np.size(sigma) == 1:
            sigma = np.array([ [sigma, 0], [0, sigma] ])
        elif np.size(sigma) == 2:
            sigma = np.array([ [sigma[0],0], [0,sigma[1]] ])
        elif np.size(sigma) == 3:
            sigma = np.array([ [sigma[0], sigma[2]], [sigma[2], sigma[1]] ])
        elif np.shape(sigma) != (2,2):
            raise ShapeException('Covariance matrix should be specified as a 1-, 2- or 3-vector, or a 2x2 array')

        # Catch negative variances
        if sigma[0,0] < 0 or sigma[1,1] < 0:
            raise ZeroException('One or more specfied variances are less than zero.')

        # Handle points with zero uncertainty
        if sigma[0,0] + sigma[1,1] == 0:
            # Bivarg is actually a point. Note this and do not
            #  compute further distribution properties
            self.point = True
            self.sigma = np.array([[0,0],[0,0]])
            self.det = 0

        else:
            # Bivarg is a distribution, not a point.
            self.point = False

            self.E,self.V = eigh(np.array(sigma))

            self.E = np.diag(np.real(self.E))

            if theta!=0:
                U = np.array([ [np.cos(theta),-np.sin(theta)],
                               [np.sin(theta), np.cos(theta)] ])
                self.V = np.dot(U,self.V)

            self.sigma = np.dot( self.V, np.dot(self.E,self.V.T) )

            sigma = self.sigma
            self.det = sigma[0,0]*sigma[1,1] - sigma[0,1]*sigma[1,0]
            self.trace = sigma[0,0] + sigma[1,1]

            self.chol = np.array([ [np.sqrt(sigma[0,0]),0.],
                                   [sigma[0,1]/np.sqrt(sigma[0,0]),
                                    np.sqrt( sigma[1,1]-sigma[1,0]*sigma[0,1]/sigma[0,0] ) ] ])

            self.theta = np.math.degrees(np.math.atan2(self.V[0,1],self.V[0,0]))

        return

    def __sub__(self,other):
        return Bivarg( mu=self.mu-other.mu, sigma=self.sigma+other.sigma )

    def __add__(self,other):
        return Bivarg( mu=self.mu+other.mu, sigma=self.sigma+other.sigma )

    def __repr__(self):
        """ Print beautiful representation of bivarg object.
        """
        reprstr = str(self.mu) + ' ' + str(self.sigma.ravel())
        return reprstr

    def __str__(self):
        """ Print more verbose representation of bivarg."""

        if self.point == True:
            rho_str = '---'
        else:
            rho_str = str(self.sigma[0,1] / np.sqrt(self.sigma[0,0]*self.sigma[1,1]))

        strstr = 'mu: ' + str(self.mu) + ', ' + \
            '[sxx syy]: ' + str(np.sqrt(self.sigma.ravel()[np.array([0,3])])) + ', ' + \
            'rho_xy: ' + rho_str
        return strstr

    def transform(self,P=Bgmap()):
        """ Maps a bivariate gaussian distribution (self) to another
        bivariate gaussian by translation (dmu), using a background mapping
        object, i.e., by scaling the principal axes (L) and rotating (theta)
        about a given point (d0).
        """

        # Prep inputs
        if P.__class__.__name__ == 'Bgmap':
            dmu = P.mu[0:2]
            theta = P.mu[2]
            d0 = P.mu[3:5]
            L = P.mu[5:7]
        elif P.__class__.__name__ == 'ndarray':
            dmu = P[0:2]
            theta = P[2]
            d0 = P[3:5]
            L = P[5:7]
        else:
            raise TypeError('Argument to background mapping transform should be a Bgmap object or a 7-vector of parameters.')

        # Calculate transformed centre
        U = np.squeeze(np.array([ [np.cos(theta),-np.sin(theta)],
                                  [np.sin(theta), np.cos(theta)] ]))
        mu = np.dot(U,(self.mu * L + dmu) - d0) + d0

        # Calculate transformed covariance
        if self.point == True:
            # Object is a point; it has no covariance. So we copy
            #  the zero covariance array it already has.
            sigma = self.sigma

        else:
            L = np.diag(L)
            V = np.dot(U,self.V)
            E = np.dot(L,self.E)
            sigma = np.dot( V, np.dot(E,V.T) )

        # Create new bivarg object with transformed values
        return LittleBivarg(mu,sigma)

    def sample(self,n=1):
        """ Draw n samples from bivariate distribution M
        """

        if self.point == True:
            # Bivarg is actually a point, can't sample
            raise SamplingException('Distribution is a point; it cannot be sampled')

        else:
            vals = np.zeros( (n,2) )
            stds = np.random.randn(2,n)
            for i in range(0,n):
                vals[i] = self.mu + np.dot( self.chol, stds[:,i] ).T

        return vals

class LittleBivarg(Bivarg):
    """ This is a minimal bivarg class that is used for representing
    transformed Bivargs that are going to be thrown away later, but might
    be used for likelihood computations.
    """
    def __init__(self,mu=np.array([0.,0.]),sigma=np.array([ [1.,0.],[0.,1.] ])):
        self.mu = mu
        self.sigma = sigma
        self.det = sigma[0,0]*sigma[1,1] - sigma[1,0]*sigma[0,1]

        return

    def promote(self):
        """ Promotes a LitteBivarg to a full Bivarg. This might happen
        when a transformed Bivarg needs to be used for transformation in
        its own right.
        Good job LittleBivarg!
        """
        return Bivarg(mu=self.mu,sigma=self.sigma)

class Amap:
    """ Implements astrometric mapping class as a gaussian process.
    """

    __author__ = "Berian James"
    __version__ = "0.3"
    __email__ = "berian@berkeley.edu"

    def __init__(self,P,A,B,scale=100.0,amp=100.0*np.eye(2)):
        """ Create instance of astrometric map from a background mapping
        (Bgmap object P) and objects in each frame (Bivarg arrays A and B).
        """
        from pyBA.distortion import astrometry_cov, d2

        self.P = P
        self.A = A
        self.B = B

        # Default GP hyperparameters
        self.scale = scale
        self.amp = amp
        self.hyperparams = {'scale': self.scale, 'amp': self.amp}

        # Gather locations of inputs and build distance matrix
        self.xyarr = np.array([o.mu for o in self.A])
        self.d2 = d2(self.xyarr,self.xyarr)

        # Use measurement uncertainties of displacement as 'nugget'
        self.V = np.array([a.sigma for a in A]) + np.array([b.sigma for b in B])

        # Build covariance matrix for data points
        self.C = astrometry_cov(self.d2, self.scale, self.amp, var = self.V)

        # Don't compute cholesky decomposition of C until needed
        self.chol = None

        return

    def draw_background(self, res=30):
        """ Method to draw maximum likelihood background mapping
        on grid of given resolution."""

        from pyBA.plotting import draw_MAP_background
        draw_MAP_background(self.A, self.B, self.P, res = res )
        return

    def draw_realisation(self, res=30):
        """ Draw realisation from Dmap gaussian process and
        plot it on grid of given resolution."""

        from pyBA.plotting import draw_realisation

        # If GP is not conditioned (as checked by self.chol not yet computed),
        #  draw realisation without using input data
        if self.chol == None:
            draw_realisation(self.A, self.B, self.P, self.scale,
                             self.amp, self.chol, res=res)

        # Otherwise, perform regression on observed data
        else:
            draw_realisation(self.A, self.B, self.P, self.scale,
                             self.amp, self.chol, res=res)

        return

    def draw_residuals(self, res=30, scaled='no'):
        """ Draw residuals of object mappings between frames
        from background mapping."""

        from pyBA.plotting import draw_MAP_residuals
        draw_MAP_residuals(self.A, self.B, self.P, scaled=scaled)
        return

    def build_covariance(self,scale=None,amp=None):

        from pyBA.distortion import astrometry_cov

        if scale is not None:
            self.scale = scale
            self.hyperparams['scale'] = scale

        if amp is not None:
            if np.size(amp) == 1:
                amp = np.array([[amp,0.],[0.,amp]])
            elif np.size(amp) == 2:
                amp = np.array([[amp[0],amp[1]],[amp[1],amp[0]]])

            self.amp = amp
            self.hyperparams['amp'] = amp

        self.C = astrometry_cov(self.d2, self.scale, self.amp, var = self.V)

        # Compute cholesky decomposition of C with optimised parameters
        from scipy.linalg import cho_factor
        self.chol = cho_factor(self.C)

    def condition(self):
        """ Conditions hyper-parameters of gaussian process.
        """

        from pyBA.distortion import optimise_HP

        HP0 = [self.scale, self.amp[0,0], self.amp[0,1]]
        #HP0 = [self.scale, self.amp[0,0]]

        # Optimise hyperparameters
        ML_output = optimise_HP(self.A, self.B, self.P, HP0)
        scale_conditioned = ML_output[0]
        amp_conditioned = ML_output[1]
        #ML_lnprob = ML_output[2]

        # Rebuild covariance matrix with updated hyperparameters
        self.build_covariance(scale_conditioned, amp_conditioned)

        return ML_output

    def regression(self, xy):
        """Performs regression on a mapping object at some locations,
        which can be points or distributions."""
        from scipy.linalg import cho_solve
        from pyBA.distortion import d2, astrometry_cov, compute_residual

        # Convert list of inputs to array if needed
        if type(xy) == list:
            xy = np.array(xy)

        # Parse input
        if type(xy)==np.ndarray:

            # Single point
            if xy.size == 2 and type(xy)==np.ndarray:
                XY = np.array([ Bivarg(mu=xy,sigma=0) ])

            # Array of points
            elif xy.ndim == 2 and type(xy[0])==np.ndarray:
                XY = np.array([ Bivarg(mu=xy[i],sigma=0) for i in range(len(xy)) ])

            # Array of query distributions
            elif type(xy[0].__class__.__name__=='Bivarg'):
                XY = xy

            else:
                raise TypeError('Regression input should be an nx2 array of coordinates, or an array of Bivarg distributions')

        # Single query distribution
        elif xy.__class__.__name__ == 'Bivarg':
            XY = np.array([ xy ])

        else:
            raise TypeError('Regression input should be an nx2 array of coordinates, or an array of Bivarg distributions')

        ## Gaussian process regression
        # Old grid coordinates
        xyobs = np.array([o.mu for o in self.A])

        # New grid coordinates
        xynew = np.array([o.mu for o in XY])

        # Get regression data (resdiual to background)
        dx, dy = compute_residual(self.A, self.B, self.P)
        dxy = np.array([dx, dy]).T.flatten()

        # Build cross covariance between old and new locations
        d2_grid = d2(xynew,xyobs)
        Cs = astrometry_cov(d2_grid, self.scale, self.amp)

        # Build covariance for new locations
        d2_grid = d2(xynew, xynew)
        Vnew = np.array([o.sigma for o in XY])
        # Don't need to add variances for input points here, they will be propagated
        #  through the background transformation.
        #Css = astrometry_cov(d2_grid, self.scale, self.amp, var=Vnew)
        Css = astrometry_cov(d2_grid, self.scale, self.amp)

        # Regression: mean function evaluated at new locations
        vxy = Cs.dot(cho_solve(self.chol, dxy)).reshape( (len(XY),2) )

        # Regression: uncertainties at new locations
        S = Css - Cs.dot(cho_solve(self.chol, Cs.T))

        ## Package output
        # Background (mean function) mapping
        R = np.array([o.transform(self.P) for o in XY])

        # Add regression residuals to mean function
        munew = np.array([o.mu for o in R]) + vxy

        # Get regression uncertainty from background mapping
        S_P = self.P.uncertainty(XY)

        # Get regression uncertainty from gaussian process
        S_gp = np.array([S[i:i+2,i:i+2] for i in range(0,len(S),2)])

        # Combine uncertainties into single covariance matrix
        sigmanew = np.array([o.sigma for o in R]) + S_gp + S_P

        # Construct output array of Bivargs
        O = np.array([ Bivarg(mu=munew[i], sigma=sigmanew[i]) for i in range(len(R)) ])

        return O, S_gp, S_P


text:
package ch.usi.inf.l3.sana.modulej

object Nodes {
  final val nodes =
    """Program,
       CompilationUnit,
       Import,
       PackageDef,
       ClassDef,
       Template,
       MethodDef,
       ValDef,
       Throw,
       Try,
       Catch,
       Select,
       This,
       Super,
       New,
       Synchronized,
       ArrayCreation,
       ArrayAccess,
       ArrayInitializer,
       ArrayTypeUse,
       Label,
       Switch,
       Case,
       Break,
       Continue,
       Assign,
       If,
       While,
       Block,
       For,
       Ternary,
       Apply,
       Return,
       Cast,
       Binary,
       Unary,
       Literal,
       TypeUse,
       Ident"""

}


text:
package startrekj.hpbasic.functions;

import startrekj.hpbasic.CONST;
import startrekj.hpbasic.NumericExpression;

import static startrekj.hpbasic.Arithmetic.*;

public class MULT implements NumericExpression {
	private NumericExpression operand1;
	private NumericExpression operand2;
	private MULT(NumericExpression operand1, NumericExpression operand2) {
		this.operand1 = operand1;
		this.operand2 = operand2;
	}
	public static MULT MULT(NumericExpression operand1, NumericExpression operand2) {
		return new MULT(operand1, operand2);
	}
	public static MULT MULT(NumericExpression operand1, Number operand2) {
		return new MULT(operand1, new CONST(operand2));
	}
	public static MULT MULT(Number operand1, NumericExpression operand2) {
		return new MULT(new CONST(operand1), operand2);
	}
	public Number evaluate() {
		return mult(operand1.evaluate(), operand2.evaluate());
	}
	@Override
	public String toString() {
		return "(" + operand1 + ")*(" + operand2 +")";
	}
}


text:
import os
import sys
import time

import numpy as np

import theano
import theano.tensor as T

# implementing flatten
class DepthConcat(object):
    """ Initialize from xml definition node """
    def __init__(self,layer_def,inputs,inputs_shape,rs,clone_from=None):
        """
            Create a depth concatenation layer. This is for concatenating outputs of convolutional layers, for example to create inception modules
            The output is created by concatenating the inputs along dimension 0

            :type layer_def: Element, xml containing configu for Conv layer

            :type inputs: a list of theano.tensor4, all should have the same height and width

            :type input_shapes: list of sizes of each tensor4

            :type rng: a random number generator used to initialize weights
        """
        self.inputs        = inputs
        n_channels         = np.sum([sz[0] for sz in inputs_shape])
        batch_size         = inputs_shape[0][3]
        dim1               = inputs_shape[0][1]
        dim2               = inputs_shape[0][2]
        for sz in inputs_shape:
            assert(dim1       == sz[1])
            assert(dim2       == sz[2])
            assert(batch_size == sz[3])
        self.output        = T.concatenate(inputs,axis=0)
        self.input_shape   = inputs_shape
        self.output_shape  = [n_channels,dim1,dim2,batch_size]
        self.params        = []


text:
#import <IDEKit/IDEViewController.h>

#import "NSMenuDelegate.h"
#import "NSTableViewDataSource.h"
#import "NSTableViewDelegate.h"

@class DVTBorderedView, DVTGradientImageButton, DVTGradientImagePopUpButton, DVTImageAndTextColumn, DVTMapTable, DVTObservingToken, DVTPreferenceSetManager, DVTScrollView, IDEControlGroup, NSArray, NSArrayController, NSMenuItem, NSString, NSTableView;

@interface IDEPreferenceSetViewController : IDEViewController <NSTableViewDelegate, NSTableViewDataSource, NSMenuDelegate>
{
    NSMenuItem *_duplicateSelectedThemeMenuItem;
    NSMenuItem *_newThemeFromTemplateMenuItem;
    DVTImageAndTextColumn *_tableColumn;
    DVTBorderedView *_viewControllerBorderedView;
    NSTableView *_tableView;
    DVTGradientImagePopUpButton *_addPopUpButton;
    DVTGradientImageButton *_removeButton;
    IDEControlGroup *_controlGroup;
    DVTBorderedView *_controlGroupBorderedView;
    NSArrayController *_prefSetsArrayController;
    DVTScrollView *_scrollView;
    DVTPreferenceSetManager *_preferenceSetManager;
    DVTMapTable *_observerTokensForPreferenceSetsMapTable;
    DVTObservingToken *_currentPreferenceSetObserver;
    BOOL _hasBeenSetup;
}

+ (id)keyPathsForValuesAffectingCanDeleteActivePreferenceSet;
- (void).cxx_destruct;
- (void)_addObserversForPreferenceSet:(id)arg1;
- (void)_duplicatePreferenceSet:(id)arg1;
- (void)_removeObserversForPreferenceSet:(id)arg1;
- (id)_selectedPreferenceSet;
- (BOOL)canDeleteActivePreferenceSet;
- (void)deleteActivePreferenceSet:(id)arg1;
- (void)duplicateActivePreferenceSet:(id)arg1;
- (void)duplicateSelectedDefaultThemeFromMenu:(id)arg1;
- (id)initWithNibName:(id)arg1 bundle:(id)arg2;
- (void)loadView;
- (void)menuNeedsUpdate:(id)arg1;
@property(retain) DVTPreferenceSetManager *preferenceSetManager; // @synthesize preferenceSetManager=_preferenceSetManager;
@property(readonly) NSTableView *preferenceSetTableView; // @synthesize preferenceSetTableView=_tableView;
@property(readonly) NSArray *preferenceSetsSortDescriptors;
- (void)primitiveInvalidate;
- (void)setupWithPreferenceSetManager:(id)arg1;
- (id)tableView:(id)arg1 selectionIndexesForProposedSelection:(id)arg2;
- (void)tableView:(id)arg1 setObjectValue:(id)arg2 forTableColumn:(id)arg3 row:(long long)arg4;
- (void)tableView:(id)arg1 willDisplayCell:(id)arg2 forTableColumn:(id)arg3 row:(long long)arg4;
- (void)tableViewSelectionDidChange:(id)arg1;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end


text:
package org.fedoraproject.xmvn.tools.install.impl;

import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.IOException;
import java.nio.file.Paths;

import org.junit.jupiter.api.Test;

import org.fedoraproject.xmvn.tools.install.Directory;
import org.fedoraproject.xmvn.tools.install.RegularFile;

/**
 * @author Mikolaj Izdebski
 */
public class DirectoryTest
    extends AbstractFileTest
{
    /**
     * Basic test for directory installation
     *
     * @throws Exception
     */
    @Test
    public void testSingleDirectoryInstallation()
        throws Exception
    {
        add( new Directory( Paths.get( "usr/src/sys/kern" ) ) );
        performInstallation();

        assertDirectoryStructure( "D /usr", "D /usr/src", "D /usr/src/sys", "D /usr/src/sys/kern" );

        assertDescriptorEquals( "%attr(0755,root,root) %dir /usr/src/sys/kern" );
    }

    /**
     * Test if installing directory which already exists doesn't cause I/O (or other) errors
     *
     * @throws Exception
     */
    @Test
    public void testExistentDirectoryInstallation()
        throws Exception
    {
        add( new Directory( Paths.get( "etc/sysconfig/java" ) ) );
        add( new Directory( Paths.get( "etc/xmvn" ) ) );
        add( new Directory( Paths.get( "etc" ) ) );
        performInstallation();

        assertDirectoryStructure( "D /etc", "D /etc/sysconfig", "D /etc/sysconfig/java", "D /etc/xmvn" );

        assertDescriptorEquals( "%attr(0755,root,root) %dir /etc", "%attr(0755,root,root) %dir /etc/sysconfig/java",
                                "%attr(0755,root,root) %dir /etc/xmvn" );
    }

    /**
     * Test if directory installation fails if target already exists and is not a directory.
     */
    @Test
    public void testExistentTargetFile()
        throws Exception
    {
        add( new RegularFile( Paths.get( "foo/bar" ), new byte[0] ) );
        add( new Directory( Paths.get( "foo/bar" ) ) );
        assertThrows( IOException.class, () -> performInstallation() );
    }

    /**
     * Test if directory installation fails if component of target directory target already exists and is not a
     * directory.
     */
    @Test
    public void testDirectoryCOmponentIsAFile()
        throws Exception
    {
        add( new RegularFile( Paths.get( "a/b/c/d" ), new byte[0] ) );
        add( new Directory( Paths.get( "a/b/c/d/e/f/g/h" ) ) );
        assertThrows( IOException.class, () -> performInstallation() );
    }

    /**
     * Test if custom access mode can be specified.
     */
    @Test
    public void testAccessMode()
        throws Exception
    {
        add( new Directory( Paths.get( "foo" ), 320 ) );
        performInstallation();

        assertDirectoryStructure( "D /foo" );

        assertDescriptorEquals( "%attr(0500,root,root) %dir /foo" );
    }
}


text:
package se.lth.cs.docforia;

import se.lth.cs.docforia.memstore.MemoryDocumentFactory;

/**
 * Json test code
 */
public class MemoryJsonLevel0 extends ModelTest {
    @Override
    public DocumentFactory documentFactory() {
        return MemoryDocumentFactory.getInstance();
    }

    @Override
    protected Document serializeDeserialize(Document doc) {
        String json = documentIO().toJson(doc, DocumentStorageLevel.LEVEL_0);
        return documentIO().fromJson(json);
    }
}


text:
<?php
/**
 * Created by IntelliJ IDEA.
 * User: mauilap
 * Date: 01/11/16
 * Time: 13.11.
 */

namespace WordCounter\Exception;

class InvalidAttributeException extends \Exception
{
    /**
     * InvalidAttributeException constructor.
     *
     * @param mixed $argumentsValue
     */
    public function __construct($argumentsValue)
    {
        parent::__construct(sprintf('invalid attribute passed %s', $argumentsValue));
    }
}


text:
echo "Installing dotfiles"

# oh-my-zsh
git clone https://github.com/robbyrussell/oh-my-zsh ~/.oh-my-zsh

# Terminal solarized
git clone https://github.com/tomislav/osx-terminal.app-colors-solarized ~/.osx_terminal_solarized

source install/link.sh

if [ "$(uname)" == "Darwin" ]; then
    xcode-select --install
    echo "Running on OSX"

    echo "Brewing all the things"
    source install/brew.sh

    echo "Updating OSX settings"
    source install/osx.sh

    echo "Installing node (from nvm)"
    source install/nvm.sh
fi

echo "creating vim directories"
mkdir -p ~/.vim-tmp

echo "Installing additional stuff"
git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim

curl "https://raw.githubusercontent.com/altercation/vim-colors-solarized/master/colors/solarized.vim" >> solarized.vim
mkdir ~/.vim/colors
mv solarized.vim ~/.vim/colors/

echo "Configuring zsh as default shell"
chsh -s $(grep /zsh$ /etc/shells | tail -1)
env zsh


text:
xclient
=======

Implements the [XCLIENT](http://www.postfix.org/XCLIENT_README.html) protocol.

## configuration

* xclient.hosts

    A list of IP addresses, one per line that should be allowed to use the
    XCLIENT protocol.  Localhost (127.0.0.1 or ::1) is allowed implicitly.


text:
<?php

declare(strict_types=1);

namespace LIN3S\SharedKernel\Domain\Model\TaxIdNumber;

use LIN3S\SharedKernel\Exception\DomainException;

/**
 * @author Beñat Espiña <benatespina@gmail.com>
 */
class TaxIdNumberInvalidException extends DomainException
{
    public static function fromSpain(string $tin) : self
    {
        return new self(sprintf('The "%s" is not a valid NIF (DNI, NIE, or CIF) number.', $tin));
    }

    public static function fromSpanishNie(string $nie) : self
    {
        return new self(sprintf('The "%s" is not a valid Spanish NIE number.', $nie));
    }

    public static function fromSpanishCif(string $cif) : self
    {
        return new self(sprintf('The "%s" is not a valid Spanish CIF number.', $cif));
    }

    public static function fromSpanishDni(string $dni) : self
    {
        return new self(sprintf('The "%s" is not a valid Spanish DNI number.', $dni));
    }
}


text:
<?php

namespace Obloquy\V1\Fixture;

interface CsvFixtureInterface
{

    /**
     * @return string
     */
    function getCsvFilename();

    /**
     * @return string
     */
    function getEntityName();

}


text:
package org.apache.isis.applib.services.grid;

import org.apache.isis.applib.annotation.Programmatic;
import org.apache.isis.applib.layout.grid.Grid;

public interface GridLoaderService2 extends GridLoaderService {

    /**
     * Returns a new instance of a {@link Grid} for the specified domain class, eg from a
     * layout.xml file, else null.
     */
    @Programmatic
    Grid load(final Class<?> domainClass, String layout);

}


text:
<?php
namespace Rolice\LaravelDbSwitch\Facades;

use Illuminate\Support\Facades\Facade;

class DbSwitch extends Facade
{

    /**
     * Get the registered name of the component.
     *
     * @return string
     *
     */
    protected static function getFacadeAccessor()
    {
        return 'db.switch';
    }

}


text:
package demo4

import java.util.UUID
import com.datastax.driver.core.{Cluster, Session}
import troy.dsl._
import scala.concurrent.Await
import scala.concurrent.duration.Duration

case class Post(id: UUID, title: String)

object Main extends App {
  import scala.concurrent.ExecutionContext.Implicits.global

  val port: Int = 9042
  val host: String = "127.0.0.1"

  private val cluster =
    new Cluster.Builder().addContactPoints(host).withPort(port).build()

  implicit val session: Session = cluster.connect()

  val listByTag = withSchema {
    (tag: String) =>
      cql"""
         SELECT post_id, post_title
         FROM test.posts
         WHERE post_tags CONTAINS $tag
       """.prepared.as(Post)
  }

  val titlesF = listByTag("test").map(_.map(_.title))
  val titles = Await.result(titlesF, Duration(1, "second"))
  println("Matching titles:")
  titles.foreach(println)

  session.close()
  cluster.close()
}


text:
module.exports = {
  root: true,
  parser: '@typescript-eslint/parser',
  plugins: [
    '@typescript-eslint',
  ],
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
  ],
  rules: {
    "@typescript-eslint/explicit-module-boundary-types": "off",
    "@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }],
    "prefer-const": ["error", { "destructuring": "all" }],
    "no-constant-condition": ["error", { "checkLoops": false }],
    "curly": ["error"],
    "brace-style": "error",
    "indent": ["error", 2]
  }
};


text:
/*!
 * Module dependencies
 */

var utils = require('./utils');

/*!
 * Prepare a set of path options for query population.
 *
 * @param {Query} query
 * @param {Object} options
 * @return {Array}
 */

exports.preparePopulationOptions = function preparePopulationOptions(query, options) {
  var pop = utils.object.vals(query.options.populate);

  // lean options should trickle through all queries
  if (options.lean) pop.forEach(makeLean);

  return pop;
};

/*!
 * Prepare a set of path options for query population. This is the MongooseQuery
 * version
 *
 * @param {Query} query
 * @param {Object} options
 * @return {Array}
 */

exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ(query, options) {
  var pop = utils.object.vals(query._mongooseOptions.populate);

  // lean options should trickle through all queries
  if (options.lean) pop.forEach(makeLean);

  return pop;
};

/*!
 * If the document is a mapped discriminator type, it returns a model instance for that type, otherwise,
 * it returns an instance of the given model.
 *
 * @param {Model}  model
 * @param {Object} doc
 * @param {Object} fields
 *
 * @return {Model}
 */
exports.createModel = function createModel(model, doc, fields) {
  var discriminatorMapping = model.schema
    ? model.schema.discriminatorMapping
    : null;

  var key = discriminatorMapping && discriminatorMapping.isRoot
    ? discriminatorMapping.key
    : null;

  if (key && doc[key] && model.discriminators && model.discriminators[doc[key]]) {
    return new model.discriminators[doc[key]](undefined, fields, true);
  }

  return new model(undefined, fields, true);
};

/*!
 * Set each path query option to lean
 *
 * @param {Object} option
 */

function makeLean(option) {
  option.options || (option.options = {});
  option.options.lean = true;
}


text:
package org.simpleflatmapper.map.context.impl;

import org.simpleflatmapper.map.context.KeyAndPredicate;
import org.simpleflatmapper.map.context.KeyDefinition;
import org.simpleflatmapper.map.context.KeySourceGetter;

import java.lang.reflect.Array;
import java.util.List;

public class KeyDefinitionBuilder<S, K> {
    private final KeySourceGetter<K, ? super S> keySourceGetter;
    private final List<KeyAndPredicate<S, K>> keyAndPredicates;
    private final int index;

    public KeyDefinitionBuilder(List<KeyAndPredicate<S, K>> keyAndPredicates, KeySourceGetter<K, ? super S> keySourceGetter, int index) {
        this.keyAndPredicates = keyAndPredicates;
        this.keySourceGetter = keySourceGetter;
        this.index = index;
    }

    public KeyDefinitionBuilder<S, K> asChild(int currentIndex) {
        return new KeyDefinitionBuilder<S, K>(keyAndPredicates,  keySourceGetter, currentIndex);
    }

    public static <S, K> KeyDefinition<S, K>[] toKeyDefinitions(KeyDefinitionBuilder<S, K>[] siblings) {
        KeyDefinition<S, K>[] keyDefinitions = new KeyDefinition[siblings.length];
        for(KeyDefinitionBuilder<S, K> builder : siblings) {
            KeyDefinition<S, K> keyDefinition = new KeyDefinition<S, K>(toArray(builder.keyAndPredicates), builder.keySourceGetter, builder.index);
            keyDefinitions[builder.index]= keyDefinition;
        }
        return keyDefinitions;
    }

    private static <K> K[] toArray(List<K> keys) {
        if (keys.size() == 0) return null;
        else return keys.toArray((K[]) Array.newInstance(keys.get(0).getClass(), 0));
    }

    public List<KeyAndPredicate<S, K>> getKeyAndPredicates() {
        return keyAndPredicates;
    }
}


text:
<?php

namespace Drupal\commerce_shipping;

/**
 * Represents a proposed shipment.
 *
 * Proposed shipments are returned from the packing process, and then mapped
 * to new or existing shipment entities. This allows the packers to be run
 * whenever the order changes, while only modifying the shipments if they
 * have changed.
 */
class ProposedShipment {

  /**
   * The shipment type.
   *
   * @var string
   */
  protected $type;

  /**
   * The order ID.
   *
   * @var int
   */
  protected $orderId;

  /**
   * The shipment title.
   *
   * @var string
   */
  protected $title;

  /**
   * The shipment items.
   *
   * @var \Drupal\commerce_shipping\ShipmentItem[]
   */
  protected $items = [];

  /**
   * The shipping profile.
   *
   * We can't store just the profile ID because
   * the profile entity might not be saved yet.
   *
   * @var \Drupal\profile\Entity\ProfileInterface
   */
  protected $shippingProfile;

  /**
   * The package type plugin ID.
   *
   * @var string
   */
  protected $packageTypeId;

  /**
   * The custom fields.
   *
   * @var array
   */
  protected $customFields = [];

  /**
   * Constructs a new ProposedShipment object.
   *
   * @param array $definition
   *   The definition.
   */
  public function __construct(array $definition) {
    foreach (['type', 'order_id', 'title', 'items', 'shipping_profile'] as $required_property) {
      if (empty($definition[$required_property])) {
        throw new \InvalidArgumentException(sprintf('Missing required property "%s".', $required_property));
      }
    }
    foreach ($definition['items'] as $shipment_item) {
      if (!($shipment_item instanceof ShipmentItem)) {
        throw new \InvalidArgumentException('Each shipment item under the "items" property must be an instance of ShipmentItem.');
      }
    }

    $this->type = $definition['type'];
    $this->orderId = $definition['order_id'];
    $this->title = $definition['title'];
    $this->items = $definition['items'];
    $this->shippingProfile = $definition['shipping_profile'];
    if (!empty($definition['package_type_id'])) {
      $this->packageTypeId = $definition['package_type_id'];
    }
    if (!empty($definition['custom_fields'])) {
      $this->customFields = $definition['custom_fields'];
    }
  }

  /**
   * Gets the shipment type.
   *
   * @return string
   *   The shipment type.
   */
  public function getType() {
    return $this->type;
  }

  /**
   * Gets the parent order ID.
   *
   * @return int
   *   The order ID.
   */
  public function getOrderId() {
    return $this->orderId;
  }

  /**
   * Gets the shipment title.
   *
   * @return string
   *   The shipment title.
   */
  public function getTitle() {
    return $this->title;
  }

  /**
   * Gets the shipment items.
   *
   * @return \Drupal\commerce_shipping\ShipmentItem[]
   *   The shipment items.
   */
  public function getItems() {
    return $this->items;
  }

  /**
   * Gets the shipping profile.
   *
   * @return \Drupal\profile\Entity\ProfileInterface\null
   *   The shipping profile, or NULL if unknown.
   */
  public function getShippingProfile() {
    return $this->shippingProfile;
  }

  /**
   * Gets the package type plugin ID.
   *
   * If the proposed shipment returns no package type ID, shipping methods
   * are expected to use their default package type.
   *
   * @return string|null
   *   The package type plugin ID, or NULL if unknown.
   */
  public function getPackageTypeId() {
    return $this->packageTypeId;
  }

  /**
   * Gets the custom fields.
   *
   * @return array
   *   The custom fields, in the $field_name => $value format.
   */
  public function getCustomFields() {
    return $this->customFields;
  }

}


text:
<?php

namespace Diside\StaticPageBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;
use Symfony\Component\Validator\Constraints as Assert;

class StaticPageTranslation
{
    use ORMBehaviors\Translatable\Translation;

    /**
     * @Assert\NotBlank(message="static_pages.error.empty_title")
     * @var string
     */
    private $title;

    /** @var string */
    private $content;

    /**
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title)
    {
        $this->title = $title;
    }

    /**
     * @return string
     */
    public function getContent()
    {
        return $this->content;
    }

    public function setContent($content)
    {
        $this->content = $content;
    }
}