text:
# Lesson 2.3: Using the `Scheduler` to Send Messages Later
Welcome to Lesson 2.3!

Where are we? At this point, we have our basic chart set up, along with our `ChartingActor`  which is supposed to be graphing system metrics. Except right now, `ChartingActor` isn't actually graphing anything! It's time to change that.

In this lesson, we'll be hooking up the various components of our system to make our Resource Monitor application actually chart system resource consumption!

To make our resource monitoring app work as intended, we need to wire up `ChartingActor` to the actual system [Performance Counters](https://msdn.microsoft.com/en-us/library/system.diagnostics.performancecounter.aspx "PerformanceCounter Class - C#") for the graph data. This needs to happen on an ongoing basis so that our chart regularly updates.

One of the most powerful capabilities Akka.NET exposes is the ability to schedule messages to be sent in the future, including regularly occurring messages. And it turns out, this is exactly the functionality we need to have `ChartingActor` regularly update our graphs.

In this lesson you'll learn two powerful Akka.NET concepts:

1. How to use the `Scheduler`, and
2. How to implement the [Publish-subscribe (pub-sub) pattern](http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern) using actors. This is a powerful technique for creating reactive systems.

## Key Concepts / Background
How do you get an actor to do something in the future? And what if you want that actor to do something on a recurring basis in the future?

Perhaps you want an actor to periodically fetch information, or to occasionally ping another actor within the system for its status.

Akka.NET provides a mechanism for doing just this sort of thing. Meet your new best friend: the `Scheduler`.

### What is the `Scheduler`?
The `ActorSystem.Scheduler` ([docs](http://api.getakka.net/docs/stable/html/FB15E2E6.htm "Akka.NET Stable API Docs - IScheduler interface")) is a singleton within every `ActorSystem` that allows you to schedule messages to be sent to an actor in the future. The `Scheduler` can send both one-off and recurring messages.

### How do I use the `Scheduler`?
As we mentioned, you can schedule one-off or recurring messages to an actor.

You can also schedule an `Action` to occur in the future, instead of sending a message to an actor.

#### Access the `Scheduler` via the `ActorSystem`
`Scheduler` must be accessed through the `ActorSystem`, like so:

```csharp
// inside Main.cs we have direct handle to the ActorSystem
var system = ActorSystem.Create("MySystem");
system.Scheduler.ScheduleTellOnce(TimeSpan.FromMinutes(30),
				              someActor,
				              someMessage, ActorRefs.Nobody);

// but inside an actor, we access the ActorSystem via the ActorContext
Context.System.Scheduler.ScheduleTellOnce(TimeSpan.FromMinutes(30),
								             someActor,
								             someMessage, ActorRefs.Nobody);
```

#### Schedule one-off messages with `ScheduleTellOnce()`
Let's say we want to have one of our actors fetch the latest content from an RSS feed 30 minutes in the future. We can use [`IScheduler.ScheduleTellOnce()`](http://api.getakka.net/docs/stable/html/190E4EB.htm "Akka.NET Stable API Docs - IScheduler.ScheduleTellOnce method") to do that:

```csharp
var system = ActorSystem.Create("MySystem");
var someActor = system.ActorOf<SomeActor>("someActor");
var someMessage = new FetchFeed() {Url = ...};
// schedule the message
system
   .Scheduler
   .ScheduleTellOnce(TimeSpan.FromMinutes(30), // initial delay of 30 min
             someActor, someMessage, ActorRefs.Nobody);
```

Voila! `someActor` will receive `someMessage` in 30 minutes time.

#### Schedule recurring messages with `ScheduleTellRepeatedly()`
Now, **what if we want to schedule this message to be delivered once *every 30 minutes*?**

For this we can use the following [`IScheduler.ScheduleTellRepeatedly()`](http://api.getakka.net/docs/stable/html/A909C289.htm "Akka.NET Stable API Docs - IScheduler.ScheduleTellRepeatedly") overload.

```csharp
var system = ActorSystem.Create("MySystem");
var someActor = system.ActorOf<SomeActor>("someActor");
var someMessage = new FetchFeed() {Url = ...};
// schedule recurring message
system
   .Scheduler
   .ScheduleTellRepeatedly(TimeSpan.FromMinutes(30), // initial delay of 30 min
             TimeSpan.FromMinutes(30), // recur every 30 minutes
             someActor, someMessage, ActorRefs.Nobody);
```

That's it!

### How do I cancel a scheduled message?
What happens if we need to cancel a scheduled or recurring message? We use a [`ICancelable`](http://api.getakka.net/docs/stable/html/3FA8058E.htm "Akka.NET Stable API Docs - ICancelable interface"), which we can create using a [`Cancelable`](http://api.getakka.net/docs/stable/html/8869EC52.htm) instance.

First, the message must be scheduled so that it can be cancelled. If a message is cancelable, we then just have to call `Cancel()` on our handle to the `ICancelable` and it will not be delivered. For example:

```csharp
var system = ActorSystem.Create("MySystem");
var cancellation = new Cancelable(system.Scheduler);
var someActor = system.ActorOf<SomeActor>("someActor");
var someMessage = new FetchFeed() {Url = ...};

// first, set up the message so that it can be canceled
system
   .Scheduler
   .ScheduleTellRepeatedly(TimeSpan.FromMinutes(30), TimeSpan.FromMinutes(30)
                 someActor, someMessage, ActorRefs.Nobody,
  			     cancellation); // add cancellation support

// here we actually cancel the message and prevent it from being delivered
cancellation.Cancel();
```

####Alternative: get an `ICancelable` task using `ScheduleTellRepeatedlyCancelable`
One of the new `IScheduler` methods we introduced in Akka.NET v1.0 is the [`ScheduleTellRepeatedlyCancelable` extension method](http://api.getakka.net/docs/stable/html/9B66375D.htm "Akka.NET API Docs - SchedulerExtensions.ScheduleTellRepeatedlyCancelable extension method").This extension method inlines the process of creating an `ICancelable` instance for your recurring messages and simply returns an `ICancelable` for you.

```csharp
var system = ActorSystem.Create("MySystem");
var someActor = system.ActorOf<SomeActor>("someActor");
var someMessage = new FetchFeed() {Url = ...};

// cancellable recurring message send created automatically
var cancellation =  system
   .Scheduler
   .ScheduleTellRepeatedlyCancelable(TimeSpan.FromMinutes(30),
                 TimeSpan.FromMinutes(30)
                 someActor,
                 someMessage,
                 ActorRefs.Nobody);

// here we actually cancel the message and prevent it from being delivered
cancellation.Cancel();
```
This is a more concise alternative to the previous example, and we recommend using it going forward even though we won't be using it in this bootcamp.

### How precise is the timing of scheduled messages?
***Scheduled messages are more than precise enough for all the use cases we've come across.***

That said, there are two situations of imprecision that we're aware of:

1. Scheduled messages are scheduled onto the CLR threadpool and use `Task.Delay` under the hood. If there is a high load on the CLR threadpool, the task might finish a little later than planned. There is no guarantee that the task will execute at EXACTLY the millisecond you expect.
2. If your scheduling requirements demand precision below 15 milliseconds then the `Scheduler` is not precise enough for you. Nor is any typical operating system such as Windows, OSX, or Linux. This is because ~15ms is the interval in which Windows and other general OSes update their system clock ("clock resolution"), so these OSs can't support any timing more precise than their own system clocks.

### What are the various overloads of `Schedule` and `ScheduleOnce`?
Here are all the overload options you have for scheduling a message.

#### Overloads of `ScheduleTellRepeatedly`
These are the various API calls you can make to schedule recurring messages.

[Refer to the `IScheduler` API documentation](http://api.getakka.net/docs/stable/html/FB15E2E6.htm "Akka.NET Stable API Documentation - IScheduler Interface").

#### Overloads of `ScheduleTellOnce`
These are the various API calls you can make to schedule one-off messages.

[Refer to the `IScheduler` API documentation](http://api.getakka.net/docs/stable/html/FB15E2E6.htm "Akka.NET Stable API Documentation - IScheduler Interface").

### How do I do Pub/Sub with Akka.NET Actors?
It's actually very simple. Many people expect this to be very complicated and are suspicious that there isn't more code involved. Rest assured, there's nothing magic about pub/sub with Akka.NET actors. It can literally be as simple as this:

```csharp
public class PubActor : ReceiveActor
{
  // HashSet automatically eliminates duplicates
  private HashSet<IActorRef> _subscribers;

  PubActor()
  {
    _subscribers = new HashSet<IActorRef>();

    Receive<Subscribe>(sub =>
    {
      _subscribers.Add(sub.IActorRef);
    });

    Receive<MessageSubscribersWant>(message =>
    {
      // notify each subscriber
      foreach (var sub in _subscribers)
      {
        sub.Tell(message);
      }
    });

    Receive<Unsubscribe>(unsub =>
    {
      _subscribers.Remove(unsub.IActorRef);
    });
  }
}
```

Pub/sub is trivial to implement in Akka.NET and it's a pattern you can feel comfortable using regularly when you have scenarios that align well with it.

Now that you're familiar with how the `Scheduler` works, lets put it to use and make our charting UI reactive!

## Exercise
**HEADS UP:** This section is where 90% of the work happens in all of Unit 2. We're going to add a few new actors who are responsible for setting up pub/sub relationships with the `ChartingActor` in order to graph `PerformanceCounter` data at regular intervals.

### Step 1 - Delete the "Add Series" Button and Click Handler from Lesson 2

We're not going to need it. **Delete the "Add Series" button** from the **[Design]** view of `Main.cs` and remove the click handler:

```csharp
// Main.cs - Main
// DELETE THIS:
private void button1_Click(object sender, EventArgs e)
{
    var series = ChartDataHelper.RandomSeries("FakeSeries" +
        _seriesCounter.GetAndIncrement());
    _chartActor.Tell(new ChartingActor.AddSeries(series));
}
```

### Step 2 - Add 3 New Buttons to `Main.cs`

We're going to add three new buttons and click handlers for each:

* **CPU (ON)**
* **MEMORY (OFF)**
* **DISK (OFF)**

Your **[Design]** view in Visual Studio for `Main.cs` should look like this:

![Add 3 buttons for tracking different performance counter metrics](images/add-3-buttons.png)

Make sure that you given a descriptive name to each of these buttons, because we're going to need to refer to them later. You can set a descriptive name for each using the **Properties** window in Visual Studio:

![Set a descriptive name for each button](images/button-properties-window.png)

Here are the names we'll be using for each button when we refer to them later:

* **CPU (ON)** - `btnCpu`
* **MEMORY (OFF)** - `btnMemory`
* **DISK (OFF)** - `btnDisk`

Once you've renamed your buttons, *add click handlers for each button by double-clicking on the button* in the **[Design]** view.

```csharp
// Main.cs - Main
private void btnCpu_Click(object sender, EventArgs e)
{

}

private void btnMemory_Click(object sender, EventArgs e)
{

}

private void btnDisk_Click(object sender, EventArgs e)
{

}
```

We'll fill these handlers in later.

### Step 3 - Add Some New Message Types
We're going to add a few new actors to our project in a moment, but before we do that let's create a new file inside the `/Actors` folder in our project and define some new message types:

```csharp
// Actors/ChartingMessages.cs

using Akka.Actor;

namespace ChartApp.Actors
{
    #region Reporting

    /// <summary>
    /// Signal used to indicate that it's time to sample all counters
    /// </summary>
    public class GatherMetrics { }

    /// <summary>
    /// Metric data at the time of sample
    /// </summary>
    public class Metric
    {
        public Metric(string series, float counterValue)
        {
            CounterValue = counterValue;
            Series = series;
        }

        public string Series { get; private set; }

        public float CounterValue { get; private set; }
    }

    #endregion

    #region Performance Counter Management

    /// <summary>
    /// All types of counters supported by this example
    /// </summary>
    public enum CounterType
    {
        Cpu,
        Memory,
        Disk
    }

    /// <summary>
    /// Enables a counter and begins publishing values to <see cref="Subscriber"/>.
    /// </summary>
    public class SubscribeCounter
    {
        public SubscribeCounter(CounterType counter, IActorRef subscriber)
        {
            Subscriber = subscriber;
            Counter = counter;
        }

        public CounterType Counter { get; private set; }

        public IActorRef Subscriber { get; private set; }
    }

    /// <summary>
    /// Unsubscribes <see cref="Subscriber"/> from receiving updates
    /// for a given counter
    /// </summary>
    public class UnsubscribeCounter
    {
        public UnsubscribeCounter(CounterType counter, IActorRef subscriber)
        {
            Subscriber = subscriber;
            Counter = counter;
        }

        public CounterType Counter { get; private set; }

        public IActorRef Subscriber { get; private set; }
    }

    #endregion
}
```

Now we can start adding the actors who depend on these message definitions.

### Step 4 - Create the `PerformanceCounterActor`

The `PerformanceCounterActor` is the actor who's going to publish `PerformanceCounter` values to the `ChartingActor` using Pub/Sub and the `Scheduler`.

Create a new file in the `/Actors` folder called `PerformanceCounterActor.cs` and type the following:

```csharp
// Actors/PerformanceCounterActor.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Akka.Actor;

namespace ChartApp.Actors
{
    /// <summary>
    /// Actor responsible for monitoring a specific <see cref="PerformanceCounter"/>
    /// </summary>
    public class PerformanceCounterActor : UntypedActor
    {
        private readonly string _seriesName;
        private readonly Func<PerformanceCounter> _performanceCounterGenerator;
        private PerformanceCounter _counter;

        private readonly HashSet<IActorRef> _subscriptions;
        private readonly ICancelable _cancelPublishing;

        public PerformanceCounterActor(string seriesName,
            Func<PerformanceCounter> performanceCounterGenerator)
        {
            _seriesName = seriesName;
            _performanceCounterGenerator = performanceCounterGenerator;
            _subscriptions = new HashSet<IActorRef>();
            _cancelPublishing = new Cancelable(Context.System.Scheduler);
        }

        #region Actor lifecycle methods

        protected override void PreStart()
        {
            //create a new instance of the performance counter
            _counter = _performanceCounterGenerator();
            Context.System.Scheduler.ScheduleTellRepeatedly(
                TimeSpan.FromMilliseconds(250),
                TimeSpan.FromMilliseconds(250),
                Self,
                new GatherMetrics(),
                Self,
                _cancelPublishing);
        }

        protected override void PostStop()
        {
            try
            {
                //terminate the scheduled task
                _cancelPublishing.Cancel(false);
                _counter.Dispose();
            }
            catch
            {
                //don't care about additional "ObjectDisposed" exceptions
            }
            finally
            {
                base.PostStop();
            }
        }

        #endregion

        protected override void OnReceive(object message)
        {
            if (message is GatherMetrics)
            {
                //publish latest counter value to all subscribers
                var metric = new Metric(_seriesName, _counter.NextValue());
                foreach(var sub in _subscriptions)
                    sub.Tell(metric);
            }
            else if (message is SubscribeCounter)
            {
                // add a subscription for this counter
                // (it's parent's job to filter by counter types)
                var sc = message as SubscribeCounter;
                _subscriptions.Add(sc.Subscriber);
            }
            else if (message is UnsubscribeCounter)
            {
                // remove a subscription from this counter
                var uc = message as UnsubscribeCounter;
                _subscriptions.Remove(uc.Subscriber);
            }
        }
    }
}

```

*Before we move onto the next step, let's talk about what you just did...*

#### Functional Programming for Reliability
Did you notice how, in the constructor of `PerformanceCounterActor`, we took a `Func<PerformanceCounter>` and NOT a `PerformanceCounter`? If you didn't, go back and look now. What gives?

This is a technique borrowed from functional programming. We use it whenever we have to inject an `IDisposable` object into the constructor of an actor. Why?

Well, we've got an actor that takes an `IDisposable` object as a parameter. So we're going to assume that this object will actually become `Disposed` at some point and will no longer be available.

What happens when the `PerformanceCounterActor` needs to restart?

**Every time the `PerformanceCounterActor` attempts to restart it will re-use its original constructor arguments, which includes reference types**. If we re-use the same reference to the now-`Disposed` `PerformanceCounter`, the actor will crash repeatedly. Until its parent decides to just kill it altogether.

A better technique is to pass a factory function that `PerformanceCounterActor` can use to get a fresh instance of its `PerformanceCounter`. That's why we use a `Func<PerformanceCounter>` in the constructor, which gets invoked during the actor's `PreStart()` lifecycle method.

```csharp
// create a new instance of the performance counter from factory that was passed in
_counter = _performanceCounterGenerator();
```

Because our `PerformanceCounter` is `IDisposable`, we also need to clean up the `PerformanceCounter` instance inside the `PostStop` lifecycle method of the actor.

We already know that we're going to get a fresh instance of that counter when the actor restarts, so we want to prevent resource leaks. This is how we do that:

```csharp
// Actors/PerformanceCounterActor.cs
// prevent resource leaks by disposing of our current PerformanceCounter
protected override void PostStop()
{
    try
    {
        // terminate the scheduled task
        _cancelPublishing.Cancel(false);
        _counter.Dispose();
    }
    catch
    {
        // we don't care about additional "ObjectDisposed" exceptions
    }
    finally
    {
        base.PostStop();
    }
}
```

#### Pub / Sub Made Easy
The `PerformanceCounterActor` has pub / sub built into it by way of its handlers for `SubscribeCounter` and `UnsubscribeCounter` messages inside its `OnReceive` method:

```csharp
// Actors/PerformanceCounterActor.cs
// ...
else if (message is SubscribeCounter)
{
    // add a subscription for this counter (it is up to the parent
    // to filter by counter types)
    var sc = message as SubscribeCounter;
    _subscriptions.Add(sc.Subscriber);
}
else if (message is UnsubscribeCounter)
{
    // remove a subscription from this counter
    var uc = message as UnsubscribeCounter;
    _subscriptions.Remove(uc.Subscriber);
}
```

In this lesson, `PerformanceCounterActor` only has one subscriber (`ChartingActor`, from inside `Main.cs`) but with a little re-architecting you could have these actors publishing their `PerformanceCounter` data to multiple recipients. Maybe that's a do-it-yourself exercise you can try later? ;)

#### How did we schedule publishing of `PerformanceCounter` data?
Inside the `PreStart` lifecycle method, we used the `Context` object to get access to the `Scheduler`, and then we had `PerformanceCounterActor` send itself a `GatherMetrics` method once every 250 milliseconds.

This causes `PerformanceCounterActor` to fetch data every 250ms and publish it to `ChartingActor`, giving us a live graph with a frame rate of 4 FPS.

```csharp
// Actors/PerformanceCounterActor.cs
protected override void PreStart()
{
    // create a new instance of the performance counter
    _counter = _performanceCounterGenerator();
    Context.System.Scheduler.ScheduleTellRepeatedly(TimeSpan.FromMilliseconds(250),
    TimeSpan.FromMilliseconds(250), Self,
        new GatherMetrics(), Self, _cancelPublishing);
}
```

Notice that inside the `PerformanceCounterActor`'s `PostStop` method, we invoke the `ICancelable` we created to cancel this recurring message:

```csharp
 // terminate the scheduled task
_cancelPublishing.Cancel();
```

We do this for the same reason we `Dispose` the `PerformanceCounter` - to eliminate resource leaks and to prevent the `IScheduler` from sending recurring messages to dead or restarted actors.

### Step 5 - Create the `PerformanceCounterCoordinatorActor`

The `PerformanceCounterCoordinatorActor` is the interface between the `ChartingActor` and all of the `PerformanceCounterActor` instances.

It has the following jobs:

* Lazily create all `PerformanceCounterActor` instances that are requested by the end-user;
* Provide the `PerformanceCounterActor` with a factory method (`Func<PerformanceCounter>`) for creating its counters;
* Manage all counter subscriptions for the `ChartingActor`; and
* Tell the `ChartingActor` how to render each of the individual counter metrics (which colors and plot types to use for each `Series` that corresponds with a `PerformanceCounter`.)

Sounds complicated, right? Well, you'll be surprised when you see how small the code footprint is!

Create a new file in the `/Actors` folder called `PerformanceCounterCoordinatorActor.cs` and type the following:

```csharp
// Actors/PerformanceCoordinatorActor.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms.DataVisualization.Charting;
using Akka.Actor;

namespace ChartApp.Actors
{
    /// <summary>
    /// Actor responsible for translating UI calls into ActorSystem messages
    /// </summary>
    public class PerformanceCounterCoordinatorActor : ReceiveActor
    {
        #region Message types

        /// <summary>
        /// Subscribe the <see cref="ChartingActor"/> to
        /// updates for <see cref="Counter"/>.
        /// </summary>
        public class Watch
        {
            public Watch(CounterType counter)
            {
                Counter = counter;
            }

            public CounterType Counter { get; private set; }
        }

        /// <summary>
        /// Unsubscribe the <see cref="ChartingActor"/> to
        /// updates for <see cref="Counter"/>
        /// </summary>
        public class Unwatch
        {
            public Unwatch(CounterType counter)
            {
                Counter = counter;
            }

            public CounterType Counter { get; private set; }
        }

        #endregion

        /// <summary>
        /// Methods for generating new instances of all <see cref="PerformanceCounter"/>s
        /// we want to monitor
        /// </summary>
        private static readonly Dictionary<CounterType, Func<PerformanceCounter>>
            CounterGenerators = new Dictionary<CounterType, Func<PerformanceCounter>>()
        {
            {CounterType.Cpu, () => new PerformanceCounter("Processor",
                "% Processor Time", "_Total", true)},
            {CounterType.Memory, () => new PerformanceCounter("Memory",
                "% Committed Bytes In Use", true)},
            {CounterType.Disk, () => new PerformanceCounter("LogicalDisk",
                "% Disk Time", "_Total", true)},
        };

        /// <summary>
        /// Methods for creating new <see cref="Series"/> with distinct colors and names
		/// corresponding to each <see cref="PerformanceCounter"/>
        /// </summary>
        private static readonly Dictionary<CounterType, Func<Series>> CounterSeries =
			new Dictionary<CounterType, Func<Series>>()
        {
            {CounterType.Cpu, () =>
			new Series(CounterType.Cpu.ToString()){
                 ChartType = SeriesChartType.SplineArea,
                 Color = Color.DarkGreen}},
            {CounterType.Memory, () =>
			new Series(CounterType.Memory.ToString()){
                ChartType = SeriesChartType.FastLine,
                Color = Color.MediumBlue}},
            {CounterType.Disk, () =>
			new Series(CounterType.Disk.ToString()){
                ChartType = SeriesChartType.SplineArea,
                Color = Color.DarkRed}},
        };

        private Dictionary<CounterType, IActorRef> _counterActors;

        private IActorRef _chartingActor;

        public PerformanceCounterCoordinatorActor(IActorRef chartingActor) :
			this(chartingActor, new Dictionary<CounterType, IActorRef>())
        {
        }

        public PerformanceCounterCoordinatorActor(IActorRef chartingActor,
            Dictionary<CounterType, IActorRef> counterActors)
        {
            _chartingActor = chartingActor;
            _counterActors = counterActors;

            Receive<Watch>(watch =>
            {
                if (!_counterActors.ContainsKey(watch.Counter))
                {
                    // create a child actor to monitor this counter if
                    // one doesn't exist already
                    var counterActor = Context.ActorOf(Props.Create(() =>
						new PerformanceCounterActor(watch.Counter.ToString(),
                                CounterGenerators[watch.Counter])));

                    // add this counter actor to our index
                    _counterActors[watch.Counter] = counterActor;
                }

                // register this series with the ChartingActor
                _chartingActor.Tell(new ChartingActor.AddSeries(
                    CounterSeries[watch.Counter]()));

                // tell the counter actor to begin publishing its
                // statistics to the _chartingActor
                _counterActors[watch.Counter].Tell(new SubscribeCounter(watch.Counter,
                    _chartingActor));
            });

            Receive<Unwatch>(unwatch =>
            {
                if (!_counterActors.ContainsKey(unwatch.Counter))
                {
                    return; // noop
                }

                // unsubscribe the ChartingActor from receiving any more updates
                _counterActors[unwatch.Counter].Tell(new UnsubscribeCounter(
                    unwatch.Counter, _chartingActor));

                // remove this series from the ChartingActor
                _chartingActor.Tell(new ChartingActor.RemoveSeries(
                    unwatch.Counter.ToString()));
            });
        }

    }
}
```
Okay, we're almost there. Just one more actor to go!

### Step 6 - Create the `ButtonToggleActor`
You didn't think we were going to let you just fire off those buttons you created in Step 2 without adding some actors to manage them, did you? ;)

In this step, we're going to add a new type of actor that will run on the UI thread just like the `ChartingActor`.

The job of the `ButtonToggleActor` is to turn click events on the `Button` it manages into messages for the `PerformanceCounterCoordinatorActor`. The `ButtonToggleActor` also makes sure that the visual state of the `Button` accurately reflects the state of the subscription managed by the `PerformanceCounterCoordinatorActor` (e.g. ON/OFF).

Okay, create a new file in the `/Actors` folder called `ButtonToggleActor.cs` and type the following:

```csharp
// Actors/ButtonToggleActor.cs

using System.Windows.Forms;
using Akka.Actor;

namespace ChartApp.Actors
{
    /// <summary>
    /// Actor responsible for managing button toggles
    /// </summary>
    public class ButtonToggleActor : UntypedActor
    {
        #region Message types

        /// <summary>
        /// Toggles this button on or off and sends an appropriate messages
        /// to the <see cref="PerformanceCounterCoordinatorActor"/>
        /// </summary>
        public class Toggle { }

        #endregion

        private readonly CounterType _myCounterType;
        private bool _isToggledOn;
        private readonly Button _myButton;
        private readonly IActorRef _coordinatorActor;

        public ButtonToggleActor(IActorRef coordinatorActor, Button myButton,
				CounterType myCounterType, bool isToggledOn = false)
        {
            _coordinatorActor = coordinatorActor;
            _myButton = myButton;
            _isToggledOn = isToggledOn;
            _myCounterType = myCounterType;
        }

        protected override void OnReceive(object message)
        {
            if (message is Toggle && _isToggledOn)
            {
                // toggle is currently on

                // stop watching this counter
                _coordinatorActor.Tell(
                    new PerformanceCounterCoordinatorActor.Unwatch(_myCounterType));

                FlipToggle();
            }
            else if (message is Toggle && !_isToggledOn)
            {
                // toggle is currently off

                // start watching this counter
                _coordinatorActor.Tell(
                    new PerformanceCounterCoordinatorActor.Watch(_myCounterType));

                FlipToggle();
            }
            else
            {
                Unhandled(message);
            }
        }

        private void FlipToggle()
        {
            // flip the toggle
            _isToggledOn = !_isToggledOn;

            // change the text of the button
            _myButton.Text = string.Format("{0} ({1})",
                _myCounterType.ToString().ToUpperInvariant(),
                _isToggledOn ? "ON" : "OFF");
        }
    }
}
```

### Step 7 - Update the `ChartingActor`
Home stretch! We're almost there.

We need to integrate all of the new message types we defined in Step 3 into the `ChartingActor`. We also need to make some changes to the way we render the `Chart` since we're going to be making *live updates* to it continuously.

To start, add this code at the very top of the `ChartingActor` class:

```csharp
// Actors/ChartingActor.cs

/// <summary>
/// Maximum number of points we will allow in a series
/// </summary>
public const int MaxPoints = 250;

/// <summary>
/// Incrementing counter we use to plot along the X-axis
/// </summary>
private int xPosCounter = 0;
```

Next, add a new message type that the `ChartingActor` is going to use. Add this inside the `Messages` region of `Actors/ChartingActor.cs`:

```csharp
// Actors/ChartingActor.cs - inside the Messages region

/// <summary>
/// Remove an existing <see cref="Series"/> from the chart
/// </summary>
public class RemoveSeries
{
    public RemoveSeries(string seriesName)
    {
        SeriesName = seriesName;
    }

    public string SeriesName { get; private set; }
}
```

Add the following method to the bottom of the `ChartingActor` class (don't worry about the specifics, it's adding UI management code that isn't directly related to actors):

```csharp
// Actors/ChartingActor.cs

private void SetChartBoundaries()
{
    double maxAxisX, maxAxisY, minAxisX, minAxisY = 0.0d;
    var allPoints = _seriesIndex.Values.SelectMany(series => series.Points).ToList();
    var yValues = allPoints.SelectMany(point => point.YValues).ToList();
    maxAxisX = xPosCounter;
    minAxisX = xPosCounter - MaxPoints;
    maxAxisY = yValues.Count > 0 ? Math.Ceiling(yValues.Max()) : 1.0d;
    minAxisY = yValues.Count > 0 ? Math.Floor(yValues.Min()) : 0.0d;
    if (allPoints.Count > 2)
    {
        var area = _chart.ChartAreas[0];
        area.AxisX.Minimum = minAxisX;
        area.AxisX.Maximum = maxAxisX;
        area.AxisY.Minimum = minAxisY;
        area.AxisY.Maximum = maxAxisY;
    }
}
```

> **NOTE**: the `SetChartBoundaries()` method is used to make sure that the boundary area of our chart gets updated as we remove old points from the beginning of the chart as time elapses.

Next, we're going to redefine all of our message handlers to use the new `SetChartBoundaries()` method.

**Delete everything inside the previous `Individual Message Type Handlers` region**, and then **replace it with the following**:

```csharp
// Actors/ChartingActor.cs - inside the Individual Message Type Handlers region
private void HandleInitialize(InitializeChart ic)
{
    if (ic.InitialSeries != null)
    {
        // swap the two series out
        _seriesIndex = ic.InitialSeries;
    }

    // delete any existing series
    _chart.Series.Clear();

    // set the axes up
    var area = _chart.ChartAreas[0];
    area.AxisX.IntervalType = DateTimeIntervalType.Number;
    area.AxisY.IntervalType = DateTimeIntervalType.Number;

    SetChartBoundaries();

    // attempt to render the initial chart
    if (_seriesIndex.Any())
    {
        foreach (var series in _seriesIndex)
        {
            // force both the chart and the internal index to use the same names
            series.Value.Name = series.Key;
            _chart.Series.Add(series.Value);
        }
    }

    SetChartBoundaries();
}

private void HandleAddSeries(AddSeries series)
{
    if(!string.IsNullOrEmpty(series.Series.Name) &&
        !_seriesIndex.ContainsKey(series.Series.Name))
    {
        _seriesIndex.Add(series.Series.Name, series.Series);
        _chart.Series.Add(series.Series);
        SetChartBoundaries();
    }
}

private void HandleRemoveSeries(RemoveSeries series)
{
    if (!string.IsNullOrEmpty(series.SeriesName) &&
        _seriesIndex.ContainsKey(series.SeriesName))
    {
        var seriesToRemove = _seriesIndex[series.SeriesName];
        _seriesIndex.Remove(series.SeriesName);
        _chart.Series.Remove(seriesToRemove);
        SetChartBoundaries();
    }
}

private void HandleMetrics(Metric metric)
{
    if (!string.IsNullOrEmpty(metric.Series) &&
        _seriesIndex.ContainsKey(metric.Series))
    {
        var series = _seriesIndex[metric.Series];
        series.Points.AddXY(xPosCounter++, metric.CounterValue);
        while(series.Points.Count > MaxPoints) series.Points.RemoveAt(0);
        SetChartBoundaries();
    }
}
```

And finally, add these `Receive<T>` handlers to the constructor for `ChartingActor`:

```csharp
// Actors/ChartingActor.cs - add these below the original Receive<T>
// handlers in the ctor
Receive<RemoveSeries>(removeSeries => HandleRemoveSeries(removeSeries));
Receive<Metric>(metric => HandleMetrics(metric));
```

### Step 8 - Replace the `Main_Load` Handler in `Main.cs`
Now that we have real data we want to plot in real-time, we need to replace the original `Main_Load` event handler, which supplied fake data to our `ChartActor` with a real one that sets us up for live charting.

Add the following declarations to the top of the `Main` class inside `Main.cs`:

```csharp
// Main.cs - at top of Main class
private IActorRef _coordinatorActor;
private Dictionary<CounterType, IActorRef> _toggleActors = new Dictionary<CounterType,
    IActorRef>();
```

Then, replace the `Main_Load` event handler in the `Init` region so that it matches this:

```csharp
// Main.cs - replace Main_Load event handler in the Init region
private void Main_Load(object sender, EventArgs e)
{
    _chartActor = Program.ChartActors.ActorOf(Props.Create(() =>
        new ChartingActor(sysChart)), "charting");
    _chartActor.Tell(new ChartingActor.InitializeChart(null)); //no initial series

    _coordinatorActor = Program.ChartActors.ActorOf(Props.Create(() =>
			new PerformanceCounterCoordinatorActor(_chartActor)), "counters");

    // CPU button toggle actor
    _toggleActors[CounterType.Cpu] = Program.ChartActors.ActorOf(
        Props.Create(() => new ButtonToggleActor(_coordinatorActor, btnCpu,
        CounterType.Cpu, false))
        .WithDispatcher("akka.actor.synchronized-dispatcher"));

    // MEMORY button toggle actor
    _toggleActors[CounterType.Memory] = Program.ChartActors.ActorOf(
       Props.Create(() => new ButtonToggleActor(_coordinatorActor, btnMemory,
        CounterType.Memory, false))
        .WithDispatcher("akka.actor.synchronized-dispatcher"));

    // DISK button toggle actor
    _toggleActors[CounterType.Disk] = Program.ChartActors.ActorOf(
       Props.Create(() => new ButtonToggleActor(_coordinatorActor, btnDisk,
       CounterType.Disk, false))
       .WithDispatcher("akka.actor.synchronized-dispatcher"));

    // Set the CPU toggle to ON so we start getting some data
    _toggleActors[CounterType.Cpu].Tell(new ButtonToggleActor.Toggle());
}
```

#### Wait a minute, what's this `WithDispatcher` nonsense?!
`Props` has a built-in fluent interface which allows you to configure your actor deployments programmatically, and in this instance we decided to use the `Props.WithDispatcher` method to guarantee that each of the `ButtonToggleActor` instances run on the UI thread.

As we saw in Lesson 2.1, you can also configure the `Dispatcher` for an actor via the HOCON config. So if an actor has a `Dispatcher` set in HOCON, *and* one declared programmatically via the `Props` fluent interface, which wins?

*In case of a conflict, `Config` wins and `Props` loses .* Any conflicting settings declared by the `Props` fluent interface will always be overriden by what was declared in configuration.

### Step 9 - Have Button Handlers Send `Toggle` Messages to Corresponding `ButtonToggleActor`
**THE LAST STEP.** We promise :) Thanks for hanging in there.

Finally, we need to wire up the button handlers we created in Step 3.

Wire up your button handlers in `Main.cs`. They should look like this:

```csharp
// Main.cs - wiring up the button handlers added in step 3
private void btnCpu_Click(object sender, EventArgs e)
{
    _toggleActors[CounterType.Cpu].Tell(new ButtonToggleActor.Toggle());
}

private void btnMemory_Click(object sender, EventArgs e)
{
    _toggleActors[CounterType.Memory].Tell(new ButtonToggleActor.Toggle());
}

private void btnDisk_Click(object sender, EventArgs e)
{
    _toggleActors[CounterType.Disk].Tell(new ButtonToggleActor.Toggle());
}
```

### Once you're done
Build and run `SystemCharting.sln` and you should see the following:

![Successful Lesson 3 Output (animated gif)](images/dothis-successful-run3.gif)
> NOTE: for those of you following along in the eBook, this is an animated GIF of the live charting function working. [Click here to see it](https://github.com/petabridge/akka-bootcamp/raw/master/src/Unit-2/lesson3/images/dothis-successful-run3.gif).

Compare your code to the code in the [/Completed/ folder](Completed/) to compare your final output to what the instructors produced.

## Great job!
*Wow*. That was *a lot* of code. Great job and thanks for sticking it out! We now have a fully functioning Resource Monitor app, implemented with actors.

Every other lesson builds on this one, so before continuing, please make sure your code matches the output of the [/Completed/ folder](Completed/).

At this point. you should understand how the `Scheduler` works and how you can use it alongside patterns like Pub-sub to make very reactive systems with actors that have a comparatively small code footprint.

Here is a high-level overview of our working system at this point:

![Akka.NET Bootcamp Unit 2 System Overview](images/system_overview_2_3.png)

**Let's move onto [Lesson 4 - Switching Actor Behavior at Run-time with `Become` and `Unbecome`](../lesson4/README.md).**

## Any questions?

Come ask any questions you have, big or small, [in this ongoing Bootcamp chat with the Petabridge & Akka.NET teams](https://gitter.im/petabridge/akka-bootcamp).

### Problems with the code?
If there is a problem with the code running, or something else that needs to be fixed in this lesson, please [create an issue](https://github.com/petabridge/akka-bootcamp/issues) and we'll get right on it. This will benefit everyone going through Bootcamp.

repository: petabridge/akka-bootcamp

repo_name: petabridge/akka-bootcamp


text:
# Retry

The retry plugin allows you to configure retry rules for your proxy. This enables you to be more resilient for any network or any other kind of failure.

## Configuration

The plain retry config:

```json
{
    "name" : "retry",
    "enabled" : false,
    "config" : {
        "attempts" : 3,
        "backoff": "1s"
    }
}
```

Configuration | Description
:---|:---|
| attempts      | Number of attempts |
| backoff       | Time that we should wait to retry. This must be given in the [ParseDuration](https://golang.org/pkg/time/#ParseDuration) format. Defaults to `1s` |
| predicate     | The rule that we will check to define if the request was successful or not. You have access to `statusCode` and all the `request` object. Defaults to `statusCode == 0 || statusCode >= 500` |

license: MIT

repository: motiv-labs/janus

branch_name: refs/heads/master

extension: md

gha_language: Go

gha_license_id: MIT

license_type: permissive

repo_name: motiv-labs/janus


text:
# Study Buddies

### A resource for quickly making study group reservations at local hot spots.

### By Melisa Lee, Mindy Jones, and Christopher Matian

# Getting Started

The structure of our application is a **React + Express** full-stack framework. React will handle the frontend portion of our code and Express will be managing the backend interactions.

If you've already cloned the repo then you can skip this step. Otherwise, go ahead and clone the repo somewhere on your machine:

`git clone https://github.com/cmatian/study-buddies.git`

Once you've done that, `cd` into the `study-buddies` directory and you should see the following structure in your file explorer (or issue `ls` on the command line):

```
/study-buddies
    /api
    /client
    /database
    .gitignore
    LICENSE
    README.md
```

The screenshots folder is used for the readme screenshots, so avoid putting anything in there that's not related to the readme.

The `/api` folder contains the code for the Express backend.

The `/client` folder contains the code for the React frontend.

## Local setup

### Set up gcloud

- Follow https://cloud.google.com/sdk/docs/#install_the_latest_cloud_sdk_version
- Run the following:

```
gcloud init
gcloud auth login
gcloud config set project study-buddies-266004
```

### Set up MySQL

```
wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O cloud_sql_proxy
chmod +x cloud_sql_proxy
export SB_MYSQL_PW=(password here)
```

### Install Node dependencies

Before starting Express or React, each of them needs dependencies installed. To prepare the Express backend, `cd` into the `/api` directory and issue `npm install`. This will initialize all of the node module dependencies for Express. To prepare the React frontend, `cd` into the `/client` directory and issue the `npm install` command to get all of your React dependencies in order.

## Running locally

### Run Cloud SQL Proxy

Run the Cloud SQL proxy (in its own terminal window):

```
./cloud_sql_proxy -instances=study-buddies-266004:us-west1:study-buddies-db=tcp:3306
```

### Running the Node Components individually

Express and React can be started individually, or together with a single handy command (see the next section for this).

#### Fire up Express

Issue `npm start` and the server will start up. The server will be hosted at `http://localhost:5000`. If you can see the Study Buddies title then that means you're all set.

#### Fire up React

Start up React by issuing `npm start`. Your React application will be served at `http://localhost:3000`.

#### Putting it all together

In order for this to all run seamlessly, you need to have **both** the React client and the Express api are running at the same time. Do the above steps each in different terminal windows and you should be good to go.

If you're mostly working on the frontend and don't need any immediate requests to the server or database, then you can probably work without starting up Express (and vice versa). Do note that if your frontend has any requests to the backend and the server isn't running, then the application will experience run time errors.

### Running the Node components with one command

To start both together, `cd` into the `/client` cirectory and issue the `npm run dev` command. This will first start Express, then start React.

# Building the docker image and deploying

## Prerequisites

- Install docker: https://docs.docker.com/install/
- Set up "docker credential helpers" as described in step 7 of https://cloud.google.com/run/docs/setup

## Building and deploying

```
cd study-buddies/
docker build -t gcr.io/study-buddies-266004/study-buddies-img .
docker push gcr.io/study-buddies-266004/study-buddies-img:latest
gcloud run deploy study-buddies-img --image gcr.io/study-buddies-266004/study-buddies-img --platform managed --region us-west1
```

# Making Changes

I'm hoping that we can all use [Git Flow](https://nvie.com/posts/a-successful-git-branching-model/) during development.

Since we are working on this project simultaneously, we don't want to be submitting changes _directly_ to the `devel` branch.

You should be working off of a feature branch and pushing that. When the feature is complete, you will then submit a PR (everyone has privileges to merge PRs) and have it pulled (merged) into the `devel` branch.

Here is a basic flow to follow:

1. First, create a new branch off of the `devel` branch: `git checkout -b your-branch-name`.

2. Make changes where you want and then issue `git status` to see a list of all the changes you've made so far.

3. When you're ready to make a commit/push issue `git add .` to stage (add) all of your changes.

4.  Try to use meaningful commit messages describing what you changed.

5. Finally, you can issue `git push origin your-branch-name`. This will push your changes to the repository where you can either continue work (and repeat the steps above) or produce a pull (merge) request on Github.

## Config
Paste config folder into client/src/config

repository: cmatian/study-buddies

branch_name: refs/heads/devel

gha_language: JavaScript

repo_name: cmatian/study-buddies


text:
# Changelog

All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.

## [1.3.0](https://github.com/Spyna/react-svg-radar-chart/compare/v1.2.0...v1.3.0) (2021-06-05)

### Features

* add chart rotation ([bbd3806](https://github.com/Spyna/react-svg-radar-chart/commit/bbd3806775391c77fc9475e71f2ad583aa420100))

# Changelog

repository: Spyna/react-svg-radar-chart

repo_name: Spyna/react-svg-radar-chart


text:
# node-mailsender

> Send email from NodeJS using Nodemailer

## Prerequisites

The project has dependencies that require Node 6.9.0 or higher, together
with NPM 3 or higher.

**Table of contents:**

1. [Installation](#installation)
1. [Usage](#usage)
1. [Environment variables](#environment-variables)
1. [Contributing](#contributing)
1. [License](#license)

## Installation

Clone this repo to your local machine with:

```sh
$ git clone https://github.com/andreasonny83/node-mailsender.git
```

Then, cd inside the project folder with:

```sh
cd node-mailsender
```

### Install the node dependencies

```sh
$ npm install
# Or Yarn for a faster installation
$ yarn install
```

## Usage

Run `npm start` for a dev server.
Navigate to `http://localhost:8009/status` to verify that
your server is up and running correctly.

The app will automatically reload if you change any of the source files.

## Environment variables

Name  | Default value | Description
--- | --- | ---
PORT | 8009 | The port where the server is listening
DEBUG | false | Enable extra debug messages
CLIENT_URLS | '' | List all the hosts from where whitelist the coming requests. They need to be separated by `;` Eg. 'https://my.website.com;http://another.website.io'

### Nodemailer configuration

Nodemailer will be set using the following environment variables

Name  | Default value | Description
--- | --- | ---
HOST_NAME | undefined | Your email host provider
PORT_NUMBER | undefined | Your email host provider port number
USER_NAME | undefined | Your email address or username
PASSWORD | undefined | Your email password
EMAIL_SENDER_ADDRESS | '' | The email address that will be displayed in the client's emails `from` field
SECURE | false | Use secure SSL
SECURE_CONNECTION | false | Use secure connection
REJECT_UNAUTHORIZED | null | Reject anouthorized requests
CIPHERS | null | ciphers must be required by your host service

## Send emails

The porpouse of this app iss sending emails. So, in order to do that, you must send a POST request to the `/send` endpoint containing the following informations in the request's `body`:

Name | Default value | Description
--- | --- | ---
from | null | The display name for the sender, the real email address will remail the one set using the `EMAIL_SENDER_ADDRESS` coming from the Environment variables.
to | null | The destinator of your email
subject | null |  Set the email's subject
text | null | If set, this will be used for displaying a text version of the email, in case the client doesn't support the HTML5 format
html | null | This will contain the HTML template you want to send in your email

## Contributing

We really appreciate your collaborations and feedbacks!

1.  Fork and clone it
1.  Install dependencies: `npm install`
1.  Create a feature branch: `git checkout -b new-feature`
1.    Push to the remote branch: `git push origin new-feature`
1.  Create a new [Pull Request](https://github.com/andreasonny83/node-mailsender/pull/new/master)

## License

MIT © [Andrea Sonny](https://andreasonny.mit-license.org/@2017)


text:
---
layout: default
---

# 1997-08-27 - How tO MutAte anD TaKE OVer tHe WOrld

## Header Data

From: "luciana luciana"<EMAIL_ADDRESS>To<EMAIL_ADDRESS>Message Hash: cad3b6a36d40b777d143f67168bd74dd68370d019637d3971c8da86d3a55d461

Message ID<EMAIL_ADDRESS>Reply To: _N/A_

UTC Datetime: 1997-08-27 04:51:42 UTC

Raw Date: Wed, 27 Aug 1997 12:51:42 +0800

## Raw message

```
{% raw  %}From: "luciana luciana"<EMAIL_ADDRESS>Date: Wed, 27 Aug 1997 12:51:42 +0800
To<EMAIL_ADDRESS>Subject: How tO MutAte anD TaKE OVer tHe WOrld
Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

I'm very interested on that.
could u let me know anything else?

______________________________________________________
Get Your Private, Free Email at http://www.hotmail.com

{% endraw %}
```

## Thread

+ Return to [August 1997](/archive/1997/08)

+ Return to "[Alan <alan@ctrl-alt-del.com>](/authors/alan_alan_at_ctrlaltdel_com_)"
+ Return to "["luciana luciana" <azwsxq@hotmail.com>](/authors/luciana_luciana_azwsxq_at_hotmail_com_)"

+ 1997-08-27 (Wed, 27 Aug 1997 12:51:42 +0800) - How tO MutAte anD TaKE OVer tHe WOrld - _"luciana luciana"<EMAIL_ADDRESS>  + 1997-08-27 (Wed, 27 Aug 1997 23:35:55 +0800) - [Re: How tO MutAte anD TaKE OVer tHe WOrld](/archive/1997/08/a883cec5870527e89b9add89754fa80fb3fe4f22eebce57e56e13852b10bc784) - _Alan<EMAIL_ADDRESS>


text:
	Next Level Week 2.0 🚀

  Project   |
  Technologies   |
  How to use   |
  How to contribute   |
  License

## 💻 Project

Proffy is an app created to support connections between teachers and students.

This application offers to teachers the opportunity to register classes, adding information such as like subject, cost per hour and time available to teach.
Students can easily search for classes.

Based on national day of education professionals.

## :rocket: Technologies

This project was developed with the following technologies:

- [Node.js][nodejs]
- [TypeScript][typescript]
- [React][reactjs]
- [React Native][rn]
- [Expo][expo]

## :information_source: How To Use

To clone and run this application, you'll need [Git](https://git-scm.com), [Node.js][nodejs] + [yarn][yarn] installed on your computer.

From your command line:

### Install API

```bash
# Clone this repository
$ git clone https://github.com/YuiMatsunaga/NLW-02.git

# Go into the repository
$ cd NLW-02/server

# Install dependencies
$ yarn install

# Run Migrates
$ yarn knex:migrate

# Start server
$ yarn start

# running on port 3333
```

### Install Front-end

```bash
# Go into the repository
$ cd NLW-02/web

# Install dependencies
$ yarn install

# Run
$ yarn start

# running on port 3000
```

### Install Mobile

```bash
# Go into the repository
$ cd NLW-02/mobile

# Install dependencies
$ yarn install

# Run
$ yarn start

# Expo will open, just scan the qrcode on terminal or expo page

# If some problem with fonts, execute:
$ expo install expo-font @expo-google-fonts/archivo @expo-google-fonts/poppins
```

## 🤔 How to contribute

- Make a fork;
- Create a branck with your feature: `git checkout -b my-feature`;
- Commit changes: `git commit -m 'feat: My new feature'`;
- Make a push to your branch: `git push origin my-feature`.

After merging your receipt request to done, you can delete a branch from yours.

## :memo: License

This project is under the MIT license. See the [LICENSE](https://github.com/YuiMatsunaga/NLW-02/blob/master/LICENSE) for details.

---

Made with 💜 by Christyan David

[nodejs]: https://nodejs.org/
[typescript]: https://www.typescriptlang.org/
[expo]: https://expo.io/
[reactjs]: https://reactjs.org
[rn]: https://facebook.github.io/react-native/
[yarn]: https://classic.yarnpkg.com/en/
[vs]: https://code.visualstudio.com/
[vceslint]: https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint
[prettier]: https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode


text:
Installation
============
### Prerequisites
You need to have Ruby installed.
Verify your installation by running ruby -v in a terminal - it should print "ruby 1.9.3" (or higher).

You need to have DevKit installed.

You can get Ruby and DevKit from [RubyInstaller.org](http://rubyinstaller.org/)

### Installation

Install `selenium-cucumber` gem by running

- `gem install selenium-cucumber`

gha_language: HTML

gha_license_id: NOASSERTION


text:
---
template: main.html
---

# Setup for Tutorials
Setup common components that are required in Iter8 tutorials.

## Local Kubernetes cluster
Use a managed K8s cluster or a local K8s cluster for running Iter8 tutorials. You can setup the latter using [Kind](https://kind.sigs.k8s.io/docs/user/quick-start/), [Minikube](https://minikube.sigs.k8s.io/docs/), or [CodeReady Containers](https://access.redhat.com/documentation/en-us/red_hat_codeready_containers/1.0/html/getting_started_guide/index) as follows.

=== "Kind"

    ```shell
    kind create cluster --wait 5m
    kubectl cluster-info --context kind-kind
    ```

=== "Minikube"

    ```shell
    minikube start
    ```

=== "CodeReady Containers"

    ```shell
    crc start
    ```

??? info "Setting CPU and memory resources for your local K8s cluster"
    Iter8 tutorials in certain K8s environments, especially those involving Istio, require additional CPU and memory resources. You can set this as follows.

    === "Kind"
        A Kind cluster inherits its CPU and memory resources of its host. If you are using Docker Desktop, you can set its resources as follows.

        ![Resources](../images/ddresourcepreferences.png)

    === "Minikube"
        Set CPU and memory resources while starting Minikube as follows.

        ```shell
        minikube start --cpus 8 --memory 12288
        ```

    === "CodeReady Containers"
        Set CPU and memory resources while starting CodeReady Containers as follows.

        ```
        crc start --cpus 8 --memory 12288
        ```

        You can also change the CPU and memory resources in settings.

        ![Resources](../images/crcresourcepreferences.png)

## Iter8 GitHub repo
Clone the Iter8 GitHub repo and set the `ITER8` environment variable as follows:

```shell
git clone https://github.com/iter8-tools/iter8.git
export ITER8=./iter8
```

## Iter8 Helm repo
Iter8 Helm repo contains charts that support Iter8's Helm-based tutorials. Get the repo as follows:

```shell
helm repo add iter8 https://iter8-tools.github.io/iter8/ --force-update
```


text:
# README

Rails app to exercise the concepts of the course "testing with RSpec", from CodeSchool.

* Ruby version:
2.0+

* Configuration:
```
bundle install
```

* How to run the test suite
```
bundle exec rspec
```


text:
About
-----

This repository contains some basic data structures for Java and is for didactic purposes only.

Included are abstract data types for:

* Stacks
* Queues
* Sequences
* Lookup Tables

And implementations of:

* Contiguous Stacks, Queues and Sequences
* Linked List Stacks, Queues and Sequences
* Linear and Binary Search Lookup Tables
* Binary Search Trees

repository: taheris/java-data-structures

repo_name: taheris/java-data-structures


text:
---
title: dotMemory
subtitle: The .NET Memory Profiler.
logo: ./logo.png
website: https://www.jetbrains.com/dotmemory/
---

dotMemory allows you to analyze memory usage in a variety of .NET and .NET Core applications: desktop applications, Windows services, ASP.NET web applications, IIS, IIS Express, arbitrary .NET processes, and more.

## See Also
- [dotMemory home page](https://www.jetbrains.com/dotmemory/)
- [dotMemory documentation](https://www.jetbrains.com/dotmemory/documentation/)

branch_name: refs/heads/main


text:
# async-change-tracker

[![Crates.io](https://img.shields.io/crates/v/async-change-tracker.svg)](https://crates.io/crates/async-change-tracker)
[![Documentation](https://docs.rs/async-change-tracker/badge.svg)](https://docs.rs/async-change-tracker/)
[![Crate License](https://img.shields.io/crates/l/async-change-tracker.svg)](https://crates.io/crates/async-change-tracker)
[![Dependency status](https://deps.rs/repo/github/astraw/async-change-tracker/status.svg)](https://deps.rs/repo/github/astraw/async-change-tracker)
[![build](https://github.com/astraw/async-change-tracker/workflows/build/badge.svg?branch=main)](https://github.com/astraw/async-change-tracker/actions?query=branch%3Amain)

Reactive change notifications using futures.

The `ChangeTracker<T>` type wraps an owned value `T`. Changes to `T` are
done within a function or closure implementing `FnOnce(&mut T)`. When this
returns, any changes are sent to listeners using a `futures::Stream`.

In slightly more detail, create a `ChangeTracker<T>` with
[`ChangeTracker::new(value: T)`](struct.ChangeTracker.html#method.new). This
will take ownership of the value of type `T`. You can then create a
`futures::Stream` (with
[`get_changes()`](struct.ChangeTracker.html#method.get_changes)) that emits
a tuple `(old_value, new_value)` of type `(T, T)` upon every change to the
owned value. The value can be changed with the
[`modify()`](struct.ChangeTracker.html#method.modify) method of
`ChangeTracker` and read using the `as_ref()` method from the `AsRef` trait.

### Example

In this example, the functionality of `ChangeTracker` is shown.

```rust
use futures::stream::StreamExt;

// Wrap an integer `with ChangeTracker`
let mut change_tracker = async_change_tracker::ChangeTracker::new( 123 );

// Create an receiver that fires when the value changes. The channel size
// is 1, meaning at most one change can be buffered before backpressure
// is applied.
let rx = change_tracker.get_changes(1);

// In this example take a single change and check that the old and new value
// are correct.
let rx_printer = rx.take(1).for_each(|(old_value, new_value)| {
    assert_eq!( old_value, 123);
    assert_eq!( new_value, 124);
    futures::future::ready(())
});

// Now, check and then change the value.
change_tracker.modify(|mut_ref_value| {
    assert_eq!(*mut_ref_value, 123);
    *mut_ref_value += 1;
});

// Wait until the stream is done. In this example, the stream ends due to
// the use of `.take(1)` prior to `for_each` above. In normal usage,
// typically the stream would finish for a different reason.
futures::executor::block_on(rx_printer);

// Finally, check that the final value is as expected.
assert!(*change_tracker.as_ref() == 124);
```

### Testing

To test, you need the `thread-pool` feature for the `futures` create:

```
cargo test --features "futures/thread-pool"
```

License: MIT/Apache-2.0

repository: astraw/async-change-tracker

gha_language: Rust

repo_name: astraw/async-change-tracker


text:
Installation
============

[doc_toc]

Composer
--------

You can install this plugin into your CakePHP application using composer.

    "require": {
        "cakemanager/cakephp-posttypes":  "~1.0"
    }

Each time you run php composer.phar update you will receive the latest stable releases when using the default version constraint ~1.0. Only bugfix and minor version releases of 1.x will be used when updating.

If you want to keep current with the latest unreleased changes in the PostTypes Plugin you can add the change your application’s composer.json:

    "require": {
        "cakemanager/cakephp-posttypes":  "dev-master"
    }

Be aware that is not recommended, as your application can break when next major version is being released. Additionally composer does not cache development branches, so it slows down consecutive composer installs/updates.

Configuration
-------------

You will need to add the following line to your application's `config/bootstrap.php` file:

        Plugin::load('PostTypes', ['bootstrap' => true, 'routes' => true]);

Now you are ready to add your PostTypes. Lets load the `PostTypesComponent` into your `AppController`:

        public function initialize()
        {
            // code

            $this->loadComponent('PostTypes.PostTypes');

            // code
        }

repository: cakemanager/posttypes-docs

repo_name: cakemanager/posttypes-docs


text:
# Shelf Rate Limiter
It limits the number of requests made to your backend in a fixed time frame.

## Usage

```dart
  final memoryStorage = MemStorage();
    final rateLimiter = ShelfRateLimiter(
      storage: memoryStorage, duration: Duration(seconds: 60), maxRequests: 10);
```
The default values for duration is 60 seconds and maxRequests is 5.

Add it as a middleware inside the handler or any route.
```dart
  var handler = const Pipeline()
      .addMiddleware(logRequests())
      .addMiddleware(rateLimiter.rateLimiter())
      .addHandler(_echoRequest);

```


text:
---
layout: page
title: Lean Prover Zulip Chat Archive
permalink: archive/116395maths/01990hornerpolynomials.html
---

## [maths](index.html)
### [horner polynomials](01990hornerpolynomials.html)

#### [Chris Hughes (Nov 29 2018 at 20:10)](https://leanprover.zulipchat.com/#narrow/stream/116395-maths/topic/horner%20polynomials/near/148810007):
I remember @**Johannes Hölzl**  saying something in Orsay about having an interface for polynomials in horner form? What exactly did he mean by this? Is something like this worth having, and is it worth proving the equation lemmas for this, and proving it in a semiring? It does make some proofs easier.
```lean
@[elab_as_eliminator] def rec_on_horner {α : Type*}
  [nonzero_comm_ring α] [decidable_eq α]
  {M : polynomial α → Sort*} : Π (p : polynomial α),
  M 0 →
  (Π p a, coeff p 0 = 0 → a ≠ 0 → M p → M (p + C a)) →
  (Π p, p ≠ 0 → M p → M (p * X)) →
  M p
| p := λ M0 MC MX,
if hp : p = 0 then eq.rec_on hp.symm M0
else
have wf : degree (p /ₘ X) < degree p,
  from degree_div_by_monic_lt _ monic_X hp (by rw degree_X; exact dec_trivial),
by rw [← mod_by_monic_add_div p monic_X, mod_by_monic_X, ← coeff_zero_eq_eval_zero,
  add_comm, mul_comm] at *;
  exact
  if hcp0 : coeff p 0 = 0
  then by rw [hcp0, C_0, add_zero];
    exact MX _ (λ h : p /ₘ X = 0, by simpa [h, hcp0] using hp)
      (rec_on_horner _ M0 MC MX)
  else MC _ _ (coeff_mul_X_zero _) hcp0 (if hpX0 : p /ₘ X = 0
    then show M (p /ₘ X * X), by rw [hpX0, zero_mul]; exact M0
    else MX (p /ₘ X) hpX0 (rec_on_horner _ M0 MC MX))
using_well_founded {dec_tac := tactic.assumption}
```

#### [Johannes Hölzl (Nov 30 2018 at 10:01)](https://leanprover.zulipchat.com/#narrow/stream/116395-maths/topic/horner%20polynomials/near/148849553):
My idea was a little bit different. Instead of using `p + C a` and assuming `coeff p 0 = 0` we only use
```lean
def horner p a := p * X + C a
```
My hope is that some proofs are easier using this construction, especially proofs about `coeff` `degree` etc.
And it would not be limited to a recursor, but would also include a lot of rewrite rules for `horner`.

I also tried to define polynomials using the horner scheme, i.e. `subtype` on `list` with an additional non-leading zero assumption.


text:
Files downloaded from:

https://github.com/golang/go/tree/master/misc/wasm

* go_js_wasm_exec
* wasm_exec.html
* wasm_exec.js

wasm_exec.html has also been split into two files:

* wasm_main.js
* index.html

Thus these entry points are equivalent:

* http://localhost:8080/console/wasm_exec.html
* http://localhost:8080/console/

repository: udhos/hellowasm

repo_name: udhos/hellowasm


text:
---
layout: post
title: "OsAP1"
description: ""
category: genes
tags:
---

* **Information**
    + Symbol: OsAP1
    + MSU: [LOC_Os05g04630](http://rice.plantbiology.msu.edu/cgi-bin/ORF_infopage.cgi?orf=LOC_Os05g04630)
    + RAPdb: [Os05g0137400](http://rapdb.dna.affrc.go.jp/viewer/gbrowse_details/irgsp1?name=Os05g0137400)

* **Publication**
    + [Biochar but not earthworms enhances rice growth through increased protein turnover](http://www.ncbi.nlm.nih.gov/pubmed?term=Biochar but not earthworms enhances rice growth through increased protein turnover%5BTitle%5D), 2012, Soil Biology and Biochemistry.

* **Genbank accession number**
    + [D12777](http://www.ncbi.nlm.nih.gov/nuccore/D12777)

* **Key message**

* **Connection**

[//]: # * **Key figures**


text:
# Fusion360 Scripts

This repo contains a number of Fusion360 scripts.  More info about each script is given in the README.md inside each folder.

## [Design Version Timelapse](Design-Version-Timelapse/)

Turn your Fusion360 version history (i.e. all your previous saves) into a timelapse animation.

## [Design History Animation](Design-History-Animation/)

Turn your Fusion360 design history timeline into an animation.

## Installation

Download this repository as ZIP and unzip the folder (put this folder in a place where you won't delete it later):

![Download button](docs/download.png)

In the *Design* workspace, go to the *Tools* tab and select *Add Ins > Scripts and Add-Ins...*:

![Tools Menu](docs/tools.png)

Click the green plus sign next to My Scripts:

![Add Script](docs/addscript.png)

Then Select the folder called e.g. `Design-History-Animation` inside `Fusion360-Scripts/Design-History-Animation`:

![Select Folder](docs/selectfolder.png)

You should now see it added to your scripts.  To Run the script, select it and press *Run*:

![Script Added](docs/scriptadded.png)


text:
### Deep Actor-Critic Agent
Contains an easy-to-follow, simple-to-use Actor-Critic architecture based reinforcement learning agent implementations that uses a deep neural
network to represent the policy and value function. Following are the agent algorithms discussed and implemented in this chapter:
  - Deep n-step Advantage Actor Critic Agent
  - Asynchronous Deep n-step Advantage Actor Critic Agent
  - Batched Deep n-step Advantaged Actor Critic Agent

### Code Structure
[To be updated]

### Pre-trained Agent brains
Trained agents brains/models and instructions to test them can be found in the [trained_models](trained_models) directory.

#### (optional) Requirements:
If you use the`CarRacing` environment to train or test the agent, you will need the following additional
python packages:
  - Python 3.5 (because Box2D from the author's official anaconda channel (kne) has binaries built only for py upto 3.5)
  - Box2D. Can be installed using:
  `conda install -c kne pybox2d`


text:
# CodeCade

An open source arcade game website, built my developers from the Code Newbie and 100 Days of Code communities. We are creating several simple games that anyone can play either on their computers or mobile devices.

## Getting Started

If you would like to get involved in this project please take a look at the documentation below:

https://arcade-docs.rahatcodes.com/

### Prerequisites

For V1: Basic HTML, CSS, and JavaScript (ES6 preferreded)
For future versions: Basic understanding of React

### Installing

V1: Clone the repo or download the files and plug into your favorite editor!

## Running the tests

Coming soon

## Deployment

Update nelify deploy link here

## Built With

V1: Html, CSS, and JavaScript

## Contributing

Please see the documentation for contributing:
https://arcade-docs.rahatcodes.com/

## Versioning

Currently working on Version 1

## Authors

Will be updated soon

## License

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details

## Acknowledgments

Coming Soon

repository: Rahat-ch/Arcade

repo_name: Rahat-ch/Arcade


text:
# BundleLoader

This repository contains some example code that demonstrates how to load and link a Mach-O bundle in memory on OSX, and call a function from it. This can be useful for building software that needs to dynamically load new code in memory at runtime.

The key functions to read up on are `NSCreateObjectFileImageFromMemory` and `NSLinkModule`.  Once the `NSModule` is loaded and linked, you can locate symbols using `NSLookupSymbolInModule`, and resolve the address to it with `NSAddressOfSymbol`. Then you can cast that to whatever type you need.

## Usage
```
[ λ ~/dev/BundleLoader ] make
[*] Cleaning
[*] Building loader (debug)
[*] Building test module
[ λ ~/dev/BundleLoader ] build/loader build/testmod _CallMe
[*] Created object file image from memory blob
[*] Linked module in memory
[*] Located function symbol at 0x100cedf50
Hello from CallMe
[*] Called _CallMe, return value was 99
[ λ ~/dev/BundleLoader ]
```


text:
Forked from rtouten's script: https://github.com/rtrouton/esxi_macos_vm_creation

Added serial number and model parameters to allow Automatic MDM enrollment (DEP)
Updated macos Mojave and ESXI 6.7/HW14 references.

Purpose: create an iOS Shortcut: https://travellingtechguy.eu/ios-shortcut-vm-esxi/

This script is designed to create and configure virtual machines running Apple operating systems, hosted on a VMware ESXi server running on Apple hardware. The script assumes that the virtual machines are built using copied VMDK disk files.

Script is designed to be stored on an ESXi datastore and run from the ESXi server's command line interface.

Usage: `/path/to/esxi_macos_vm_creation.sh -n -d -c -h -i -o -r -s -v -p`

Options:

* **-n**: Name of VM (required)
* **-d**: Location of a VMDK disk file (required).  Location must be in this format - `/vmfs/volumes/datastore_number_here/path/to/vmdk_file.vmdk`
* **-c**: Number of virtual CPUs
* **-h**: VMware Hardware Version
* **-i**: Location of an ISO image. Location must be in this format - `/vmfs/volumes/datastore_number_here/path/to/iso_file.iso`
* **-o**: Apple OS version
* **-r**: RAM size in MB
* **-s**: Disk size in GB
* **-v**: VNC port between 5900 and 5909
* **-p**: VNC password. Maximum password length is eight characters.

**Examples:**

To set up a VM specifying only the VM name and VMDK location:

`/path/to/esxi_macos_vm_creation.sh -n VM_Name_Goes_Here -d /vmfs/volumes/datastore_number_here/path/to/filename_here.vmdk`

To set up a VM using a name with spaces and/or special characters, add quotation marks to the VM name:

`/path/to/esxi_macos_vm_creation.sh -n "VM's Name Goes Here!" -d /vmfs/volumes/datastore_number_here/path/to/filename_here.vmdk`

Other flags can be added as needed:

To set up a VM and add more CPUs:

`/path/to/esxi_macos_vm_creation.sh -n VM_Name_Goes_Here -c 4 -d /vmfs/volumes/datastore_number_here/path/to/filename_here.vmdk`

 To set up a VM and enable VNC on port 5901 with the password set to the word `password`:

`/path/to/esxi_macos_vm_creation.sh -n VM_Name_Goes_Here -d /vmfs/volumes/datastore_number_here/path/to/filename_here.vmdk -v 5901 -p password`

To set up a VM named `MacOS VM 10.12` using a VDMK stored on `/vmfs/volumes/datastore1/template` and named `macos-vm.vmdk` with 4 CPUs, 8 GBs of RAM, a 52 GB hard drive, set to HW Version 13, guest OS set to macOS Sierra and VNC enabled on port 5902 with the VNC password set to the word `password`:

`/path/to/esxi_macos_vm_creation.sh -n "MacOS VM 10.12" -d /vmfs/volumes/datastore1/template/macos-vm.vmdk -c 4 -r 8192 -s 52 -h 13 -o darwin16-64 -v 5902 -p password`

Based on [Tamas Piros](https://github.com/tpiros)'s auto-create: [https://github.com/tpiros/auto-create](https://github.com/tpiros/auto-create)

Blog post: [http://www.tamas.io/automatic-virtual-machine-creation-from-command-line-in-vmwares-esxi/](http://www.tamas.io/automatic-virtual-machine-creation-from-command-line-in-vmwares-esxi/)


text:
# multi2unicast

This small utility program was designed to connect to a multicast address and port and relay any packets received on this connection to predefined UDP port. I originally wrote this program as Matlab does not support the ability to connect to muticast network sources (without a lot of difficulty anyway). Matlab does work very well with UDP network sources but the external instrument that I needed to extract data from only operated via multicast. This program operated as a "go-between" for the two, but, of course, could be used in an senario.

This program was written on a raspberry pi but there is no reason why it shouldn't work on other platforms provided that the target machine's network adaptor/kernel support multicast.

To compile, simply:
gcc multi2uni.c -o multi2uni

To execute:
./multi2uni <multicast address> <multicast port>

The UDP address and port can be adjusted as desired in multi2uni.c


text:
# iOSHowTo-s
This repository contains different "how to do" stuff in iOS with Swift

For information about the **MyPlistPlayground.playground** checkout my article on medium -><EMAIL_ADDRESS>
For information about the **Scaled Fonts** checkout my article on medium ->
<EMAIL_ADDRESS>
For information about the **Document Interaction Demo** checkout my article on medium ->
https://medium.com/if-let-swift-programming/managing-files-in-ios-dfcdfdc1f426


text:
## _Hack and Dash_

#### _Legend says:_
> Escape the Dungeon Sprite with the help of a speed potion.

#### _Goals:_
+ _Escape the trap_

#### _Topics:_
+ **Basic Sintax**
+ **Arguments**
+ **Strings**
+ **While Loops**

#### _Items we've got (- or need):_
+ Simpla boots
+ _Optional: Elemental codex 1+_

#### _Solutions:_
+ **[JavaScript](hackAndDash.js)**
+ **[Python](hack_and_dash.py "#2 : 8,88s")**

#### _Rewards:_
+ 29 xp
+ 27 gems

#### _Victory words:_
+ _SIDE EFFECTS MAY INCLUDE DIZZINESS AND INSOMNIA._

___

### _HINTS_

![](img/hack-and-dash.jpg)

There's danger in the air! You need to escape from the dungeon, but why not check that `"Chest"` before you go?
Use `attack()` it to open the `"Chest"`, then use a **while-loop** to escape.

You're not fast enough to outrun the Sprite without drinking the Speed Potion.

Before the **while-loop**, you'll want to `moveUp()` and attack the `"Chest"` then `moveDown()` back into the main hallway.

Inside the **while-loop** you'll want to `moveDown()`. Use an argument to  `moveDown()` multiple times wthout having write more lines of code.

Don't worry, the Sprite is activated by stepping on the X, so you'll have time to grab the potion!

___

repository: ripssr/Code-Combat

repo_name: ripssr/Code-Combat


text:
---
layout: post
title: "Take the Police's Public Access Survey"
permalink: /archives/2011/05/take_the_polices_public_access_survey.html
commentfile: 2011-05-05-take_the_polices_public_access_survey
category: news
date: 2011-05-05 15:05:58

---

The Metropolitan Police Service (MPS) has launched a review into the different ways in which the public can contact police and access our services. These range from telephone, online and face-to-face methods, including via police stations and appointments.

In these challenging financial times, it is essential that the MPS makes best use of available resources. This is one of the key aims of the review that will ensure we can deliver an efficient and cost effective service in the right place at the right time.

As part of the review, we have launched an anonymous online survey. We will use the results of the survey, which runs until 27th May 2011, to develop a strategy to maintain and enhance public access to policing services within a core minimum standard. No decisions have yet been made and any changes will only take place with the approval of the most senior officers and staff who form the MPS Management Board and the Metropolitan Police Authority (MPA), an independent governing body that holds the MPS to account.

To have your say and influence the future of local policing in your area please take ten minutes to complete this survey; your views are important to us and will help us improve our services to better meet your needs.

[Take the survey online](http://www.keysurvey.co.uk/survey/360083/41a8/)

repository: pmahnke/stmgrts

repo_name: pmahnke/stmgrts


text:
#Project Description
This Program was created as an alternative to the traditional hangman game, to add a more colorful, less morbid, gaming experience. Who Killed Naruto is about someone in WDI19 developing the tech to travel back in time to make sure the awesomeness of Naruto will never see the light of day, or the future.

#Link To Deployed App
https://boring-heisenberg-f0c4f6.netlify.com

#Link to the Trello Board
https://trello.com/b/vlL0c9uL/wdi19-unit-1-project

#list of technologies used
HTML, CSS, JavaScript, and jQuery

#Additions for version 2
animations and sounds for greater interactivity, a greater array of randomized words, the ability to screenshot your own pic from your mac camera.


text:
# API Review 11/28/2022

## [Analyzer] Warn on inconsistent constraints between route params and types

**Approved** | [#aspnetcore/45218](https://github.com/dotnet/aspnetcore/issues/45218#issuecomment-1329588106)

API Review Notes:

1. Usage and error makes sense. We're confident these endpoints will be completely broken when hit at runtime.
2. This only fires for routes that have constraints already.
3. Given that this "[s]hould also work on MVC actions and Razor pages." How do you read from a slug in a razor page? What would be invalid? A `datetime` constraint?
4. `app.MapGet("/{id:int}", (long id) => ...);` should not trigger the analyzer because the route is more constrained than the parameter. It should fire for the opposite where the route is less constrained.
5. Should we have a fixer? It would be easy to suggest removing the constraint, but developers probably added them for a reason. However suggesting an `int` constraint for `int` parameters seems redundant. That would just turn 400 results into 404. tl;dr: We're fine without a fixer for now.

API Approved!

```
Message: $"The constraint '{constraint}' on parameter '{parameter}' can't be used with type {typeName}."
Category: Usage
Severity Level: Error
```

## Enable Option to Use Content Negotiation for ProblemDetails

**NeedsWork** | [#aspnetcore/45159](https://github.com/dotnet/aspnetcore/issues/45159#issuecomment-1329610038)

API Review Notes

1. Where is this options used? When writing problem details via the new service for MVC, the error handler middleware, status page result, the developer exception page.
2. Is there another name for `UseContentNegotiation` that can default for false? `IgnoreAcceptHeader`?
3. Can we change the default and make a breaking change announcement? The developer exception page will try to render to HTML first, so it shouldn't break that. @commonsensesoftware Do you think it would be too breaking to change the default here?

We'll hold off on approving this until we're confident what we want the default to be. Ideally, we'll have whatever we name the option false by default.

repository: dotnet/apireviews

repo_name: dotnet/apireviews


text:
# Newsspec-8939

US mid term elections 2014

## Getting started

Set up the project

```
grunt
```

Make images responsive

```
grunt images
```

Build World Service version

```
grunt translate
```

##How it works

This project was created using HTML/CSS/Javascript only.
1. A request is made to http://www.bbc.co.uk/indepthtoolkit/data_set/us-midterms-2014 for elections data.
2. The data goes through validation, if successful, hydrates a model which works out percentages for a chart.
3. This is then passed to a view for rendering. The view just adds some divs at a percentage width.

##Troubleshooting

If the data does not pass validation or the data request doesn't succeed for any reason the graph will result to a default display so...

1. Make sure the data is in the correct format

|               | democrat | republican | independent |
| ------------- |---------:| ----------:|------------:|
| senate_total  | 40       | 60         |0            |
| house_total   | 50       | 75         |0            |

```
{"senate_total":{"democrat":"36","republican":"30","independent":"0"},"house_total":{"democrat":"0","republican":"0","independent":"0"}}
```
2. Make sure that there are int values in all required sections. See json above.
3. Make sure the values make sense. If you try to add 100 republicans or democrats into the senate it will not validate.
 * Senate democrats + republicans should not exceed 100
 * House democrats + republicans should not exceed 435

##Testing

Use fixtures to see and test what impact variances in data have on the chart. This is useful if changing the data at the endpoint is out of the question (this will be the case when the endpoint is being used for live data).

To use fixture data, add your data to /source/js/spec/fixtures.js then edit /source/js/app.js to use it.

e.g. app.js
```
            require(['http://www.bbc.co.uk/indepthtoolkit/data_set/us-midterms-2014?callback=define'],
                function (data) {
                    var error,
                        validationObj,
                        modelObj,
                        viewObj;

                    //USE FIXTURE DATA INSTEAD
                    data = fixture['14'];

                    if (typeof data === 'undefined') {
                        error = true;
                    }

                    if (!error) {
                        validationObj = new Validation(data, true);
                        if (!validationObj.error) {
                            modelObj = new Model(data, true);
                            viewObj = new View(modelObj);
                        }
                    } else {
                        new View(false, false);
                    }
                }, function (err) {
                    new View(false, false);
                }
            );
```
You may need to add the fixture path as an argument the define function in app.js as well

e.g. in app.js

```
define(['fixture'], function (fixture)
```

##If all esle fails

Just remove the javascript and hard code the chart and css values.

For example to show senate 50/50 split (with 1 Independent vote), and house 100/100 split (with 2 Independent votes) edit the following files as below.

source/tmpl/index.html.tmpl

```
...
<span class="midterms-widget__senate-results__crats">50*</span>
<span class="midterms-widget__senate-results__gop">50</span>
...
<span class="midterms-widget__senate-results__independent">Independent : 1</span>
...
<span class="midterms-widget__house-results__crats">100</span>
<span class="midterms-widget__house-results__gop">100</span>
<span class="midterms-widget__house-results__independent">Independent : 2</span>
```

source/scss/main.scss

```
...
.midterms-widget__senate-results__chart {
    margin: 10px 0 20px 0;
    height: 2em;
    width: 100%;
    .crat-uc {width:34%; float:left; background: #7A8DA2; height:100%;}
    .crat-c {width:16%; float:left; background: #1C3054; height:100%;}
    .pending {width:0; float:left; background: #FFF; height:100%;}
    .gop-c {width:20%; float:left; background: #AC1315; height:100%;}
    .gop-uc {width:30%; float:left; background: #CC696A; height:100%;}
}
...
```

Then run grunt, grunt live and deploy.

If you are dealing with compiled files you can do the same in the following files

* content/english/index.html
* content/english/css/main.css

## iFrame scaffold

This project was built using the iFrame scaffold v1.5.3

## License
Copyright (c) 2014 BBC


text:
# Geo-L

A tool for discovery of geo-spatial links.

Geo-L retrieves specified properties of spatial objects from source and target datasets, through their respective SPARQL endpoints, and finds topological relations between objects in source and target datasets according to topological predicates.

The specifications of the relevant properties are provided in a configuration file, which allows constraining the number of object by specifying offset and limit . A dataset can be created through properties which already exist in the graph, and, in addition, Geo-L allows direct construction of ad-hoc values through a SPARQL select statement for a given resource.

## Installation

1. Install Python3
2. Install the required libraries with `pip install -r requirements.txt`
3. Install PostgreSQL and PostGIS
4. Create a database and add extensions postgis and postgis_topology

## Measures

The following measures are supported:

- contains
- contains_properly
- covered_by
- covers
- crosses
- disjoint
- distance
- distance_within
- equals
- hausdorff_distance
- intersects
- overlaps
- touches
- within

The distance_within measure needs a threshold to work.

## Run
Geo-L can be run from the command line or as server with a Rest API.

### Command line

To run geo-L from the command line, a config file and a database config file are needed. Example configs are in the configs folder. (Also see README in configs folder)
```bash
python main.py -c config.json -d postgresql_config.json
```

### Server with Rest API

To run the server, a database config file is needed.

```bash
python server.py -d postgresql_config.json
```

Send a Post request to `serverurl:8888/limes` with a Json body, which contains the geo-L config.

repository: KMI-KPZ/geo-L

gha_language: Python

repo_name: KMI-KPZ/geo-L