commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13 values | lang stringclasses 23 values |
|---|---|---|---|---|---|---|---|---|
33b3702f1ed7d061bca16306c8f19aee06dbb255 | Add Unlisted to VideoPrivacyEnum, fixed #65 | mfilippov/vimeo-dot-net,mohibsheth/vimeo-dot-net | src/VimeoDotNet/Enums/VideoPrivacyEnum.cs | src/VimeoDotNet/Enums/VideoPrivacyEnum.cs | namespace VimeoDotNet.Enums
{
/// <summary>
/// View privacy
/// </summary>
public enum VideoPrivacyEnum
{
/// <summary>
/// Unknown
/// </summary>
Unknown,
/// <summary>
/// Nobody
/// </summary>
Nobody,
/// <summary>
/// Anybody
/// </summary>
Anybody,
/// <summary>
/// Only contacts
/// </summary>
Contacts,
/// <summary>
/// Only users
/// </summary>
Users,
/// <summary>
/// Password
/// </summary>
Password,
/// <summary>
/// Disable
/// </summary>
Disable,
/// <summary>
/// Unlisted
/// </summary>
Unlisted
}
} | namespace VimeoDotNet.Enums
{
/// <summary>
/// View privacy
/// </summary>
public enum VideoPrivacyEnum
{
/// <summary>
/// Unknown
/// </summary>
Unknown,
/// <summary>
/// Nobody
/// </summary>
Nobody,
/// <summary>
/// Anybody
/// </summary>
Anybody,
/// <summary>
/// Only contacts
/// </summary>
Contacts,
/// <summary>
/// Only users
/// </summary>
Users,
/// <summary>
/// Password
/// </summary>
Password,
/// <summary>
/// Disable
/// </summary>
Disable
}
} | mit | C# |
cd6ce6f2391c07b7bd42dca03ed165ba2cf6ecb1 | Set version to 1.0.0.0 since AppVeyor is handling nuget versions | robfe/SpecLight | SpecLight/Properties/AssemblyInfo.cs | SpecLight/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("SpecLight")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SpecLight")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: InternalsVisibleTo("SpecLight.Tests")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion(SpeclightVersion.Version)]
[assembly: AssemblyFileVersion(SpeclightVersion.Version)]
static class SpeclightVersion
{
internal const string Version = "1.0.0.0";
} | using System.Reflection;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("SpecLight")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SpecLight")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: InternalsVisibleTo("SpecLight.Tests")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion(SpeclightVersion.Version)]
[assembly: AssemblyFileVersion(SpeclightVersion.Version)]
static class SpeclightVersion
{
internal const string Version = "1.0.4.0";
} | mit | C# |
7ff0d753a198d3dede4b02d6ff0aced8faba7789 | Add 'SKIPPED' resource status | stoiveyp/Alexa.NET.Management | Alexa.NET.Management/Package/ResourceStatus.cs | Alexa.NET.Management/Package/ResourceStatus.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace Alexa.NET.Management.Package
{
public enum ResourceStatus
{
FAILED,
IN_PROGRESS,
SKIPPED,
SUCCEEDED,
ROLLBACK_IN_PROGRESS,
ROLLBACK_SUCCEEDED,
ROLLBACK_FAILED
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace Alexa.NET.Management.Package
{
public enum ResourceStatus
{
FAILED,
IN_PROGRESS,
SUCCEEDED,
ROLLBACK_IN_PROGRESS,
ROLLBACK_SUCCEEDED,
ROLLBACK_FAILED
}
}
| mit | C# |
018aad234d1ac9c7605fffd73e222f4bf150065b | Switch to the less restrictive IConfiguration | rapidcore/rapidcore,rapidcore/rapidcore | src/core/main/Configuration/ConfigBase.cs | src/core/main/Configuration/ConfigBase.cs | #if NETSTANDARD1_6
using System;
using Microsoft.Extensions.Configuration;
namespace RapidCore.Configuration
{
/// <summary>
/// Base class for strongly typed configuration classes.
///
/// The idea is to allow you to define a config class specific
/// for your project, but gain easy access to reading config values
/// from wherever.
/// </summary>
public abstract class ConfigBase
{
private readonly IConfiguration configuration;
protected ConfigBase(IConfiguration configuration)
{
this.configuration = configuration;
}
protected T Get<T>(string key, T defaultValue)
{
string value = configuration[key];
if (string.IsNullOrEmpty(value))
{
return defaultValue;
}
return (T)Convert.ChangeType(value, typeof(T));
}
}
}
#endif | #if NETSTANDARD1_6
using System;
using Microsoft.Extensions.Configuration;
namespace RapidCore.Configuration
{
/// <summary>
/// Base class for strongly typed configuration classes.
///
/// The idea is to allow you to define a config class specific
/// for your project, but gain easy access to reading config values
/// from wherever.
/// </summary>
public abstract class ConfigBase
{
private readonly IConfigurationRoot configuration;
public ConfigBase(IConfigurationRoot configuration)
{
this.configuration = configuration;
}
protected T Get<T>(string key, T defaultValue)
{
string value = configuration[key];
if (string.IsNullOrEmpty(value))
{
return defaultValue;
}
return (T)Convert.ChangeType(value, typeof(T));
}
}
}
#endif | mit | C# |
6a51d51bcef029273198d4558ec8612c68ba8083 | Test StaticReadonlyFieldsMustBeginWithUpperCaseLetter sylecop property | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Backend/Models/FeeEstimationPair.cs | WalletWasabi/Backend/Models/FeeEstimationPair.cs | using System.ComponentModel.DataAnnotations;
namespace WalletWasabi.Backend.Models
{
/// <summary>
/// Satoshi per byte.
/// </summary>
public class FeeEstimationPair
{
private static readonly int testStaticReadonlyField;
[Required]
public long Economical { get; set; }
[Required]
public long Conservative { get; set; }
}
}
| using System.ComponentModel.DataAnnotations;
namespace WalletWasabi.Backend.Models
{
/// <summary>
/// Satoshi per byte.
/// </summary>
public class FeeEstimationPair
{
[Required]
public long Economical { get; set; }
[Required]
public long Conservative { get; set; }
}
}
| mit | C# |
8e4da23b176401803c8496e397f5ff5d792070ba | allow aggregates to be populated externally | Pondidum/Ledger,Pondidum/Ledger | Ledger/AggregateRoot.cs | Ledger/AggregateRoot.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Ledger.Infrastructure;
namespace Ledger
{
public class AggregateRoot<TKey>
{
public TKey ID { get; protected set; }
protected internal DateTime Stamp { get; set; }
protected internal int Sequence { get; set; }
private readonly Func<DateTime> _getTimestamp;
private readonly LightweightCache<Type, List<Action<DomainEvent<TKey>>>> _handlers;
private readonly List<DomainEvent<TKey>> _events;
protected AggregateRoot()
: this(DefaultStamper.Now)
{
}
protected AggregateRoot(Func<DateTime> getTimestamp)
{
_getTimestamp = getTimestamp;
_handlers = new LightweightCache<Type, List<Action<DomainEvent<TKey>>>>(
key => new List<Action<DomainEvent<TKey>>>()
);
_events = new List<DomainEvent<TKey>>();
Stamp = DateTime.MinValue;
Sequence = -1;
//BeforeApplyEvent<DomainEvent<TKey>>(e => e.Sequence = ++Sequence);
BeforeApplyEvent<DomainEvent<TKey>>(e => e.Stamp = _getTimestamp());
}
public IEnumerable<DomainEvent<TKey>> GetUncommittedEvents()
{
return _events;
}
internal void MarkEventsCommitted()
{
if (_events.Any())
{
Stamp = _events.Last().Stamp;
Sequence = _events.Last().Sequence;
_events.Clear();
}
}
public void LoadFromEvents(IEnumerable<DomainEvent<TKey>> eventStream)
{
DomainEvent<TKey> last = null;
var dynamic = this.AsDynamic();
eventStream
.Apply(e => last = e)
.ForEach(e => dynamic.Handle(e));
if (last != null)
{
Stamp = last.Stamp;
Sequence = last.Sequence;
}
}
public void LoadFromSnapshot<TSnapshot>(TSnapshot snapshot, IEnumerable<DomainEvent<TKey>> events)
where TSnapshot : Snapshot<TKey>
{
if (snapshot != null)
{
this.AsDynamic().ApplySnapshot(snapshot);
Stamp = snapshot.Stamp;
Sequence = snapshot.Sequence;
ID = snapshot.AggregateID;
}
LoadFromEvents(events);
}
protected void BeforeApplyEvent<TEvent>(Action<TEvent> handler)
where TEvent : DomainEvent<TKey>
{
_handlers[typeof(TEvent)].Add(e => handler((TEvent)e));
}
protected void ApplyEvent(DomainEvent<TKey> @event)
{
var eventType = @event.GetType();
_handlers
.Dictionary
.Where(p => p.Key.IsAssignableFrom(eventType))
.SelectMany(p => p.Value)
.ForEach(handler => handler.Invoke(@event));
this.AsDynamic().Handle(@event);
_events.Add(@event);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Ledger.Infrastructure;
namespace Ledger
{
public class AggregateRoot<TKey>
{
public TKey ID { get; protected set; }
protected internal DateTime Stamp { get; set; }
protected internal int Sequence { get; set; }
private readonly Func<DateTime> _getTimestamp;
private readonly LightweightCache<Type, List<Action<DomainEvent<TKey>>>> _handlers;
private readonly List<DomainEvent<TKey>> _events;
protected AggregateRoot()
: this(DefaultStamper.Now)
{
}
protected AggregateRoot(Func<DateTime> getTimestamp)
{
_getTimestamp = getTimestamp;
_handlers = new LightweightCache<Type, List<Action<DomainEvent<TKey>>>>(
key => new List<Action<DomainEvent<TKey>>>()
);
_events = new List<DomainEvent<TKey>>();
Stamp = DateTime.MinValue;
Sequence = -1;
//BeforeApplyEvent<DomainEvent<TKey>>(e => e.Sequence = ++Sequence);
BeforeApplyEvent<DomainEvent<TKey>>(e => e.Stamp = _getTimestamp());
}
public IEnumerable<DomainEvent<TKey>> GetUncommittedEvents()
{
return _events;
}
internal void MarkEventsCommitted()
{
if (_events.Any())
{
Stamp = _events.Last().Stamp;
Sequence = _events.Last().Sequence;
_events.Clear();
}
}
internal void LoadFromEvents(IEnumerable<DomainEvent<TKey>> eventStream)
{
DomainEvent<TKey> last = null;
var dynamic = this.AsDynamic();
eventStream
.Apply(e => last = e)
.ForEach(e => dynamic.Handle(e));
if (last != null)
{
Stamp = last.Stamp;
Sequence = last.Sequence;
}
}
internal void LoadFromSnapshot<TSnapshot>(TSnapshot snapshot, IEnumerable<DomainEvent<TKey>> events)
where TSnapshot : Snapshot<TKey>
{
if (snapshot != null)
{
this.AsDynamic().ApplySnapshot(snapshot);
Stamp = snapshot.Stamp;
Sequence = snapshot.Sequence;
ID = snapshot.AggregateID;
}
LoadFromEvents(events);
}
protected void BeforeApplyEvent<TEvent>(Action<TEvent> handler)
where TEvent : DomainEvent<TKey>
{
_handlers[typeof(TEvent)].Add(e => handler((TEvent)e));
}
protected void ApplyEvent(DomainEvent<TKey> @event)
{
var eventType = @event.GetType();
_handlers
.Dictionary
.Where(p => p.Key.IsAssignableFrom(eventType))
.SelectMany(p => p.Value)
.ForEach(handler => handler.Invoke(@event));
this.AsDynamic().Handle(@event);
_events.Add(@event);
}
}
}
| lgpl-2.1 | C# |
36d94b1e6515e98e06075235346099304ac1df49 | add won bool to cell | svmnotn/friendly-guacamole | Assets/src/data/Cell.cs | Assets/src/data/Cell.cs | public struct Cell {
public static Cell def = new Cell();
public bool won;
public bool played;
public string type;
public Cell(string type) {
this.played = true;
this.type = type;
}
}
| public struct Cell {
public static Cell def = new Cell();
public bool played;
public string type;
public Cell(string type) {
this.played = true;
this.type = type;
}
}
| mit | C# |
cc1da561878dfb6ffb8b5e320837017214292f45 | Add Travis to contact list. | jpfultonzm/trainingsandbox,jpfultonzm/trainingsandbox,jpfultonzm/trainingsandbox | ZirMed.TrainingSandbox/Views/Home/Contact.cshtml | ZirMed.TrainingSandbox/Views/Home/Contact.cshtml | @{
ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<address>
One Microsoft Way<br />
Redmond, WA 98052-6399<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>
<address>
<strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br />
<strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a>
<strong>Travis:</strong> <a href="mailto:travis.elkins@zirmed.com">travis.elkins@zirmed.com</a>
</address> | @{
ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<address>
One Microsoft Way<br />
Redmond, WA 98052-6399<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>
<address>
<strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br />
<strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a>
</address> | mit | C# |
bf2898120e117a93582f5c62564b4e232d9775e2 | Add in an explicit cast to convert DateTime to NSDate | directhex/xwt,mminns/xwt,hwthomas/xwt,lytico/xwt,steffenWi/xwt,akrisiun/xwt,hamekoz/xwt,iainx/xwt,antmicro/xwt,mminns/xwt,TheBrainTech/xwt,residuum/xwt,mono/xwt,cra0zy/xwt | Xwt.Mac/Xwt.Mac/DatePickerBackend.cs | Xwt.Mac/Xwt.Mac/DatePickerBackend.cs | //
// DatePickerBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2013 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using AppKit;
using Foundation;
namespace Xwt.Mac
{
public class DatePickerBackend: ViewBackend<NSDatePicker,IDatePickerEventSink>, IDatePickerBackend
{
public DatePickerBackend ()
{
}
public override void Initialize ()
{
base.Initialize ();
ViewObject = new MacDatePicker ();
}
public override void EnableEvent (object eventId)
{
base.EnableEvent (eventId);
if (eventId is DatePickerEvent)
Widget.Activated += HandleActivated;
}
public override void DisableEvent (object eventId)
{
base.DisableEvent (eventId);
if (eventId is DatePickerEvent)
Widget.Activated -= HandleActivated;
}
void HandleActivated (object sender, EventArgs e)
{
ApplicationContext.InvokeUserCode (((IDatePickerEventSink)EventSink).ValueChanged);
}
#region IDatePickerBackend implementation
public DateTime DateTime {
get {
return (DateTime)Widget.DateValue;
}
set {
Widget.DateValue = (NSDate) value;
}
}
#endregion
}
class MacDatePicker: NSDatePicker, IViewObject
{
public NSView View { get { return this; } }
public ViewBackend Backend { get; set; }
}
}
| //
// DatePickerBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2013 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using AppKit;
using Foundation;
namespace Xwt.Mac
{
public class DatePickerBackend: ViewBackend<NSDatePicker,IDatePickerEventSink>, IDatePickerBackend
{
public DatePickerBackend ()
{
}
public override void Initialize ()
{
base.Initialize ();
ViewObject = new MacDatePicker ();
}
public override void EnableEvent (object eventId)
{
base.EnableEvent (eventId);
if (eventId is DatePickerEvent)
Widget.Activated += HandleActivated;
}
public override void DisableEvent (object eventId)
{
base.DisableEvent (eventId);
if (eventId is DatePickerEvent)
Widget.Activated -= HandleActivated;
}
void HandleActivated (object sender, EventArgs e)
{
ApplicationContext.InvokeUserCode (((IDatePickerEventSink)EventSink).ValueChanged);
}
#region IDatePickerBackend implementation
public DateTime DateTime {
get {
return (DateTime)Widget.DateValue;
}
set {
Widget.DateValue = value;
}
}
#endregion
}
class MacDatePicker: NSDatePicker, IViewObject
{
public NSView View { get { return this; } }
public ViewBackend Backend { get; set; }
}
}
| mit | C# |
fc2c96fb921aa32d0b8c52a99434fdcaf895ddd8 | Change assembly version for release | githubpermutation/Flirper | Flirper/AssemblyInfo.cs | Flirper/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Flirper1.1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.1.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Flirper1.0")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| mit | C# |
1a70baa3b5460a095df5570e8b11f906f43b98c4 | Modifica parametri long 'd', 'n' in Classe Frazione | Azzeccagarbugli/Frazionetor | Frazionetor/Frazione.cs | Frazionetor/Frazione.cs | using System;
namespace Frazionetor
{
public class Frazione
{
private long numeratore = 1;
private long denominatore = 1;
public Frazione (long n, long d)
{
numeratore = n;
denominatore = d;
}
public void Semplifica ()
{
long i;
if (numeratore > denominatore)
{
i = numeratore;
}
else
{
i = denominatore;
}
while(i>0)
{
if (numeratore % i == 0 && denominatore % i == 0)
{
numeratore = numeratore / i;
denominatore = denominatore / i;
if (numeratore != numeratore / i && denominatore != denominatore / i)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine ("\nLa frazione semplificata è: {0}/{1}\n", numeratore, denominatore);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine ("\nLa frazione non può essere semplificata\n");
}
break;
}
i--;
}
}
}
}
| using System;
namespace Frazionetor
{
public class Frazione
{
private long numeratore = 1;
private long denominatore = 1;
public Frazione (long num, long den)
{
numeratore = num;
denominatore = den;
}
public void Semplifica ()
{
long i;
if (numeratore > denominatore)
{
i = numeratore;
}
else
{
i = denominatore;
}
while(i>0)
{
if (numeratore % i == 0 && denominatore % i == 0)
{
numeratore = numeratore / i;
denominatore = denominatore / i;
if (numeratore != numeratore / i && denominatore != denominatore / i)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine ("\nLa frazione semplificata è: {0}/{1}\n", numeratore, denominatore);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine ("\nLa frazione non può essere semplificata\n");
}
break;
}
i--;
}
}
}
}
| mit | C# |
81a0f60db37db3cced0467fa38e40815715462a8 | Update LogSeverity to reflect cef_log_severity_t | dga711/CefSharp,ITGlobal/CefSharp,Livit/CefSharp,rover886/CefSharp,illfang/CefSharp,jamespearce2006/CefSharp,ruisebastiao/CefSharp,battewr/CefSharp,jamespearce2006/CefSharp,gregmartinhtc/CefSharp,AJDev77/CefSharp,Livit/CefSharp,wangzheng888520/CefSharp,Haraguroicha/CefSharp,VioletLife/CefSharp,NumbersInternational/CefSharp,battewr/CefSharp,yoder/CefSharp,haozhouxu/CefSharp,windygu/CefSharp,ruisebastiao/CefSharp,rlmcneary2/CefSharp,ruisebastiao/CefSharp,rover886/CefSharp,NumbersInternational/CefSharp,rover886/CefSharp,ITGlobal/CefSharp,rover886/CefSharp,windygu/CefSharp,twxstar/CefSharp,zhangjingpu/CefSharp,haozhouxu/CefSharp,jamespearce2006/CefSharp,Haraguroicha/CefSharp,Haraguroicha/CefSharp,ITGlobal/CefSharp,zhangjingpu/CefSharp,Octopus-ITSM/CefSharp,joshvera/CefSharp,windygu/CefSharp,NumbersInternational/CefSharp,VioletLife/CefSharp,jamespearce2006/CefSharp,AJDev77/CefSharp,battewr/CefSharp,gregmartinhtc/CefSharp,wangzheng888520/CefSharp,yoder/CefSharp,joshvera/CefSharp,Haraguroicha/CefSharp,battewr/CefSharp,NumbersInternational/CefSharp,wangzheng888520/CefSharp,Octopus-ITSM/CefSharp,twxstar/CefSharp,dga711/CefSharp,haozhouxu/CefSharp,twxstar/CefSharp,VioletLife/CefSharp,gregmartinhtc/CefSharp,rlmcneary2/CefSharp,illfang/CefSharp,VioletLife/CefSharp,yoder/CefSharp,Haraguroicha/CefSharp,zhangjingpu/CefSharp,AJDev77/CefSharp,joshvera/CefSharp,dga711/CefSharp,illfang/CefSharp,zhangjingpu/CefSharp,gregmartinhtc/CefSharp,joshvera/CefSharp,Octopus-ITSM/CefSharp,windygu/CefSharp,rlmcneary2/CefSharp,AJDev77/CefSharp,twxstar/CefSharp,rover886/CefSharp,haozhouxu/CefSharp,dga711/CefSharp,Livit/CefSharp,rlmcneary2/CefSharp,ruisebastiao/CefSharp,illfang/CefSharp,jamespearce2006/CefSharp,Octopus-ITSM/CefSharp,yoder/CefSharp,Livit/CefSharp,ITGlobal/CefSharp,wangzheng888520/CefSharp | CefSharp/LogSeverity.cs | CefSharp/LogSeverity.cs | namespace CefSharp
{
public enum LogSeverity
{
/// <summary>
/// Default logging (currently Info logging)
/// </summary>
Default = 0,
/// <summary>
/// Verbose logging.
/// </summary>
Verbose,
/// <summary>
/// Info logging
/// </summary>
Info,
/// <summary>
/// Warning logging
/// </summary>
Warning,
/// <summary>
/// Error logging
/// </summary>
Error,
/// <summary>
/// ErrorReport logging
/// </summary>
ErrorReport,
/// <summary>
/// Completely disable logging
/// </summary>
Disable = 99
};
} | namespace CefSharp
{
public enum LogSeverity
{
Verbose,
Info,
Warning,
Error,
ErrorReport,
Disable,
};
} | bsd-3-clause | C# |
56f3b806c73a1b1f5b276bb2a1f7724532150084 | remove the manual overload. Now we get a sane error message. | Norgg/Principia,pleroy/Principia,pleroy/Principia,eggrobin/Principia,mockingbirdnest/Principia,eggrobin/Principia,Norgg/Principia,eggrobin/Principia,pleroy/Principia,mockingbirdnest/Principia,Norgg/Principia,mockingbirdnest/Principia,pleroy/Principia,Norgg/Principia,mockingbirdnest/Principia | ksp_plugin_adapter/interface.cs | ksp_plugin_adapter/interface.cs | using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace principia {
namespace ksp_plugin_adapter {
internal partial struct XYZ {
public static explicit operator XYZ(Vector3d v) {
return new XYZ{x = v.x, y = v.y, z = v.z};
}
public static explicit operator Vector3d(XYZ v) {
return new Vector3d{x = v.x, y = v.y, z = v.z};
}
}
internal partial struct WXYZ {
public static explicit operator WXYZ(UnityEngine.QuaternionD q) {
return new WXYZ{w = q.w, x = q.x, y = q.y, z = q.z};
}
public static explicit operator UnityEngine.QuaternionD(WXYZ q) {
return new UnityEngine.QuaternionD{w = q.w, x = q.x, y = q.y, z = q.z};
}
}
internal static partial class Interface {
#if __MonoCS__
internal const string kDllPath = "GameData/Principia/principia.so";
#else
internal const string kDllPath = "GameData/Principia/principia.dll";
#endif
[DllImport(dllName : Interface.kDllPath,
EntryPoint = "principia__ActivateRecorder",
CallingConvention = CallingConvention.Cdecl)]
internal static extern void ActivateRecorder(bool activate,
bool verbose);
}
} // namespace ksp_plugin_adapter
} // namespace principia
| using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace principia {
namespace ksp_plugin_adapter {
internal partial struct XYZ {
public static explicit operator XYZ(Vector3d v) {
return new XYZ{x = v.x, y = v.y, z = v.z};
}
public static explicit operator Vector3d(XYZ v) {
return new Vector3d{x = v.x, y = v.y, z = v.z};
}
}
internal partial struct WXYZ {
public static explicit operator WXYZ(UnityEngine.QuaternionD q) {
return new WXYZ{w = q.w, x = q.x, y = q.y, z = q.z};
}
public static explicit operator UnityEngine.QuaternionD(WXYZ q) {
return new UnityEngine.QuaternionD{w = q.w, x = q.x, y = q.y, z = q.z};
}
}
internal static partial class Interface {
#if __MonoCS__
internal const string kDllPath = "GameData/Principia/principia.so";
#else
internal const string kDllPath = "GameData/Principia/principia.dll";
#endif
[DllImport(dllName : Interface.kDllPath,
EntryPoint = "principia__ActivateRecorder",
CallingConvention = CallingConvention.Cdecl)]
internal static extern void ActivateRecorder(bool activate,
bool verbose);
// Manual overload needed to be able to pass |null| for a missing
// |parent_index|.
[DllImport(dllName : kDllPath,
EntryPoint = "principia__InsertCelestialAbsoluteCartesian",
CallingConvention = CallingConvention.Cdecl)]
internal static extern void InsertCelestialAbsoluteCartesian(
this IntPtr plugin,
int celestial_index,
IntPtr parent_index,
[MarshalAs(UnmanagedType.LPStr)] String gravitational_parameter,
[MarshalAs(UnmanagedType.LPStr)] String axis_right_ascension,
[MarshalAs(UnmanagedType.LPStr)] String axis_declination,
[MarshalAs(UnmanagedType.LPStr)] String j2,
[MarshalAs(UnmanagedType.LPStr)] String reference_radius,
[MarshalAs(UnmanagedType.LPStr)] String x,
[MarshalAs(UnmanagedType.LPStr)] String y,
[MarshalAs(UnmanagedType.LPStr)] String z,
[MarshalAs(UnmanagedType.LPStr)] String vx,
[MarshalAs(UnmanagedType.LPStr)] String vy,
[MarshalAs(UnmanagedType.LPStr)] String vz);
}
} // namespace ksp_plugin_adapter
} // namespace principia
| mit | C# |
9036016a470f1c397825870e10335262bd379224 | Add IsToConfig.TrueStringArray{set;} | Kuick/IsTo | IsTo/Misc/IsToConfig.cs | IsTo/Misc/IsToConfig.cs | // Copyright (c) kuicker.org. All rights reserved.
// Modified By YYYY-MM-DD
// kevinjong 2016-02-11 - Creation
using System.Collections.Generic;
using System.Linq;
namespace IsTo
{
public class IsToConfig
{
private static object _Lock = new object();
private static readonly string[] _DefaultTrueStringArray =
new[] { "1", "t", "y", "true", "yes", "on", "o" };
private static List<string> _TrueStringArray;
public static List<string> TrueStringArray
{
get
{
if(!TrueStringArrayNullOrEmpty) {
return _TrueStringArray;
}
lock(_Lock) {
if(!TrueStringArrayNullOrEmpty) {
return _TrueStringArray;
}
if(null == _TrueStringArray) {
_TrueStringArray = new List<string>();
}
if(_TrueStringArray.Count() == 0) {
_TrueStringArray.AddRange(
_DefaultTrueStringArray
);
}
return _TrueStringArray;
}
}
set
{
_TrueStringArray = value;
}
}
private static bool TrueStringArrayNullOrEmpty
{
get
{
return
null == _TrueStringArray
||
_TrueStringArray.Count() == 0;
}
}
}
}
| // Copyright (c) kuicker.org. All rights reserved.
// Modified By YYYY-MM-DD
// kevinjong 2016-02-11 - Creation
using System.Collections.Generic;
using System.Linq;
namespace IsTo
{
public class IsToConfig
{
private static object _Lock = new object();
private static readonly string[] _DefaultTrueStringArray =
new[] { "1", "t", "y", "true", "yes", "on", "o" };
private static List<string> _TrueStringArray;
public static List<string> TrueStringArray
{
get
{
if(!TrueStringArrayNullOrEmpty) {
return _TrueStringArray;
}
lock(_Lock) {
if(!TrueStringArrayNullOrEmpty) {
return _TrueStringArray;
}
if(null == _TrueStringArray) {
_TrueStringArray = new List<string>();
}
if(_TrueStringArray.Count() == 0) {
_TrueStringArray.AddRange(
_DefaultTrueStringArray
);
}
return _TrueStringArray;
}
}
}
private static bool TrueStringArrayNullOrEmpty
{
get
{
return
null == _TrueStringArray
||
_TrueStringArray.Count() == 0;
}
}
}
}
| apache-2.0 | C# |
b87615990487b90a90dc24d6fc17c758fda3da19 | Add code to load questions and images from zip | kiljacken/ProgrammingExamProject | Eksamensprojekt/Quiz.cs | Eksamensprojekt/Quiz.cs | using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace Eksamensprojekt
{
[Serializable()]
class Quiz
{
public String Name;
public String Description;
public IList<QuestionReference> QuestionReferences;
public IList<ImageReference> ImageReferences;
[field: NonSerialized()]
public IList<Question> Questions;
[field: NonSerialized()]
public IList<Image> Images;
public static Quiz LoadFromZip(String path)
{
ZipArchive archive = ZipFile.Open(path, ZipArchiveMode.Read);
ZipArchiveEntry quizEntry = archive.GetEntry("quiz.xml");
Quiz quiz = null;
using (Stream stream = quizEntry.Open())
{
XmlSerializer x = new XmlSerializer(typeof(Quiz));
quiz = (Quiz)x.Deserialize(stream);
}
quiz.Questions = new List<Question>(quiz.QuestionReferences.Count);
for (int i = 0; i < quiz.QuestionReferences.Count; i++)
{
QuestionReference reference = quiz.QuestionReferences[i];
quiz.Questions.Add(Question.LoadFromReference(reference, archive));
}
quiz.Images = new List<Image>(quiz.ImageReferences.Count);
for (int i = 0; i < quiz.ImageReferences.Count; i++)
{
ImageReference reference = quiz.ImageReferences[i];
Image image = null;
using(Stream stream = archive.GetEntry(@"images/"+reference.Path).Open())
{
image = Image.FromStream(stream);
}
quiz.Images.Add(image);
}
return quiz;
}
}
[Serializable()]
class QuestionReference
{
public String Path;
}
[Serializable()]
class Question
{
public QuestionType Type;
public String Value;
public static Question LoadFromReference(QuestionReference reference, ZipArchive archive)
{
Question question = null;
using(Stream stream = archive.GetEntry(@"questions/"+reference.Path).Open())
{
XmlSerializer x = new XmlSerializer(typeof(Question));
question = (Question)x.Deserialize(stream);
}
return question;
}
}
enum QuestionType
{
TEXT, IMAGE
}
[Serializable()]
class ImageReference
{
public String Path;
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace Eksamensprojekt
{
[Serializable()]
class Quiz
{
public String Name;
public String Description;
public IList<QuestionReference> QuestionReferences;
public IList<ImageReference> ImageReferences;
public static Quiz LoadFromZip(String path)
{
ZipArchive archive = ZipFile.Open(path, ZipArchiveMode.Read);
ZipArchiveEntry quizEntry = archive.GetEntry("quiz.xml");
Quiz quiz = null;
using (Stream stream = quizEntry.Open())
{
XmlSerializer x = new XmlSerializer(typeof(Quiz));
quiz = (Quiz)x.Deserialize(stream);
}
return quiz;
}
}
[Serializable()]
class QuestionReference
{
public String Path;
}
[Serializable()]
class ImageReference
{
public String Path;
}
}
| mit | C# |
851d070d39271a9017d6673c712c5564cb438c96 | Remove redundancy method | evelasco85/PoEAA,evelasco85/PoEAA,evelasco85/PoEAA,evelasco85/PoEAA,evelasco85/PoEAA | Framework/Repository.cs | Framework/Repository.cs | using System.Collections.Generic;
using System.Linq;
using Framework.Data_Manipulation;
using Framework.Domain;
namespace Framework
{
public interface IRepository<TEntity>
where TEntity : IDomainObject
{
IList<TEntity> Matching<TSearchInput>(TSearchInput criteria);
}
public class Repository<TEntity> : IRepository<TEntity>
where TEntity : IDomainObject
{
private readonly IDataSynchronizationManager _manager;
public Repository(IDataSynchronizationManager manager)
{
_manager = manager;
}
void ApplyDomainObjectSettings(ref IList<TEntity> newResult, IBaseQueryObject query)
{
if ((newResult == null) || (!newResult.Any()))
return;
IBaseMapper<TEntity> mapper = DataSynchronizationManager.GetInstance().GetMapper<TEntity>();
((List<TEntity>)newResult).ForEach(entity =>
{
((ISystemManipulation)entity).SetQueryObject(query);
((ISystemManipulation)entity).SetMapper(mapper);
});
}
IList<TEntity> Matching(IBaseQueryObject<TEntity> query)
{
IList<TEntity> results = query.Execute();
ApplyDomainObjectSettings(ref results, query);
return results;
}
public IList<TEntity> Matching<TSearchInput>(TSearchInput criteria)
{
IBaseQueryObject<TEntity> query = _manager.GetQueryBySearchCriteria<TEntity, TSearchInput>();
query.SearchInputObject = criteria;
return Matching(query);
}
}
}
| using System.Collections.Generic;
using System.Linq;
using Framework.Data_Manipulation;
using Framework.Domain;
namespace Framework
{
public interface IRepository<TEntity>
where TEntity : IDomainObject
{
IList<TEntity> Matching<TSearchInput>(TSearchInput criteria);
}
public class Repository<TEntity> : IRepository<TEntity>
where TEntity : IDomainObject
{
private readonly IDataSynchronizationManager _manager;
public Repository(IDataSynchronizationManager manager)
{
_manager = manager;
}
void ApplyDomainObjectSettings(ref IList<TEntity> newResult, IBaseQueryObject query)
{
if ((newResult == null) || (!newResult.Any()))
return;
IBaseMapper<TEntity> mapper = DataSynchronizationManager.GetInstance().GetMapper<TEntity>();
((List<TEntity>)newResult).ForEach(entity =>
{
((ISystemManipulation)entity).SetQueryObject(query);
((ISystemManipulation)entity).SetMapper(mapper);
});
}
IList<TEntity> Matching(IBaseQueryObject<TEntity> query)
{
IList<TEntity> results = query.Execute();
ApplyDomainObjectSettings(ref results, query);
return results;
}
public IList<TEntity> Matching<TSearchInput>(TSearchInput criteria)
{
IBaseQueryObject<TEntity> query = GetQueryBySearchCriteria<TSearchInput>();
query.SearchInputObject = criteria;
return Matching(query);
}
IBaseQueryObject<TEntity> GetQueryBySearchCriteria<TSearchInput>()
{
return _manager.GetQueryBySearchCriteria<TEntity, TSearchInput>();
}
}
}
| mit | C# |
5366973788ce8e9fe7a55aae61e05b7c469a1603 | Add missing HW pixel format | ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework | osu.Framework/Graphics/Video/FfmpegExtensions.cs | osu.Framework/Graphics/Video/FfmpegExtensions.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using FFmpeg.AutoGen;
namespace osu.Framework.Graphics.Video
{
internal static class FfmpegExtensions
{
internal static double GetValue(this AVRational rational) => rational.num / (double)rational.den;
internal static bool IsHardwarePixelFormat(this AVPixelFormat pixFmt)
{
switch (pixFmt)
{
case AVPixelFormat.AV_PIX_FMT_VDPAU:
case AVPixelFormat.AV_PIX_FMT_CUDA:
case AVPixelFormat.AV_PIX_FMT_VAAPI:
case AVPixelFormat.AV_PIX_FMT_VAAPI_IDCT:
case AVPixelFormat.AV_PIX_FMT_VAAPI_MOCO:
case AVPixelFormat.AV_PIX_FMT_DXVA2_VLD:
case AVPixelFormat.AV_PIX_FMT_QSV:
case AVPixelFormat.AV_PIX_FMT_VIDEOTOOLBOX:
case AVPixelFormat.AV_PIX_FMT_D3D11:
case AVPixelFormat.AV_PIX_FMT_D3D11VA_VLD:
case AVPixelFormat.AV_PIX_FMT_DRM_PRIME:
case AVPixelFormat.AV_PIX_FMT_OPENCL:
case AVPixelFormat.AV_PIX_FMT_MEDIACODEC:
case AVPixelFormat.AV_PIX_FMT_VULKAN:
case AVPixelFormat.AV_PIX_FMT_MMAL:
case AVPixelFormat.AV_PIX_FMT_XVMC:
return true;
default:
return false;
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using FFmpeg.AutoGen;
namespace osu.Framework.Graphics.Video
{
internal static class FfmpegExtensions
{
internal static double GetValue(this AVRational rational) => rational.num / (double)rational.den;
internal static bool IsHardwarePixelFormat(this AVPixelFormat pixFmt)
{
switch (pixFmt)
{
case AVPixelFormat.AV_PIX_FMT_VDPAU:
case AVPixelFormat.AV_PIX_FMT_CUDA:
case AVPixelFormat.AV_PIX_FMT_VAAPI:
case AVPixelFormat.AV_PIX_FMT_VAAPI_IDCT:
case AVPixelFormat.AV_PIX_FMT_VAAPI_MOCO:
case AVPixelFormat.AV_PIX_FMT_DXVA2_VLD:
case AVPixelFormat.AV_PIX_FMT_QSV:
case AVPixelFormat.AV_PIX_FMT_VIDEOTOOLBOX:
case AVPixelFormat.AV_PIX_FMT_D3D11:
case AVPixelFormat.AV_PIX_FMT_D3D11VA_VLD:
case AVPixelFormat.AV_PIX_FMT_DRM_PRIME:
case AVPixelFormat.AV_PIX_FMT_OPENCL:
case AVPixelFormat.AV_PIX_FMT_MEDIACODEC:
case AVPixelFormat.AV_PIX_FMT_VULKAN:
case AVPixelFormat.AV_PIX_FMT_MMAL:
return true;
default:
return false;
}
}
}
}
| mit | C# |
ec2bb601876d48bee36869a7735ca9b8874ff15e | Format code | mstrother/BmpListener | BmpListener/Bgp/PathAttributeAggregator.cs | BmpListener/Bgp/PathAttributeAggregator.cs | using System.Net;
namespace BmpListener.Bgp
{
public class PathAttributeAggregator : PathAttribute
{
public PathAttributeAggregator(byte[] data, int offset)
: base(data, offset)
{
Decode(data, Offset);
}
public int AS { get; private set; }
public IPAddress IPAddress { get; private set; }
protected void Decode(byte[] data, int offset)
{
// TODO: fix
//AS = BitConverter.ToInt16(data, 0);
//if (data.Length == 6)
//{
// var ipBytes = data.Skip(2).ToArray();
// IPAddress = new IPAddress(ipBytes);
//}
//else
//{
// var ipBytes = data.Skip(4).ToArray();
// IPAddress = new IPAddress(ipBytes);
//}
}
}
} | using System;
using System.Net;
namespace BmpListener.Bgp
{
public class PathAttributeAggregator : PathAttribute
{
public PathAttributeAggregator(byte[] data, int offset) : base(data, offset)
{
Decode(data, Offset);
}
public int AS { get; private set; }
public IPAddress IPAddress { get; private set; }
protected void Decode(byte[] data, int offset)
{
// TODO: fix
//AS = BitConverter.ToInt16(data, 0);
//if (data.Length == 6)
//{
// var ipBytes = data.Skip(2).ToArray();
// IPAddress = new IPAddress(ipBytes);
//}
//else
//{
// var ipBytes = data.Skip(4).ToArray();
// IPAddress = new IPAddress(ipBytes);
//}
}
}
} | mit | C# |
2c5995f045e733cfc13d2d123f97c5cc5548161e | Update DumpAllTheStuff.cs | overtools/OWLib | DataTool/ToolLogic/Dump/DumpAllTheStuff.cs | DataTool/ToolLogic/Dump/DumpAllTheStuff.cs | using System;
using System.IO;
using DataTool.JSON;
using DataTool.Flag;
using DataTool.ToolLogic.Extract;
using DataTool.ToolLogic.List;
using DataTool.ToolLogic.List.Misc;
namespace DataTool.ToolLogic.Dump {
[Tool("dump-all-stuff", CustomFlags = typeof(ExtractFlags), IsSensitive = true)]
public class DumpAllTheStuff : JSONTool, ITool {
public void Parse(ICLIFlags toolFlags) {
var flags = (ExtractFlags) toolFlags;
if (flags.OutputPath == null)
throw new Exception("no output path");
new ListAchievements().Parse(GetFlagsForCommand(flags, "achievements"));
new ListArcadeModes().Parse(GetFlagsForCommand(flags, "arcade-modes"));
new ListChatSettings().Parse(GetFlagsForCommand(flags, "chat-settings"));
new ListEsportTeams().Parse(GetFlagsForCommand(flags, "esport-teams"));
new ListGameModes().Parse(GetFlagsForCommand(flags, "gamemodes"));
new ListGameParams().Parse(GetFlagsForCommand(flags, "game-rulesets"));
new ListGeneralUnlocks().Parse(GetFlagsForCommand(flags, "general-unlocks"));
new ListHeroes().Parse(GetFlagsForCommand(flags, "heroes"));
new ListLoobox().Parse(GetFlagsForCommand(flags, "lootboxes"));
new ListMaps().Parse(GetFlagsForCommand(flags, "maps"));
new ListReportResponses().Parse(GetFlagsForCommand(flags, "report-responses"));
new DumpStrings().Parse(GetFlagsForCommand(flags, "strings", true));
new ListSubtitles().Parse(GetFlagsForCommand(flags, "subtitles"));
new ListHeroUnlocks().Parse(GetFlagsForCommand(flags, "unlocks"));
new ListRankedSeasons().Parse(GetFlagsForCommand(flags, "ranked-seasons"));
new DumpFileLists().Parse(toolFlags);
}
private static ListFlags GetFlagsForCommand(ExtractFlags flags, string output, bool useDumpFlags = false) {
if (useDumpFlags)
return new DumpFlags {
JSON = true,
Output = $"{Path.Combine(flags.OutputPath, output)}.json"
};
return new ListFlags {
JSON = true,
Output = $"{Path.Combine(flags.OutputPath, output)}.json"
};
}
}
} | using System;
using System.IO;
using DataTool.JSON;
using DataTool.Flag;
using DataTool.ToolLogic.Extract;
using DataTool.ToolLogic.List;
using DataTool.ToolLogic.List.Misc;
namespace DataTool.ToolLogic.Dump {
[Tool("dump-all-stuff", CustomFlags = typeof(ExtractFlags), IsSensitive = true)]
public class DumpAllTheStuff : JSONTool, ITool {
public void Parse(ICLIFlags toolFlags) {
var flags = (ExtractFlags) toolFlags;
if (flags.OutputPath == null)
throw new Exception("no output path");
new ListAchievements().Parse(GetFlagsForCommand(flags, "achievements"));
new ListArcadeModes().Parse(GetFlagsForCommand(flags, "arcade-modes"));
new ListChatSettings().Parse(GetFlagsForCommand(flags, "chat-settings"));
new ListEsportTeams().Parse(GetFlagsForCommand(flags, "esport-teams"));
new ListGameModes().Parse(GetFlagsForCommand(flags, "gamemodes"));
new ListGameParams().Parse(GetFlagsForCommand(flags, "game-rulesets"));
new ListGeneralUnlocks().Parse(GetFlagsForCommand(flags, "general-unlocks"));
new ListHeroes().Parse(GetFlagsForCommand(flags, "heroes"));
new ListLoobox().Parse(GetFlagsForCommand(flags, "lootboxes"));
new ListMaps().Parse(GetFlagsForCommand(flags, "maps"));
new ListReportResponses().Parse(GetFlagsForCommand(flags, "report-responses"));
new DumpStrings().Parse(GetFlagsForCommand(flags, "strings", true));
new ListSubtitles().Parse(GetFlagsForCommand(flags, "subtitles"));
new ListHeroUnlocks().Parse(GetFlagsForCommand(flags, "unlocks"));
new DumpFileLists().Parse(toolFlags);
}
private static ListFlags GetFlagsForCommand(ExtractFlags flags, string output, bool useDumpFlags = false) {
if (useDumpFlags)
return new DumpFlags {
JSON = true,
Output = $"{Path.Combine(flags.OutputPath, output)}.json"
};
return new ListFlags {
JSON = true,
Output = $"{Path.Combine(flags.OutputPath, output)}.json"
};
}
}
} | mit | C# |
96de9d15e5be2b0586c5546482626fe87193b520 | Add missing Include for CircleType | Trojaner25/Rocket-Safezone,Trojaner25/Rocket-Regions | Rocket_Safezone/Model/Safezone/SafeZoneType.cs | Rocket_Safezone/Model/Safezone/SafeZoneType.cs | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Xml.Serialization;
using Rocket.Unturned.Player;
namespace Safezone.Model
{
[XmlInclude(typeof(RectangleType))]
[XmlInclude(typeof(CircleType))]
public abstract class SafeZoneType
{
private static readonly Dictionary<String, Type> RegistereTypes = new Dictionary<String, Type>();
public static SafeZoneType CreateSafeZoneType(String name)
{
if (!RegistereTypes.ContainsKey(name))
{
return null;
}
Type t = RegistereTypes[name];
return (SafeZoneType)Activator.CreateInstance(t);
}
public static void RegisterSafeZoneType(String name, Type t)
{
if(typeof(SafeZoneType).IsAssignableFrom(t))
{
throw new ArgumentException(t.Name + " is not a SafeZoneType!");
}
if (RegistereTypes.ContainsKey(name))
{
throw new ArgumentException(name + " is already registered!");
}
RegistereTypes.Add(name, t);
}
public abstract SafeZone Create(RocketPlayer player, String name, string[] args);
public abstract bool IsInSafeZone(Position p);
public abstract bool Redefine(RocketPlayer player, string[] args);
public static ReadOnlyCollection<String> GetTypes()
{
return new ReadOnlyCollection<string>(new List<string>(RegistereTypes.Keys));
}
}
} | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Xml.Serialization;
using Rocket.Unturned.Player;
namespace Safezone.Model
{
[XmlInclude(typeof(RectangleType))]
public abstract class SafeZoneType
{
private static readonly Dictionary<String, Type> RegistereTypes = new Dictionary<String, Type>();
public static SafeZoneType CreateSafeZoneType(String name)
{
if (!RegistereTypes.ContainsKey(name))
{
return null;
}
Type t = RegistereTypes[name];
return (SafeZoneType)Activator.CreateInstance(t);
}
public static void RegisterSafeZoneType(String name, Type t)
{
if(typeof(SafeZoneType).IsAssignableFrom(t))
{
throw new ArgumentException(t.Name + " is not a SafeZoneType!");
}
if (RegistereTypes.ContainsKey(name))
{
throw new ArgumentException(name + " is already registered!");
}
RegistereTypes.Add(name, t);
}
public abstract SafeZone Create(RocketPlayer player, String name, string[] args);
public abstract bool IsInSafeZone(Position p);
public abstract bool Redefine(RocketPlayer player, string[] args);
public static ReadOnlyCollection<String> GetTypes()
{
return new ReadOnlyCollection<string>(new List<string>(RegistereTypes.Keys));
}
}
} | agpl-3.0 | C# |
5ec3ffddb6ea40c1c4ff9169e54fe1e97eb19754 | Change Person.cs to use remapping again | Shaddix/realm-dotnet,realm/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet,Shaddix/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet | realm/Tests/IntegrationTests.Win32/Person.cs | realm/Tests/IntegrationTests.Win32/Person.cs | using System;
using RealmNet;
namespace IntegrationTests
{
public class Person : RealmObject
{
// Automatically implemented (overridden) properties
public string FirstName { get; set; }
public string LastName { get; set; }
// Ignored property
[Ignore]
public bool IsOnline { get; set; }
// Composite property
[Ignore]
public string FullName
{
get { return FirstName + " " + LastName; }
set
{
var parts = value.Split(' ');
FirstName = parts[0];
LastName = parts[parts.Length - 1];
}
}
// Re-mapped property
[MapTo("Email")]
private string Email_ { get; set; }
// Wrapped version of previous property
[Ignore]
public string Email
{
get { return Email_; }
set
{
if (!value.Contains("@")) throw new Exception("Invalid email address");
Email_ = value;
}
}
public bool IsInteresting { get; set; }
}
}
| using System;
using RealmNet;
namespace IntegrationTests
{
public class Person : RealmObject
{
// Automatically implemented (overridden) properties
public string FirstName { get; set; }
public string LastName { get; set; }
// Ignored property
[Ignore]
public bool IsOnline { get; set; }
// Composite property
[Ignore]
public string FullName
{
get { return FirstName + " " + LastName; }
set
{
var parts = value.Split(' ');
FirstName = parts[0];
LastName = parts[parts.Length - 1];
}
}
public string Email { get; set; }
//// Re-mapped property
//[MapTo("Email")]
//private string Email_ { get; set; }
//// Wrapped version of previous property
//[Ignore]
//public string Email
//{
// get { return Email_; }
// set {
// if (!value.Contains("@")) throw new Exception("Invalid email address");
// Email_ = value;
// }
//}
public bool IsInteresting { get; set; }
}
}
| apache-2.0 | C# |
4fff08d241a2158da662863426e07fa1f1621f8a | Remove unused using | ppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu-new,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu | osu.Game.Tests/Visual/UserInterface/TestSceneNowPlayingOverlay.cs | osu.Game.Tests/Visual/UserInterface/TestSceneNowPlayingOverlay.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Overlays;
using osu.Game.Rulesets.Osu;
namespace osu.Game.Tests.Visual.UserInterface
{
[TestFixture]
public class TestSceneNowPlayingOverlay : OsuTestScene
{
[Cached]
private MusicController musicController = new MusicController();
private WorkingBeatmap currentBeatmap;
private NowPlayingOverlay nowPlayingOverlay;
[BackgroundDependencyLoader]
private void load()
{
Beatmap.Value = CreateWorkingBeatmap(new OsuRuleset().RulesetInfo);
nowPlayingOverlay = new NowPlayingOverlay
{
Origin = Anchor.Centre,
Anchor = Anchor.Centre
};
Add(musicController);
Add(nowPlayingOverlay);
}
[Test]
public void TestShowHideDisable()
{
AddStep(@"show", () => nowPlayingOverlay.Show());
AddToggleStep(@"toggle beatmap lock", state => Beatmap.Disabled = state);
AddStep(@"hide", () => nowPlayingOverlay.Hide());
}
[Test]
public void TestPrevTrackBehavior()
{
AddStep(@"Next track", () => musicController.NextTrack());
AddStep("Store track", () => currentBeatmap = Beatmap.Value);
AddStep(@"Seek track to 6 second", () => musicController.SeekTo(6000));
AddUntilStep(@"Wait for current time to update", () => currentBeatmap.Track.CurrentTime > 5000);
AddStep(@"Set previous", () => musicController.PreviousTrack());
AddAssert(@"Check track didn't change", () => currentBeatmap == Beatmap.Value);
AddUntilStep("Wait for current time to update", () => currentBeatmap.Track.CurrentTime < 5000);
AddStep(@"Set previous", () => musicController.PreviousTrack());
AddAssert(@"Check track did change", () => currentBeatmap != Beatmap.Value);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Overlays;
using osu.Game.Rulesets.Osu;
namespace osu.Game.Tests.Visual.UserInterface
{
[TestFixture]
public class TestSceneNowPlayingOverlay : OsuTestScene
{
[Cached]
private MusicController musicController = new MusicController();
private WorkingBeatmap currentBeatmap;
private NowPlayingOverlay nowPlayingOverlay;
[BackgroundDependencyLoader]
private void load()
{
Beatmap.Value = CreateWorkingBeatmap(new OsuRuleset().RulesetInfo);
nowPlayingOverlay = new NowPlayingOverlay
{
Origin = Anchor.Centre,
Anchor = Anchor.Centre
};
Add(musicController);
Add(nowPlayingOverlay);
}
[Test]
public void TestShowHideDisable()
{
AddStep(@"show", () => nowPlayingOverlay.Show());
AddToggleStep(@"toggle beatmap lock", state => Beatmap.Disabled = state);
AddStep(@"hide", () => nowPlayingOverlay.Hide());
}
[Test]
public void TestPrevTrackBehavior()
{
AddStep(@"Next track", () => musicController.NextTrack());
AddStep("Store track", () => currentBeatmap = Beatmap.Value);
AddStep(@"Seek track to 6 second", () => musicController.SeekTo(6000));
AddUntilStep(@"Wait for current time to update", () => currentBeatmap.Track.CurrentTime > 5000);
AddStep(@"Set previous", () => musicController.PreviousTrack());
AddAssert(@"Check track didn't change", () => currentBeatmap == Beatmap.Value);
AddUntilStep("Wait for current time to update", () => currentBeatmap.Track.CurrentTime < 5000);
AddStep(@"Set previous", () => musicController.PreviousTrack());
AddAssert(@"Check track did change", () => currentBeatmap != Beatmap.Value);
}
}
}
| mit | C# |
5e911727418511e737b3aac491b709211f3fb770 | Update CircleBounds.cs | wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D | src/Draw2D.ViewModels/Bounds/CircleBounds.cs | src/Draw2D.ViewModels/Bounds/CircleBounds.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.Serialization;
using Draw2D.Input;
using Draw2D.ViewModels.Shapes;
using Spatial;
namespace Draw2D.ViewModels.Bounds
{
[DataContract(IsReference = true)]
public class CircleBounds : ViewModelBase, IBounds
{
public IPointShape TryToGetPoint(IBaseShape shape, Point2 target, double radius, IHitTest hitTest, Modifier modifier)
{
var circle = shape as CircleShape ?? throw new ArgumentNullException("shape");
if (circle.StartPoint.Bounds?.TryToGetPoint(circle.StartPoint, target, radius, hitTest, modifier) != null)
{
return circle.StartPoint;
}
if (circle.Point.Bounds?.TryToGetPoint(circle.Point, target, radius, hitTest, modifier) != null)
{
return circle.Point;
}
foreach (var point in circle.Points)
{
if (point.Bounds?.TryToGetPoint(point, target, radius, hitTest, modifier) != null)
{
return point;
}
}
return null;
}
public IBaseShape Contains(IBaseShape shape, Point2 target, double radius, IHitTest hitTest, Modifier modifier)
{
var circle = shape as CircleShape ?? throw new ArgumentNullException("shape");
var distance = circle.StartPoint.DistanceTo(circle.Point);
return circle.StartPoint.ToRect2(distance).Contains(target) ? shape : null;
}
public IBaseShape Overlaps(IBaseShape shape, Rect2 target, double radius, IHitTest hitTest, Modifier modifier)
{
var circle = shape as CircleShape ?? throw new ArgumentNullException("shape");
var distance = circle.StartPoint.DistanceTo(circle.Point);
return circle.StartPoint.ToRect2(distance).IntersectsWith(target) ? shape : null;
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.Serialization;
using Draw2D.Input;
using Draw2D.ViewModels.Shapes;
using Spatial;
namespace Draw2D.ViewModels.Bounds
{
[DataContract(IsReference = true)]
public class CircleBounds : ViewModelBase, IBounds
{
public IPointShape TryToGetPoint(IBaseShape shape, Point2 target, double radius, IHitTest hitTest, Modifier modifier)
{
var circle = shape as CircleShape ?? throw new ArgumentNullException("shape");
if (circle.StartPoint.Bounds?.TryToGetPoint(circle.StartPoint, target, radius, hitTest, modifier) != null)
{
return circle.StartPoint;
}
if (circle.Point.Bounds?.TryToGetPoint(circle.Point, target, radius, hitTest, modifier) != null)
{
return circle.Point;
}
foreach (var point in circle.Points)
{
if (point.Bounds?.TryToGetPoint(point, target, radius, hitTest, modifier) != null)
{
return point;
}
}
return null;
}
public IBaseShape Contains(IBaseShape shape, Point2 target, double radius, IHitTest hitTest, Modifier modifier)
{
var circle = shape as CircleShape ?? throw new ArgumentNullException("shape");
var distance = circle.StartPoint.DistanceTo(circle.Point);
return Rect2.FromPoints(
circle.StartPoint.X - distance,
circle.StartPoint.Y - distance,
circle.StartPoint.X + distance,
circle.StartPoint.Y + distance).Contains(target) ? shape : null;
}
public IBaseShape Overlaps(IBaseShape shape, Rect2 target, double radius, IHitTest hitTest, Modifier modifier)
{
var circle = shape as CircleShape ?? throw new ArgumentNullException("shape");
var distance = circle.StartPoint.DistanceTo(circle.Point);
return Rect2.FromPoints(
circle.StartPoint.X - distance,
circle.StartPoint.Y - distance,
circle.StartPoint.X + distance,
circle.StartPoint.Y + distance).IntersectsWith(target) ? shape : null;
}
}
}
| mit | C# |
4a4476f5192438e64a5643b8ee9731b7fc0e678f | Add workaround for XS initialization issue | cra0zy/xwt,hamekoz/xwt,antmicro/xwt,lytico/xwt,hwthomas/xwt,mono/xwt,TheBrainTech/xwt | Xwt.XamMac/Xwt.Mac/NSApplicationInitializer.cs | Xwt.XamMac/Xwt.Mac/NSApplicationInitializer.cs | //
// NSApplicationInitializer.cs
//
// Author:
// Lluis Sanchez Gual <lluis@xamarin.com>
//
// Copyright (c) 2016 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using AppKit;
namespace Xwt.Mac
{
static class NSApplicationInitializer
{
public static void Initialize ()
{
var ds = System.Threading.Thread.GetNamedDataSlot ("NSApplication.Initialized");
if (System.Threading.Thread.GetData (ds) == null) {
System.Threading.Thread.SetData (ds, true);
NSApplication.IgnoreMissingAssembliesDuringRegistration = true;
NSApplication.Init ();
}
}
}
}
| //
// NSApplicationInitializer.cs
//
// Author:
// Lluis Sanchez Gual <lluis@xamarin.com>
//
// Copyright (c) 2016 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using AppKit;
namespace Xwt.Mac
{
static class NSApplicationInitializer
{
public static void Initialize ()
{
var ds = System.Threading.Thread.GetNamedDataSlot ("NSApplication.Initialized");
if (System.Threading.Thread.GetData (ds) == null) {
System.Threading.Thread.SetData (ds, true);
NSApplication.Init ();
}
}
}
}
| mit | C# |
beadb77c2c24553090edb9dcf3ad4edafaaa5b5d | Clean Up AppDelegate | xamarin/monotouch-samples,xamarin/monotouch-samples,xamarin/monotouch-samples | ActivityRings/ActivityRings/AppDelegate.cs | ActivityRings/ActivityRings/AppDelegate.cs | using Foundation;
using UIKit;
using HealthKit;
using System;
namespace ActivityRings
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to application events from iOS.
[Register("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
// class-level declarations
public override UIWindow Window
{
get;
set;
}
HKHealthStore healthStore = new HKHealthStore();
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
// Override point for customization after application launch.
// If not required for your application you can safely delete this method
// Code to start the Xamarin Test Cloud Agent
#if ENABLE_TEST_CLOUD
Xamarin.Calabash.Start();
#endif
return true;
}
public override void ShouldRequestHealthAuthorization(UIApplication application)
{
healthStore.HandleAuthorizationForExtension( (bool success, NSError error) =>
{
if (error != null && !success)
{
Console.WriteLine("You didn't allow HealthKit to access these read/write data types. " +
"In your app, try to handle this error gracefully when a user decides not to provide access. " +
"The error was: {0}. If you're using a simulator, try it on a device.", error.LocalizedDescription);
}
});
}
public override void OnResignActivation(UIApplication application)
{
// Invoked when the application is about to move from active to inactive state.
// This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message)
// or when the user quits the application and it begins the transition to the background state.
// Games should use this method to pause the game.
}
public override void DidEnterBackground(UIApplication application)
{
// Use this method to release shared resources, save user data, invalidate timers and store the application state.
// If your application supports background exection this method is called instead of WillTerminate when the user quits.
}
public override void WillEnterForeground(UIApplication application)
{
// Called as part of the transiton from background to active state.
// Here you can undo many of the changes made on entering the background.
}
public override void OnActivated(UIApplication application)
{
// Restart any tasks that were paused (or not yet started) while the application was inactive.
// If the application was previously in the background, optionally refresh the user interface.
}
public override void WillTerminate(UIApplication application)
{
// Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground.
}
}
}
| using Foundation;
using UIKit;
using HealthKit;
using System;
namespace ActivityRings
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to application events from iOS.
[Register("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
// class-level declarations
public override UIWindow Window
{
get;
set;
}
HKHealthStore healthStore = new HKHealthStore();
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
// Override point for customization after application launch.
// If not required for your application you can safely delete this method
// Code to start the Xamarin Test Cloud Agent
#if ENABLE_TEST_CLOUD
Xamarin.Calabash.Start();
#endif
return true;
}
public override void ShouldRequestHealthAuthorization(UIApplication application)
{
//Action<bool, NSError> completionAction;
//completionAction = delegate (bool success, NSError error) {
// if (error != null && !success)
// {
// Console.WriteLine("You didn't allow HealthKit to access these read/write data types. " +
// "In your app, try to handle this error gracefully when a user decides not to provide access. " +
// "The error was: {0}. If you're using a simulator, try it on a device.", error.LocalizedDescription);
// }
//};
healthStore.HandleAuthorizationForExtension( (bool success, NSError error) =>
{
if (error != null && !success)
{
Console.WriteLine("You didn't allow HealthKit to access these read/write data types. " +
"In your app, try to handle this error gracefully when a user decides not to provide access. " +
"The error was: {0}. If you're using a simulator, try it on a device.", error.LocalizedDescription);
}
});
}
public override void OnResignActivation(UIApplication application)
{
// Invoked when the application is about to move from active to inactive state.
// This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message)
// or when the user quits the application and it begins the transition to the background state.
// Games should use this method to pause the game.
}
public override void DidEnterBackground(UIApplication application)
{
// Use this method to release shared resources, save user data, invalidate timers and store the application state.
// If your application supports background exection this method is called instead of WillTerminate when the user quits.
}
public override void WillEnterForeground(UIApplication application)
{
// Called as part of the transiton from background to active state.
// Here you can undo many of the changes made on entering the background.
}
public override void OnActivated(UIApplication application)
{
// Restart any tasks that were paused (or not yet started) while the application was inactive.
// If the application was previously in the background, optionally refresh the user interface.
}
public override void WillTerminate(UIApplication application)
{
// Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground.
}
}
}
| mit | C# |
bfbad5e792ade8fc73a07141c69d69d2275b228f | Update Setting.cs | LanguagePatches/LanguagePatches-Framework | LanguagePatches/LanguagePatches/Setting.cs | LanguagePatches/LanguagePatches/Setting.cs | /**
* Language Patches
* Copyright (C) 2015 Thomas P. (http://kerbalspaceprogram.de), simon56modder
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*
* This library is intended to be used as a plugin for Kerbal Space Program
* which is copyright 2011-2015 Squad. Your usage of Kerbal Space Program
* itself is governed by the terms of its EULA, not the license above.
*
* https://kerbalspaceprogram.com
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
namespace LanguagePatches
{
[KSPAddon(KSPAddon.Startup.Settings, false)]
public class Setting : MonoBehaviour
{
public static bool toggle = true;
public GUISkin skin;
public extern static GUISkin Skin { get; }
void Start()
{
if (Loader.loadCache == "active") { Setting.toggle = true; }
else { Setting.toggle = false; }
}
void OnGUI()
{
// Settings window
if (HighLogic.LoadedScene.ToString() == "SETTINGS")
{
if (toggle)
{
toggle = GUI.Toggle(new Rect(Screen.width - 100, 0, 100, 20), toggle, " " + Loader.fullLang);
}
else
{
toggle = GUI.Toggle(new Rect(Screen.width - 100, 0, 100, 20), toggle, " English");
}
GUI.Label(new Rect(Screen.width - 135, 20, 150, 50), Loader.mustRestart);
GUI.Label(new Rect(10,10,200,120), "Translated in " + Loader.fullLangEnglish + " by " + Loader.credits);
GUI.skin = HighLogic.Skin;
if (toggle == true)
{
Loader.writeCache("active");
}
else
{
Loader.writeCache("inactive");
}
}
}
}
}
| /**
* Language Patches
* Copyright (C) 2015 Thomas P. (http://kerbalspaceprogram.de), simon56modder
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*
* This library is intended to be used as a plugin for Kerbal Space Program
* which is copyright 2011-2015 Squad. Your usage of Kerbal Space Program
* itself is governed by the terms of its EULA, not the license above.
*
* https://kerbalspaceprogram.com
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
namespace LanguagePatches
{
[KSPAddon(KSPAddon.Startup.Settings, false)]
public class Setting : MonoBehaviour
{
public static bool toggle = true;
public GUISkin skin;
public extern static GUISkin Skin { get; }
void Start()
{
if (Loader.loadCache == "active") { Setting.toggle = true; }
else { Setting.toggle = false; }
}
void OnGUI()
{
// Settings window
if (HighLogic.LoadedScene.ToString() == "SETTINGS")
{
toggle = GUI.Toggle(new Rect(Screen.width - 100, 0, 100, 20), toggle, " " + Loader.fullLang);
GUI.Label(new Rect(Screen.width - 135, 20, 150, 50), Loader.mustRestart);
GUI.skin = HighLogic.Skin;
if (toggle == true)
{
Loader.writeCache("active");
}
else
{
Loader.writeCache("inactive");
}
}
}
}
}
| mit | C# |
28bd8cb6852d74c1a0ab8735ccf7c22d4feeb3cf | Fix invalidator offset | Glurmo/LiveSplit,Glurmo/LiveSplit,kugelrund/LiveSplit,ROMaster2/LiveSplit,LiveSplit/LiveSplit,kugelrund/LiveSplit,Glurmo/LiveSplit,ROMaster2/LiveSplit,kugelrund/LiveSplit,ROMaster2/LiveSplit | LiveSplit/LiveSplit.Core/UI/Invalidator.cs | LiveSplit/LiveSplit.Core/UI/Invalidator.cs | using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace LiveSplit.UI
{
public class Invalidator : IInvalidator
{
public Form Form { get; protected set; }
public Matrix Transform { get; set; }
protected const double Offset = 0.535;
public Invalidator(Form form)
{
Transform = new Matrix();
Form = form;
}
public void Restart()
{
try
{
Transform?.Dispose();
}
catch { }
Transform = new Matrix();
}
public void Invalidate(float x, float y, float width, float height)
{
var points = new[]
{
new PointF(x, y),
new PointF(x+width, y+height)
};
Transform.TransformPoints(points);
var roundedX = (int)Math.Ceiling(points[0].X - Offset);
var roundedY = (int)Math.Ceiling(points[0].Y - Offset);
var rect = new Rectangle(
roundedX,
roundedY,
(int)Math.Ceiling(points[1].X - roundedX - Offset),
(int)Math.Ceiling(points[1].Y - roundedY - Offset));
Form.Invalidate(rect);
}
}
}
| using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace LiveSplit.UI
{
public class Invalidator : IInvalidator
{
public Form Form { get; protected set; }
public Matrix Transform { get; set; }
protected const double Offset = 0.035;
public Invalidator(Form form)
{
Transform = new Matrix();
Form = form;
}
public void Restart()
{
try
{
Transform?.Dispose();
}
catch { }
Transform = new Matrix();
}
public void Invalidate(float x, float y, float width, float height)
{
var points = new[]
{
new PointF(x, y),
new PointF(x+width, y+height)
};
Transform.TransformPoints(points);
var roundedX = (int)Math.Ceiling(points[0].X - Offset);
var roundedY = (int)Math.Ceiling(points[0].Y - Offset);
var rect = new Rectangle(
roundedX,
roundedY,
(int)Math.Ceiling(points[1].X - roundedX - Offset),
(int)Math.Ceiling(points[1].Y - roundedY - Offset));
Form.Invalidate(rect);
}
}
}
| mit | C# |
9ddc9f724d1898ca1c5d33b48a965abb30958ed7 | Change destination for slack notifications | LykkeCity/EthereumApiDotNetCore,LykkeCity/EthereumApiDotNetCore,LykkeCity/EthereumApiDotNetCore | src/AzureRepositories/Notifiers/SlackNotifier.cs | src/AzureRepositories/Notifiers/SlackNotifier.cs | using AzureStorage.Queue;
using Core;
using Core.Notifiers;
using Lykke.JobTriggers.Abstractions;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace AzureRepositories.Notifiers
{
public class SlackNotifier : ISlackNotifier, IPoisionQueueNotifier
{
private readonly IQueueExt _queue;
private const string _sender = "ethereumcoreservice";
public SlackNotifier(Func<string, IQueueExt> queueFactory)
{
_queue = queueFactory(Constants.SlackNotifierQueue);
}
public async Task WarningAsync(string message)
{
var obj = new
{
Type = "Warnings",
Sender = _sender,
Message = message
};
await _queue.PutRawMessageAsync(JsonConvert.SerializeObject(obj));
}
public async Task ErrorAsync(string message)
{
var obj = new
{
Type = "Ethereum",//"Errors",
Sender = _sender,
Message = message
};
await _queue.PutRawMessageAsync(JsonConvert.SerializeObject(obj));
}
public async Task FinanceWarningAsync(string message)
{
var obj = new
{
Type = "Financewarnings",
Sender = _sender,
Message = message
};
await _queue.PutRawMessageAsync(JsonConvert.SerializeObject(obj));
}
public Task NotifyAsync(string message)
{
return ErrorAsync(message);
}
}
}
| using AzureStorage.Queue;
using Core;
using Core.Notifiers;
using Lykke.JobTriggers.Abstractions;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace AzureRepositories.Notifiers
{
public class SlackNotifier : ISlackNotifier, IPoisionQueueNotifier
{
private readonly IQueueExt _queue;
private const string _sender = "ethereumcoreservice";
public SlackNotifier(Func<string, IQueueExt> queueFactory)
{
_queue = queueFactory(Constants.SlackNotifierQueue);
}
public async Task WarningAsync(string message)
{
var obj = new
{
Type = "Warnings",
Sender = _sender,
Message = message
};
await _queue.PutRawMessageAsync(JsonConvert.SerializeObject(obj));
}
public async Task ErrorAsync(string message)
{
var obj = new
{
Type = "Errors",
Sender = _sender,
Message = message
};
await _queue.PutRawMessageAsync(JsonConvert.SerializeObject(obj));
}
public async Task FinanceWarningAsync(string message)
{
var obj = new
{
Type = "Financewarnings",
Sender = _sender,
Message = message
};
await _queue.PutRawMessageAsync(JsonConvert.SerializeObject(obj));
}
public Task NotifyAsync(string message)
{
return ErrorAsync(message);
}
}
}
| mit | C# |
ddf914b317b12fe3af887f23bd0d445b834c4ccc | add default Guid value | frhagn/Typewriter | src/CodeModel/Extensions/Types/TypeExtensions.cs | src/CodeModel/Extensions/Types/TypeExtensions.cs | using System.Linq;
using Type = Typewriter.CodeModel.Type;
namespace Typewriter.Extensions.Types
{
/// <summary>
/// Extension methods for working with types.
/// </summary>
public static class TypeExtensions
{
/// <summary>
/// Returns the name of the type without []
/// </summary>
public static string ClassName(this Type type)
{
return type.Name.TrimEnd('[', ']');
}
/// <summary>
/// The default value of the type.
/// (Dictionary types returns {}, enumerable types returns [], boolean types returns false,
/// numeric types returns 0, void returns void(0), all other types return null)
/// </summary>
public static string Default(this Type type)
{
// Dictionary = { [key: type]: type; }
if (type.Name.StartsWith("{")) return "{}";
if (type.IsEnumerable) return "[]";
if (type.Name == "boolean") return "false";
if (type.Name == "number") return "0";
if (type.Name == "void") return "void(0)";
if (type.IsGuid) return "00000000-0000-0000-0000-000000000000";
return "null";
}
/// <summary>
/// Returns the first TypeArgument of a generic type or the type itself if it's not generic.
/// </summary>
public static Type Unwrap(this Type type)
{
return type.IsGeneric ? type.TypeArguments.First() : type;
}
}
}
| using System.Linq;
using Type = Typewriter.CodeModel.Type;
namespace Typewriter.Extensions.Types
{
/// <summary>
/// Extension methods for working with types.
/// </summary>
public static class TypeExtensions
{
/// <summary>
/// Returns the name of the type without []
/// </summary>
public static string ClassName(this Type type)
{
return type.Name.TrimEnd('[', ']');
}
/// <summary>
/// The default value of the type.
/// (Dictionary types returns {}, enumerable types returns [], boolean types returns false,
/// numeric types returns 0, void returns void(0), all other types return null)
/// </summary>
public static string Default(this Type type)
{
// Dictionary = { [key: type]: type; }
if (type.Name.StartsWith("{")) return "{}";
if (type.IsEnumerable) return "[]";
if (type.Name == "boolean") return "false";
if (type.Name == "number") return "0";
if (type.Name == "void") return "void(0)";
return "null";
}
/// <summary>
/// Returns the first TypeArgument of a generic type or the type itself if it's not generic.
/// </summary>
public static Type Unwrap(this Type type)
{
return type.IsGeneric ? type.TypeArguments.First() : type;
}
}
}
| apache-2.0 | C# |
43c28d1ef1d998faacc520d9adb572938c2894b6 | Remove unused code. | yojimbo87/ArangoDB-NET,kangkot/ArangoDB-NET | src/Arango/Arango.Client/API/ArangoDatabase.cs | src/Arango/Arango.Client/API/ArangoDatabase.cs | using System.Collections.Generic;
using Arango.Client.Protocol;
namespace Arango.Client
{
public class ArangoDatabase
{
private Connection _connection;
public ArangoCollectionOperation Collection
{
get
{
return new ArangoCollectionOperation(new CollectionOperation(_connection));
}
}
public ArangoDocumentOperation Document
{
get
{
return new ArangoDocumentOperation(new DocumentOperation(_connection));
}
}
public ArangoEdgeOperation Edge
{
get
{
return new ArangoEdgeOperation(new EdgeOperation(_connection));
}
}
public ArangoQueryOperation Query
{
get
{
return new ArangoQueryOperation(new CursorOperation(_connection));
}
}
public ArangoDatabase(string alias)
{
_connection = ArangoClient.GetConnection(alias);
}
}
}
| using System.Collections.Generic;
using Arango.Client.Protocol;
namespace Arango.Client
{
public class ArangoDatabase
{
private Connection _connection;
public ArangoCollectionOperation Collection
{
get
{
return new ArangoCollectionOperation(new CollectionOperation(_connection));
}
}
public ArangoDocumentOperation Document
{
get
{
return new ArangoDocumentOperation(new DocumentOperation(_connection));
}
}
public ArangoEdgeOperation Edge
{
get
{
return new ArangoEdgeOperation(new EdgeOperation(_connection));
}
}
public ArangoQueryOperation Query
{
get
{
return new ArangoQueryOperation(new CursorOperation(_connection));
}
}
public ArangoDatabase(string alias)
{
_connection = ArangoClient.GetConnection(alias);
}
/*#region Query
public List<Document> Query(string aql, out int count, Dictionary<string, object> bindVars = null, int batchSize = 0)
{
CursorOperation cursorOperation = new CursorOperation(_connection);
return cursorOperation.Post(aql, true, out count, batchSize, bindVars);
}
public List<Document> Query(string aql, Dictionary<string, object> bindVars = null, int batchSize = 0)
{
CursorOperation cursorOperation = new CursorOperation(_connection);
int count = 0;
return cursorOperation.Post(aql, false, out count, batchSize, bindVars);
}
public List<T> Query<T>(string aql, Dictionary<string, object> bindVars = null, int batchSize = 0) where T : class, new()
{
List<Document> documents = Query(aql, bindVars, batchSize);
List<T> genericCollection = new List<T>();
foreach (Document document in documents)
{
T genericObject = document.To<T>();
document.MapAttributesTo(genericObject);
genericCollection.Add(genericObject);
}
return genericCollection;
}
#endregion*/
}
}
| mit | C# |
56f6bba03b90e0ca69c2525d3d4f6f5d8b5f6ea8 | fix bug in client | corvusalba/my-little-lispy,corvusalba/my-little-lispy | src/CorvusAlba.MyLittleLispy.Client/Program.cs | src/CorvusAlba.MyLittleLispy.Client/Program.cs | using System.IO;
using System.Linq;
using CorvusAlba.MyLittleLispy.Runtime;
using CorvusAlba.MyLittleLispy.Hosting;
namespace CorvusAlba.MyLittleLispy.Client
{
internal class Program
{
private static int Main(string[] args)
{
if (!args.Any())
{
return new Repl(new ScriptEngine()).Loop();
}
else
{
using (var stream = new FileStream(args[0], FileMode.Open))
{
try
{
(new ScriptEngine()).Execute(stream, true);
return 0;
}
catch (HaltException e)
{
return e.Code;
}
}
}
}
}
} | using System.IO;
using System.Linq;
using CorvusAlba.MyLittleLispy.Runtime;
using CorvusAlba.MyLittleLispy.Hosting;
namespace CorvusAlba.MyLittleLispy.Client
{
internal class Program
{
private static int Main(string[] args)
{
if (!args.Any())
{
return new Repl(new ScriptEngine()).Loop();
}
else
{
using (var stream = new FileStream(args[0], FileMode.Open))
{
try
{
(new ScriptEngine()).Execute(stream);
return 0;
}
catch (HaltException e)
{
return e.Code;
}
}
}
}
}
} | mit | C# |
930583b3c0e378239416256c4c1812c9b53c5fbc | Fix V3025 | Insire/Maple,Insire/InsireBot-V2 | src/Maple.Core/Extensions/GenericExtensions.cs | src/Maple.Core/Extensions/GenericExtensions.cs | using System;
using System.Runtime.CompilerServices;
using Maple.Localization.Properties;
namespace Maple.Core.Extensions
{
public static class GenericExtensions
{
public static T ThrowIfNull<T>(this T obj, string objName, [CallerMemberName]string callerName = null)
{
if (obj == null)
throw new ArgumentNullException(objName, string.Format("{0} {1} {2}", objName, Resources.IsRequired, callerName));
return obj;
}
}
}
| using System;
using System.Runtime.CompilerServices;
using Maple.Localization.Properties;
namespace Maple.Core.Extensions
{
public static class GenericExtensions
{
public static T ThrowIfNull<T>(this T obj, string objName, [CallerMemberName]string callerName = null)
{
if (obj == null)
throw new ArgumentNullException(objName, string.Format("{0} {1} (2)", objName, Resources.IsRequired, callerName));
return obj;
}
}
}
| mit | C# |
d13cf5d3e2060b8a7715ceff5dde02bb7a5363ce | Add --base-tile option to Deserialize-Tilemap. | Prof9/PixelPet | PixelPet/Commands/DeserializeTilemapCmd.cs | PixelPet/Commands/DeserializeTilemapCmd.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PixelPet.Commands {
internal class DeserializeTilemapCmd : CliCommand {
public DeserializeTilemapCmd()
: base("Deserialize-Tilemap", new Parameter[] {
new Parameter("base-tile", "bt", false, new ParameterValue("index", "0"))
}) { }
public override void Run(Workbench workbench, Cli cli) {
int baseTile = FindNamedParameter("--base-tile").Values[0].ToInt32();
cli.Log("Deserializing tilemap...");
workbench.Stream.Position = 0;
workbench.Tilemap = new Tilemap();
int bpe = 2; // bytes per tile entry
byte[] buffer = new byte[bpe];
while (workbench.Stream.Read(buffer, 0, 2) == bpe) {
int scrn = buffer[0] | (buffer[1] << 8);
TileEntry te = new TileEntry() {
TileNumber = (scrn & 0x3FF) - baseTile,
HFlip = (scrn & (1 << 10)) != 0,
VFlip = (scrn & (1 << 11)) != 0,
PaletteNumber = (scrn >> 12) & 0xF
};
workbench.Tilemap.TileEntries.Add(te);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PixelPet.Commands {
internal class DeserializeTilemapCmd : CliCommand {
public DeserializeTilemapCmd()
: base("Deserialize-Tilemap") { }
public override void Run(Workbench workbench, Cli cli) {
cli.Log("Deserializing tilemap...");
workbench.Stream.Position = 0;
workbench.Tilemap = new Tilemap();
int bpe = 2; // bytes per tile entry
byte[] buffer = new byte[bpe];
while (workbench.Stream.Read(buffer, 0, 2) == bpe) {
int scrn = buffer[0] | (buffer[1] << 8);
TileEntry te = new TileEntry() {
TileNumber = scrn & 0x3FF,
HFlip = (scrn & (1 << 10)) != 0,
VFlip = (scrn & (1 << 11)) != 0,
PaletteNumber = (scrn >> 12) & 0xF
};
workbench.Tilemap.TileEntries.Add(te);
}
}
}
}
| mit | C# |
4474215c1e7826c27ad10939440a58939c8b0885 | Update FlanGrab_ArmBehaviour.cs | uulltt/NitoriWare | Assets/Resources/Microgames/_Finished/FlanGrab/Scripts/FlanGrab_ArmBehaviour.cs | Assets/Resources/Microgames/_Finished/FlanGrab/Scripts/FlanGrab_ArmBehaviour.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FlanGrab_ArmBehaviour : MonoBehaviour {
private Animator anim;
// Use this for initialization
void Start () {
anim = this.GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
if (MicrogameController.instance.getVictoryDetermined())
{
anim.SetTrigger(MicrogameController.instance.getVictory() ? "HandClutch" : "OpenHand");
enabled = false;
return;
}
if (Input.GetMouseButtonDown(0))
{
anim.SetTrigger("HandClutch");
}
else if (Input.GetMouseButtonUp(0))
{
anim.SetTrigger("OpenHand");
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FlanGrab_ArmBehaviour : MonoBehaviour {
private Animator anim;
// Use this for initialization
void Start () {
anim = this.GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
if (MicrogameController.instance.getVictoryDetermined())
{
if (MicrogameController.instance.getVictory())
anim.SetTrigger("HandClutch");
else
anim.SetTrigger("OpenHand");
enabled = false;
return;
}
if (Input.GetMouseButtonDown(0))
{
anim.SetTrigger("HandClutch");
}
else if (Input.GetMouseButtonUp(0))
{
anim.SetTrigger("OpenHand");
}
}
}
| mit | C# |
bf59a8261107c0dbf45bc356bcbdee2584a98d33 | undo removing xml formatter | s093294/Thinktecture.AuthorizationServer,yfann/AuthorizationServer,IdentityModel/AuthorizationServer,s093294/Thinktecture.AuthorizationServer,IdentityModel/AuthorizationServer,yfann/AuthorizationServer | source/WebHost/App_Start/WebApiConfig.cs | source/WebHost/App_Start/WebApiConfig.cs | /*
* Copyright (c) Dominick Baier, Brock Allen. All rights reserved.
* see license.txt
*/
using Newtonsoft.Json.Serialization;
using System.Net.Http.Formatting;
using System.Web.Http;
using Thinktecture.IdentityModel.Tokens.Http;
namespace Thinktecture.AuthorizationServer.WebHost
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "OAuth2 Token Endpoint",
routeTemplate: "{appName}/oauth/token",
defaults: new { Controller = "Token" },
constraints: null,
handler: new AuthenticationHandler(CreateClientAuthConfig(), config)
);
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
public static AuthenticationConfiguration CreateClientAuthConfig()
{
var authConfig = new AuthenticationConfiguration
{
InheritHostClientIdentity = false,
};
// accept arbitrary credentials on basic auth header,
// validation will be done in the protocol endpoint
authConfig.AddBasicAuthentication((id, secret) => true, retainPassword: true);
return authConfig;
}
}
}
| /*
* Copyright (c) Dominick Baier, Brock Allen. All rights reserved.
* see license.txt
*/
using Newtonsoft.Json.Serialization;
using System.Net.Http.Formatting;
using System.Web.Http;
using Thinktecture.IdentityModel.Tokens.Http;
namespace Thinktecture.AuthorizationServer.WebHost
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "OAuth2 Token Endpoint",
routeTemplate: "{appName}/oauth/token",
defaults: new { Controller = "Token" },
constraints: null,
handler: new AuthenticationHandler(CreateClientAuthConfig(), config)
);
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
public static AuthenticationConfiguration CreateClientAuthConfig()
{
var authConfig = new AuthenticationConfiguration
{
InheritHostClientIdentity = false,
};
// accept arbitrary credentials on basic auth header,
// validation will be done in the protocol endpoint
authConfig.AddBasicAuthentication((id, secret) => true, retainPassword: true);
return authConfig;
}
}
}
| bsd-3-clause | C# |
757b41f2e5584080583579bd7664eca687936ce7 | Fix animation FrameDelay not being locale independent. | Damnae/storybrew | common/Storyboarding/OsbAnimation.cs | common/Storyboarding/OsbAnimation.cs | using System;
using System.IO;
namespace StorybrewCommon.Storyboarding
{
public class OsbAnimation : OsbSprite
{
public int FrameCount;
public double FrameDelay;
public OsbLoopType LoopType;
public override string GetTexturePathAt(double time)
{
var dotIndex = TexturePath.LastIndexOf('.');
if (dotIndex < 0) return TexturePath + GetFrameAt(time);
return TexturePath.Substring(0, dotIndex) + GetFrameAt(time) + TexturePath.Substring(dotIndex, TexturePath.Length - dotIndex);
}
public int GetFrameAt(double time)
{
var frame = (time - CommandsStartTime) / FrameDelay;
switch (LoopType)
{
case OsbLoopType.LoopForever:
frame %= FrameCount;
break;
case OsbLoopType.LoopOnce:
frame = Math.Min(frame, FrameCount - 1);
break;
}
return Math.Max(0, (int)frame);
}
protected override void WriteHeader(TextWriter writer, ExportSettings exportSettings, OsbLayer layer)
=> writer.WriteLine($"Animation,{layer},{Origin.ToString()},\"{TexturePath.Trim()}\",{InitialPosition.X.ToString(exportSettings.NumberFormat)},{InitialPosition.Y.ToString(exportSettings.NumberFormat)},{FrameCount},{FrameDelay.ToString(exportSettings.NumberFormat)},{LoopType}");
}
}
| using System;
using System.IO;
namespace StorybrewCommon.Storyboarding
{
public class OsbAnimation : OsbSprite
{
public int FrameCount;
public double FrameDelay;
public OsbLoopType LoopType;
public override string GetTexturePathAt(double time)
{
var dotIndex = TexturePath.LastIndexOf('.');
if (dotIndex < 0) return TexturePath + GetFrameAt(time);
return TexturePath.Substring(0, dotIndex) + GetFrameAt(time) + TexturePath.Substring(dotIndex, TexturePath.Length - dotIndex);
}
public int GetFrameAt(double time)
{
var frame = (time - CommandsStartTime) / FrameDelay;
switch (LoopType)
{
case OsbLoopType.LoopForever:
frame %= FrameCount;
break;
case OsbLoopType.LoopOnce:
frame = Math.Min(frame, FrameCount - 1);
break;
}
return Math.Max(0, (int)frame);
}
protected override void WriteHeader(TextWriter writer, ExportSettings exportSettings, OsbLayer layer)
=> writer.WriteLine($"Animation,{layer},{Origin.ToString()},\"{TexturePath.Trim()}\",{InitialPosition.X.ToString(exportSettings.NumberFormat)},{InitialPosition.Y.ToString(exportSettings.NumberFormat)},{FrameCount},{FrameDelay},{LoopType}");
}
}
| mit | C# |
3a4960dd7517ef40a887601f5bc7078bcc9d41be | Remove full stops from player names. | paulbatum/Dominion,paulbatum/Dominion | Dominion.Web/Controllers/HomeController.cs | Dominion.Web/Controllers/HomeController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Web.Mvc;
using Dominion.GameHost;
using System.Reflection;
using Dominion.Cards.Actions;
using Dominion.Rules;
using Dominion.Cards.Treasure;
using Dominion.Cards.Victory;
using Dominion.Cards.Curses;
using Dominion.Web.ViewModels;
namespace Dominion.Web.Controllers
{
public class HomeController : Controller
{
private readonly MultiGameHost _host;
public HomeController(MultiGameHost host)
{
_host = host;
}
public ActionResult Index()
{
return RedirectToAction("NewGame");
}
[HttpGet]
public ActionResult NewGame()
{
var model = new NewGameViewModel();
model.CardsToChooseFrom = CardFactory.OptionalCardsForBank.OrderBy(c => c).ToList();
model.ChosenCards = model.CardsToChooseFrom.Take(10).ToList();
return View(model);
}
[HttpPost]
public ActionResult NewGame(NewGameViewModel model)
{
var namesArray = model.Names
.Split(new[] {',', '.'}, StringSplitOptions.RemoveEmptyEntries)
.Select(n => n.Trim());
string gameKey = _host.CreateNewGame(namesArray, model.NumberOfPlayers, model.ChosenCards);
return this.RedirectToAction(x => x.ViewPlayers(gameKey));
}
[HttpGet]
public ActionResult ViewPlayers(string gameKey)
{
var model = _host.GetGameData(gameKey);
return View("ViewPlayers", model);
}
[HttpPost]
public ActionResult JoinGame(Guid id)
{
return RedirectToAction("Play", "Game", new { id });
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Web.Mvc;
using Dominion.GameHost;
using System.Reflection;
using Dominion.Cards.Actions;
using Dominion.Rules;
using Dominion.Cards.Treasure;
using Dominion.Cards.Victory;
using Dominion.Cards.Curses;
using Dominion.Web.ViewModels;
namespace Dominion.Web.Controllers
{
public class HomeController : Controller
{
private readonly MultiGameHost _host;
public HomeController(MultiGameHost host)
{
_host = host;
}
public ActionResult Index()
{
return RedirectToAction("NewGame");
}
[HttpGet]
public ActionResult NewGame()
{
var model = new NewGameViewModel();
model.CardsToChooseFrom = CardFactory.OptionalCardsForBank.OrderBy(c => c).ToList();
model.ChosenCards = model.CardsToChooseFrom.Take(10).ToList();
return View(model);
}
[HttpPost]
public ActionResult NewGame(NewGameViewModel model)
{
var namesArray = model.Names
.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
.Select(n => n.Trim());
string gameKey = _host.CreateNewGame(namesArray, model.NumberOfPlayers, model.ChosenCards);
return this.RedirectToAction(x => x.ViewPlayers(gameKey));
}
[HttpGet]
public ActionResult ViewPlayers(string gameKey)
{
var model = _host.GetGameData(gameKey);
return View("ViewPlayers", model);
}
[HttpPost]
public ActionResult JoinGame(Guid id)
{
return RedirectToAction("Play", "Game", new { id });
}
}
}
| mit | C# |
94102ca525e37ba03d0cfba45261069b66c93c52 | Convert this in a different way | bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity | src/BugsnagUnity/DictionaryExtensions.cs | src/BugsnagUnity/DictionaryExtensions.cs | using System;
using System.Collections.Generic;
using BugsnagUnity.Payload;
using UnityEngine;
namespace BugsnagUnity
{
static class DictionaryExtensions
{
internal static void PopulateDictionaryFromAndroidData(this IDictionary<string, object> dictionary, AndroidJavaObject source)
{
using (var set = source.Call<AndroidJavaObject>("entrySet"))
using (var iterator = set.Call<AndroidJavaObject>("iterator"))
{
while (iterator.Call<bool>("hasNext"))
{
using (var mapEntry = iterator.Call<AndroidJavaObject>("next"))
{
var key = mapEntry.Call<string>("getKey");
using (var value = mapEntry.Call<AndroidJavaObject>("getValue"))
{
if (value != null)
{
using (var @class = value.Call<AndroidJavaObject>("getClass"))
{
if (@class.Call<bool>("isArray"))
{
var values = AndroidJNIHelper.ConvertFromJNIArray<string[]>(value.GetRawObject());
dictionary.AddToPayload(key, values);
}
else
{
dictionary.AddToPayload(key, value.Call<string>("toString"));
}
}
}
}
}
}
}
}
}
}
| using System;
using System.Collections.Generic;
using BugsnagUnity.Payload;
using UnityEngine;
namespace BugsnagUnity
{
static class DictionaryExtensions
{
private static IntPtr Arrays { get; } = AndroidJNI.FindClass("java/util/Arrays");
private static IntPtr ToStringMethod { get; } = AndroidJNIHelper.GetMethodID(Arrays, "toString", "([Ljava/lang/Object;)Ljava/lang/String;", true);
internal static void PopulateDictionaryFromAndroidData(this IDictionary<string, object> dictionary, AndroidJavaObject source)
{
using (var set = source.Call<AndroidJavaObject>("entrySet"))
using (var iterator = set.Call<AndroidJavaObject>("iterator"))
{
while (iterator.Call<bool>("hasNext"))
{
using (var mapEntry = iterator.Call<AndroidJavaObject>("next"))
{
var key = mapEntry.Call<string>("getKey");
using (var value = mapEntry.Call<AndroidJavaObject>("getValue"))
{
if (value != null)
{
using (var @class = value.Call<AndroidJavaObject>("getClass"))
{
if (@class.Call<bool>("isArray"))
{
var args = AndroidJNIHelper.CreateJNIArgArray(new[] {value});
var formattedValue = AndroidJNI.CallStaticStringMethod(Arrays, ToStringMethod, args);
dictionary.AddToPayload(key, formattedValue);
}
else
{
dictionary.AddToPayload(key, value.Call<string>("toString"));
}
}
}
}
}
}
}
}
}
}
| mit | C# |
0cdcc98cd0e51d4fbe481bd72352b7fde1ee7d12 | Remove filter. We filter for Xamarin per default | planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin | src/Firehose.Web/Authors/VijayAnandEG.cs | src/Firehose.Web/Authors/VijayAnandEG.cs | using Firehose.Web.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
namespace Firehose.Web.Authors
{
public class VijayAnandEG : IAmACommunityMember
{
public string FirstName => "Vijay Anand";
public string LastName => "E G";
public string StateOrRegion => "Chennai, Tamil Nadu, India";
public string EmailAddress => "egvijayanand@outlook.com";
public string ShortBioOrTagLine => "passionate software professional working on .NET";
public Uri WebSite => new Uri("https://egvijayanand.in/");
public string TwitterHandle => "egvijayanand";
public string GitHubHandle => "egvijayanand";
public string GravatarHash => "60f1549aa56354c8b770040db12a23f8";
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://egvijayanand.in/feed/"); } }
public GeoPosition Position => new GeoPosition(12.986768, 80.2117061);
public string FeedLanguageCode => "en";
}
}
| using Firehose.Web.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
namespace Firehose.Web.Authors
{
public class VijayAnandEG : IAmACommunityMember, IFilterMyBlogPosts
{
public string FirstName => "Vijay Anand";
public string LastName => "E G";
public string StateOrRegion => "Chennai, Tamil Nadu, India";
public string EmailAddress => "egvijayanand@outlook.com";
public string ShortBioOrTagLine => "passionate software professional working on .NET";
public Uri WebSite => new Uri("https://egvijayanand.in/");
public string TwitterHandle => "egvijayanand";
public string GitHubHandle => "egvijayanand";
public string GravatarHash => "60f1549aa56354c8b770040db12a23f8";
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://egvijayanand.in/feed/"); } }
public GeoPosition Position => new GeoPosition(12.986768, 80.2117061);
public string FeedLanguageCode => "en";
// As am planning to publish articles on non-Xamarin .NET stuff like Blazor
// Hence introducing the filter
public bool Filter(SyndicationItem item)
{
if (item.Title?.Text?.ToLowerInvariant().Contains("xamarin") ?? false)
{
return true;
}
// This filters out only the posts that have the "xamarin" category
// Not all blog posts have categories, please guard against this
return item.Categories?.Any(c => c.Name.ToLowerInvariant().Contains("xamarin")) ?? false;
}
}
} | mit | C# |
2951f00e7fb02fc65b7ab65604d93b8002ef7eee | Revert "removed unused code" | ZA-PT/Obsidian,ZA-PT/Obsidian,ZA-PT/Obsidian,ZA-PT/Obsidian | src/Obsidian/Views/OAuth20/SignIn.cshtml | src/Obsidian/Views/OAuth20/SignIn.cshtml | @*
For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*@
@model Obsidian.Models.OAuthSignInModel
@{
ViewData["Title"] = "Sign in";
}
@section scripts{
<script src="~/js/OAuthBundle.js"></script>
}
<!--
<div class="main fullscreen">
<div class="bg cover text-padding left-div">
@*Left Section*@
<h1>Obsidian</h1>
<h3>One-stop Authenication Solution</h3>
</div>
<div class="white form form-padding">
<form class="text-padding" asp-action="Authorize" asp-controller="OAuth20">
@*Right Section*@
<div class="form-group">
<label asp-for="UserName" class="control-label"></label>
<input asp-for="UserName" class="form-control" type="text" placeholder="Enter your E-mail address" required/>
</div>
<div class="form-group">
<label class="control-label" asp-for="Password"></label>
<input class="form-control" asp-for="Password" type="password" placeholder="Enter your password" required/>
</div>
<br/>
<div class="form-inline">
<input class="form-inline checkbox" asp-for="RememberMe" type="checkbox" />
<label class="control-label" asp-for="RememberMe"></label>
</div>
<input asp-for="ProtectedOAuthContext" type="hidden" />
<br/>
<hr/>
<button class="btn btn-lg btn-info form-btn" type="submit">Sign In</button>
</form>
</div>
</div>
!-->
<div id="oauth"></div>
<link href="~/css/SignIn.css" rel="stylesheet" /> | @*
For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*@
@model Obsidian.Models.OAuthSignInModel
@{
ViewData["Title"] = "Sign in";
}
@section scripts{
<script src="~/js/OAuthBundle.js"></script>
}
<div id="oauth"></div>
<link href="~/css/SignIn.css" rel="stylesheet" /> | apache-2.0 | C# |
bc8dbdec2185f6f428dda436023ed7b2c0885189 | Stop using confiuration service in OWinStartup to load IdentityServerConfiguration | SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers | src/SFA.DAS.EmployerUsers.Web/Startup.cs | src/SFA.DAS.EmployerUsers.Web/Startup.cs | using Microsoft.Owin;
using NLog;
using Owin;
using SFA.DAS.Configuration;
using SFA.DAS.EmployerUsers.Domain.Data;
using SFA.DAS.EmployerUsers.Infrastructure.Configuration;
[assembly: OwinStartup(typeof(SFA.DAS.EmployerUsers.Web.Startup))]
namespace SFA.DAS.EmployerUsers.Web
{
public partial class Startup
{
private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
public void Configuration(IAppBuilder app)
{
_logger.Debug("Started running Owin Configuration");
var identityServerConfiguration = StructuremapMvc.Container.GetInstance<IdentityServerConfiguration>();
var relyingPartyRepository = StructuremapMvc.Container.GetInstance<IRelyingPartyRepository>();
ConfigureIdentityServer(app, identityServerConfiguration, relyingPartyRepository);
ConfigureRelyingParty(app, identityServerConfiguration);
}
}
} | using Microsoft.Owin;
using NLog;
using Owin;
using SFA.DAS.Configuration;
using SFA.DAS.EmployerUsers.Domain.Data;
using SFA.DAS.EmployerUsers.Infrastructure.Configuration;
[assembly: OwinStartup(typeof(SFA.DAS.EmployerUsers.Web.Startup))]
namespace SFA.DAS.EmployerUsers.Web
{
public partial class Startup
{
private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
public void Configuration(IAppBuilder app)
{
_logger.Debug("Started running Owin Configuration");
var configurationService = StructuremapMvc.Container.GetInstance<IConfigurationService>();
var relyingPartyRepository = StructuremapMvc.Container.GetInstance<IRelyingPartyRepository>();
configurationService.GetAsync<EmployerUsersConfiguration>().ContinueWith((task) =>
{
if (task.Exception != null)
{
task.Exception.UnpackAndLog(_logger);
throw task.Exception.InnerExceptions[0];
}
_logger.Debug("EmployerUsersConfiguration read successfully");
var configuration = task.Result;
ConfigureIdentityServer(app, configuration.IdentityServer, relyingPartyRepository);
ConfigureRelyingParty(app, configuration.IdentityServer);
}).Wait();
}
}
} | mit | C# |
8f5804e15590151337bd974bffe8020a04ab6b16 | Write help topics instruction | appharbor/appharbor-cli | src/AppHarbor/Program.cs | src/AppHarbor/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Windsor;
namespace AppHarbor
{
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer()
.Install(new AppHarborInstaller());
var commandDispatcher = container.Resolve<CommandDispatcher>();
if (args.Any())
{
commandDispatcher.Dispatch(args);
}
Console.WriteLine("Usage: appharbor COMMAND [command-options]");
Console.WriteLine("");
Console.WriteLine("Help topics (type \"appharbor help TOPIC\"):");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Windsor;
namespace AppHarbor
{
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer()
.Install(new AppHarborInstaller());
var commandDispatcher = container.Resolve<CommandDispatcher>();
if (args.Any())
{
commandDispatcher.Dispatch(args);
}
Console.WriteLine("Usage: appharbor COMMAND [command-options]");
Console.WriteLine("");
}
}
}
| mit | C# |
f58aaa3bd1cfa72422c70a33681c340fb3a0e864 | Fix a typo (#8143) | hoopsomuah/orleans,dotnet/orleans,dotnet/orleans,hoopsomuah/orleans | samples/Presence/src/Grains/PresenceGrain.cs | samples/Presence/src/Grains/PresenceGrain.cs | using Orleans;
using Orleans.Concurrency;
using Presence.Grains.Models;
namespace Presence.Grains;
/// <summary>
/// Stateless grain that decodes binary blobs and routes then to the appropriate game grains based on the blob content.
/// Simulates how a cloud service receives raw data from a device and needs to preprocess it before forwarding for the actual computation.
/// </summary>
[StatelessWorker]
public class PresenceGrain : Grain, IPresenceGrain
{
public Task HeartbeatAsync(byte[] data)
{
var heartbeatData = HeartbeatDataDotNetSerializer.Deserialize(data);
var game = GrainFactory.GetGrain<IGameGrain>(heartbeatData.GameKey);
return game.UpdateGameStatusAsync(heartbeatData.Status);
}
}
| using Orleans;
using Orleans.Concurrency;
using Presence.Grains.Models;
namespace Presence.Grains;
/// <summary>
/// Stateless grain that decodes binary blobs and routes then to the appropriate game grains based on the blob content.
/// Simulates how a cloud service receives raw data from a device and needs to preprocess it before forwarding for the actial computation.
/// </summary>
[StatelessWorker]
public class PresenceGrain : Grain, IPresenceGrain
{
public Task HeartbeatAsync(byte[] data)
{
var heartbeatData = HeartbeatDataDotNetSerializer.Deserialize(data);
var game = GrainFactory.GetGrain<IGameGrain>(heartbeatData.GameKey);
return game.UpdateGameStatusAsync(heartbeatData.Status);
}
}
| mit | C# |
f260156fabd28268b185da0ee751cf38c3703390 | Fix image hash computing (PNG gives different results on different ms windows versions) | cezarypiatek/MaintainableSelenium,cezarypiatek/MaintainableSelenium,cezarypiatek/Tellurium,cezarypiatek/Tellurium,cezarypiatek/Tellurium,cezarypiatek/MaintainableSelenium | Src/MaintainableSelenium/MaintainableSelenium.MvcPages/Utils/ImageExtensions.cs | Src/MaintainableSelenium/MaintainableSelenium.MvcPages/Utils/ImageExtensions.cs | using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace MaintainableSelenium.MvcPages.Utils
{
public static class ImageExtensions
{
public static Bitmap ToBitmap(this byte[] screenshot)
{
using (MemoryStream memoryStream = new MemoryStream(screenshot))
{
var image = Image.FromStream(memoryStream);
return new Bitmap(image);
}
}
public static byte[] ToBytes(this Image imageIn)
{
using (var ms = new MemoryStream())
{
imageIn.Save(ms, ImageFormat.Bmp);
return ms.ToArray();
}
}
}
}
| using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace MaintainableSelenium.MvcPages.Utils
{
public static class ImageExtensions
{
public static Bitmap ToBitmap(this byte[] screenshot)
{
using (MemoryStream memoryStream = new MemoryStream(screenshot))
{
var image = Image.FromStream(memoryStream);
return new Bitmap(image);
}
}
public static byte[] ToBytes(this Image imageIn)
{
using (var ms = new MemoryStream())
{
imageIn.Save(ms, ImageFormat.Png);
return ms.ToArray();
}
}
}
}
| mit | C# |
2d1e02102a5cebc9924501efa2d43cf8d3afb005 | Fix Navigationlink | hotelde/regtesting,AlexEndris/regtesting | RegTesting.Mvc/Views/Shared/_Layout.cshtml | RegTesting.Mvc/Views/Shared/_Layout.cshtml |
<!DOCTYPE html>
<html>
<head>
<title>UI-Testing</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
@*<link href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />*@
<!-- Bootstrap -->
<link href="@Url.Content("~/Content/bootstrap.css")" rel="stylesheet"/>
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="@Url.Content("~/Content/bootstrap-theme.css")" rel="stylesheet"/>
<link href="@Url.Content("~/Content/uitesting.css")" rel="stylesheet"/>
<script src="@Url.Content("~/Scripts/jquery-2.1.3.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery-ui.min.js")"></script>
<script src="@Url.Content("~/Content/jquery-ui.theme.min.css")"></script>
@*<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>*@
<script src="@Url.Content("~/Scripts/bootstrap.min.js")"></script>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="@Url.Action("Index","TestsystemSummary")">RegTesting</a>
</div>
<div class="collapse navbar-collapse">
<div class="navbar-collapse collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>@Html.MenuLink("Summary", "Index", "TestsystemSummary", new {})</li>
<li>@Html.MenuLink("Testing", "Index", "Testing", new {})</li>
<li>@Html.MenuLink("Status", "Index", "Status", new {})</li>
<li>@Html.MenuLink("Settings", "Index", "Settings", new {})</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Logged in as @User.Identity.GetLogin()</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="container">
<section id="main">
@RenderBody()
</section>
</div> <!-- /container -->
</body>
</html> |
<!DOCTYPE html>
<html>
<head>
<title>UI-Testing</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
@*<link href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />*@
<!-- Bootstrap -->
<link href="@Url.Content("~/Content/bootstrap.css")" rel="stylesheet"/>
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="@Url.Content("~/Content/bootstrap-theme.css")" rel="stylesheet"/>
<link href="@Url.Content("~/Content/uitesting.css")" rel="stylesheet"/>
<script src="@Url.Content("~/Scripts/jquery-2.1.3.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery-ui.min.js")"></script>
<script src="@Url.Content("~/Content/jquery-ui.theme.min.css")"></script>
@*<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>*@
<script src="@Url.Content("~/Scripts/bootstrap.min.js")"></script>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="http://regtesting/">RegTesting</a>
</div>
<div class="collapse navbar-collapse">
<div class="navbar-collapse collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>@Html.MenuLink("Summary", "Index", "TestsystemSummary", new {})</li>
<li>@Html.MenuLink("Testing", "Index", "Testing", new {})</li>
<li>@Html.MenuLink("Status", "Index", "Status", new {})</li>
<li>@Html.MenuLink("Settings", "Index", "Settings", new {})</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Logged in as @User.Identity.GetLogin()</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="container">
<section id="main">
@RenderBody()
</section>
</div> <!-- /container -->
</body>
</html> | apache-2.0 | C# |
3b3aec8ae534604783d8428aae292e1008157872 | Set focus on login control at page load. | cdrnet/Lokad.Cloud,cdrnet/Lokad.Cloud | Source/Lokad.Cloud.WebRole/Default.aspx.cs | Source/Lokad.Cloud.WebRole/Default.aspx.cs | #region Copyright (c) Lokad 2009
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Configuration;
using DotNetOpenAuth.OpenId.RelyingParty;
using Microsoft.ServiceHosting.ServiceRuntime;
namespace Lokad.Cloud.Web
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Verify storage credentials
if(!Page.IsPostBack)
{
var verifier = new StorageCredentialsVerifier(
GlobalSetup.Container.Resolve<Microsoft.Samples.ServiceHosting.StorageClient.BlobStorage>());
_credentialsWarningPanel.Visible = !verifier.VerifyCredentials();
}
_openIdLogin.Focus();
}
protected void OpenIdLogin_OnLoggingIn(object sender, OpenIdEventArgs e)
{
// HACK: logic to retrieve admins is duplicated with 'Default.aspx'
var admins = string.Empty;
if (RoleManager.IsRoleManagerRunning)
{
admins = RoleManager.GetConfigurationSetting("Admins");
}
else
{
admins = ConfigurationManager.AppSettings["Admins"];
}
foreach(var admin in admins.Split(new [] {" "}, StringSplitOptions.RemoveEmptyEntries))
{
if(e.ClaimedIdentifier == admin)
{
return;
}
}
// if the user isn't listed as an administrator, cancel the login
e.Cancel = true;
}
}
}
| #region Copyright (c) Lokad 2009
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Configuration;
using DotNetOpenAuth.OpenId.RelyingParty;
using Microsoft.ServiceHosting.ServiceRuntime;
namespace Lokad.Cloud.Web
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Verify storage credentials
if(!Page.IsPostBack)
{
var verifier = new StorageCredentialsVerifier(
GlobalSetup.Container.Resolve<Microsoft.Samples.ServiceHosting.StorageClient.BlobStorage>());
_credentialsWarningPanel.Visible = !verifier.VerifyCredentials();
}
}
protected void OpenIdLogin_OnLoggingIn(object sender, OpenIdEventArgs e)
{
// HACK: logic to retrieve admins is duplicated with 'Default.aspx'
var admins = string.Empty;
if (RoleManager.IsRoleManagerRunning)
{
admins = RoleManager.GetConfigurationSetting("Admins");
}
else
{
admins = ConfigurationManager.AppSettings["Admins"];
}
foreach(var admin in admins.Split(new [] {" "}, StringSplitOptions.RemoveEmptyEntries))
{
if(e.ClaimedIdentifier == admin)
{
return;
}
}
// if the user isn't listed as an administrator, cancel the login
e.Cancel = true;
}
}
}
| bsd-3-clause | C# |
f64d7e66b9d7ef3535848c4a37eca73efbe19466 | Simplify expression | appharbor/appharbor-cli | src/AppHarbor.Tests/CommandDispatcherTest.cs | src/AppHarbor.Tests/CommandDispatcherTest.cs | using System;
using System.Linq;
using Castle.MicroKernel;
using Moq;
using Ploeh.AutoFixture.Xunit;
using Xunit.Extensions;
namespace AppHarbor.Tests
{
public class CommandDispatcherTest
{
private static Type FooCommandType = typeof(FooCommand);
public class FooCommand : ICommand
{
public virtual void Execute(string[] arguments)
{
}
}
[Theory, AutoCommandData]
public void ShouldDispatchHelpWhenNoCommand(
[Frozen]Mock<ITypeNameMatcher> typeNameMatcher,
[Frozen]Mock<IKernel> kernel,
Mock<FooCommand> command,
CommandDispatcher commandDispatcher)
{
typeNameMatcher.Setup(x => x.GetMatchedType("help")).Returns(FooCommandType);
kernel.Setup(x => x.Resolve(FooCommandType)).Returns(command.Object);
commandDispatcher.Dispatch(new string[0]);
typeNameMatcher.VerifyAll();
}
[Theory]
[InlineAutoCommandData("foo")]
[InlineAutoCommandData("foo:bar")]
public void ShouldDispatchCommandWithoutParameters(
string argument,
[Frozen]Mock<ITypeNameMatcher> typeNameMatcher,
[Frozen]Mock<IKernel> kernel,
Mock<FooCommand> command,
CommandDispatcher commandDispatcher)
{
typeNameMatcher.Setup(x => x.GetMatchedType(argument)).Returns(FooCommandType);
kernel.Setup(x => x.Resolve(FooCommandType)).Returns(command.Object);
commandDispatcher.Dispatch(new string[] { argument });
command.Verify(x => x.Execute(It.Is<string[]>(y => !y.Any())));
}
[Theory]
[InlineAutoCommandData("foo:bar baz", "baz")]
[InlineAutoCommandData("foo baz", "baz")]
public void ShouldDispatchCommandWithParameter(
string argument,
string commandArgument,
[Frozen]Mock<ITypeNameMatcher> typeNameMatcher,
[Frozen]Mock<IKernel> kernel,
Mock<FooCommand> command,
CommandDispatcher commandDispatcher)
{
typeNameMatcher.Setup(x => x.GetMatchedType(argument.Split().First())).Returns(FooCommandType);
kernel.Setup(x => x.Resolve(FooCommandType)).Returns(command.Object);
commandDispatcher.Dispatch(argument.Split());
command.Verify(x => x.Execute(It.Is<string[]>(y => y.Length == 1 && y.Any(z => z == commandArgument))));
}
}
}
| using System;
using System.Linq;
using Castle.MicroKernel;
using Moq;
using Ploeh.AutoFixture.Xunit;
using Xunit.Extensions;
namespace AppHarbor.Tests
{
public class CommandDispatcherTest
{
private static Type FooCommandType = typeof(FooCommand);
public class FooCommand : ICommand
{
public virtual void Execute(string[] arguments)
{
}
}
[Theory, AutoCommandData]
public void ShouldDispatchHelpWhenNoCommand(
[Frozen]Mock<ITypeNameMatcher> typeNameMatcher,
[Frozen]Mock<IKernel> kernel,
Mock<FooCommand> command,
CommandDispatcher commandDispatcher)
{
typeNameMatcher.Setup(x => x.GetMatchedType("help")).Returns(FooCommandType);
kernel.Setup(x => x.Resolve(FooCommandType)).Returns(command.Object);
commandDispatcher.Dispatch(new string[0]);
typeNameMatcher.VerifyAll();
}
[Theory]
[InlineAutoCommandData("foo")]
[InlineAutoCommandData("foo:bar")]
public void ShouldDispatchCommandWithoutParameters(
string argument,
[Frozen]Mock<ITypeNameMatcher> typeNameMatcher,
[Frozen]Mock<IKernel> kernel,
Mock<FooCommand> command,
CommandDispatcher commandDispatcher)
{
typeNameMatcher.Setup(x => x.GetMatchedType(argument)).Returns(FooCommandType);
kernel.Setup(x => x.Resolve(FooCommandType)).Returns(command.Object);
var dispatchArguments = new string[] { argument };
commandDispatcher.Dispatch(dispatchArguments);
command.Verify(x => x.Execute(It.Is<string[]>(y => !y.Any())));
}
[Theory]
[InlineAutoCommandData("foo:bar baz", "baz")]
[InlineAutoCommandData("foo baz", "baz")]
public void ShouldDispatchCommandWithParameter(
string argument,
string commandArgument,
[Frozen]Mock<ITypeNameMatcher> typeNameMatcher,
[Frozen]Mock<IKernel> kernel,
Mock<FooCommand> command,
CommandDispatcher commandDispatcher)
{
typeNameMatcher.Setup(x => x.GetMatchedType(argument.Split().First())).Returns(FooCommandType);
kernel.Setup(x => x.Resolve(FooCommandType)).Returns(command.Object);
commandDispatcher.Dispatch(argument.Split());
command.Verify(x => x.Execute(It.Is<string[]>(y => y.Length == 1 && y.Any(z => z == commandArgument))));
}
}
}
| mit | C# |
1996f41574aebfafa0c732a524af76a35e1e802e | fix release build | Fody/Fielder | Tests/CheckForErrors.cs | Tests/CheckForErrors.cs | using System.Collections.Generic;
using System.IO;
using Mono.Cecil;
using NUnit.Framework;
[TestFixture]
public class CheckForErrors
{
[Test]
public void VerifyRefError()
{
var errors = new List<string>();
var assemblyPath = Path.GetFullPath(@"..\..\..\AssemblyToProcessWithErrors\bin\Debug\AssemblyToProcessWithErrors.dll");
#if (!DEBUG)
assemblyPath = assemblyPath.Replace("Debug", "Release");
#endif
var moduleDefinition = ModuleDefinition.ReadModule(assemblyPath);
var weavingTask = new ModuleWeaver
{
ModuleDefinition = moduleDefinition,
LogError = s => errors.Add(s)
};
weavingTask.Execute();
Assert.Contains("Method 'ClassUsingOutParam.Method' uses member 'ClassWithField.Member' as a 'ref' or 'out' parameter. This is not supported by Fielder. Please convert this field to a property manually.", errors);
Assert.Contains("Method 'ClassUsingRefParam.Method' uses member 'ClassWithField.Member' as a 'ref' or 'out' parameter. This is not supported by Fielder. Please convert this field to a property manually.", errors);
Assert.AreEqual(2, errors.Count);
}
}
| using System.Collections.Generic;
using System.IO;
using Mono.Cecil;
using NUnit.Framework;
[TestFixture]
public class CheckForErrors
{
[Test]
public void VerifyRefError()
{
var errors = new List<string>();
var assemblyPath = Path.GetFullPath(@"..\..\..\AssemblyToProcessWithErrors\bin\Debug\AssemblyToProcessWithErrors.dll");
#if (!DEBUG)
assemblyPath = beforeAssemblyPath.Replace("Debug", "Release");
#endif
var moduleDefinition = ModuleDefinition.ReadModule(assemblyPath);
var weavingTask = new ModuleWeaver
{
ModuleDefinition = moduleDefinition,
LogError = s => errors.Add(s)
};
weavingTask.Execute();
Assert.Contains("Method 'ClassUsingOutParam.Method' uses member 'ClassWithField.Member' as a 'ref' or 'out' parameter. This is not supported by Fielder. Please convert this field to a property manually.", errors);
Assert.Contains("Method 'ClassUsingRefParam.Method' uses member 'ClassWithField.Member' as a 'ref' or 'out' parameter. This is not supported by Fielder. Please convert this field to a property manually.", errors);
Assert.AreEqual(2, errors.Count);
}
}
| mit | C# |
76e379198d9bcd302065e563843dbe351ef61103 | remove array | Appleseed/base,Appleseed/base | Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/SolrResponseItem.cs | Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/SolrResponseItem.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Appleseed.Base.Alerts.Model
{
class SolrResponseItem
{
public string id { get; set; }
public string item_type { get; set; }
public string address_1 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string classification { get; set; }
public string country { get; set; }
public string postal_code { get; set; }
public string product_description { get; set; }
public string[] product_quantity { get; set; }
public string[] product_type { get; set; }
public string[] code_info { get; set; }
public string[] reason_for_recall { get; set; }
public DateTime recall_initiation_date { get; set; }
public string[] recall_number { get; set; }
public string recalling_firm { get; set; }
public string[] voluntary_mandated { get; set; }
public DateTime report_date { get; set; }
public string[] status { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Appleseed.Base.Alerts.Model
{
class SolrResponseItem
{
public string id { get; set; }
public string item_type { get; set; }
public string address_1 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string classification { get; set; }
public string country { get; set; }
public string postal_code { get; set; }
public string[] product_description { get; set; }
public string[] product_quantity { get; set; }
public string[] product_type { get; set; }
public string[] code_info { get; set; }
public string[] reason_for_recall { get; set; }
public DateTime recall_initiation_date { get; set; }
public string[] recall_number { get; set; }
public string recalling_firm { get; set; }
public string[] voluntary_mandated { get; set; }
public DateTime report_date { get; set; }
public string[] status { get; set; }
}
}
| apache-2.0 | C# |
312723dbba83669dfda24bb5e07829adaa4c7cac | Update Extensions to include new Functions for finding specific types of IVNodes in IEnumerables | BenVlodgi/VMFParser | VMFParser/Extensions.cs | VMFParser/Extensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace VMFParser
{
public static class Extensions
{
/// <summary>Returns a new array from given index with the specified length. </summary>
public static T[] SubArray<T>(this T[] data, int index, int length)
{
T[] result = new T[length];
Array.Copy(data, index, result, 0, length);
return result;
}
/// <summary> Returns first <see cref="VBlock"/> in list. </summary>
public static VBlock VBlock(this IEnumerable<IVNode> body)
{
return body.WhereClass<VBlock>().FirstOrDefault();
}
/// <summary> Returns first <see cref="VBlock"/> in list that matches the predicate. </summary>
public static VBlock VBlock(this IEnumerable<IVNode> body, Func<VBlock,bool> predicate)
{
return body.WhereClass<VBlock>().FirstOrDefault(predicate);
}
/// <summary> Returns first <see cref="VProperty"/> in list. </summary>
public static VProperty VProperty(this IEnumerable<IVNode> body)
{
return body.WhereClass<VProperty>().FirstOrDefault();
}
/// <summary> Returns first <see cref="VProperty"/> in list that matches the predicate. </summary>
public static VProperty VProperty(this IEnumerable<IVNode> body, Func<VProperty, bool> predicate)
{
return body.WhereClass<VProperty>().FirstOrDefault(predicate);
}
/// <summary> Returns given list, with values cast to given type, nulls are removed. </summary>
/// <typeparam name="AsType">Type all values will be cast to. </typeparam>
public static IEnumerable<AsType> WhereClass<AsType>(this IEnumerable<object> data) where AsType : class
{
return data.Where(d => d as AsType != null).Cast<AsType>();
}
}
}
| using System;
namespace VMFParser
{
public static class Extensions
{
/// <summary>Returns a new array from given index with the specified length. </summary>
public static T[] SubArray<T>(this T[] data, int index, int length)
{
T[] result = new T[length];
Array.Copy(data, index, result, 0, length);
return result;
}
}
}
| mit | C# |
94374f952997ba8d7efaa091796c70cbfadb8566 | Bump version to 0.6.2 | ar3cka/Journalist | src/SolutionInfo.cs | src/SolutionInfo.cs | // <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.6.2")]
[assembly: AssemblyInformationalVersionAttribute("0.6.2")]
[assembly: AssemblyFileVersionAttribute("0.6.2")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.6.2";
}
}
| // <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.6.1")]
[assembly: AssemblyInformationalVersionAttribute("0.6.1")]
[assembly: AssemblyFileVersionAttribute("0.6.1")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.6.1";
}
}
| apache-2.0 | C# |
a68383a1b0f1c67ed2d449f1d99a8f6389806454 | Bump version to 0.14.0 | ar3cka/Journalist | src/SolutionInfo.cs | src/SolutionInfo.cs | // <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.14.0")]
[assembly: AssemblyInformationalVersionAttribute("0.14.0")]
[assembly: AssemblyFileVersionAttribute("0.14.0")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.14.0";
}
}
| // <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.13.6")]
[assembly: AssemblyInformationalVersionAttribute("0.13.6")]
[assembly: AssemblyFileVersionAttribute("0.13.6")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.13.6";
}
}
| apache-2.0 | C# |
d4ac9cd58fd5ead806ea3a6d229b20e41e51aabd | Add properties for tracked data | sakapon/Samples-2016,sakapon/Samples-2016 | Wpf3DSample/DiceOrientationWpf/AppModel.cs | Wpf3DSample/DiceOrientationWpf/AppModel.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using System.Windows.Media.Media3D;
using Reactive.Bindings;
using Windows.Devices.Sensors;
namespace DiceOrientationWpf
{
public class AppModel
{
public Transform3D CubeTransform { get; }
MatrixTransform3D matrixTransform = new MatrixTransform3D();
public ReactiveProperty<InclinometerReading> InclinationData { get; } = new ReactiveProperty<InclinometerReading>(mode: ReactivePropertyMode.None);
public ReactiveProperty<OrientationSensorReading> OrientationData { get; } = new ReactiveProperty<OrientationSensorReading>(mode: ReactivePropertyMode.None);
public ReadOnlyReactiveProperty<Quaternion> RotationQuaternion { get; }
public ReadOnlyReactiveProperty<string> RotationQuaternionString { get; }
public ReadOnlyReactiveProperty<Matrix3D> RotationMatrix { get; }
public AppModel()
{
CubeTransform = InitializeCubeTransform();
var inclinometer = Inclinometer.GetDefault();
if (inclinometer != null)
{
inclinometer.ReportInterval = 200;
inclinometer.ReadingChanged += (o, e) => InclinationData.Value = e.Reading;
}
var orientationSensor = OrientationSensor.GetDefault();
if (orientationSensor != null)
{
orientationSensor.ReportInterval = 200;
orientationSensor.ReadingChanged += (o, e) => OrientationData.Value = e.Reading;
}
RotationQuaternion = OrientationData.Select(d => d.Quaternion.ToQuaternion()).ToReadOnlyReactiveProperty();
RotationQuaternionString = RotationQuaternion.Select(q => $"{q.W:F2}; ({q.X:F2}, {q.Y:F2}, {q.Z:F2})").ToReadOnlyReactiveProperty();
RotationMatrix = OrientationData.Select(d => d.RotationMatrix.ToMatrix3D()).ToReadOnlyReactiveProperty();
}
Transform3D InitializeCubeTransform()
{
var transform = new Transform3DGroup();
transform.Children.Add(matrixTransform);
return transform;
}
}
public static class SensorsHelper
{
public static Matrix3D ToMatrix3D(this SensorRotationMatrix m) =>
new Matrix3D(m.M11, m.M21, m.M31, 0, m.M12, m.M22, m.M32, 0, m.M13, m.M23, m.M33, 0, 0, 0, 0, 1);
public static Quaternion ToQuaternion(this SensorQuaternion q) =>
new Quaternion(q.X, q.Y, q.Z, q.W);
public static Matrix3D Transpose(this Matrix3D m) =>
new Matrix3D(m.M11, m.M21, m.M31, m.M14, m.M12, m.M22, m.M32, m.M24, m.M13, m.M23, m.M33, m.M34, m.OffsetX, m.OffsetY, m.OffsetZ, m.M44);
public static Matrix3D ToMatrix3D(this Quaternion q)
{
var m = new Matrix3D();
m.Rotate(q);
return m;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using System.Windows.Media.Media3D;
using Reactive.Bindings;
using Windows.Devices.Sensors;
namespace DiceOrientationWpf
{
public class AppModel
{
public Transform3D CubeTransform { get; }
MatrixTransform3D matrixTransform = new MatrixTransform3D();
public AppModel()
{
CubeTransform = InitializeCubeTransform();
}
Transform3D InitializeCubeTransform()
{
var transform = new Transform3DGroup();
transform.Children.Add(matrixTransform);
return transform;
}
}
}
| mit | C# |
f4a9801e2d94015d4cbbb86f42981a95db6fe5f8 | Use debug verbosity by default instead of info, since console now scales to it | kamsar/Unicorn,kamsar/Unicorn | src/Unicorn/ControlPanel/Controls/Heading.cs | src/Unicorn/ControlPanel/Controls/Heading.cs | using System.Web.UI;
using Unicorn.ControlPanel.Headings;
using Unicorn.Data.Dilithium;
namespace Unicorn.ControlPanel.Controls
{
internal class Heading : IControlPanelControl
{
private readonly bool _isAuthenticated;
public Heading(bool isAuthenticated)
{
_isAuthenticated = isAuthenticated;
}
public void Render(HtmlTextWriter writer)
{
writer.Write(new HeadingService().GetControlPanelHeadingHtml());
if (_isAuthenticated)
{
writer.Write($"<p class=\"version\">Version {UnicornVersion.Current} | <a href=\"#\" data-modal=\"options\">Options</a></p>");
if (ReactorContext.IsActive)
{
writer.Write(@"<p class=""warning"">Dilithium cache context is active. <br><br>
Do not sync any Dilithium configurations until the cache has released from the other sync or reserialize operation.
If this remains visible and no operations are in progress this may indicate a bug in Unicorn;
report what you did right before this in an issue on GitHub and then restart your app pool to clear.</p>");
}
writer.Write(@"<div class=""overlay"" id=""options"">
<article class=""modal"">
<label for=""verbosity"">Sync/reserialize console verbosity</label>
<select id=""verbosity"">
<option value=""Debug"" selected>Items synced + detailed info</option>
<option value=""Info"">Items synced</option>
<option value=""Warning"">Warnings and errors only</option>
<option value=""Error"">Errors only</option>
</select>
<br>
<p class=""help"">Use lower verbosity when expecting many changes to avoid slowing down the browser.<br>Log files always get full verbosity.</p>
<p>
<input type=""checkbox"" id=""skipTransparent"" value=""1"">
<label for=""skipTransparent"">When syncing multiple configurations, skip configurations using Transparent Sync</label>
<br>
</p>
<p class=""help"">Skipping transparent sync configurations can make your development synchronizations faster.</p>
<p class=""help""><strong>Note:</strong> Changes are saved immediately.</p>
<p><a class=""button"" onclick=""$('.overlay').trigger('hide'); return false;"">Close</a></p>
</div>");
}
}
}
}
| using System.Web.UI;
using Unicorn.ControlPanel.Headings;
using Unicorn.Data.Dilithium;
namespace Unicorn.ControlPanel.Controls
{
internal class Heading : IControlPanelControl
{
private readonly bool _isAuthenticated;
public Heading(bool isAuthenticated)
{
_isAuthenticated = isAuthenticated;
}
public void Render(HtmlTextWriter writer)
{
writer.Write(new HeadingService().GetControlPanelHeadingHtml());
if (_isAuthenticated)
{
writer.Write($"<p class=\"version\">Version {UnicornVersion.Current} | <a href=\"#\" data-modal=\"options\">Options</a></p>");
if (ReactorContext.IsActive)
{
writer.Write(@"<p class=""warning"">Dilithium cache context is active. <br><br>
Do not sync any Dilithium configurations until the cache has released from the other sync or reserialize operation.
If this remains visible and no operations are in progress this may indicate a bug in Unicorn;
report what you did right before this in an issue on GitHub and then restart your app pool to clear.</p>");
}
writer.Write(@"<div class=""overlay"" id=""options"">
<article class=""modal"">
<label for=""verbosity"">Sync/reserialize console verbosity</label>
<select id=""verbosity"">
<option value=""Debug"">Items synced + detailed info</option>
<option value=""Info"" selected>Items synced</option>
<option value=""Warning"">Warnings and errors only</option>
<option value=""Error"">Errors only</option>
</select>
<br>
<p class=""help"">Use lower verbosity when expecting many changes to avoid slowing down the browser.<br>Log files always get full verbosity.</p>
<p>
<input type=""checkbox"" id=""skipTransparent"" value=""1"">
<label for=""skipTransparent"">When syncing multiple configurations, skip configurations using Transparent Sync</label>
<br>
</p>
<p class=""help"">Skipping transparent sync configurations can make your development synchronizations faster.</p>
<p class=""help""><strong>Note:</strong> Changes are saved immediately.</p>
<p><a class=""button"" onclick=""$('.overlay').trigger('hide'); return false;"">Close</a></p>
</div>");
}
}
}
}
| mit | C# |
3ba7426e0f3be1695f97fc99dee6e9593d13b13c | Remove obsolete ifdefs and property | Xablu/Xablu.WebApiClient | src/Xablu.WebApiClient/CrossRestApiClient.cs | src/Xablu.WebApiClient/CrossRestApiClient.cs | using System;
using Xablu.WebApiClient.Exceptions;
namespace Xablu.WebApiClient
{
public class CrossRestApiClient
{
private static Action<RestApiClientOptions> _configureRestApiClient;
private static Lazy<IRestApiClient> _restApiClientImplementation = new Lazy<IRestApiClient>(() => CreateRestApiClient(), System.Threading.LazyThreadSafetyMode.PublicationOnly);
public static void Configure(Action<RestApiClientOptions> options)
{
_configureRestApiClient = options;
}
public static IRestApiClient Current
{
get
{
var ret = _restApiClientImplementation.Value;
if (ret == null)
{
throw NotImplementedInReferenceAssembly();
}
return ret;
}
}
private static IRestApiClient CreateRestApiClient()
{
if (_configureRestApiClient == null)
throw NotConfiguredException();
var options = new RestApiClientOptions();
_configureRestApiClient.Invoke(options);
return new RestApiClientImplementation(options);
}
internal static Exception NotImplementedInReferenceAssembly() =>
new NotImplementedException("This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.");
internal static Exception NotConfiguredException() =>
new NotConfiguredException("The `CrossRestApiClient` has not been configured. Make sure you call the `CrossRestApiClient.Configure` method before accessing the `CrossRestApiClient.Current` property.");
}
}
| using System;
using Xablu.WebApiClient.Exceptions;
namespace Xablu.WebApiClient
{
public class CrossRestApiClient
{
private static Action<RestApiClientOptions> _configureRestApiClient;
private static Lazy<IRestApiClient> _restApiClientImplementation = new Lazy<IRestApiClient>(() => CreateRestApiClient(), System.Threading.LazyThreadSafetyMode.PublicationOnly);
public static bool IsSupported => _restApiClientImplementation.Value == null ? false : true;
public static void Configure(Action<RestApiClientOptions> options)
{
_configureRestApiClient = options;
}
public static IRestApiClient Current
{
get
{
var ret = _restApiClientImplementation.Value;
if (ret == null)
{
throw NotImplementedInReferenceAssembly();
}
return ret;
}
}
private static IRestApiClient CreateRestApiClient()
{
#if NETSTANDARD2_0
return null;
#else
if (_configureRestApiClient == null)
throw NotConfiguredException();
var options = new RestApiClientOptions();
_configureRestApiClient.Invoke(options);
return new RestApiClientImplementation(options);
#endif
}
internal static Exception NotImplementedInReferenceAssembly() =>
new NotImplementedException("This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.");
internal static Exception NotConfiguredException() =>
new NotConfiguredException("The `CrossRestApiClient` has not been configured. Make sure you call the `CrossRestApiClient.Configure` method before accessing the `CrossRestApiClient.Current` property.");
}
}
| mit | C# |
0394d27ae17f8e30e660ba4a5cce1176957f0a7c | Update assembly copyright | mminns/xwt,hamekoz/xwt,iainx/xwt,sevoku/xwt,mono/xwt,TheBrainTech/xwt,steffenWi/xwt,akrisiun/xwt,directhex/xwt,cra0zy/xwt,antmicro/xwt,lytico/xwt,residuum/xwt,hwthomas/xwt,mminns/xwt | Xwt.WPF/AssemblyInfo.cs | Xwt.WPF/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Xwt.WPF")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Copyright (c) XWT Contributors, 2011-2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.0.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Xwt.WPF")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Carlos Alberto Cortez 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.0.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| mit | C# |
6108e0e84a36db8963ac5ae9dc6bb0d671a281aa | fix registration for UnityCodeInsight Higlighting | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | resharper/resharper-unity/src/Rider/CodeInsights/UnityInspectorCodeInsightsHighlighting.cs | resharper/resharper-unity/src/Rider/CodeInsights/UnityInspectorCodeInsightsHighlighting.cs | using JetBrains.Annotations;
using JetBrains.DocumentModel;
using JetBrains.ReSharper.Daemon.CodeInsights;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Stages.Highlightings;
using JetBrains.ReSharper.Psi;
using JetBrains.Rider.Model;
using JetBrains.TextControl.DocumentMarkup;
using Severity = JetBrains.ReSharper.Feature.Services.Daemon.Severity;
namespace JetBrains.ReSharper.Plugins.Unity.Rider.CodeInsights
{
[
RegisterHighlighter(
Id,
GroupId = HighlighterGroupIds.HIDDEN,
Layer = HighlighterLayer.SYNTAX + 1,
EffectType = EffectType.NONE,
NotRecyclable = false,
TransmitUpdates = true
)
]
[StaticSeverityHighlighting(
Severity.INFO,
typeof(HighlightingGroupIds.CodeInsights),
AttributeId = Id,
OverlapResolve = OverlapResolveKind.NONE
)]
public class UnityInspectorCodeInsightsHighlighting : CodeInsightsHighlighting, IUnityHighlighting
{
public new const string Id = "UnityInspectorCodeInsights";
public readonly UnityCodeInsightFieldUsageProvider.UnityPresentationType UnityPresentationType;
public UnityInspectorCodeInsightsHighlighting(DocumentRange range, [NotNull] string lenText, string tooltipText, [NotNull] string moreText,
[NotNull] ICodeInsightsProvider provider, IDeclaredElement element,
[CanBeNull] IconModel icon, UnityCodeInsightFieldUsageProvider.UnityPresentationType unityPresentationType)
: base(range, lenText, tooltipText, moreText, provider, element, icon)
{
UnityPresentationType = unityPresentationType;
}
}
} | using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using JetBrains.Application.UI.Controls.BulbMenu.Items;
using JetBrains.DocumentModel;
using JetBrains.ReSharper.Daemon.CodeInsights;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Stages.Highlightings;
using JetBrains.ReSharper.Plugins.Unity.Rider.CodeInsights;
using JetBrains.ReSharper.Psi;
using JetBrains.Rider.Model;
using JetBrains.TextControl.DocumentMarkup;
using Severity = JetBrains.ReSharper.Feature.Services.Daemon.Severity;
[assembly: RegisterHighlighter(UnityInspectorCodeInsightsHighlighting.Id, EffectType = EffectType.NONE,
Layer = HighlighterLayer.SYNTAX + 1, NotRecyclable = true, GroupId = HighlighterGroupIds.HIDDEN, TransmitUpdates = true)]
namespace JetBrains.ReSharper.Plugins.Unity.Rider.CodeInsights
{
[StaticSeverityHighlighting(Severity.INFO, HighlightingGroupIds.CodeInsightsGroup, AttributeId = Id,
OverlapResolve = OverlapResolveKind.NONE)]
public class UnityInspectorCodeInsightsHighlighting : CodeInsightsHighlighting, IUnityHighlighting
{
public const string Id = "UnityInspectorCodeInsights";
public readonly UnityCodeInsightFieldUsageProvider.UnityPresentationType UnityPresentationType;
public UnityInspectorCodeInsightsHighlighting(DocumentRange range, [NotNull] string lenText, string tooltipText, [NotNull] string moreText,
[NotNull] ICodeInsightsProvider provider, IDeclaredElement element,
[CanBeNull] IconModel icon, UnityCodeInsightFieldUsageProvider.UnityPresentationType unityPresentationType)
: base(range, lenText, tooltipText, moreText, provider, element, icon)
{
UnityPresentationType = unityPresentationType;
}
}
} | apache-2.0 | C# |
bb706e0aef53188c2deb41bc9135d75f77b998d1 | Fix installments to use the correct type | stripe/stripe-dotnet | src/Stripe.net/Entities/PaymentIntents/PaymentIntentPaymentMethodOptionsCard.cs | src/Stripe.net/Entities/PaymentIntents/PaymentIntentPaymentMethodOptionsCard.cs | namespace Stripe
{
using System;
using Newtonsoft.Json;
using Stripe.Infrastructure;
public class PaymentIntentPaymentMethodOptionsCard : StripeEntity<PaymentIntentPaymentMethodOptionsCard>
{
/// <summary>
/// Installment details for this payment (Mexico only).
/// </summary>
[JsonProperty("installments")]
public PaymentIntentPaymentMethodOptionsCardInstallments Installments { get; set; }
/// <summary>
/// We strongly recommend that you rely on our SCA engine to automatically prompt your
/// customers for authentication based on risk level and other requirements. However, if
/// you wish to request authentication based on logic from your own fraud engine, provide
/// this option. Permitted values include: <c>automatic</c>, <c>any</c>, or
/// <c>challenge_only</c>.
/// </summary>
[JsonProperty("request_three_d_secure")]
public string RequestThreeDSecure { get; set; }
}
}
| namespace Stripe
{
using System;
using Newtonsoft.Json;
using Stripe.Infrastructure;
public class PaymentIntentPaymentMethodOptionsCard : StripeEntity<PaymentIntentPaymentMethodOptionsCard>
{
/// <summary>
/// Installment details for this payment (Mexico only).
/// </summary>
[JsonProperty("installments")]
public string Installments { get; set; }
/// <summary>
/// We strongly recommend that you rely on our SCA engine to automatically prompt your
/// customers for authentication based on risk level and other requirements. However, if
/// you wish to request authentication based on logic from your own fraud engine, provide
/// this option. Permitted values include: <c>automatic</c>, <c>any</c>, or
/// <c>challenge_only</c>.
/// </summary>
[JsonProperty("request_three_d_secure")]
public string RequestThreeDSecure { get; set; }
}
}
| apache-2.0 | C# |
56975f3675121702a2c6437b7881a6004cc1bab0 | Update Index.cshtml | swcurran/hets,bcgov/hets,swcurran/hets,swcurran/hets,swcurran/hets,bcgov/hets,bcgov/hets,bcgov/hets,swcurran/hets,asanchezr/hets,asanchezr/hets,asanchezr/hets,asanchezr/hets | PDF/src/PDF.Server/Views/Home/Index.cshtml | PDF/src/PDF.Server/Views/Home/Index.cshtml | @{ViewBag.Title = "PDFAPI - Api Home";}<!DOCTYPE html><html><head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"]</title> <style> body { background-color: #fff; padding: 10px; font-family: Verdana, Geneva, sans-serif; font-size: 12pt; } </style> </head><body><h2>@ViewData["Title"]</h2><hr />
@if (Model.DevelopmentEnvironment){<div> <h3>View HETS API</h3> <a href="~/swagger/ui/index.html">Swagger</a></div> }
</body></html>
| temp
| apache-2.0 | C# |
63128c9465669cda7e699d608cc33aeb46b8c844 | Extend mouse hiding in catch to include catcher area | UselessToucan/osu,johnneijzen/osu,ppy/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,EVAST9919/osu,smoogipooo/osu,UselessToucan/osu,2yangk23/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,ppy/osu,johnneijzen/osu,peppy/osu,smoogipoo/osu,2yangk23/osu,NeoAdonis/osu,peppy/osu-new,EVAST9919/osu | osu.Game.Rulesets.Catch/UI/CatchPlayfield.cs | osu.Game.Rulesets.Catch/UI/CatchPlayfield.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Catch.Objects.Drawable;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.UI.Scrolling;
using osuTK;
namespace osu.Game.Rulesets.Catch.UI
{
public class CatchPlayfield : ScrollingPlayfield
{
public const float BASE_WIDTH = 512;
internal readonly CatcherArea CatcherArea;
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => base.ReceivePositionalInputAt(screenSpacePos) || CatcherArea.ReceivePositionalInputAt(screenSpacePos);
public CatchPlayfield(BeatmapDifficulty difficulty, Func<CatchHitObject, DrawableHitObject<CatchHitObject>> createDrawableRepresentation)
{
Container explodingFruitContainer;
InternalChildren = new Drawable[]
{
explodingFruitContainer = new Container
{
RelativeSizeAxes = Axes.Both,
},
CatcherArea = new CatcherArea(difficulty)
{
CreateDrawableRepresentation = createDrawableRepresentation,
ExplodingFruitTarget = explodingFruitContainer,
Anchor = Anchor.BottomLeft,
Origin = Anchor.TopLeft,
},
HitObjectContainer
};
}
public bool CheckIfWeCanCatch(CatchHitObject obj) => CatcherArea.AttemptCatch(obj);
public override void Add(DrawableHitObject h)
{
h.OnNewResult += onNewResult;
base.Add(h);
var fruit = (DrawableCatchHitObject)h;
fruit.CheckPosition = CheckIfWeCanCatch;
}
private void onNewResult(DrawableHitObject judgedObject, JudgementResult result)
=> CatcherArea.OnResult((DrawableCatchHitObject)judgedObject, result);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Catch.Objects.Drawable;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.UI.Scrolling;
namespace osu.Game.Rulesets.Catch.UI
{
public class CatchPlayfield : ScrollingPlayfield
{
public const float BASE_WIDTH = 512;
internal readonly CatcherArea CatcherArea;
public CatchPlayfield(BeatmapDifficulty difficulty, Func<CatchHitObject, DrawableHitObject<CatchHitObject>> createDrawableRepresentation)
{
Container explodingFruitContainer;
InternalChildren = new Drawable[]
{
explodingFruitContainer = new Container
{
RelativeSizeAxes = Axes.Both,
},
CatcherArea = new CatcherArea(difficulty)
{
CreateDrawableRepresentation = createDrawableRepresentation,
ExplodingFruitTarget = explodingFruitContainer,
Anchor = Anchor.BottomLeft,
Origin = Anchor.TopLeft,
},
HitObjectContainer
};
}
public bool CheckIfWeCanCatch(CatchHitObject obj) => CatcherArea.AttemptCatch(obj);
public override void Add(DrawableHitObject h)
{
h.OnNewResult += onNewResult;
base.Add(h);
var fruit = (DrawableCatchHitObject)h;
fruit.CheckPosition = CheckIfWeCanCatch;
}
private void onNewResult(DrawableHitObject judgedObject, JudgementResult result)
=> CatcherArea.OnResult((DrawableCatchHitObject)judgedObject, result);
}
}
| mit | C# |
8e7c16e8e8690378f4f8484911d49b1ab8916360 | Add namespace to Utils. | Zonr0/SealsOfFate,legitbiz/SealsOfFate,connorkuehl/SealsOfFate | Assets/Scripts/LevelGeneration/FeatureOption.cs | Assets/Scripts/LevelGeneration/FeatureOption.cs | using System;
using Utility;
/// <summary>
/// The "rule book" for level generation. This class serves as a reference
/// for the level; a range of chunks to generate (at least and at most),
/// as well as weights for how richly populated certain feature representations
/// are (walls, enemies, loot, etc.)
///</summary>
public class FeatureOption {
/// <summary>The default minimum number of chunks a level should enforcably generate.</summary>
private const int MIN_CHUNKS = 30;
/// <summary>The default maximum number of chunks a level should enforcably generate.</summary>
private const int DEFAULT_MAX_CHUNKS = 50;
/// <summary>A value [0.0, 1.0] that weighs the calculation of how many of these decorations to place.</summary>
/// <remarks>
/// For example, FeatureWeights[levelRepresentations.Loot] can be adjusted to
/// (in/de)crease loot for the whole level.
/// </remarks>
public float[] FeatureWeights { get; private set; }
/// <summary>The minimum and maximum number of chunks to generate.</summary>
public Range Chunks { get; private set; }
/// <summary>Enforces a generateable level.</summary>
/// <param name="chunksToMake">
/// Default argument parameter enforces a level with sane defaults, but a
/// value should be provided to this nonetheless.
/// </param>
public FeatureOption(Range chunksToMake = new Range(DEFAULT_MAX_CHUNKS, MIN_CHUNKS)) {
FeatureWeights = new float[levelRepresentations.TOTAL];
Chunks = chunksToMake;
}
/// <summary>Sets the specified weight to the given value.</summary>
/// <param name="rep">The enum to target.</param>
/// <param name="weight">A decimal value in the interval [0.0, 1.0] to set as a weight.</param>
public FeatureOption SetWeight(levelRepresentations rep, float weight) {
if (weight >= 0.0 && weight <= 1.0) {
FeatureWeights[rep] = weight;
}
return this;
}
}
| using System;
/// <summary>
/// The "rule book" for level generation. This class serves as a reference
/// for the level; a range of chunks to generate (at least and at most),
/// as well as weights for how richly populated certain feature representations
/// are (walls, enemies, loot, etc.)
///</summary>
public class FeatureOption {
/// <summary>The default minimum number of chunks a level should enforcably generate.</summary>
private const int MIN_CHUNKS = 30;
/// <summary>The default maximum number of chunks a level should enforcably generate.</summary>
private const int DEFAULT_MAX_CHUNKS = 50;
/// <summary>A value [0.0, 1.0] that weighs the calculation of how many of these decorations to place.</summary>
/// <remarks>
/// For example, FeatureWeights[levelRepresentations.Loot] can be adjusted to
/// (in/de)crease loot for the whole level.
/// </remarks>
public float[] FeatureWeights { get; private set; }
/// <summary>The minimum and maximum number of chunks to generate.</summary>
public Range Chunks { get; private set; }
/// <summary>Enforces a generateable level.</summary>
/// <param name="chunksToMake">
/// Default argument parameter enforces a level with sane defaults, but a
/// value should be provided to this nonetheless.
/// </param>
public FeatureOption(Range chunksToMake = new Range(DEFAULT_MAX_CHUNKS, MIN_CHUNKS)) {
FeatureWeights = new float[levelRepresentations.TOTAL];
Chunks = chunksToMake;
}
/// <summary>Sets the specified weight to the given value.</summary>
/// <param name="rep">The enum to target.</param>
/// <param name="weight">A decimal value in the interval [0.0, 1.0] to set as a weight.</param>
public FeatureOption SetWeight(levelRepresentations rep, float weight) {
if (weight >= 0.0 && weight <= 1.0) {
FeatureWeights[rep] = weight;
}
return this;
}
}
| mit | C# |
31fe257ec85d7fa7ad25f997b0491daac4c6c0fe | test clear the cache for the LockingInMemoryCache | modulexcite/lokad-cqrs | Cqrs.Portable.Tests/TapeStorage/LockingInMemoryCacheTests/when_clearing_cache.cs | Cqrs.Portable.Tests/TapeStorage/LockingInMemoryCacheTests/when_clearing_cache.cs | using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Lokad.Cqrs;
using Lokad.Cqrs.TapeStorage;
using NUnit.Framework;
namespace Cqrs.Portable.Tests.TapeStorage.LockingInMemoryCacheTests
{
[TestFixture]
public sealed class when_clearing_cache : fixture_with_cache_helpers
{
[Test]
public void given_empty_cache()
{
var cache = new LockingInMemoryCache();
cache.Clear(() => { });
Assert.AreEqual(0, cache.StoreVersion);
}
[Test]
public void given_reloaded_cache()
{
var cache = new LockingInMemoryCache();
cache.ConcurrentAppend("stream1", new byte[1], (version, storeVersion) => { });
Assert.Throws<LockRecursionException>(() => cache.Clear(() =>
cache.LoadHistory(CreateFrames("stream2"))
));
Assert.AreEqual(1, cache.StoreVersion);
Assert.AreEqual("stream1", cache.ReadAll(0, 1).First().Key);
}
[Test]
public void given_appended_cache()
{
var cache = new LockingInMemoryCache();
cache.ConcurrentAppend("stream1", new byte[1], (version, storeVersion) => { });
Assert.Throws<LockRecursionException>(() => cache.Clear(() =>
cache.ConcurrentAppend("stream2", new byte[1], (version, storeVersion) => { })
));
Assert.AreEqual(1, cache.StoreVersion);
Assert.AreEqual("stream1", cache.ReadAll(0, 1).First().Key);
}
[Test]
public void given_filled_cache_and_failing_commit_function()
{
var cache = new LockingInMemoryCache();
cache.ConcurrentAppend("stream1", new byte[1], (version, storeVersion) => { });
Assert.Throws<FileNotFoundException>(() => cache.Clear(() =>
{
throw new FileNotFoundException();
}));
Assert.AreEqual(1, cache.StoreVersion);
}
}
} | using System.IO;
using System.Text;
using Lokad.Cqrs;
using Lokad.Cqrs.TapeStorage;
using NUnit.Framework;
namespace Cqrs.Portable.Tests.TapeStorage.LockingInMemoryCacheTests
{
[TestFixture]
public sealed class when_clearing_cache : fixture_with_cache_helpers
{
[Test]
public void given_empty_cache()
{
var cache = new LockingInMemoryCache();
cache.Clear(() => { });
Assert.AreEqual(0, cache.StoreVersion);
}
[Test]
public void given_reloaded_cache()
{
// TODO: fill this
}
[Test]
public void given_appended_cache()
{
// TODO: fill this
}
[Test]
public void given_filled_cache_and_failing_commit_function()
{
var cache = new LockingInMemoryCache();
cache.ConcurrentAppend("stream1", new byte[1], (version, storeVersion) => { });
Assert.Throws<FileNotFoundException>(() => cache.Clear(() =>
{
throw new FileNotFoundException();
}));
Assert.AreEqual(1, cache.StoreVersion);
}
}
} | bsd-3-clause | C# |
9f5ad8c561e2de8509b0f78896dbc603edb9085a | Update version number. | spacechase0/StardewValleyMP,blommers/StardewValleyMP | StardewValleyMP/Properties/AssemblyInfo.cs | StardewValleyMP/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("StardewValleyMP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("StardewValleyMP")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5ebad6ae-af68-4b31-ac1a-b6d96355dc27")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.8.*")]
[assembly: AssemblyFileVersion("0.1.8.*")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("StardewValleyMP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("StardewValleyMP")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5ebad6ae-af68-4b31-ac1a-b6d96355dc27")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
61c6e661b35a49b2c54e1bcd499079d323d41fc3 | Fix warning for CI | LordMike/TMDbLib | TMDbLibTests/TestClasses/EnumTestStruct.cs | TMDbLibTests/TestClasses/EnumTestStruct.cs | namespace TMDbLibTests.TestClasses
{
struct EnumTestStruct
{
}
}
| namespace TMDbLibTests.TestClasses
{
struct EnumTestStruct
{
public int A;
}
}
| mit | C# |
023ae3372d61cef6ed9de526f289accacb1795e1 | Add TODOs | fredatgithub/PaperBoy | PaperBoy/Program.cs | PaperBoy/Program.cs | /*
The MIT License(MIT)
Copyright(c) 2015 Freddy Juhel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Net;
namespace PaperBoy
{
class Program
{
static void Main()
{
Action<string> Display = s => Console.WriteLine(s);
Display("Getting Direct Matin electronic PDF newspaper");
// http://kiosque.directmatin.fr/Pdf.aspx?edition=NEP&date=20150415
string url = "http://kiosque.directmatin.fr/Pdf.aspx?edition=NEP&date=";
string dateEnglish = DateTime.Now.Year +
ToTwoDigits(DateTime.Now.Month) +
ToTwoDigits(DateTime.Now.Day);
url += dateEnglish;
string fileName = "DirectMatin-" + dateEnglish + ".pdf";
Display(GetWebClientBinaries(url, fileName) ? "download ok and file saved" : "error while downloading");
// TODO delete file if size equals zero
Display("Press a key to exit:");
Console.ReadKey();
}
private static string ToTwoDigits(int number)
{
return number < 10 ? "0" + number : number.ToString();
}
private static bool GetWebClientBinaries(string url = "http://www.google.com/",
string fileName = "untitled-file.pdf")
{
WebClient client = new WebClient();
bool result = false;
// set the user agent to IE6
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)");
try
{
client.DownloadFile(url, fileName);
result = true;
}
catch (WebException we)
{
Console.WriteLine(we.Message + "\n" + we.Status);
result = false;
}
catch (NotSupportedException ne)
{
Console.WriteLine(ne.Message);
result = false;
}
return result;
}
}
} | /*
The MIT License(MIT)
Copyright(c) 2015 Freddy Juhel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Net;
namespace PaperBoy
{
class Program
{
static void Main()
{
Action<string> Display = s => Console.WriteLine(s);
Display("Getting Direct Matin electronic PDF newspaper");
// http://kiosque.directmatin.fr/Pdf.aspx?edition=NEP&date=20150415
string url = "http://kiosque.directmatin.fr/Pdf.aspx?edition=NEP&date=";
string dateEnglish = DateTime.Now.Year +
ToTwoDigits(DateTime.Now.Month) +
ToTwoDigits(DateTime.Now.Day);
url += dateEnglish;
string fileName = "DirectMatin-" + dateEnglish + ".pdf";
Display(GetWebClientBinaries(url, fileName) ? "download ok and file saved" : "error while downloading");
Display("Press a key to exit:");
Console.ReadKey();
}
private static string ToTwoDigits(int number)
{
return number < 10 ? "0" + number : number.ToString();
}
private static bool GetWebClientBinaries(string url = "http://www.google.com/",
string fileName = "untitled-file.pdf")
{
WebClient client = new WebClient();
bool result = false;
// set the user agent to IE6
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)");
try
{
client.DownloadFile(url, fileName);
result = true;
}
catch (WebException we)
{
Console.WriteLine(we.Message + "\n" + we.Status);
result = false;
}
catch (NotSupportedException ne)
{
Console.WriteLine(ne.Message);
result = false;
}
return result;
}
}
} | mit | C# |
bc9eb11ebdfdf481ea2b98343c1d818682daff1c | 更新版本1.8.6.5 | herix001/ElectronicObserver,kanonmelodis/ElectronicObserver,CNA-Bld/ElectronicObserver,tsanie/ElectronicObserver | ElectronicObserver/Properties/AssemblyInfo.cs | ElectronicObserver/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle( "ElectronicObserver" )]
[assembly: AssemblyDescription( "" )]
[assembly: AssemblyConfiguration( "" )]
[assembly: AssemblyCompany( "" )]
[assembly: AssemblyProduct( "ElectronicObserver" )]
[assembly: AssemblyCopyright( "Copyright © 2014 Andante" )]
[assembly: AssemblyTrademark( "" )]
[assembly: AssemblyCulture( "" )]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible( false )]
// 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です
[assembly: Guid( "bee10a07-cace-44fe-8a74-53ae44d224c2" )]
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.8.0.5")]
[assembly: AssemblyFileVersion("1.8.6.5")]
[assembly: AssemblyInformationalVersion("1.8.6.5")] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle( "ElectronicObserver" )]
[assembly: AssemblyDescription( "" )]
[assembly: AssemblyConfiguration( "" )]
[assembly: AssemblyCompany( "" )]
[assembly: AssemblyProduct( "ElectronicObserver" )]
[assembly: AssemblyCopyright( "Copyright © 2014 Andante" )]
[assembly: AssemblyTrademark( "" )]
[assembly: AssemblyCulture( "" )]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible( false )]
// 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です
[assembly: Guid( "bee10a07-cace-44fe-8a74-53ae44d224c2" )]
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.8.0.0")]
[assembly: AssemblyFileVersion("1.8.6.0")]
[assembly: AssemblyInformationalVersion("1.8.6.0")] | mit | C# |
a48d17e5bd2d22c6fbbef55959f768e5808b2804 | add add-barbershop and getAll | psyun/HDO2O-RestfulAPI | HDO2O.API/Controllers/BarbershopController.cs | HDO2O.API/Controllers/BarbershopController.cs | using HDO2O.DTO;
using HDO2O.IServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace HDO2O.API.Controllers
{
[RoutePrefix("rest/barbershop")]
public class BarbershopController : ApiController
{
private IBarbershopService _servBabershop;
public BarbershopController(IBarbershopService servBarbershop)
{
_servBabershop = servBarbershop;
}
/// <summary>
///
/// </summary>
/// <param name="barbershop"></param>
/// <uri>POST:rest/barbershop/add</uri>
/// <returns></returns>
[HttpPost]
[Route("add")]
public IHttpActionResult AddBabershop([FromBody] BarbershopDTO barbershop)
{
return Ok(_servBabershop.Add(barbershop));
}
/// <summary>
///
/// </summary>
/// <uri>rest/barbershop/getAll</uri>
/// <returns></returns>
[HttpGet]
[Route("getAll")]
public IHttpActionResult GetAll()
{
return Ok(_servBabershop.GetAll());
}
}
}
| using HDO2O.DTO;
using HDO2O.IServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace HDO2O.API.Controllers
{
[RoutePrefix("rest/barbershop")]
public class BarbershopController : ApiController
{
private IBarbershopService _servBabershop;
public BarbershopController(IBarbershopService servBarbershop)
{
_servBabershop = servBarbershop;
}
/// <summary>
///
/// </summary>
/// <param name="barbershop"></param>
/// <uri>POST:rest/barbershop/add</uri>
/// <returns></returns>
[HttpPost]
[Route("add")]
public IHttpActionResult AddBabershop(BarbershopDTO barbershop)
{
return Ok(_servBabershop.Add(barbershop));
}
/// <summary>
///
/// </summary>
/// <uri>rest/barbershop/getAll</uri>
/// <returns></returns>
[HttpGet]
[Route("getAll")]
public IHttpActionResult GetAll()
{
return Ok(_servBabershop.GetAll());
}
}
}
| apache-2.0 | C# |
e6ef03bd966fa2a48c20deaf534c0bd60d0162ba | Add assertions checking file existence | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Common/IO/TextTasks.cs | source/Nuke.Common/IO/TextTasks.cs | // Copyright 2018 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using JetBrains.Annotations;
namespace Nuke.Common.IO
{
[PublicAPI]
public static class TextTasks
{
public static UTF8Encoding UTF8NoBom => new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
public static void WriteAllLines(string path, IEnumerable<string> lines, Encoding encoding = null)
{
WriteAllLines(path, lines.ToArray(), encoding);
}
public static void WriteAllLines(string path, string[] lines, Encoding encoding = null)
{
FileSystemTasks.EnsureExistingParentDirectory(path);
File.WriteAllLines(path, lines, encoding ?? UTF8NoBom);
}
public static void WriteAllText(string path, string content, Encoding encoding = null)
{
FileSystemTasks.EnsureExistingParentDirectory(path);
File.WriteAllText(path, content, encoding ?? UTF8NoBom);
}
public static void WriteAllBytes(string path, byte[] bytes)
{
FileSystemTasks.EnsureExistingParentDirectory(path);
File.WriteAllBytes(path, bytes);
}
public static string ReadAllText(string path, Encoding encoding = null)
{
ControlFlow.Assert(File.Exists(path), $"File.Exists({path})");
return File.ReadAllText(path, encoding ?? Encoding.UTF8);
}
public static string[] ReadAllLines(string path, Encoding encoding = null)
{
ControlFlow.Assert(File.Exists(path), $"File.Exists({path})");
return File.ReadAllLines(path, encoding ?? Encoding.UTF8);
}
public static byte[] ReadAllBytes(string path)
{
ControlFlow.Assert(File.Exists(path), $"File.Exists({path})");
return File.ReadAllBytes(path);
}
}
}
| // Copyright 2018 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using JetBrains.Annotations;
namespace Nuke.Common.IO
{
[PublicAPI]
public static class TextTasks
{
public static UTF8Encoding UTF8NoBom => new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
public static void WriteAllLines(string path, IEnumerable<string> lines, Encoding encoding = null)
{
WriteAllLines(path, lines.ToArray(), encoding);
}
public static void WriteAllLines(string path, string[] lines, Encoding encoding = null)
{
FileSystemTasks.EnsureExistingParentDirectory(path);
File.WriteAllLines(path, lines, encoding ?? UTF8NoBom);
}
public static void WriteAllText(string path, string content, Encoding encoding = null)
{
FileSystemTasks.EnsureExistingParentDirectory(path);
File.WriteAllText(path, content, encoding ?? UTF8NoBom);
}
public static void WriteAllBytes(string path, byte[] bytes)
{
FileSystemTasks.EnsureExistingParentDirectory(path);
File.WriteAllBytes(path, bytes);
}
public static string ReadAllText(string path, Encoding encoding = null)
{
return File.ReadAllText(path, encoding ?? Encoding.UTF8);
}
public static string[] ReadAllLines(string path, Encoding encoding = null)
{
return File.ReadAllLines(path, encoding ?? Encoding.UTF8);
}
public static byte[] ReadAllBytes(string path)
{
return File.ReadAllBytes(path);
}
}
}
| mit | C# |
9fc6231e18e12eaa4269e2fe75071ac469473cf4 | add some events to Button and IsPressed var | jpbruyere/Crow,jpbruyere/Crow | src/GraphicObjects/Button.cs | src/GraphicObjects/Button.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using OpenTK.Graphics.OpenGL;
using System.Diagnostics;
using System.Xml.Serialization;
using Cairo;
using System.ComponentModel;
namespace Crow
{
[DefaultStyle("#Crow.Styles.Button.style")]
[DefaultTemplate("#Crow.Templates.Button.crow")]
public class Button : TemplatedContainer
{
string caption;
string image;
bool isPressed;
Container _contentContainer;
#region CTOR
public Button() : base()
{}
#endregion
public event EventHandler Pressed;
public event EventHandler Released;
public event EventHandler Clicked;
#region TemplatedContainer overrides
public override GraphicObject Content {
get {
return _contentContainer == null ? null : _contentContainer.Child;
}
set {
if (_contentContainer != null)
_contentContainer.SetChild(value);
}
}
protected override void loadTemplate(GraphicObject template = null)
{
base.loadTemplate (template);
_contentContainer = this.child.FindByName ("Content") as Container;
}
#endregion
#region GraphicObject Overrides
public override void ResolveBindings ()
{
base.ResolveBindings ();
if (Content != null)
Content.ResolveBindings ();
}
public override void onMouseDown (object sender, MouseButtonEventArgs e)
{
IsPressed = true;
base.onMouseDown (sender, e);
//TODO:remove
NotifyValueChanged ("State", "pressed");
}
public override void onMouseUp (object sender, MouseButtonEventArgs e)
{
IsPressed = false;
base.onMouseUp (sender, e);
//TODO:remove
NotifyValueChanged ("State", "normal");
}
#endregion
[XmlAttributeAttribute()][DefaultValue("Button")]
public string Caption {
get { return caption; }
set {
if (caption == value)
return;
caption = value;
NotifyValueChanged ("Caption", caption);
}
}
[XmlAttributeAttribute()][DefaultValue("#Crow.Images.button.svg")]
public string Image {
get { return image; }
set {
if (image == value)
return;
image = value;
NotifyValueChanged ("Image", image);
}
}
[XmlAttributeAttribute()][DefaultValue(false)]
public bool IsPressed
{
get { return isPressed; }
set
{
if (isPressed == value)
return;
isPressed = value;
NotifyValueChanged ("IsPressed", isPressed);
if (isPressed)
Pressed.Raise (this, null);
else
Released.Raise (this, null);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using OpenTK.Graphics.OpenGL;
using System.Diagnostics;
using System.Xml.Serialization;
using Cairo;
using System.ComponentModel;
namespace Crow
{
[DefaultStyle("#Crow.Styles.Button.style")]
[DefaultTemplate("#Crow.Templates.Button.crow")]
public class Button : TemplatedContainer
{
#region CTOR
public Button() : base()
{}
#endregion
string caption;
string image;
Container _contentContainer;
public override GraphicObject Content {
get {
return _contentContainer == null ? null : _contentContainer.Child;
}
set {
if (_contentContainer != null)
_contentContainer.SetChild(value);
}
}
protected override void loadTemplate(GraphicObject template = null)
{
base.loadTemplate (template);
_contentContainer = this.child.FindByName ("Content") as Container;
}
#region GraphicObject Overrides
public override void ResolveBindings ()
{
base.ResolveBindings ();
if (Content != null)
Content.ResolveBindings ();
}
public override void onMouseDown (object sender, MouseButtonEventArgs e)
{
base.onMouseDown (sender, e);
NotifyValueChanged ("State", "pressed");
}
public override void onMouseUp (object sender, MouseButtonEventArgs e)
{
base.onMouseUp (sender, e);
NotifyValueChanged ("State", "normal");
}
#endregion
[XmlAttributeAttribute()][DefaultValue("Button")]
public string Caption {
get { return caption; }
set {
if (caption == value)
return;
caption = value;
NotifyValueChanged ("Caption", caption);
}
}
[XmlAttributeAttribute()][DefaultValue("#Crow.Images.button.svg")]
public string Image {
get { return image; }
set {
if (image == value)
return;
image = value;
NotifyValueChanged ("Image", image);
}
}
}
}
| mit | C# |
7e039a36bba6113d332db58eca04dc3963ca6921 | Fix ControlList_CheckBox test | atata-framework/atata,YevgeniyShunevych/Atata,YevgeniyShunevych/Atata,atata-framework/atata | src/Atata.Tests/ControlListTest.cs | src/Atata.Tests/ControlListTest.cs | using NUnit.Framework;
namespace Atata.Tests
{
public class ControlListTest : AutoTest
{
[Test]
public void ControlList_CheckBox()
{
CheckBoxListPage page = Go.To<CheckBoxListPage>();
page.
AllItems.Should.HaveCount(6).
AllItems.Should.Not.HaveCount(1).
AllItems.Count.Should.Equal(6).
AllItems.Count.Should.BeGreaterOrEqual(6).
AllItems.Count.Should.Not.BeLess(6).
AllItems.Should.Not.Contain(true).
AllItems.Should.Not.Contain(x => x.IsChecked).
AllItems[x => x.IsChecked].Should.Not.Exist();
////AllItems[2].Check().
////AllItems.Should.Contain(x => x.IsChecked).
////AllItems[2].IsChecked.Should.BeTrue();
}
}
}
| using NUnit.Framework;
namespace Atata.Tests
{
public class ControlListTest : AutoTest
{
[Test]
public void ControlList_CheckBox()
{
CheckBoxListPage page = Go.To<CheckBoxListPage>();
page.
AllItems.Should.HaveCount(6).
AllItems.Should.Not.HaveCount(1).
AllItems.Count.Should.Equal(6).
AllItems.Count.Should.BeGreaterOrEqual(6).
AllItems.Count.Should.Not.BeLess(6).
AllItems.Should.Not.Contain(true).
AllItems.Should.Not.Contain(x => x.IsChecked).
AllItems[x => !x.IsChecked].Should.Not.Exist().
AllItems[x => x.IsChecked == false].Should.Not.Exist();
////AllItems[2].Check().
////AllItems.Should.Contain(x => x.IsChecked).
////AllItems[2].IsChecked.Should.BeTrue();
}
}
}
| apache-2.0 | C# |
c5aacaea2f78cefcdd39e3079e6c7fef7fe552bb | resolve the code analysis | jwChung/Experimentalism,jwChung/Experimentalism | src/Experiment/TheoremAttribute.cs | src/Experiment/TheoremAttribute.cs | using System;
using System.Collections.Generic;
using Xunit;
using Xunit.Extensions;
using Xunit.Sdk;
namespace Jwc.Experiment
{
/// <summary>
/// 이 attribute는 method위에 선언되어 해당 method가 test-case라는 것을
/// 지칭하게 되며, non-parameterized test 뿐 아니라 parameterized test에도
/// 사용될 수 있다.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class TheoremAttribute : FactAttribute
{
/// <summary>
/// Enumerates the test commands represented by this test method.
/// Derived classes should override this method to return instances of
/// <see cref="ITestCommand" />, one per execution of a test method.
/// </summary>
/// <param name="method">The test method</param>
/// <returns>
/// The test commands which will execute the test runs for the given method
/// </returns>
protected override IEnumerable<ITestCommand> EnumerateTestCommands(IMethodInfo method)
{
if (method == null)
{
throw new ArgumentNullException("method");
}
return !method.MethodInfo.IsDefined(typeof(DataAttribute), false)
? base.EnumerateTestCommands(method)
: new TheoryAttribute().CreateTestCommands(method);
}
}
} | using System;
using System.Collections.Generic;
using Xunit;
using Xunit.Extensions;
using Xunit.Sdk;
namespace Jwc.Experiment
{
/// <summary>
/// 이 attribute는 method위에 선언되어 해당 method가 test-case라는 것을
/// 지칭하게 되며, non-parameterized test 뿐 아니라 parameterized test에도
/// 사용될 수 있다.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class TheoremAttribute : FactAttribute
{
/// <summary>
/// Enumerates the test commands represented by this test method.
/// Derived classes should override this method to return instances of
/// <see cref="ITestCommand" />, one per execution of a test method.
/// </summary>
/// <param name="method">The test method</param>
/// <returns>
/// The test commands which will execute the test runs for the given method
/// </returns>
protected override IEnumerable<ITestCommand> EnumerateTestCommands(IMethodInfo method)
{
return !method.MethodInfo.IsDefined(typeof(DataAttribute), false)
? base.EnumerateTestCommands(method)
: new TheoryAttribute().CreateTestCommands(method);
}
}
} | mit | C# |
2a958907918d820e67b55d83e1796a78ff506819 | Print full exception name. | GunioRobot/sdb-cli,GunioRobot/sdb-cli | Mono.Debugger.Cli/Debugging/ExceptionPrinter.cs | Mono.Debugger.Cli/Debugging/ExceptionPrinter.cs | using System.Collections.Generic;
using Mono.Debugger.Cli.Logging;
using Mono.Debugger.Soft;
namespace Mono.Debugger.Cli.Debugging
{
public static class ExceptionPrinter
{
public static void Print(ThreadMirror thread, ObjectMirror ex)
{
// We disregard thread safety here, since an extra lookup really doesn't matter...
var exception = _exception ?? (_exception = thread.Domain.Corlib.GetType("System.Exception"));
var getMessage = _exGetMsg ?? (_exGetMsg = exception.GetProperty("Message").GetGetMethod());
var getInner = _exGetInner ?? (_exGetInner = exception.GetProperty("InnerException").GetGetMethod());
PrintException(string.Empty, thread, getMessage, ex);
var innerEx = ex.InvokeMethod(thread, getInner, new List<Value>());
while (!(innerEx is PrimitiveValue)) // If it's a PrimitiveValue, it's null.
{
var exMirror = (ObjectMirror)innerEx;
PrintException("--> ", thread, getMessage, exMirror);
innerEx = exMirror.InvokeMethod(thread, getInner, _noValues);
}
}
private static void PrintException(string p, ThreadMirror thread, MethodMirror getMsg, ObjectMirror x)
{
var msg = (StringMirror)x.InvokeMethod(thread, getMsg, new List<Value>());
Logger.WriteErrorLine("{0}{1}: {2}", p, x.Type.FullName, msg.Value);
}
private static readonly List<Value> _noValues = new List<Value>();
private static TypeMirror _exception;
private static MethodMirror _exGetMsg;
private static MethodMirror _exGetInner;
}
}
| using System.Collections.Generic;
using Mono.Debugger.Cli.Logging;
using Mono.Debugger.Soft;
namespace Mono.Debugger.Cli.Debugging
{
public static class ExceptionPrinter
{
public static void Print(ThreadMirror thread, ObjectMirror ex)
{
// We disregard thread safety here, since an extra lookup really doesn't matter...
var exception = _exception ?? (_exception = thread.Domain.Corlib.GetType("System.Exception"));
var getMessage = _exGetMsg ?? (_exGetMsg = exception.GetProperty("Message").GetGetMethod());
var getInner = _exGetInner ?? (_exGetInner = exception.GetProperty("InnerException").GetGetMethod());
PrintException(string.Empty, thread, getMessage, ex);
var innerEx = ex.InvokeMethod(thread, getInner, new List<Value>());
while (!(innerEx is PrimitiveValue)) // If it's a PrimitiveValue, it's null.
{
var exMirror = (ObjectMirror)innerEx;
PrintException("--> ", thread, getMessage, exMirror);
innerEx = exMirror.InvokeMethod(thread, getInner, _noValues);
}
}
private static void PrintException(string p, ThreadMirror thread, MethodMirror getMsg, ObjectMirror x)
{
var msg = (StringMirror)x.InvokeMethod(thread, getMsg, new List<Value>());
Logger.WriteErrorLine("{0}{1}: {2}", p, x.Type.Name, msg.Value);
}
private static readonly List<Value> _noValues = new List<Value>();
private static TypeMirror _exception;
private static MethodMirror _exGetMsg;
private static MethodMirror _exGetInner;
}
}
| mit | C# |
637132a7d8abec76a469ea0357313ac6bf81ba49 | Allow for null callbacks in Notifications | orand/Xamarin.Mobile,xamarin/Xamarin.Mobile,nexussays/Xamarin.Mobile,xamarin/Xamarin.Mobile,moljac/Xamarin.Mobile,haithemaraissia/Xamarin.Mobile | MonoTouch/MonoMobile.Extensions/Notification.cs | MonoTouch/MonoMobile.Extensions/Notification.cs | using System;
using MonoTouch.UIKit;
using MonoTouch.AudioToolbox;
namespace MonoMobile.Extensions
{
public class Notification
{
public Notification ()
{
}
public void Alert (string message, Action alertCallback)
{
Alert(message, alertCallback, "Alert", "OK");
}
public void Alert (string message, Action alertCallback, string title)
{
Alert(message, alertCallback, title, "OK");
}
public void Alert (string message, Action alertCallback, string title, string buttonName)
{
using(var alertView = new UIAlertView(title, message, null, buttonName, null))
{
alertView.Show();
alertView.Dismissed += delegate(object sender, UIButtonEventArgs e) {
if(alertCallback != null)
alertCallback();
};
}
}
public void Confirm (string message, Action<int> confirmCallback)
{
Confirm(message, confirmCallback, "Alert", "OK");
}
public void Confirm (string message, Action<int> confirmCallback, string title)
{
Confirm(message, confirmCallback, title, "OK");
}
public void Confirm (string message, Action<int> confirmCallback, string title, string buttonLabels)
{
using(var alertView = new UIAlertView(title, message, null, null, null))
{
var labels = buttonLabels.Split(new Char[]{','});
foreach(var label in labels)
{
alertView.AddButton(label);
}
alertView.Show();
alertView.Clicked += delegate(object sender, UIButtonEventArgs e) {
if(confirmCallback != null)
confirmCallback(e.ButtonIndex);
};
}
}
public void Beep ()
{
var beep = SystemSound.FromFile("beep.wav");
beep.PlaySystemSound();
}
public void Beep (int times)
{
Beep();
}
public void Vibrate ()
{
SystemSound.Vibrate.PlaySystemSound();
}
public void Vibrate (int milliseconds)
{
Vibrate();
}
}
}
| using System;
using MonoTouch.UIKit;
using MonoTouch.AudioToolbox;
namespace MonoMobile.Extensions
{
public class Notification
{
public Notification ()
{
}
public void Alert (string message, Action alertCallback)
{
Alert(message, alertCallback, "Alert", "OK");
}
public void Alert (string message, Action alertCallback, string title)
{
Alert(message, alertCallback, title, "OK");
}
public void Alert (string message, Action alertCallback, string title, string buttonName)
{
using(var alertView = new UIAlertView(title, message, null, buttonName, null))
{
alertView.Show();
alertView.Dismissed += delegate(object sender, UIButtonEventArgs e) {
alertCallback();
};
}
}
public void Confirm (string message, Action<int> confirmCallback)
{
Confirm(message, confirmCallback, "Alert", "OK");
}
public void Confirm (string message, Action<int> confirmCallback, string title)
{
Confirm(message, confirmCallback, title, "OK");
}
public void Confirm (string message, Action<int> confirmCallback, string title, string buttonLabels)
{
using(var alertView = new UIAlertView(title, message, null, null, null))
{
var labels = buttonLabels.Split(new Char[]{','});
foreach(var label in labels)
{
alertView.AddButton(label);
}
alertView.Show();
alertView.Clicked += delegate(object sender, UIButtonEventArgs e) {
confirmCallback(e.ButtonIndex);
};
}
}
public void Beep ()
{
var beep = SystemSound.FromFile("beep.wav");
beep.PlaySystemSound();
}
public void Beep (int times)
{
Beep();
}
public void Vibrate ()
{
SystemSound.Vibrate.PlaySystemSound();
}
public void Vibrate (int milliseconds)
{
Vibrate();
}
}
}
| apache-2.0 | C# |
377d171750cc3f2c5ba6e600027eb54cc3318e04 | delete extra license comment. | StephenBonikowsky/wcf,mconnew/wcf,StephenBonikowsky/wcf,mconnew/wcf,mconnew/wcf,dotnet/wcf,imcarolwang/wcf,dotnet/wcf,imcarolwang/wcf,dotnet/wcf,imcarolwang/wcf | src/System.ServiceModel.Security/tests/ServiceModel/SecutityBindingElementTest.cs | src/System.ServiceModel.Security/tests/ServiceModel/SecutityBindingElementTest.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ServiceModel.Channels;
using System.ServiceModel.Security.Tokens;
using Infrastructure.Common;
using Xunit;
public static class SecutityBindingElementTest
{
[WcfFact]
public static void Method_CreateUserNameOverTransportBindingElement()
{
TransportSecurityBindingElement securityBindingElement = SecurityBindingElement.CreateUserNameOverTransportBindingElement();
Assert.True(securityBindingElement != null, "The created TransportSecurityBindingElement should not be null.");
Assert.True(securityBindingElement.IncludeTimestamp);
Assert.False(securityBindingElement.LocalClientSettings.DetectReplays);
Assert.True(securityBindingElement.EndpointSupportingTokenParameters.SignedEncrypted[0] is UserNameSecurityTokenParameters);
securityBindingElement.IncludeTimestamp = false;
securityBindingElement.SecurityHeaderLayout = SecurityHeaderLayout.Lax;
var binding = new CustomBinding();
binding.Elements.Add(securityBindingElement);
SecurityBindingElement element = binding.Elements.Find<SecurityBindingElement>();
Assert.True(element != null, "SecurityBindingElement added to binding elements should not be null.");
Assert.Equal(element, securityBindingElement);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ServiceModel.Channels;
using System.ServiceModel.Security.Tokens;
using Infrastructure.Common;
using Xunit;
public static class SecutityBindingElementTest
{
[WcfFact]
public static void Method_CreateUserNameOverTransportBindingElement()
{
TransportSecurityBindingElement securityBindingElement = SecurityBindingElement.CreateUserNameOverTransportBindingElement();
Assert.True(securityBindingElement != null, "The created TransportSecurityBindingElement should not be null.");
Assert.True(securityBindingElement.IncludeTimestamp);
Assert.False(securityBindingElement.LocalClientSettings.DetectReplays);
Assert.True(securityBindingElement.EndpointSupportingTokenParameters.SignedEncrypted[0] is UserNameSecurityTokenParameters);
securityBindingElement.IncludeTimestamp = false;
securityBindingElement.SecurityHeaderLayout = SecurityHeaderLayout.Lax;
var binding = new CustomBinding();
binding.Elements.Add(securityBindingElement);
SecurityBindingElement element = binding.Elements.Find<SecurityBindingElement>();
Assert.True(element != null, "SecurityBindingElement added to binding elements should not be null.");
Assert.Equal(element, securityBindingElement);
}
} | mit | C# |
4aa046d62922cf5d5ff5288a9acb2cd3d7334124 | Test for ColumnConstraintCollection. | msallin/SQLiteCodeFirst | SQLite.CodeFirst/Statement/ColumnStatement.cs | SQLite.CodeFirst/Statement/ColumnStatement.cs | using System.Text;
using SQLite.CodeFirst.Statement.ColumnConstraint;
namespace SQLite.CodeFirst.Statement
{
internal class ColumnStatement : IStatement
{
private const string Template = "[{column-name}] {type-name} {column-constraint}";
public string ColumnName { get; set; }
public string TypeName { get; set; }
public IColumnConstraintCollection ColumnConstraints { get; set; }
public string CreateStatement()
{
var sb = new StringBuilder(Template);
sb.Replace("{column-name}", ColumnName);
sb.Replace("{type-name}", TypeName);
sb.Replace("{column-constraint}", ColumnConstraints.CreateStatement());
return sb.ToString().Trim();
}
}
}
| using System.Text;
using SQLite.CodeFirst.Statement.ColumnConstraint;
namespace SQLite.CodeFirst.Statement
{
internal class ColumnStatement : IStatement
{
private const string Template = "[{column-name}] {type-name} {column-constraint}";
public string ColumnName { get; set; }
public string TypeName { get; set; }
public ColumnConstraintCollection ColumnConstraints { get; set; }
public string CreateStatement()
{
var sb = new StringBuilder(Template);
sb.Replace("{column-name}", ColumnName);
sb.Replace("{type-name}", TypeName);
sb.Replace("{column-constraint}", ColumnConstraints.CreateStatement());
return sb.ToString().Trim();
}
}
}
| apache-2.0 | C# |
8b27684976df4fc33006b6e7a02e0aae7cfebde4 | fix typo | DeonHeyns/Metrics.NET,ntent-ad/Metrics.NET,cvent/Metrics.NET,mnadel/Metrics.NET,mnadel/Metrics.NET,Recognos/Metrics.NET,DeonHeyns/Metrics.NET,ntent-ad/Metrics.NET,etishor/Metrics.NET,MetaG8/Metrics.NET,MetaG8/Metrics.NET,Liwoj/Metrics.NET,MetaG8/Metrics.NET,huoxudong125/Metrics.NET,etishor/Metrics.NET,alhardy/Metrics.NET,cvent/Metrics.NET,alhardy/Metrics.NET,Liwoj/Metrics.NET,Recognos/Metrics.NET,huoxudong125/Metrics.NET | Samples/Metrics.StupidBenchmarks/Benchmark.cs | Samples/Metrics.StupidBenchmarks/Benchmark.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace Metrics.StupidBenchmarks
{
public static class Benchmark
{
public struct Result
{
public TimeSpan Elapsed;
public long Total;
public double PerSecond
{
get
{
return Total / Elapsed.TotalSeconds;
}
}
public override string ToString()
{
return string.Format("Runs\t{0}\nTotal\t{1}\nRate\t{2}", Total, Elapsed, PerSecond);
}
}
public static Result Run(Action<int, long> action, int threadCount = 8, long iterations = 1 * 1000 * 1000)
{
#if DEBUG
Console.WriteLine("DEBUG MODE - results are NOT relevant");
#endif
// warm - up
for (int i = 0; i < 100; i++) { action(0, 0); }
List<Thread> threads = new List<Thread>();
TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
for (int i = 0; i < threadCount; i++)
{
var x = i;
threads.Add(new Thread(s =>
{
tcs.Task.Wait();
for (long j = 0; j < iterations; j++)
action(x, j);
}));
}
// all thread will be waiting on tcs
threads.ForEach(t => t.Start());
var w = Stopwatch.StartNew();
tcs.SetResult(0);
threads.ForEach(t => t.Join());
var elapsed = w.Elapsed;
return new Result { Elapsed = elapsed, Total = threadCount * iterations };
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace Metrics.StupidBenchmarks
{
public static class Benchmark
{
public struct Result
{
public TimeSpan Elapsed;
public long Total;
public double PerSecond
{
get
{
return Total / Elapsed.TotalSeconds;
}
}
public override string ToString()
{
return string.Format("Runs\t{0}\nTotal\t{1}\nRate\t{2}", Total, Elapsed, PerSecond);
}
}
public static Result Run(Action<int, long> action, int threadCount = 8, long iterations = 1 * 1000 * 1000)
{
#if DEBUG
Console.WriteLine("DEBUG MODE - results are relevant");
#endif
// warm - up
for (int i = 0; i < 100; i++) { action(0, 0); }
List<Thread> threads = new List<Thread>();
TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
for (int i = 0; i < threadCount; i++)
{
var x = i;
threads.Add(new Thread(s =>
{
tcs.Task.Wait();
for (long j = 0; j < iterations; j++)
action(x, j);
}));
}
// all thread will be waiting on tcs
threads.ForEach(t => t.Start());
var w = Stopwatch.StartNew();
tcs.SetResult(0);
threads.ForEach(t => t.Join());
var elapsed = w.Elapsed;
return new Result { Elapsed = elapsed, Total = threadCount * iterations };
}
}
}
| apache-2.0 | C# |
52a409ea25bd249618cd89fe3188d3092dcfc015 | remove method parameter | bradwestness/SecretSanta,bradwestness/SecretSanta | SecretSanta/Controllers/WishlistController.cs | SecretSanta/Controllers/WishlistController.cs | using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SecretSanta.Models;
using SecretSanta.Utilities;
namespace SecretSanta.Controllers;
[Authorize]
public class WishlistController : Controller
{
[HttpGet]
[ResponseCache(VaryByQueryKeys = new[] { "t" } )]
public IActionResult Index()
{
if (User.GetAccount() is Account account
&& account.Id.HasValue)
{
var model = new WishlistEditModel(account.Id.Value);
return View(model);
}
return RedirectToAction("Index", "Home");
}
[HttpGet]
public IActionResult Details(Guid id)
{
var model = new WishlistEditModel(id);
return View(model);
}
[HttpPost]
public IActionResult AddItem(WishlistItem model, CancellationToken token = default)
{
if (ModelState.IsValid && User.GetAccount() is Account account)
{
WishlistManager.AddItem(account, model, token);
this.SetResultMessage($"<strong>Successfully added</strong> {model.Name}.");
}
return RedirectToAction("Index", new { t = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() });
}
[HttpPost]
public IActionResult EditItem(WishlistItem model, CancellationToken token = default)
{
if (ModelState.IsValid && User.GetAccount() is Account account)
{
WishlistManager.EditItem(account, model, token);
this.SetResultMessage($"<strong>Successfully updated</strong> {model.Name}.");
}
return RedirectToAction("Index", new { t = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() });
}
[HttpPost]
public IActionResult DeleteItem(WishlistItem model)
{
if (ModelState.IsValid && User.GetAccount() is Account account)
{
WishlistManager.DeleteItem(account, model);
this.SetResultMessage($"<strong>Successfully deleted</strong> {model.Name}.");
}
return RedirectToAction("Index", new { t = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() });
}
[HttpGet]
public IActionResult Remind(Guid id)
{
WishlistManager.SendReminder(id, Url);
this.SetResultMessage("<strong>Reminder sent</strong> successfully.");
return RedirectToAction("Details", new { id });
}
} | using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SecretSanta.Models;
using SecretSanta.Utilities;
namespace SecretSanta.Controllers;
[Authorize]
public class WishlistController : Controller
{
[HttpGet]
[ResponseCache(VaryByQueryKeys = new[] { "t" } )]
public IActionResult Index(long? t = null)
{
if (User.GetAccount() is Account account
&& account.Id.HasValue)
{
var model = new WishlistEditModel(account.Id.Value);
return View(model);
}
return RedirectToAction("Index", "Home");
}
[HttpGet]
public IActionResult Details(Guid id)
{
var model = new WishlistEditModel(id);
return View(model);
}
[HttpPost]
public IActionResult AddItem(WishlistItem model, CancellationToken token = default)
{
if (ModelState.IsValid && User.GetAccount() is Account account)
{
WishlistManager.AddItem(account, model, token);
this.SetResultMessage($"<strong>Successfully added</strong> {model.Name}.");
}
return RedirectToAction("Index", new { t = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() });
}
[HttpPost]
public IActionResult EditItem(WishlistItem model, CancellationToken token = default)
{
if (ModelState.IsValid && User.GetAccount() is Account account)
{
WishlistManager.EditItem(account, model, token);
this.SetResultMessage($"<strong>Successfully updated</strong> {model.Name}.");
}
return RedirectToAction("Index", new { t = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() });
}
[HttpPost]
public IActionResult DeleteItem(WishlistItem model)
{
if (ModelState.IsValid && User.GetAccount() is Account account)
{
WishlistManager.DeleteItem(account, model);
this.SetResultMessage($"<strong>Successfully deleted</strong> {model.Name}.");
}
return RedirectToAction("Index", new { t = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() });
}
[HttpGet]
public IActionResult Remind(Guid id)
{
WishlistManager.SendReminder(id, Url);
this.SetResultMessage("<strong>Reminder sent</strong> successfully.");
return RedirectToAction("Details", new { id });
}
} | apache-2.0 | C# |
fa9a11afe9f8aed40003466587d580447e8d2bb2 | deploy test | dreanor/StreamCompanion | src/app/Properties/AssemblyInfo.cs | src/app/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
[assembly: AssemblyTitle("App")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("App")]
[assembly: AssemblyCopyright("Copyright © Dreanor 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None,
ResourceDictionaryLocation.SourceAssembly
)]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
[assembly: AssemblyTitle("App")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("App")]
[assembly: AssemblyCopyright("Copyright © Dreanor 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None,
ResourceDictionaryLocation.SourceAssembly
)]
[assembly: AssemblyVersion("1.0.6.2")]
[assembly: AssemblyFileVersion("1.0.6.2")]
| mit | C# |
442cde265e4c9059970cdb4b1e157c418ab2d720 | Remove unnecessary submit method from WebForm | cezarypiatek/MaintainableSelenium,cezarypiatek/Tellurium,cezarypiatek/Tellurium,cezarypiatek/MaintainableSelenium,cezarypiatek/Tellurium,cezarypiatek/MaintainableSelenium | Src/MaintainableSelenium/MaintainableSelenium.Toolbox/WebPages/WebForms/WebForm.cs | Src/MaintainableSelenium/MaintainableSelenium.Toolbox/WebPages/WebForms/WebForm.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
namespace MaintainableSelenium.Toolbox.WebPages.WebForms
{
/// <summary>
/// Strongly typed adapter for web form
/// </summary>
/// <typeparam name="TModel">Type of model connected with given web form</typeparam>
public class WebForm<TModel>: PageFragment
{
private static TimeSpan InputSearchTimeout = TimeSpan.FromSeconds(30);
private List<IFormInputAdapter> SupportedInputs { get; set; }
public WebForm(IWebElement webElement, RemoteWebDriver driver, List<IFormInputAdapter> supportedInputs) : base(driver, webElement)
{
SupportedInputs = supportedInputs;
}
private IWebElement GetField<TFieldValue>(Expression<Func<TModel, TFieldValue>> field)
{
var fieldName = ExpressionHelper.GetExpressionText(field);
var waiter = new WebDriverWait(Driver, InputSearchTimeout);
try
{
return waiter.Until(d => WebElement.FindElement(By.Name(fieldName)));
}
catch (TimeoutException)
{
throw new NoWebForFieldException(fieldName);
}
}
/// <summary>
/// Set value for field indicated by expression
/// </summary>
/// <param name="field">Expression indicating given form field</param>
/// <param name="value">Value to set for fields</param>
public void SetFieldValue<TFieldValue>(Expression<Func<TModel, TFieldValue>> field, string value)
{
var fieldElement = GetField(field);
var input = SupportedInputs.FirstOrDefault(x => x.CanHandle(fieldElement));
if (input == null)
{
throw new NotSupportedException("Not supported form element");
}
input.SetValue(fieldElement, value);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
namespace MaintainableSelenium.Toolbox.WebPages.WebForms
{
/// <summary>
/// Strongly typed adapter for web form
/// </summary>
/// <typeparam name="TModel">Type of model connected with given web form</typeparam>
public class WebForm<TModel>: PageFragment
{
private static TimeSpan InputSearchTimeout = TimeSpan.FromSeconds(30);
private List<IFormInputAdapter> SupportedInputs { get; set; }
public WebForm(IWebElement webElement, RemoteWebDriver driver, List<IFormInputAdapter> supportedInputs) : base(driver, webElement)
{
SupportedInputs = supportedInputs;
}
private IWebElement GetField<TFieldValue>(Expression<Func<TModel, TFieldValue>> field)
{
var fieldName = ExpressionHelper.GetExpressionText(field);
var waiter = new WebDriverWait(Driver, InputSearchTimeout);
try
{
return waiter.Until(d => WebElement.FindElement(By.Name(fieldName)));
}
catch (TimeoutException)
{
throw new NoWebForFieldException(fieldName);
}
}
/// <summary>
/// Set value for field indicated by expression
/// </summary>
/// <param name="field">Expression indicating given form field</param>
/// <param name="value">Value to set for fields</param>
public void SetFieldValue<TFieldValue>(Expression<Func<TModel, TFieldValue>> field, string value)
{
var fieldElement = GetField(field);
var input = SupportedInputs.FirstOrDefault(x => x.CanHandle(fieldElement));
if (input == null)
{
throw new NotSupportedException("Not supported form element");
}
input.SetValue(fieldElement, value);
}
public void Submit()
{
this.WebElement.Submit();
}
}
} | mit | C# |
1ee87a33ca278ff9af254b1e4eedf678341e3ca3 | Copy IsRequired to Action | CrOrc/Cr.ArgParse | src/Cr.ArgParse/ArgumentAction.cs | src/Cr.ArgParse/ArgumentAction.cs | using System.Collections.Generic;
namespace Cr.ArgParse
{
public abstract class ArgumentAction
{
public Argument Argument { get; private set; }
public ActionContainer Container { get; set; }
public IList<string> OptionStrings { get; private set; }
public bool IsRequired { get; set; }
protected ArgumentAction(Argument argument)
{
Argument = argument;
OptionStrings = new List<string>(Argument.OptionStrings ?? new string[] {});
Destination = Argument.Destination;
IsRequired = Argument.IsRequired;
}
public string Destination { get; private set; }
public abstract void Call(ParseResult parseResult, object values, string optionString);
}
} | using System.Collections.Generic;
namespace Cr.ArgParse
{
public abstract class ArgumentAction
{
public Argument Argument { get; private set; }
public ActionContainer Container { get; set; }
public IList<string> OptionStrings { get; private set; }
public bool IsRequired { get; set; }
protected ArgumentAction(Argument argument)
{
Argument = argument;
OptionStrings = new List<string>(Argument.OptionStrings ?? new string[] {});
Destination = Argument.Destination;
}
public string Destination { get; private set; }
public abstract void Call(ParseResult parseResult, object values, string optionString);
}
} | mit | C# |
66608aa70879269f9ca656c26df4ca31f7785a2c | Allow Runnable to be comparable | bigbearstudios/sharp-test | SharpTest/Source/Internal/Runnable.cs | SharpTest/Source/Internal/Runnable.cs | using System;
using System.Text;
using SharpTest.Reporters;
using SharpTest.Results;
namespace SharpTest.Internal
{
public abstract class Runnable : IComparable<Runnable>
{
private String name = null;
private String description = null;
private TestFormat format = TestFormat.Run;
private UInt32 order = 100;
protected Result result;
public String Name
{
get { return this.name; }
internal set { this.name = value; }
}
public String Description
{
get { return this.description; }
internal set { this.description = value; }
}
internal TestFormat Format
{
get { return this.format; }
set { this.format = value; }
}
internal UInt32 Order
{
get { return this.order; }
set { this.order = value; }
}
internal Result Result
{
get { return this.result; }
set { this.result = value; }
}
public int CompareTo(Runnable runnable)
{
return this.Order.CompareTo(runnable.Order);
}
internal abstract void Run(Reporter reporter);
internal abstract void SetSkipped();
internal abstract Result TestResult();
internal abstract void ParseReflectiveProperties();
internal virtual void Prepare()
{
ParseReflectiveProperties();
ParseTestSuiteAttribute();
}
internal void ParseTestSuiteAttribute()
{
TestAttribute testAttribute = FindTestAttribute();
if(testAttribute != null)
{
if(testAttribute.Name != null)
{
Name = testAttribute.Name;
}
Description = testAttribute.Description;
Format = testAttribute.Format;
Order = testAttribute.Order;
}
}
internal virtual TestAttribute FindTestAttribute()
{
return (TestAttribute)Attribute.GetCustomAttribute(this.GetType(), typeof(TestAttribute));
}
internal String ParseName(String name)
{
StringBuilder builder = new StringBuilder();
foreach (char c in name) {
if(Char.IsUpper(c) && builder.Length > 0)
{
builder.Append(' ');
}
builder.Append(c);
}
return builder.ToString();
}
}
}
| using System;
using System.Text;
namespace SharpTest.Internal
{
public class Runnable : IComparable<Runnable>
{
private String name = null;
private String description = null;
private TestFormat format = TestFormat.Run;
private UInt32 order = 0;
public String Name
{
get { return this.name; }
internal set { this.name = value; }
}
public String Description
{
get { return this.description; }
internal set { this.description = value; }
}
internal TestFormat Format
{
get { return this.format; }
set { this.format = value; }
}
internal UInt32 Order
{
get { return this.order; }
set { this.order = value; }
}
public Runnable()
{
}
public int CompareTo(Runnable runnable)
{
return this.Order.CompareTo(runnable.Order);
}
internal virtual void Prepare()
{
ParseReflectiveProperties();
ParseTestSuiteAttribute();
}
internal virtual void ParseReflectiveProperties()
{
Name = this.GetType().Name;
}
internal void ParseTestSuiteAttribute()
{
TestAttribute testAttribute = (TestAttribute)Attribute.GetCustomAttribute(this.GetType(), typeof(TestAttribute));
if(testAttribute != null)
{
if(testAttribute.Name != null)
{
Name = testAttribute.Name;
}
Description = testAttribute.Description;
Format = testAttribute.Format;
Order = testAttribute.Order;
}
}
internal String ParseName(String name)
{
StringBuilder builder = new StringBuilder();
foreach (char c in name) {
if(Char.IsUpper(c) && builder.Length > 0)
{
builder.Append(' ');
}
builder.Append(c);
}
return builder.ToString();
}
}
}
| mit | C# |
bace6d1bb9c7a5ed00dc096cd71e7f73c03a163a | fix url format str | dhawalharsora/connectedcare-sdk,SnapMD/connectedcare-sdk | SnapMD.VirtualCare.Sdk/PaymentsApi.cs | SnapMD.VirtualCare.Sdk/PaymentsApi.cs | // Copyright 2016 SnapMD, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Newtonsoft.Json.Linq;
using SnapMD.VirtualCare.ApiModels;
using SnapMD.VirtualCare.ApiModels.Payments;
using SnapMD.VirtualCare.Sdk.Models;
using SnapMD.VirtualCare.Sdk.Interfaces;
namespace SnapMD.VirtualCare.Sdk
{
public class PaymentsApi : ApiCall
{
public PaymentsApi(string baseUrl, string bearerToken, int hospitalId, string developerId, string apiKey, IWebClient webClient)
: base(baseUrl, webClient, bearerToken, developerId, apiKey)
{
HospitalId = hospitalId;
}
public PaymentsApi(string baseUrl, int hospitalId, IWebClient webClient)
: base(baseUrl, webClient)
{
HospitalId = hospitalId;
}
public int HospitalId { get; private set; }
public ApiResponseV2<CimCustomer> GetCustomerProfile(int? patientUserId)
{
//fixed to match the unit test
var result = MakeCall<ApiResponseV2<CimCustomer>>(string.Format("v2/patients/{0}/payments", patientUserId));
return result;
}
public ApiResponseV2<PaymentProfilePostResult> RegisterProfile(object paymentData)
{
var result = Post<ApiResponseV2<PaymentProfilePostResult>>(string.Format("v2/patients/payments"), paymentData);
return result;
}
public ApiResponseV2<bool> GetPaymentStatus(int consultationId)
{
var result = MakeCall<ApiResponseV2<bool>>(string.Format("v2/patients/copay/{0}/paymentstatus", consultationId));
return result;
}
}
} | // Copyright 2016 SnapMD, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Newtonsoft.Json.Linq;
using SnapMD.VirtualCare.ApiModels;
using SnapMD.VirtualCare.ApiModels.Payments;
using SnapMD.VirtualCare.Sdk.Models;
using SnapMD.VirtualCare.Sdk.Interfaces;
namespace SnapMD.VirtualCare.Sdk
{
public class PaymentsApi : ApiCall
{
public PaymentsApi(string baseUrl, string bearerToken, int hospitalId, string developerId, string apiKey, IWebClient webClient)
: base(baseUrl, webClient, bearerToken, developerId, apiKey)
{
HospitalId = hospitalId;
}
public PaymentsApi(string baseUrl, int hospitalId, IWebClient webClient)
: base(baseUrl, webClient)
{
HospitalId = hospitalId;
}
public int HospitalId { get; private set; }
public ApiResponseV2<CimCustomer> GetCustomerProfile(int? patientUserId)
{
//API looks so strange
var result = MakeCall<ApiResponseV2<CimCustomer>>(string.Format("v2/patients/payments", patientUserId));
return result;
}
public ApiResponseV2<PaymentProfilePostResult> RegisterProfile(object paymentData)
{
//hospital/{hospitalId}/payments/{userId}
var result = Post<ApiResponseV2<PaymentProfilePostResult>>(string.Format("v2/patients/payments"), paymentData);
return result;
}
public ApiResponseV2<bool> GetPaymentStatus(int consultationId)
{
var result = MakeCall<ApiResponseV2<bool>>(string.Format("v2/patients/copay/{0}/paymentstatus", consultationId));
return result;
}
}
} | apache-2.0 | C# |
af62c96c770f08ede2383894512f94b7e5f4276e | Update WMR camera settings to use base class | killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity | Assets/MixedRealityToolkit.Providers/WindowsMixedReality/WindowsMixedRealityCameraSettings.cs | Assets/MixedRealityToolkit.Providers/WindowsMixedReality/WindowsMixedRealityCameraSettings.cs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.CameraSystem;
using Microsoft.MixedReality.Toolkit.Utilities;
#if UNITY_WSA
using UnityEngine.XR.WSA;
#endif // UNITY_WSA
namespace Microsoft.MixedReality.Toolkit.WindowsMixedReality
{
/// <summary>
/// Camera settings provider for use with the Unity AR Foundation system.
/// </summary>
[MixedRealityDataProvider(
typeof(IMixedRealityCameraSystem),
SupportedPlatforms.WindowsUniversal,
"Windows Mixed Reality Camera Settings")]
public class WindowsMixedRealityCameraSettings : BaseCameraSettingsProvider
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="cameraSystem">The instance of the camera system which is managing this provider.</param>
/// <param name="name">Friendly name of the provider.</param>
/// <param name="priority">Provider priority. Used to determine order of instantiation.</param>
/// <param name="profile">The provider's configuration profile.</param>
public WindowsMixedRealityCameraSettings(
IMixedRealityCameraSystem cameraSystem,
string name = null,
uint priority = DefaultPriority,
BaseCameraSettingsProfile profile = null) : base(cameraSystem, name, priority, profile)
{ }
#region IMixedRealityCameraSettings
/// <inheritdoc/>
public override bool IsOpaque =>
#if UNITY_WSA
HolographicSettings.IsDisplayOpaque;
#else
false;
#endif
#endregion IMixedRealityCameraSettings
}
}
| // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.CameraSystem;
using Microsoft.MixedReality.Toolkit.Utilities;
using UnityEngine;
#if UNITY_WSA
using UnityEngine.XR.WSA;
#endif // UNITY_WSA
namespace Microsoft.MixedReality.Toolkit.WindowsMixedReality
{
/// <summary>
/// Camera settings provider for use with the Unity AR Foundation system.
/// </summary>
[MixedRealityDataProvider(
typeof(IMixedRealityCameraSystem),
SupportedPlatforms.WindowsUniversal,
"Windows Mixed Reality Camera Settings")]
public class WindowsMixedRealityCameraSettings : BaseDataProvider, IMixedRealityCameraSettingsProvider
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="cameraSystem">The instance of the camera system which is managing this provider.</param>
/// <param name="name">Friendly name of the provider.</param>
/// <param name="priority">Provider priority. Used to determine order of instantiation.</param>
/// <param name="profile">The provider's configuration profile.</param>
public WindowsMixedRealityCameraSettings(
IMixedRealityCameraSystem cameraSystem,
string name = null,
uint priority = DefaultPriority,
BaseCameraSettingsProfile profile = null) : base(cameraSystem, name, priority, profile)
{ }
#region IMixedRealityCameraSettings
/// <inheritdoc/>
public bool IsOpaque =>
#if UNITY_WSA
HolographicSettings.IsDisplayOpaque;
#else
false;
#endif
/// <inheritdoc/>
public void ApplyDisplaySettings()
{
MixedRealityCameraProfile cameraProfile = (Service as IMixedRealityCameraSystem)?.CameraProfile;
if (cameraProfile == null) { return; }
if (IsOpaque)
{
CameraCache.Main.clearFlags = cameraProfile.CameraClearFlagsOpaqueDisplay;
CameraCache.Main.nearClipPlane = cameraProfile.NearClipPlaneOpaqueDisplay;
CameraCache.Main.farClipPlane = cameraProfile.FarClipPlaneOpaqueDisplay;
CameraCache.Main.backgroundColor = cameraProfile.BackgroundColorOpaqueDisplay;
QualitySettings.SetQualityLevel(cameraProfile.OpaqueQualityLevel, false);
}
else
{
CameraCache.Main.clearFlags = cameraProfile.CameraClearFlagsTransparentDisplay;
CameraCache.Main.backgroundColor = cameraProfile.BackgroundColorTransparentDisplay;
CameraCache.Main.nearClipPlane = cameraProfile.NearClipPlaneTransparentDisplay;
CameraCache.Main.farClipPlane = cameraProfile.FarClipPlaneTransparentDisplay;
QualitySettings.SetQualityLevel(cameraProfile.TransparentQualityLevel, false);
}
}
#endregion IMixedRealityCameraSettings
}
}
| mit | C# |
c2ab3fee11f9bdd185a4cba0c9d6d378396ab5e9 | Resolve broken xmldoc | smoogipooo/osu-framework,ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework | osu.Framework/Input/StateChanges/TouchInput.cs | osu.Framework/Input/StateChanges/TouchInput.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Input.StateChanges.Events;
using osu.Framework.Input.States;
namespace osu.Framework.Input.StateChanges
{
/// <summary>
/// Denotes a change of a touch input.
/// </summary>
public class TouchInput : IInput
{
/// <summary>
/// The touch structure providing the source and position to move to.
/// </summary>
public readonly Touch Touch;
/// <summary>
/// Whether to activate the provided <see cref="Touch"/>.
/// </summary>
public readonly bool Activate;
/// <summary>
/// Constructs a new <see cref="TouchInput"/>.
/// </summary>
/// <param name="touch">The <see cref="Touch"/>.</param>
/// <param name="activate">Whether to activate the provided <see cref="Touch"/>, must be true if changing position only.</param>
public TouchInput(Touch touch, bool activate)
{
Touch = touch;
Activate = activate;
}
public void Apply(InputState state, IInputStateChangeHandler handler)
{
var touches = state.Touch;
var lastPosition = touches.GetTouchPosition(Touch.Source);
if (lastPosition == Touch.Position)
// The provided touch position did not change,
// mark lastPosition as null to indicate that.
lastPosition = null;
touches.TouchPositions[(int)Touch.Source] = Touch.Position;
bool activityChanged = touches.ActiveSources.SetPressed(Touch.Source, Activate);
if (activityChanged || lastPosition != null)
handler.HandleInputStateChange(new TouchStateChangeEvent(state, this, Touch, Activate, lastPosition));
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Input.StateChanges.Events;
using osu.Framework.Input.States;
namespace osu.Framework.Input.StateChanges
{
/// <summary>
/// Denotes a change of the touch activity & position state.
/// </summary>
public class TouchInput : IInput
{
/// <summary>
/// The touch structure providing the source and position to move to.
/// </summary>
public readonly Touch Touch;
/// <summary>
/// Whether to activate the provided <see cref="Touch"/>.
/// </summary>
public readonly bool Activate;
/// <summary>
/// Constructs a new <see cref="TouchInput"/>.
/// </summary>
/// <param name="touch">The <see cref="Touch"/>.</param>
/// <param name="activate">Whether to activate the provided <see cref="Touch"/>, must be true if changing position only.</param>
public TouchInput(Touch touch, bool activate)
{
Touch = touch;
Activate = activate;
}
public void Apply(InputState state, IInputStateChangeHandler handler)
{
var touches = state.Touch;
var lastPosition = touches.GetTouchPosition(Touch.Source);
if (lastPosition == Touch.Position)
// The provided touch position did not change,
// mark lastPosition as null to indicate that.
lastPosition = null;
touches.TouchPositions[(int)Touch.Source] = Touch.Position;
bool activityChanged = touches.ActiveSources.SetPressed(Touch.Source, Activate);
if (activityChanged || lastPosition != null)
handler.HandleInputStateChange(new TouchStateChangeEvent(state, this, Touch, Activate, lastPosition));
}
}
}
| mit | C# |
421c95156b420c5eda20807419c19393646cc9ab | Fix ClickableText test case | peppy/osu,ZLima12/osu,UselessToucan/osu,EVAST9919/osu,smoogipooo/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu-new,UselessToucan/osu,ZLima12/osu,smoogipoo/osu,smoogipoo/osu,johnneijzen/osu,peppy/osu,2yangk23/osu,NeoAdonis/osu,EVAST9919/osu,johnneijzen/osu,smoogipoo/osu,ppy/osu,2yangk23/osu,UselessToucan/osu,ppy/osu | osu.Game.Tests/Visual/TestCaseClickableText.cs | osu.Game.Tests/Visual/TestCaseClickableText.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using System;
using System.Collections.Generic;
namespace osu.Game.Tests.Visual
{
public class TestCaseClickableText : OsuTestCase
{
public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(ClickableText), typeof(FillFlowContainer) };
private readonly ClickableText text;
public TestCaseClickableText() => Child = new FillFlowContainer
{
Children = new[]
{
new ClickableText { Text = "Default", },
new ClickableText { IsEnabled = false, Text = "Disabled", },
new ClickableText { Text = "Without sounds", IsMuted = true, },
new ClickableText { Text = "Without click sounds", IsClickMuted = true, },
new ClickableText { Text = "Without hover sounds", IsHoverMuted = true, },
text = new ClickableText { Text = "Disables after click (Action)", Action = () => text.IsEnabled = false },
new ClickableText { Text = "Has tooltip", TooltipText = "Yep", },
}
};
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using System;
using System.Collections.Generic;
namespace osu.Game.Tests.Visual
{
public class TestCaseClickableText : OsuTestCase
{
public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(ClickableText), typeof(FillFlowContainer) };
public TestCaseClickableText() => Child = new FillFlowContainer
{
Children = new[]
{
new ClickableText { Text = "Default", },
new ClickableText { IsEnabled = false, Text = "Disabled", },
new ClickableText { Text = "Without sounds", IsMuted = true, },
new ClickableText { Text = "Without click sounds", IsClickMuted = true, },
new ClickableText { Text = "Without hover sounds", IsHoverMuted = true, },
new ClickableText { Text = "Disables after click (Action)", },
new ClickableText { Text = "Has tooltip", TooltipText = "Yep", },
}
};
}
}
| mit | C# |
f747956026d74f02bd6dd59c4ee7e86752c76805 | Use {0:c} rather than ToString("c") where possible. | bleroy/Nwazet.Commerce,bleroy/Nwazet.Commerce | Views/Parts/Product.PriceTiers.cshtml | Views/Parts/Product.PriceTiers.cshtml | @using System.Linq;
@using Nwazet.Commerce.Models;
@{
var priceTiers = new List<PriceTier>(Model.PriceTiers);
var discountedPriceTiers = new List<PriceTier>(Model.DiscountedPriceTiers);
}
@if (Model.PriceTiers != null && Enumerable.Count(Model.PriceTiers) > 0) {
<table class="tiered-prices">
<tr>
<td>@T("Quantity")</td>
<td>@T("Price")</td>
</tr>
@for (var i = 0; i < priceTiers.Count(); i++ ) {
<tr>
<td>@priceTiers[i].Quantity</td>
<td>
@if (priceTiers[i].Price != discountedPriceTiers[i].Price) {
<span class="inactive-price" style="text-decoration:line-through" title="@T("Was {0:c}", priceTiers[i].Price)">@priceTiers[i].Price.ToString("c")</span>
<span class="discounted-price" title="@T("Now {0:c}", discountedPriceTiers[i].Price)">@discountedPriceTiers[i].Price.ToString("c")</span>
}
else {
<span class="regular-price">@priceTiers[i].Price.ToString("c")</span>
}
</td>
</tr>
}
</table>
} | @using System.Linq;
@using Nwazet.Commerce.Models;
@{
var priceTiers = new List<PriceTier>(Model.PriceTiers);
var discountedPriceTiers = new List<PriceTier>(Model.DiscountedPriceTiers);
}
@if (Model.PriceTiers != null && Enumerable.Count(Model.PriceTiers) > 0) {
<table class="tiered-prices">
<tr>
<td>@T("Quantity")</td>
<td>@T("Price")</td>
</tr>
@for (var i = 0; i < priceTiers.Count(); i++ ) {
<tr>
<td>@priceTiers[i].Quantity</td>
<td>
@if (priceTiers[i].Price != discountedPriceTiers[i].Price) {
<span class="inactive-price" style="text-decoration:line-through" title="@T("Was {0}", priceTiers[i].Price.ToString("c"))">@priceTiers[i].Price.ToString("c")</span>
<span class="discounted-price" title="@T("Now {0}", discountedPriceTiers[i].Price.ToString("c"))">@discountedPriceTiers[i].Price.ToString("c")</span>
}
else {
<span class="regular-price">@priceTiers[i].Price.ToString("c")</span>
}
</td>
</tr>
}
</table>
} | bsd-3-clause | C# |
ecedb81e0e570cce01bc6a3ae892ac3ae4479999 | Add missing properties to IActionViewMessage | zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype | src/Glimpse.Agent.Web/Providers/Mvc/Messages/IActionViewMessage.cs | src/Glimpse.Agent.Web/Providers/Mvc/Messages/IActionViewMessage.cs | using System.Collections.Generic;
namespace Glimpse.Agent.AspNet.Mvc.Messages
{
public interface IActionViewMessage
{
string ActionId { get; set; }
string ViewName { get; set; }
bool DidFind { get; set; }
IEnumerable<string> SearchedLocations { get; set; }
string Path { get; set; }
ViewResult ViewData { get; set; }
}
} | using System.Collections.Generic;
namespace Glimpse.Agent.AspNet.Mvc.Messages
{
public interface IActionViewMessage
{
string ActionId { get; set; }
string ViewName { get; set; }
bool DidFind { get; set; }
ViewResult ViewData { get; set; }
}
} | mit | C# |
1a137844c2691c1364319991ebd0543f9a62aa42 | Make same connect.dll work for debug and release (with different destinations on Parse.com) | gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork | src/BloomExe/WebLibraryIntegration/KeyManager.cs | src/BloomExe/WebLibraryIntegration/KeyManager.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Palaso.Extensions;
using Palaso.IO;
namespace Bloom.WebLibraryIntegration
{
/// <summary>
/// This class is responsible for the key bits of information that are needed to access our backend sites.
/// These keys are not very secret and could easily be found, for example, by packet snooping.
/// However, we want to keep them out of source code where someone might be able to do a google search
/// and easily find our keys and use our storage.
/// The keys are currently stored in a file called connections.dll. The installer must place a version of this
/// in the EXE directory. Developers must do so manually.
/// You can see what keys are stored in what order by checking the constructor.
/// Enhance: it may be helpful to use a distinct version of connections.dll for developers, testers,
/// and others who should be working in a sandbox rather than modifying the live data.
/// That will work for Parse.com, where we currently have different API keys for the sandbox.
/// For the S3 data, we currently just use different buckets. If we wanted to, we could put the
/// 'real data' bucket name here also, and put the appropriate one into the testing version of connections.dll.
/// Todo: Some of the real keys are still in our version control history. Before we go live, we may want
/// to change the keys so any keys discovered in our version control are obsolete.
/// </summary>
static class KeyManager
{
public static string S3AccessKey { get; private set; }
public static string S3SecretAccessKey { get; private set; }
public static string ParseApiKey { get; private set; }
public static string ParseApplicationKey { get; private set; }
public static string ParseUnitTestApiKey { get; private set; }
public static string ParseUnitTextApplicationKey { get; private set; }
static KeyManager()
{
var connectionsPath = FileLocator.GetFileDistributedWithApplication("connections.dll");
var lines = File.ReadAllLines(connectionsPath);
S3AccessKey = lines[0];
S3SecretAccessKey = lines[1];
#if DEBUG
// Lines 4 & 5 should be the keys for the BloomLibrarySandbox
ParseApiKey = lines[4];
ParseApplicationKey = lines[5];
#else
// Lines 2 & 3 should be the keys for the real BloomLibrary
ParseApiKey = lines[2];
ParseApplicationKey = lines[3];
#endif
ParseUnitTestApiKey = lines[6];
ParseUnitTextApplicationKey = lines[7];
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Palaso.Extensions;
using Palaso.IO;
namespace Bloom.WebLibraryIntegration
{
/// <summary>
/// This class is responsible for the key bits of information that are needed to access our backend sites.
/// These keys are not very secret and could easily be found, for example, by packet snooping.
/// However, we want to keep them out of source code where someone might be able to do a google search
/// and easily find our keys and use our storage.
/// The keys are currently stored in a file called connections.dll. The installer must place a version of this
/// in the EXE directory. Developers must do so manually.
/// You can see what keys are stored in what order by checking the constructor.
/// Enhance: it may be helpful to use a distinct version of connections.dll for developers, testers,
/// and others who should be working in a sandbox rather than modifying the live data.
/// That will work for Parse.com, where we currently have different API keys for the sandbox.
/// For the S3 data, we currently just use different buckets. If we wanted to, we could put the
/// 'real data' bucket name here also, and put the appropriate one into the testing version of connections.dll.
/// Todo: Some of the real keys are still in our version control history. Before we go live, we may want
/// to change the keys so any keys discovered in our version control are obsolete.
/// </summary>
static class KeyManager
{
public static string S3AccessKey { get; private set; }
public static string S3SecretAccessKey { get; private set; }
public static string ParseApiKey { get; private set; }
public static string ParseApplicationKey { get; private set; }
public static string ParseUnitTestApiKey { get; private set; }
public static string ParseUnitTextApplicationKey { get; private set; }
static KeyManager()
{
var connectionsPath = FileLocator.GetFileDistributedWithApplication("connections.dll");
var lines = File.ReadAllLines(connectionsPath);
S3AccessKey = lines[0];
S3SecretAccessKey = lines[1];
ParseApiKey = lines[2];
ParseApplicationKey = lines[3];
ParseUnitTestApiKey = lines[4];
ParseUnitTextApplicationKey = lines[5];
}
}
}
| mit | C# |
a8f8e84dfdc41f60860f05cdee4226bf3b4b6b4e | Edit it | 2Toad/websocket-sharp,jogibear9988/websocket-sharp,2Toad/websocket-sharp,2Toad/websocket-sharp,jogibear9988/websocket-sharp,sta/websocket-sharp,2Toad/websocket-sharp,sta/websocket-sharp,sta/websocket-sharp,sta/websocket-sharp,jogibear9988/websocket-sharp,jogibear9988/websocket-sharp | websocket-sharp/Net/HttpBasicIdentity.cs | websocket-sharp/Net/HttpBasicIdentity.cs | #region License
/*
* HttpBasicIdentity.cs
*
* This code is derived from System.Net.HttpListenerBasicIdentity.cs of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
using System;
using System.Security.Principal;
namespace WebSocketSharp.Net
{
/// <summary>
/// Holds the username and password from an HTTP Basic authentication attempt.
/// </summary>
public class HttpBasicIdentity : GenericIdentity
{
#region Private Fields
private string _password;
#endregion
#region internal Constructors
internal HttpBasicIdentity (string username, string password)
: base (username, "Basic")
{
_password = password;
}
#endregion
#region Public Properties
/// <summary>
/// Gets the password from the HTTP Basic authentication credentials.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the password.
/// </value>
public virtual string Password {
get {
return _password;
}
}
#endregion
}
}
| #region License
/*
* HttpBasicIdentity.cs
*
* This code is derived from System.Net.HttpListenerBasicIdentity.cs of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
using System;
using System.Security.Principal;
namespace WebSocketSharp.Net
{
/// <summary>
/// Holds the user name and password from the HTTP Basic authentication credentials.
/// </summary>
public class HttpBasicIdentity : GenericIdentity
{
#region Private Fields
private string _password;
#endregion
#region internal Constructors
internal HttpBasicIdentity (string username, string password)
: base (username, "Basic")
{
_password = password;
}
#endregion
#region Public Properties
/// <summary>
/// Gets the password from the HTTP Basic authentication credentials.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the password.
/// </value>
public virtual string Password {
get {
return _password;
}
}
#endregion
}
}
| mit | C# |
0e4cef7caa64070d6b1fb9c42206f0a6b8864ae2 | clean up | dkataskin/bstrkr | bstrkr.mobile/bstrkr.android/Views/MapView.cs | bstrkr.mobile/bstrkr.android/Views/MapView.cs | using System;
using Android.Gms.Common;
using Android.Gms.Maps;
using Android.OS;
using Android.Views;
using Cirrious.MvvmCross.Binding.BindingContext;
using Cirrious.MvvmCross.Binding.Droid.BindingContext;
using Cirrious.MvvmCross.Droid.Fragging.Fragments;
using Xamarin;
using bstrkr.core.android.extensions;
using bstrkr.core.consts;
using bstrkr.mvvm.converters;
using bstrkr.mvvm.maps;
using bstrkr.mvvm.viewmodels;
using bstrkr.mvvm.views;
namespace bstrkr.android.views
{
public class MapView : MvxFragment
{
private IMapView _mapViewWrapper;
private VehicleMarkerManager _vehicleMarkerManager;
private RouteStopMarkerManager _routeStopMarkerManager;
private MapLocationManager _mapLocationManager;
public MapView()
{
this.RetainInstance = true;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var ignored = base.OnCreateView(inflater, container, savedInstanceState);
this.EnsureBindingContextIsSet(savedInstanceState);
return this.BindingInflate(Resource.Layout.fragment_map_view, null);
}
public override void OnViewCreated(View view, Bundle savedInstanceState)
{
base.OnViewCreated(view, savedInstanceState);
try
{
MapsInitializer.Initialize(this.Activity.ApplicationContext);
}
catch (GooglePlayServicesNotAvailableException e)
{
Insights.Report(e, ReportSeverity.Error);
}
var mapFragment = (SupportMapFragment)this.ChildFragmentManager.FindFragmentById(Resource.Id.map);
GoogleMap map = mapFragment.Map;
if (map != null)
{
var cameraUpdate = CameraUpdateFactory.NewLatLngZoom(
AppConsts.DefaultLocation.ToLatLng(),
AppConsts.DefaultZoom);
map.MyLocationEnabled = true;
map.MoveCamera(cameraUpdate);
_mapViewWrapper = new MonoDroidGoogleMapsView(map);
_vehicleMarkerManager = new VehicleMarkerManager(_mapViewWrapper);
_routeStopMarkerManager = new RouteStopMarkerManager(_mapViewWrapper);
_mapLocationManager = new MapLocationManager(_mapViewWrapper);
}
var set = this.CreateBindingSet<MapView, MapViewModel>();
set.Bind(_vehicleMarkerManager).For(m => m.ItemsSource).To(vm => vm.Vehicles);
set.Bind(_routeStopMarkerManager).For(m => m.ItemsSource).To(vm => vm.Stops);
set.Bind(_mapLocationManager).For(m => m.Location).To(vm => vm.Location);
set.Bind(_mapViewWrapper).For(x => x.Zoom)
.To(vm => vm.MarkerSize)
.WithConversion(new ZoomToMarkerSizeConverter());
set.Apply();
}
}
} | using System;
using Android.Gms.Common;
using Android.Gms.Maps;
using Android.OS;
using Android.Views;
using Cirrious.MvvmCross.Binding.BindingContext;
using Cirrious.MvvmCross.Binding.Droid.BindingContext;
using Cirrious.MvvmCross.Droid.Fragging.Fragments;
using Xamarin;
using bstrkr.core.android.extensions;
using bstrkr.core.consts;
using bstrkr.mvvm.converters;
using bstrkr.mvvm.maps;
using bstrkr.mvvm.viewmodels;
using bstrkr.mvvm.views;
namespace bstrkr.android.views
{
public class MapView : MvxFragment
{
private IMapView _mapViewWrapper;
private VehicleMarkerManager _vehicleMarkerManager;
private RouteStopMarkerManager _routeStopMarkerManager;
private MapLocationManager _mapLocationManager;
public MapView()
{
this.RetainInstance = true;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var ignored = base.OnCreateView(inflater, container, savedInstanceState);
this.EnsureBindingContextIsSet(savedInstanceState);
return this.BindingInflate(Resource.Layout.fragment_map_view, null);
}
public override void OnViewCreated(View view, Bundle savedInstanceState)
{
base.OnViewCreated(view, savedInstanceState);
try
{
MapsInitializer.Initialize(this.Activity.ApplicationContext);
}
catch (GooglePlayServicesNotAvailableException e)
{
Insights.Report(e, ReportSeverity.Error);
}
var mapFragment = (SupportMapFragment)this.FragmentManager.FindFragmentById(Resource.Id.map);
GoogleMap map = mapFragment.Map;
if (map != null)
{
var cameraUpdate = CameraUpdateFactory.NewLatLngZoom(
AppConsts.DefaultLocation.ToLatLng(),
AppConsts.DefaultZoom);
map.MyLocationEnabled = true;
map.MoveCamera(cameraUpdate);
_mapViewWrapper = new MonoDroidGoogleMapsView(map);
_vehicleMarkerManager = new VehicleMarkerManager(_mapViewWrapper);
_routeStopMarkerManager = new RouteStopMarkerManager(_mapViewWrapper);
_mapLocationManager = new MapLocationManager(_mapViewWrapper);
}
var set = this.CreateBindingSet<MapView, MapViewModel>();
set.Bind(_vehicleMarkerManager).For(m => m.ItemsSource).To(vm => vm.Vehicles);
set.Bind(_routeStopMarkerManager).For(m => m.ItemsSource).To(vm => vm.Stops);
set.Bind(_mapLocationManager).For(m => m.Location).To(vm => vm.Location);
set.Bind(_mapViewWrapper).For(x => x.Zoom)
.To(vm => vm.MarkerSize)
.WithConversion(new ZoomToMarkerSizeConverter());
set.Apply();
}
}
} | bsd-2-clause | C# |
2ee4fb0fa5b9eb815cb7bd7fb57a6d50608face1 | Rename variable for funzies | substantial/mapify-example | app/Assets/Scripts/GameInitializer.cs | app/Assets/Scripts/GameInitializer.cs | using UnityEngine;
using System.Collections;
using Substantial;
public class GameInitializer : MonoBehaviour {
public TextAsset LevelAsset;
public TileRepository TileRepository;
public Transform LevelContainer;
public float TileSize = 1.0f;
private void Start() {
Mapify.Generate(LevelAsset.text, LevelContainer, TileRepository, TileSize, MapifyLayout.Vertical);
}
}
| using UnityEngine;
using System.Collections;
using Substantial;
public class GameInitializer : MonoBehaviour {
public TextAsset LevelAsset;
public TileRepository TileRepository;
public Transform LevelContainer;
public float TileOffset = 1.0f;
private void Start() {
Mapify.Generate(LevelAsset.text, LevelContainer, TileRepository, TileOffset, MapifyLayout.Vertical);
}
}
| mit | C# |
2f9bd51e03ed1dead00bfe9abc108b59ad9c38f0 | refactor to use map and traverse instead of match | louthy/language-ext,StefanBertels/language-ext,StanJav/language-ext | Samples/Contoso/Contoso.Application/Instructors/Commands/CreateInstructorHandler.cs | Samples/Contoso/Contoso.Application/Instructors/Commands/CreateInstructorHandler.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using Contoso.Core;
using Contoso.Core.Domain;
using Contoso.Core.Interfaces.Repositories;
using LanguageExt;
using MediatR;
using static Contoso.Validators;
using static LanguageExt.Prelude;
namespace Contoso.Application.Instructors.Commands
{
public class CreateInstructorHandler : IRequestHandler<CreateInstructor, Either<Error, int>>
{
private readonly IInstructorRepository _instructorRepository;
public CreateInstructorHandler(IInstructorRepository instructorRepository) => _instructorRepository = instructorRepository;
public Task<Either<Error, int>> Handle(CreateInstructor request, CancellationToken cancellationToken) =>
Validate(request)
.Map(PersistInstructor)
.ToEither()
.MapLeft(errors => errors.Join())
.Traverse(t => t);
private Task<int> PersistInstructor(Instructor instructor) =>
_instructorRepository.Add(instructor);
private Validation<Error, Instructor> Validate(CreateInstructor command) =>
(ValidateFirstName(command), ValidateLastName(command), ValidateHireDate(command))
.Apply((f, s, h) => new Instructor { FirstName = f, LastName = s, HireDate = h });
private Validation<Error, string> ValidateFirstName(CreateInstructor createStudent) =>
NotEmpty(createStudent.FirstName)
.Bind(firstName => NotLongerThan(50)(firstName));
private Validation<Error, string> ValidateLastName(CreateInstructor createStudent) =>
NotEmpty(createStudent.LastName)
.Bind(lastName => NotLongerThan(50)(lastName));
private Validation<Error, DateTime> ValidateHireDate(CreateInstructor createStudent) =>
createStudent.HireDate > DateTime.Now.AddYears(5)
? Fail<Error, DateTime>($"The enrollment date is too far in the future")
: Success<Error, DateTime>(createStudent.HireDate);
}
}
| using System;
using System.Threading;
using System.Threading.Tasks;
using Contoso.Core;
using Contoso.Core.Domain;
using Contoso.Core.Interfaces.Repositories;
using LanguageExt;
using MediatR;
using static Contoso.Validators;
using static LanguageExt.Prelude;
namespace Contoso.Application.Instructors.Commands
{
public class CreateInstructorHandler : IRequestHandler<CreateInstructor, Either<Error, int>>
{
private readonly IInstructorRepository _instructorRepository;
public CreateInstructorHandler(IInstructorRepository instructorRepository) => _instructorRepository = instructorRepository;
public Task<Either<Error, int>> Handle(CreateInstructor request, CancellationToken cancellationToken) =>
Validate(request)
.Map(i => _instructorRepository.Add(i))
.MatchAsync<Either<Error, int>>(
SuccAsync: async id => Right(await id),
Fail: err => Left(err.Join()));
private Validation<Error, Instructor> Validate(CreateInstructor command) =>
(ValidateFirstName(command), ValidateLastName(command), ValidateHireDate(command))
.Apply((f, s, h) => new Instructor { FirstName = f, LastName = s, HireDate = h });
private Validation<Error, string> ValidateFirstName(CreateInstructor createStudent) =>
NotEmpty(createStudent.FirstName)
.Bind(firstName => NotLongerThan(50)(firstName));
private Validation<Error, string> ValidateLastName(CreateInstructor createStudent) =>
NotEmpty(createStudent.LastName)
.Bind(lastName => NotLongerThan(50)(lastName));
private Validation<Error, DateTime> ValidateHireDate(CreateInstructor createStudent) =>
createStudent.HireDate > DateTime.Now.AddYears(5)
? Fail<Error, DateTime>($"The enrollment date is too far in the future")
: Success<Error, DateTime>(createStudent.HireDate);
}
}
| mit | C# |
86dfed38584e664b956c3df9f816873b7e2faa8a | bump version | raml-org/raml-dotnet-parser,raml-org/raml-dotnet-parser | source/AMF.Parser/Properties/AssemblyInfo.cs | source/AMF.Parser/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AMF.Parser")]
[assembly: AssemblyDescription("RAML and OAS (swagger) parser for .Net")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MuleSoft")]
[assembly: AssemblyProduct("AMF.Parser")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("af24976e-d021-4aa5-b7d7-1de6574cd6f6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.9.5")]
[assembly: AssemblyFileVersion("0.9.5")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AMF.Parser")]
[assembly: AssemblyDescription("RAML and OAS (swagger) parser for .Net")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MuleSoft")]
[assembly: AssemblyProduct("AMF.Parser")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("af24976e-d021-4aa5-b7d7-1de6574cd6f6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.9.4.1")]
[assembly: AssemblyFileVersion("0.9.4.1")]
| apache-2.0 | C# |
1e66f1c4b0a8435c6ffd9dcc47e416f504034edf | fix running tests from within VS. No idea if this is the correct fix and what 'SideBySideSpecification' is. | rflechner/FAKE,MichalDepta/FAKE,MichalDepta/FAKE,MichalDepta/FAKE,MichalDepta/FAKE,Kazark/FAKE,MiloszKrajewski/FAKE,Kazark/FAKE,MiloszKrajewski/FAKE,beeker/FAKE,MiloszKrajewski/FAKE,rflechner/FAKE,beeker/FAKE,rflechner/FAKE,rflechner/FAKE,Kazark/FAKE,MiloszKrajewski/FAKE,Kazark/FAKE,beeker/FAKE,beeker/FAKE | src/test/Test.FAKECore/TestData.cs | src/test/Test.FAKECore/TestData.cs | using System;
using System.IO;
namespace Test.FAKECore
{
public static class TestData
{
public static string SideBySideFolder;
static TestData()
{
try
{
BaseDir = Directory.GetCurrentDirectory();
InitializeFromBase();
}
catch (UnauthorizedAccessException)
{
// Take temp (for example when running in VS)
BaseDir = Path.GetTempFileName();
File.Delete(BaseDir);
CreateDir(BaseDir);
InitializeFromBase();
}
}
private static void InitializeFromBase()
{
SideBySideFolder =
new DirectoryInfo(Path.Combine(BaseDir, "SideBySideSpecification")).FullName;
TestDir = Path.Combine(BaseDir, "Test");
CreateDir(TestDir);
TestDir2 = Path.Combine(BaseDir, "Test2");
CreateDir(TestDir2);
SubDir1 = Path.Combine(TestDir, "Dir1");
SubDir7 = Path.Combine(TestDir, "Dir7");
TestDataDir = "TestData";
}
public static string TestDir { get; set; }
public static string TestDir2 { get; set; }
public static string BaseDir { get; set; }
public static string SubDir1 { get; set; }
public static string SubDir7 { get; set; }
public static string TestDataDir { get; set; }
static void CreateDir(string testDir)
{
var di = new DirectoryInfo(testDir);
if (!di.Exists)
di.Create();
}
}
} | using System;
using System.IO;
namespace Test.FAKECore
{
public static class TestData
{
public static readonly string SideBySideFolder =
new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "SideBySideSpecification")).FullName;
static TestData()
{
BaseDir = Directory.GetCurrentDirectory();
TestDir = Path.Combine(BaseDir, "Test");
CreateDir(TestDir);
TestDir2 = Path.Combine(BaseDir, "Test2");
CreateDir(TestDir2);
SubDir1 = Path.Combine(TestDir, "Dir1");
SubDir7 = Path.Combine(TestDir, "Dir7");
TestDataDir = "TestData";
}
public static string TestDir { get; set; }
public static string TestDir2 { get; set; }
public static string BaseDir { get; set; }
public static string SubDir1 { get; set; }
public static string SubDir7 { get; set; }
public static string TestDataDir { get; set; }
static void CreateDir(string testDir)
{
var di = new DirectoryInfo(testDir);
if (!di.Exists)
di.Create();
}
}
} | apache-2.0 | C# |
1d737d0b1867d238fd8d62967214fb48a2beac0c | Bump version to 0.6.5 | quisquous/cactbot,quisquous/cactbot,sqt/cactbot,quisquous/cactbot,sqt/cactbot,sqt/cactbot,sqt/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,sqt/cactbot | CactbotOverlay/Properties/AssemblyInfo.cs | CactbotOverlay/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CactbotOverlay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CactbotOverlay")]
[assembly: AssemblyCopyright("Copyright 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")]
// Version:
// - Major Version
// - Minor Version
// - Build Number
// - Revision
// GitHub has only 3 version components, so Revision should always be 0.
[assembly: AssemblyVersion("0.6.5.0")]
[assembly: AssemblyFileVersion("0.6.5.0")] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CactbotOverlay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CactbotOverlay")]
[assembly: AssemblyCopyright("Copyright 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")]
// Version:
// - Major Version
// - Minor Version
// - Build Number
// - Revision
// GitHub has only 3 version components, so Revision should always be 0.
[assembly: AssemblyVersion("0.6.4.0")]
[assembly: AssemblyFileVersion("0.6.4.0")] | apache-2.0 | C# |
0e6fab4149c967a86b0bfd7e7ab408f4a2f8d189 | add total | lderache/LeTruck,lderache/LeTruck,lderache/LeTruck | src/mvc5/TheTruck.Web/Views/Cart/ShowCart.cshtml | src/mvc5/TheTruck.Web/Views/Cart/ShowCart.cshtml | @model IEnumerable<TheTruck.Web.Models.CartViewModel>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Category)
</th>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th>
@Html.DisplayNameFor(model => model.Image)
</th>
<th>
@Html.DisplayNameFor(model => model.Quantity)
</th>
<th>
@Html.DisplayNameFor(model => model.SubTotal)
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Category)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.Image)
</td>
<td>
@Html.DisplayFor(modelItem => item.Quantity)
</td>
<td>
@Html.DisplayFor(modelItem => item.SubTotal)
</td>
</tr>
}
<tr>
<td>@Model.Sum(x => x.SubTotal)</td>
</tr>
</table>
| @model IEnumerable<TheTruck.Web.Models.CartViewModel>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Category)
</th>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th>
@Html.DisplayNameFor(model => model.Image)
</th>
<th>
@Html.DisplayNameFor(model => model.Quantity)
</th>
<th>
@Html.DisplayNameFor(model => model.SubTotal)
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Category)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.Image)
</td>
<td>
@Html.DisplayFor(modelItem => item.Quantity)
</td>
<td>
@Html.DisplayFor(modelItem => item.SubTotal)
</td>
</tr>
}
</table>
| mit | C# |
67df96c63d2ed5bd5d2a3606eae8fa63a08cf961 | fix reyes voicelines not extracting | overtools/OWLib | DataTool/ToolLogic/Extract/ExtractNPCVoice.cs | DataTool/ToolLogic/Extract/ExtractNPCVoice.cs | using System;
using System.Collections.Generic;
using System.IO;
using DataTool.FindLogic;
using DataTool.Flag;
using DataTool.Helper;
using DataTool.JSON;
using TankLib.STU.Types;
using static DataTool.Helper.STUHelper;
using static DataTool.Helper.IO;
namespace DataTool.ToolLogic.Extract {
[Tool("extract-npc-voice", Description = "Extracts NPC voicelines.", CustomFlags = typeof(ExtractFlags))]
class ExtractNPCVoice : JSONTool, ITool {
private const string Container = "NPCVoice";
private static readonly List<string> WhitelistedNPCs = new List<string> {"OR14-NS", "B73-NS"};
public void Parse(ICLIFlags toolFlags) {
string basePath;
if (toolFlags is ExtractFlags flags) {
basePath = Path.Combine(flags.OutputPath, Container);
} else {
throw new Exception("no output path");
}
foreach (var guid in Program.TrackedFiles[0x5F]) {
var voiceSet = GetInstance<STUVoiceSet>(guid);
if (voiceSet == null) continue;
var npcName = $"{GetString(voiceSet.m_269FC4E9)} {GetString(voiceSet.m_C0835C08)}".Trim();
if (string.IsNullOrEmpty(npcName)) {
continue;
}
var npcFileName = GetValidFilename(npcName);
Logger.Log($"Processing NPC {npcName}");
var info = new Combo.ComboInfo();
var ignoreGroups = !WhitelistedNPCs.Contains(npcName);
ExtractHeroVoiceBetter.SaveVoiceSet(flags, basePath, npcFileName, guid, ref info, ignoreGroups: ignoreGroups);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using DataTool.FindLogic;
using DataTool.Flag;
using DataTool.Helper;
using DataTool.JSON;
using TankLib.STU.Types;
using static DataTool.Helper.STUHelper;
using static DataTool.Helper.IO;
namespace DataTool.ToolLogic.Extract {
[Tool("extract-npc-voice", Description = "Extracts NPC voicelines.", CustomFlags = typeof(ExtractFlags))]
class ExtractNPCVoice : JSONTool, ITool {
private const string Container = "NPCVoice";
private static readonly List<string> WhitelistedNPCs = new List<string> {"OR14-NS", "B73-NS"};
public void Parse(ICLIFlags toolFlags) {
string basePath;
if (toolFlags is ExtractFlags flags) {
basePath = Path.Combine(flags.OutputPath, Container);
} else {
throw new Exception("no output path");
}
foreach (var guid in Program.TrackedFiles[0x5F]) {
var voiceSet = GetInstance<STUVoiceSet>(guid);
if (voiceSet == null) continue;
var npcName = GetValidFilename(GetString(voiceSet.m_269FC4E9));
if (npcName == null) continue;
Logger.Log($"Processing NPC {npcName}");
var info = new Combo.ComboInfo();
var ignoreGroups = !WhitelistedNPCs.Contains(npcName);
ExtractHeroVoiceBetter.SaveVoiceSet(flags, basePath, npcName, guid, ref info, ignoreGroups: ignoreGroups);
}
}
}
}
| mit | C# |
ea10907f6e927a0dab596159dfa28200720603d1 | Update AccessTokenResponse.cs | Q42/Q42.HueApi | src/Q42.HueApi/Models/AccessTokenResponse.cs | src/Q42.HueApi/Models/AccessTokenResponse.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Q42.HueApi.Models
{
public class AccessTokenResponse
{
public DateTimeOffset CreatedDate { get; set; }
public string Access_token { get; set; }
public int Expires_in { get; set; }
public string Refresh_token { get; set; }
public string Token_type { get; set; }
public AccessTokenResponse()
{
CreatedDate = DateTimeOffset.UtcNow;
}
public DateTimeOffset AccessTokenExpireTime()
{
return CreatedDate.AddSeconds(Expires_in);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Q42.HueApi.Models
{
public class AccessTokenResponse
{
public DateTimeOffset CreatedDate { get; set; }
public string Access_token { get; set; }
public int Access_token_expires_in { get; set; }
public string Refresh_token { get; set; }
public int Refresh_token_expires_in { get; set; }
public string Token_type { get; set; }
public AccessTokenResponse()
{
CreatedDate = DateTimeOffset.UtcNow;
}
public DateTimeOffset AccessTokenExpireTime()
{
return CreatedDate.AddSeconds(Access_token_expires_in);
}
public DateTimeOffset RefreshTokenExpireTime()
{
return CreatedDate.AddSeconds(Refresh_token_expires_in);
}
}
}
| mit | C# |
67e39d6181a3d5f7ece310c264dca1fcb2580edb | Remove unnecessary null check from TriggerWrapperComparator.GetHashCode() (#1466) | sean-gilliam/quartznet,quartznet/quartznet,quartznet/quartznet,quartznet/quartznet,quartznet/quartznet,sean-gilliam/quartznet,sean-gilliam/quartznet,sean-gilliam/quartznet,quartznet/quartznet,sean-gilliam/quartznet | src/Quartz/Simpl/TriggerWrapperComparator.cs | src/Quartz/Simpl/TriggerWrapperComparator.cs | using System;
using System.Collections.Generic;
namespace Quartz.Simpl
{
/// <summary>
/// Comparer for trigger wrappers.
/// </summary>
internal class TriggerWrapperComparator : IComparer<TriggerWrapper>, IEquatable<TriggerWrapperComparator>
{
private readonly TriggerTimeComparator ttc = new TriggerTimeComparator();
public int Compare(TriggerWrapper? trig1, TriggerWrapper? trig2)
{
return ttc.Compare(trig1?.Trigger, trig2?.Trigger);
}
public override bool Equals(object? obj)
{
return obj is TriggerWrapperComparator;
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public bool Equals(TriggerWrapperComparator? other)
{
return true;
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
/// <filterpriority>2</filterpriority>
public override int GetHashCode()
{
return ttc.GetHashCode();
}
}
} | using System;
using System.Collections.Generic;
namespace Quartz.Simpl
{
/// <summary>
/// Comparer for trigger wrappers.
/// </summary>
internal class TriggerWrapperComparator : IComparer<TriggerWrapper>, IEquatable<TriggerWrapperComparator>
{
private readonly TriggerTimeComparator ttc = new TriggerTimeComparator();
public int Compare(TriggerWrapper? trig1, TriggerWrapper? trig2)
{
return ttc.Compare(trig1?.Trigger, trig2?.Trigger);
}
public override bool Equals(object? obj)
{
return obj is TriggerWrapperComparator;
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public bool Equals(TriggerWrapperComparator? other)
{
return true;
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
/// <filterpriority>2</filterpriority>
public override int GetHashCode()
{
return ttc?.GetHashCode() ?? 0;
}
}
} | apache-2.0 | C# |
d6753f6f65c5fb5a2ac1c74de51a51b40c22100c | Implement AddHostnameCommand#Execute | appharbor/appharbor-cli | src/AppHarbor/Commands/AddHostnameCommand.cs | src/AppHarbor/Commands/AddHostnameCommand.cs | using System;
namespace AppHarbor.Commands
{
public class AddHostnameCommand : ICommand
{
private readonly IApplicationConfiguration _applicationConfiguration;
private readonly IAppHarborClient _appharborClient;
public AddHostnameCommand(IApplicationConfiguration applicationConfiguration, IAppHarborClient appharborClient)
{
_applicationConfiguration = applicationConfiguration;
_appharborClient = appharborClient;
}
public void Execute(string[] arguments)
{
if (arguments.Length == 0)
{
throw new CommandException("No hostname was specified");
}
var applicationId = _applicationConfiguration.GetApplicationId();
_appharborClient.CreateHostname(applicationId, arguments[0]);
}
}
}
| using System;
namespace AppHarbor.Commands
{
public class AddHostnameCommand : ICommand
{
private readonly IApplicationConfiguration _applicationConfiguration;
private readonly IAppHarborClient _appharborClient;
public AddHostnameCommand(IApplicationConfiguration applicationConfiguration, IAppHarborClient appharborClient)
{
_applicationConfiguration = applicationConfiguration;
_appharborClient = appharborClient;
}
public void Execute(string[] arguments)
{
if (arguments.Length == 0)
{
throw new CommandException("No hostname was specified");
}
throw new NotImplementedException();
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.