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 |
|---|---|---|---|---|---|---|---|---|
fc34e2ef7feca53a9cbc9f689e2181511742c512 | Add a level script that can trigger the ending cutscene | makerslocal/LudumDare38 | bees-in-the-trap/Assets/Scripts/BuilderLevel.cs | bees-in-the-trap/Assets/Scripts/BuilderLevel.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BuilderLevel : MonoBehaviour {
public CameraManager camera;
public void doTakeoff() {
double time = 1.5;
Vector3 pos = camera.transform.position;
pos.y += -10;
//camera.scootTo (pos, time);
camera.rotateTo (new Vector3 (0, 0, 180), time);
camera.zoomTo (25, time);
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyUp ("return")) {
doTakeoff ();
}
}
}
| mit | C# | |
bbff1fa76ea492efc461d1d0d5288f800efc3b5f | Create FixedRingBuffer.cs | efruchter/UnityUtilities | MiscDataStructures/FixedRingBuffer.cs | MiscDataStructures/FixedRingBuffer.cs | namespace ADT
{
using UnityEngine.Assertions;
public class FixedRingBuffer<T>
{
public T[] _buffer;
public DequeueMemoryPolicy dequeuePolicy;
int _firstEntryIndex;
public int Count { private set; get; }
public int Capacity => _buffer.Length;
public bool NonEmpty => Count > 0;
public bool Empty => Count == 0;
public FixedRingBuffer(int capacity, DequeueMemoryPolicy dequeuePolicy)
{
_buffer = new T[capacity];
_firstEntryIndex = 0;
this.dequeuePolicy = dequeuePolicy;
}
public FixedRingBuffer(int capacity) : this(capacity, DequeueMemoryPolicy.Clear)
{
}
public int GetRawIndex(int relativeIndex)
{
Assert.IsTrue(_buffer.Length > 0);
return (_firstEntryIndex + relativeIndex) % _buffer.Length;
}
public T this[int relativeIndex]
{
get
{
Assert.IsTrue(Count > 0);
return _buffer[GetRawIndex(relativeIndex)];
}
set
{
Assert.IsTrue(Count >= 0);
_buffer[GetRawIndex(relativeIndex)] = value;
}
}
public T Dequeue()
{
Assert.IsTrue(Count > 0);
var t = _buffer[_firstEntryIndex];
if (dequeuePolicy == DequeueMemoryPolicy.Clear)
{
_buffer[_firstEntryIndex] = default;
}
_firstEntryIndex = GetRawIndex(1);
Count--;
return t;
}
public void Enqueue(T t)
{
Assert.IsTrue(Count <= Capacity);
if (Count == Capacity)
{
Dequeue();
}
_buffer[GetRawIndex(Count)] = t;
Count++;
}
public enum DequeueMemoryPolicy
{
Preserve, Clear
}
}
}
| mit | C# | |
5f5f0916a69eaa1162e55fabcb6e988948efc0c1 | Add tracingheader for support Diagnostics | dotnetcore/CAP,ouraspnet/cap,dotnetcore/CAP,dotnetcore/CAP | src/DotNetCore.CAP/Diagnostics/TracingHeaders.cs | src/DotNetCore.CAP/Diagnostics/TracingHeaders.cs | // Copyright (c) .NET Core Community. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace DotNetCore.CAP.Diagnostics
{
public class TracingHeaders : IEnumerable<KeyValuePair<string, string>>
{
private List<KeyValuePair<string, string>> _dataStore;
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
return _dataStore.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Add(string name, string value)
{
if (_dataStore == null)
{
_dataStore = new List<KeyValuePair<string, string>>();
}
_dataStore.Add(new KeyValuePair<string, string>(name, value));
}
public bool Contains(string name)
{
return _dataStore != null && _dataStore.Any(x => x.Key == name);
}
public void Remove(string name)
{
_dataStore?.RemoveAll(x => x.Key == name);
}
public void Cleaar()
{
_dataStore?.Clear();
}
}
} | mit | C# | |
230ccbb556f7fbe7664fcee9adbb20a31eeed213 | Fix xml comment | damianh/Nancy,horsdal/Nancy,NancyFx/Nancy,MetSystem/Nancy,charleypeng/Nancy,adamhathcock/Nancy,dbolkensteyn/Nancy,fly19890211/Nancy,duszekmestre/Nancy,anton-gogolev/Nancy,Worthaboutapig/Nancy,xt0rted/Nancy,hitesh97/Nancy,davidallyoung/Nancy,jmptrader/Nancy,JoeStead/Nancy,jchannon/Nancy,joebuschmann/Nancy,albertjan/Nancy,dbabox/Nancy,jongleur1983/Nancy,AIexandr/Nancy,grumpydev/Nancy,EliotJones/NancyTest,cgourlay/Nancy,tareq-s/Nancy,jchannon/Nancy,dbabox/Nancy,davidallyoung/Nancy,daniellor/Nancy,tsdl2013/Nancy,tsdl2013/Nancy,wtilton/Nancy,sroylance/Nancy,anton-gogolev/Nancy,rudygt/Nancy,sloncho/Nancy,MetSystem/Nancy,charleypeng/Nancy,fly19890211/Nancy,jmptrader/Nancy,anton-gogolev/Nancy,AlexPuiu/Nancy,sloncho/Nancy,jongleur1983/Nancy,ayoung/Nancy,xt0rted/Nancy,khellang/Nancy,jeff-pang/Nancy,AIexandr/Nancy,NancyFx/Nancy,felipeleusin/Nancy,fly19890211/Nancy,asbjornu/Nancy,JoeStead/Nancy,wtilton/Nancy,daniellor/Nancy,sloncho/Nancy,nicklv/Nancy,jongleur1983/Nancy,thecodejunkie/Nancy,blairconrad/Nancy,tparnell8/Nancy,tsdl2013/Nancy,cgourlay/Nancy,murador/Nancy,dbabox/Nancy,adamhathcock/Nancy,AcklenAvenue/Nancy,horsdal/Nancy,charleypeng/Nancy,dbolkensteyn/Nancy,albertjan/Nancy,asbjornu/Nancy,nicklv/Nancy,vladlopes/Nancy,sadiqhirani/Nancy,tareq-s/Nancy,adamhathcock/Nancy,phillip-haydon/Nancy,tparnell8/Nancy,xt0rted/Nancy,guodf/Nancy,AcklenAvenue/Nancy,sadiqhirani/Nancy,lijunle/Nancy,damianh/Nancy,JoeStead/Nancy,dbolkensteyn/Nancy,AcklenAvenue/Nancy,VQComms/Nancy,wtilton/Nancy,guodf/Nancy,vladlopes/Nancy,charleypeng/Nancy,VQComms/Nancy,joebuschmann/Nancy,asbjornu/Nancy,davidallyoung/Nancy,ayoung/Nancy,khellang/Nancy,lijunle/Nancy,adamhathcock/Nancy,JoeStead/Nancy,khellang/Nancy,SaveTrees/Nancy,jonathanfoster/Nancy,davidallyoung/Nancy,ccellar/Nancy,jchannon/Nancy,tparnell8/Nancy,daniellor/Nancy,danbarua/Nancy,EIrwin/Nancy,cgourlay/Nancy,Novakov/Nancy,EIrwin/Nancy,thecodejunkie/Nancy,VQComms/Nancy,hitesh97/Nancy,cgourlay/Nancy,dbolkensteyn/Nancy,jeff-pang/Nancy,khellang/Nancy,duszekmestre/Nancy,murador/Nancy,jmptrader/Nancy,rudygt/Nancy,SaveTrees/Nancy,charleypeng/Nancy,malikdiarra/Nancy,phillip-haydon/Nancy,wtilton/Nancy,EliotJones/NancyTest,malikdiarra/Nancy,murador/Nancy,ccellar/Nancy,felipeleusin/Nancy,malikdiarra/Nancy,thecodejunkie/Nancy,AIexandr/Nancy,jchannon/Nancy,asbjornu/Nancy,grumpydev/Nancy,AcklenAvenue/Nancy,sroylance/Nancy,tparnell8/Nancy,murador/Nancy,jonathanfoster/Nancy,MetSystem/Nancy,danbarua/Nancy,tareq-s/Nancy,jonathanfoster/Nancy,sadiqhirani/Nancy,dbabox/Nancy,Worthaboutapig/Nancy,EliotJones/NancyTest,jeff-pang/Nancy,ccellar/Nancy,AlexPuiu/Nancy,AIexandr/Nancy,blairconrad/Nancy,davidallyoung/Nancy,danbarua/Nancy,joebuschmann/Nancy,vladlopes/Nancy,phillip-haydon/Nancy,tareq-s/Nancy,EliotJones/NancyTest,hitesh97/Nancy,joebuschmann/Nancy,blairconrad/Nancy,SaveTrees/Nancy,xt0rted/Nancy,asbjornu/Nancy,felipeleusin/Nancy,malikdiarra/Nancy,blairconrad/Nancy,tsdl2013/Nancy,NancyFx/Nancy,VQComms/Nancy,duszekmestre/Nancy,Worthaboutapig/Nancy,ccellar/Nancy,ayoung/Nancy,Novakov/Nancy,sadiqhirani/Nancy,SaveTrees/Nancy,jeff-pang/Nancy,AlexPuiu/Nancy,albertjan/Nancy,rudygt/Nancy,vladlopes/Nancy,hitesh97/Nancy,fly19890211/Nancy,Worthaboutapig/Nancy,grumpydev/Nancy,lijunle/Nancy,danbarua/Nancy,guodf/Nancy,phillip-haydon/Nancy,Novakov/Nancy,NancyFx/Nancy,nicklv/Nancy,damianh/Nancy,EIrwin/Nancy,duszekmestre/Nancy,sroylance/Nancy,albertjan/Nancy,felipeleusin/Nancy,nicklv/Nancy,jonathanfoster/Nancy,VQComms/Nancy,thecodejunkie/Nancy,jchannon/Nancy,rudygt/Nancy,sroylance/Nancy,horsdal/Nancy,ayoung/Nancy,horsdal/Nancy,AlexPuiu/Nancy,EIrwin/Nancy,daniellor/Nancy,guodf/Nancy,jongleur1983/Nancy,Novakov/Nancy,AIexandr/Nancy,jmptrader/Nancy,grumpydev/Nancy,sloncho/Nancy,lijunle/Nancy,MetSystem/Nancy,anton-gogolev/Nancy | src/Nancy/Conventions/ViewLocationConventions.cs | src/Nancy/Conventions/ViewLocationConventions.cs | namespace Nancy.Conventions
{
using System;
using System.Collections;
using System.Collections.Generic;
using Nancy.ViewEngines;
/// <summary>
/// This is a wrapper around the type
/// <c>IEnumerable<Func<string, object, ViewLocationContext, string>></c> and its
/// only purpose is to make Ninject happy which was throwing an exception
/// when constructor injecting this type.
/// </summary>
public class ViewLocationConventions : IEnumerable<Func<string, object, ViewLocationContext, string>>
{
private readonly IEnumerable<Func<string, object, ViewLocationContext, string>> conventions;
public ViewLocationConventions(IEnumerable<Func<string, object, ViewLocationContext, string>> conventions)
{
this.conventions = conventions;
}
public IEnumerator<Func<string, object, ViewLocationContext, string>> GetEnumerator()
{
return conventions.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
} | namespace Nancy.Conventions
{
using System;
using System.Collections;
using System.Collections.Generic;
using Nancy.ViewEngines;
/// <summary>
/// This is a wrapper around the type
/// 'IEnumerable<Func<string, object, ViewLocationContext, string>>' and its
/// only purpose is to make Ninject happy which was throwing an exception
/// when constructor injecting this type.
/// </summary>
public class ViewLocationConventions : IEnumerable<Func<string, object, ViewLocationContext, string>>
{
private readonly IEnumerable<Func<string, object, ViewLocationContext, string>> conventions;
public ViewLocationConventions(IEnumerable<Func<string, object, ViewLocationContext, string>> conventions)
{
this.conventions = conventions;
}
public IEnumerator<Func<string, object, ViewLocationContext, string>> GetEnumerator()
{
return conventions.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
} | mit | C# |
b80177732dd5e63a59ba0822d37d75b73b9bc42b | Add IAspectActivator to activation aspect | AspectCore/AspectCore-Framework,AspectCore/AspectCore-Framework,AspectCore/Lite,AspectCore/Abstractions | src/AspectCore.Lite.Abstractions/IAspectActivator.cs | src/AspectCore.Lite.Abstractions/IAspectActivator.cs | using System;
using System.Reflection;
namespace AspectCore.Lite.Abstractions
{
[NonAspect]
public interface IAspectActivator
{
void InitializationMetaData(Type serviceType, MethodInfo serviceMethod, MethodInfo targetMethod, MethodInfo proxyMethod);
T Invoke<T>(object targetInstance, object proxyInstance, params object[] paramters);
T InvokeAsync<T>(object targetInstance, object proxyInstance, params object[] paramters);
}
}
| mit | C# | |
813fcb2a58ed307ea7182fdb460af14098c98972 | Create Hello_Neyo | neyogiry/Examples_Csharp | Hello_Neyo.cs | Hello_Neyo.cs | public class Hello_Neyo{
static void Main(){
System.Console.WriteLine("Hola Neyo!");
System.Console.ReadLine();
}
} | mpl-2.0 | C# | |
549ba51466e56dec67056499706213524bfa6c63 | Move PreserveDependencyAttribute to shared (dotnet/corefx#42174) | cshung/coreclr,cshung/coreclr,poizan42/coreclr,poizan42/coreclr,poizan42/coreclr,cshung/coreclr,cshung/coreclr,poizan42/coreclr,cshung/coreclr,poizan42/coreclr,cshung/coreclr,poizan42/coreclr | src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/PreserveDependencyAttribute.cs | src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/PreserveDependencyAttribute.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.
#nullable enable
// TODO https://github.com/dotnet/corefx/issues/41201: Design and expose this publicly.
namespace System.Runtime.CompilerServices
{
/// <summary>States a dependency that one member has on another.</summary>
/// <remarks>
/// This can be used to inform tooling of a dependency that is otherwise not evident purely from
/// metadata and IL, for example a member relied on via reflection.
/// </remarks>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Field /* AttributeTargets.Class | AttributeTargets.Struct */, // TODO: https://github.com/mono/linker/issues/797
AllowMultiple = true, Inherited = false)]
internal sealed class PreserveDependencyAttribute : Attribute
{
/// <summary>Initializes the attribute.</summary>
/// <param name="memberSignature">The signature of the member depended.</param>
public PreserveDependencyAttribute(string memberSignature)
{
MemberSignature = memberSignature;
}
/// <summary>Initializes the attribute.</summary>
/// <param name="memberSignature">The signature of the member depended on.</param>
/// <param name="typeName">The full name of the type containing <paramref name="memberSignature"/>.</param>
public PreserveDependencyAttribute(string memberSignature, string typeName)
{
MemberSignature = memberSignature;
TypeName = typeName;
}
/// <summary>Initializes the attribute.</summary>
/// <param name="memberSignature">The signature of the member depended on.</param>
/// <param name="typeName">The full name of the type containing <paramref name="memberSignature"/>.</param>
/// <param name="assemblyName">The name of the assembly containing <paramref name="typeName"/>.</param>
public PreserveDependencyAttribute(string memberSignature, string typeName, string assemblyName)
{
MemberSignature = memberSignature;
TypeName = typeName;
AssemblyName = assemblyName;
}
/// <summary>Gets the signature of the member depended on.</summary>
public string MemberSignature { get; }
/// <summary>Gets the full name of the type containing the specified member.</summary>
/// <remarks>If no type name is specified, the type of the consumer is assumed.</remarks>
public string? TypeName { get; }
/// <summary>Gets the assembly name of the specified type.</summary>
/// <remarks>If no assembly name is specified, the assembly of the consumer is assumed.</remarks>
public string? AssemblyName { get; }
/// <summary>Gets or sets the condition in which the dependency is applicable, e.g. "DEBUG".</summary>
public string? Condition { get; set; }
}
}
| mit | C# | |
a3c87f5d62fea9e6b671a30670bbfbe34991830e | Update CargoShuttleComponent.cs (#9333) | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Shared/Cargo/Components/CargoShuttleComponent.cs | Content.Shared/Cargo/Components/CargoShuttleComponent.cs | using Robust.Shared.Map;
namespace Content.Shared.Cargo.Components;
/// <summary>
/// Present on cargo shuttles to provide metadata such as preventing spam calling.
/// </summary>
[RegisterComponent, Access(typeof(SharedCargoSystem))]
public sealed class CargoShuttleComponent : Component
{
[ViewVariables(VVAccess.ReadWrite), DataField("nextCall")]
public TimeSpan? NextCall;
[ViewVariables(VVAccess.ReadWrite), DataField("cooldown")]
public float Cooldown = 150f;
[ViewVariables]
public bool CanRecall;
/// <summary>
/// The shuttle's assigned coordinates on the cargo map.
/// </summary>
[ViewVariables]
public EntityCoordinates Coordinates;
/// <summary>
/// The assigned station for this cargo shuttle.
/// </summary>
[ViewVariables, DataField("station")]
public EntityUid? Station;
}
| using Robust.Shared.Map;
namespace Content.Shared.Cargo.Components;
/// <summary>
/// Present on cargo shuttles to provide metadata such as preventing spam calling.
/// </summary>
[RegisterComponent, Access(typeof(SharedCargoSystem))]
public sealed class CargoShuttleComponent : Component
{
[ViewVariables(VVAccess.ReadWrite), DataField("nextCall")]
public TimeSpan? NextCall;
[ViewVariables(VVAccess.ReadWrite), DataField("cooldown")]
public float Cooldown = 45f;
[ViewVariables]
public bool CanRecall;
/// <summary>
/// The shuttle's assigned coordinates on the cargo map.
/// </summary>
[ViewVariables]
public EntityCoordinates Coordinates;
/// <summary>
/// The assigned station for this cargo shuttle.
/// </summary>
[ViewVariables, DataField("station")]
public EntityUid? Station;
}
| mit | C# |
756a081b120b065b570824783c1290c9e975b96e | add missing file to source code | konradsikorski/smartCAML | KoS.Apps.SharePoint.SmartCAML/Providers.SharePoint2013ServerProvider/SharePoint2013ServerModelProvider.cs | KoS.Apps.SharePoint.SmartCAML/Providers.SharePoint2013ServerProvider/SharePoint2013ServerModelProvider.cs | using System;
using System.Collections.Generic;
using System.Linq;
using KoS.Apps.SharePoint.SmartCAML.Model;
using KoS.Apps.SharePoint.SmartCAML.SharePointProvider;
using Microsoft.SharePoint;
namespace KoS.Apps.SharePoint.SmartCAML.Providers.SharePoint2013ServerProvider
{
public class SharePoint2013ServerModelProvider : ISharePointProvider
{
public Web Web { get; private set; }
public Web Connect(string url)
{
using (var site = new SPSite(url))
{
using (var web = site.OpenWeb())
{
Web = new Web
{
Id = web.ID,
Url = url,
Title = web.Title
};
Web.Lists = web.Lists.Cast<SPList>().Select(l => new SList
{
Web = Web,
Title = l.Title,
Id = l.ID,
IsHidden = l.Hidden
}).ToList();
return Web;
}
}
}
public List<ListItem> ExecuteQuery(ListQuery query)
{
using (var site = new SPSite(query.List.Web.Id))
{
using (var web = site.OpenWeb())
{
var serverList = web.Lists.TryGetList(query.List.Title);
var listQuery = new SPQuery {Query = query.Query};
return serverList.GetItems(listQuery).Cast<SPListItem>()
.Select(i => new ListItem
{
Id = i.ID,
Columns =
query.List
.Fields
.ToDictionary(
f => f.InternalName,
f => i.GetFormattedValue(f.InternalName))
})
.ToList();
}
}
}
public void FillListFields(SList list)
{
using (var site = new SPSite(list.Web.Id))
{
using (var web = site.OpenWeb())
{
var serverList = web.Lists.TryGetList(list.Title);
list.Fields = serverList.Fields.Cast<SPField>().Select(f => new Field
{
Id = f.Id,
IsHidden = f.Hidden,
IsReadonly = f.ReadOnlyField,
Title = f.Title,
InternalName = f.InternalName,
Group = f.Group,
Type = (FieldType)f.Type
}).ToList();
}
}
}
}
}
| apache-2.0 | C# | |
ee1c3d42d884167d1657027ca9dad17704df7231 | Add spinner tick judgement | UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,peppy/osu,ppy/osu,peppy/osu-new,NeoAdonis/osu,smoogipoo/osu,ppy/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,smoogipooo/osu,ppy/osu,NeoAdonis/osu | osu.Game.Rulesets.Osu/Judgements/OsuSpinnerTickJudgement.cs | osu.Game.Rulesets.Osu/Judgements/OsuSpinnerTickJudgement.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.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Osu.Judgements
{
public class OsuSpinnerTickJudgement : OsuJudgement
{
internal bool HasBonusPoints;
public override bool AffectsCombo => false;
protected override int NumericResultFor(HitResult result) => 100 + (HasBonusPoints ? 1000 : 0);
protected override double HealthIncreaseFor(HitResult result) => 0;
}
}
| mit | C# | |
314031d56d342f722d998d0897769ea2de4bde9c | Add test cases ensuring music actions are handled from a game instance | NeoAdonis/osu,smoogipooo/osu,ppy/osu,peppy/osu-new,UselessToucan/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu | osu.Game.Tests/Visual/Menus/TestSceneMusicActionHandling.cs | osu.Game.Tests/Visual/Menus/TestSceneMusicActionHandling.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.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Input.Bindings;
using osu.Game.Overlays;
using osu.Game.Tests.Resources;
using osu.Game.Tests.Visual.Navigation;
namespace osu.Game.Tests.Visual.Menus
{
public class TestSceneMusicActionHandling : OsuGameTestScene
{
[Test]
public void TestMusicPlayAction()
{
AddStep("ensure playing something", () => Game.MusicController.EnsurePlayingSomething());
AddStep("trigger music playback toggle action", () => Game.GlobalBinding.TriggerPressed(GlobalAction.MusicPlay));
AddAssert("music paused", () => !Game.MusicController.IsPlaying && Game.MusicController.IsUserPaused);
AddStep("trigger music playback toggle action", () => Game.GlobalBinding.TriggerPressed(GlobalAction.MusicPlay));
AddAssert("music resumed", () => Game.MusicController.IsPlaying && !Game.MusicController.IsUserPaused);
}
[Test]
public void TestMusicNavigationActions()
{
int importId = 0;
Queue<(WorkingBeatmap working, TrackChangeDirection dir)> trackChangeQueue = null;
// ensure we have at least two beatmaps available to identify the direction the music controller navigated to.
AddRepeatStep("import beatmap", () => Game.BeatmapManager.Import(new BeatmapSetInfo
{
Beatmaps = new List<BeatmapInfo>
{
new BeatmapInfo
{
BaseDifficulty = new BeatmapDifficulty(),
}
},
Metadata = new BeatmapMetadata
{
Artist = $"a test map {importId++}",
Title = "title",
}
}).Wait(), 5);
AddStep("import beatmap with track", () =>
{
var setWithTrack = Game.BeatmapManager.Import(TestResources.GetTestBeatmapForImport()).Result;
Beatmap.Value = Game.BeatmapManager.GetWorkingBeatmap(setWithTrack.Beatmaps.First());
});
AddStep("bind to track change", () =>
{
trackChangeQueue = new Queue<(WorkingBeatmap working, TrackChangeDirection dir)>();
Game.MusicController.TrackChanged += (working, dir) => trackChangeQueue.Enqueue((working, dir));
});
AddStep("seek track to 6 second", () => Game.MusicController.SeekTo(6000));
AddUntilStep("wait for current time to update", () => Game.MusicController.CurrentTrack.CurrentTime > 5000);
AddStep("trigger music prev action", () => Game.GlobalBinding.TriggerPressed(GlobalAction.MusicPrev));
AddAssert("no track change", () => trackChangeQueue.Count == 0);
AddUntilStep("track restarted", () => Game.MusicController.CurrentTrack.CurrentTime < 5000);
AddStep("trigger music prev action", () => Game.GlobalBinding.TriggerPressed(GlobalAction.MusicPrev));
AddAssert("track changed to previous", () =>
trackChangeQueue.Count == 1 &&
trackChangeQueue.Dequeue().dir == TrackChangeDirection.Prev);
AddStep("trigger music next action", () => Game.GlobalBinding.TriggerPressed(GlobalAction.MusicNext));
AddAssert("track changed to next", () =>
trackChangeQueue.Count == 1 &&
trackChangeQueue.Dequeue().dir == TrackChangeDirection.Next);
}
}
}
| mit | C# | |
5656167c0446069919aaf54d9956fbe6e04b0896 | Change Start(source) to have the source as an optional parameter. | plmwong/librato4net | librato4net/MetricsPublisher.cs | librato4net/MetricsPublisher.cs | using System;
namespace librato4net
{
public abstract class MetricsPublisher
{
private static readonly object PublisherLock = new object();
private static volatile MetricsPublisher _publisher;
public static void Start(MetricsPublisher metricsPublisher)
{
if (_publisher == null)
{
lock (PublisherLock)
{
if (_publisher == null)
{
_publisher = metricsPublisher;
}
}
}
}
public static void Start(string source = null)
{
Start(new LibratoMetricsPublisher(new LibratoBufferingClient(new LibratoClient(() => new WebClientAdapter())), source));
}
public static MetricsPublisher Current
{
get
{
return _publisher;
}
}
protected ObservableConcurrentDictionary<string, long> CurrentCounts { get; private set; }
protected MetricsPublisher()
{
CurrentCounts = new ObservableConcurrentDictionary<string, long>();
CurrentCounts.CollectionChanged += CountsChanged;
}
protected MetricsPublisher(string source) : this()
{
Source = source;
}
protected abstract void CountsChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e);
protected string Source { get; private set; }
internal abstract void Measure(string metricName, Number value);
internal abstract void Increment(string metricName, long @by = 1);
internal TimedContext Time(string metricName)
{
return new TimedContext(Current, metricName);
}
}
public static class MetricsPublisherExtensions
{
public static void Measure(this MetricsPublisher publisher, string metricName, Number value)
{
if (publisher == null) return;
publisher.Measure(metricName.ToLowerInvariant(), value);
}
public static void Increment(this MetricsPublisher publisher, string metricName, long @by = 1)
{
if (publisher == null) return;
publisher.Increment(metricName.ToLowerInvariant(), @by);
}
public static IDisposable Time(this MetricsPublisher publisher, string metricName)
{
if (publisher == null)
{
return new EmptyDisposable();
}
return publisher.Time(metricName.ToLowerInvariant());
}
}
}
| using System;
namespace librato4net
{
public abstract class MetricsPublisher
{
private static readonly object PublisherLock = new object();
private static volatile MetricsPublisher _publisher;
public static void Start(MetricsPublisher metricsPublisher)
{
if (_publisher == null)
{
lock (PublisherLock)
{
if (_publisher == null)
{
_publisher = metricsPublisher;
}
}
}
}
public static void Start(string source)
{
Start(new LibratoMetricsPublisher(new LibratoBufferingClient(new LibratoClient(() => new WebClientAdapter())), source));
}
public static MetricsPublisher Current
{
get
{
return _publisher;
}
}
protected ObservableConcurrentDictionary<string, long> CurrentCounts { get; private set; }
protected MetricsPublisher()
{
CurrentCounts = new ObservableConcurrentDictionary<string, long>();
CurrentCounts.CollectionChanged += CountsChanged;
}
protected MetricsPublisher(string source) : this()
{
Source = source;
}
protected abstract void CountsChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e);
protected string Source { get; private set; }
internal abstract void Measure(string metricName, Number value);
internal abstract void Increment(string metricName, long @by = 1);
internal TimedContext Time(string metricName)
{
return new TimedContext(Current, metricName);
}
}
public static class MetricsPublisherExtensions
{
public static void Measure(this MetricsPublisher publisher, string metricName, Number value)
{
if (publisher == null) return;
publisher.Measure(metricName.ToLowerInvariant(), value);
}
public static void Increment(this MetricsPublisher publisher, string metricName, long @by = 1)
{
if (publisher == null) return;
publisher.Increment(metricName.ToLowerInvariant(), @by);
}
public static IDisposable Time(this MetricsPublisher publisher, string metricName)
{
if (publisher == null)
{
return new EmptyDisposable();
}
return publisher.Time(metricName.ToLowerInvariant());
}
}
}
| mit | C# |
f28f5b6f27df2a1e4f3f3d6ff60dc85ecad4d455 | Update the example to skip authentication | samcragg/Crest,samcragg/Crest,samcragg/Crest | example/BasicExample/DisableJwtAuthentication.cs | example/BasicExample/DisableJwtAuthentication.cs | namespace BasicExample
{
using System;
using System.Collections.Generic;
using Crest.Abstractions;
/// <summary>
/// Shows an example of how to disable JWT authentication.
/// </summary>
public sealed class DisableJwtAuthentication : IJwtSettings
{
/// <inheritdoc />
public ISet<string> Audiences { get; }
/// <inheritdoc />
public string AuthenticationType { get; }
/// <inheritdoc />
public TimeSpan ClockSkew { get; }
/// <inheritdoc />
public ISet<string> Issuers { get; }
/// <inheritdoc />
public IReadOnlyDictionary<string, string> JwtClaimMappings { get; }
/// <inheritdoc />
public bool SkipAuthentication => true;
}
}
| mit | C# | |
74788e15bff4db38be391bb692f32b11286eb8dc | Create AssemblyInfo.cs | keith-hall/reactive-animation | src/Properties/AssemblyInfo.cs | src/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("ReactiveAnimation")]
[assembly: AssemblyDescription("Simple Animation framework built on Reactive Extensions")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Keith Hall")]
[assembly: AssemblyProduct("ReactiveAnimation")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("ead15993-b604-461c-9897-9ff19feb1041")]
// 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")]
| apache-2.0 | C# | |
692d4497a60d7c2f43aa9ceee98d792388ab8a5f | Create Physics.Raycast.cs | carcarc/unity3d | Physics.Raycast.cs | Physics.Raycast.cs | RayCastHit hit; //儲存物件
Ray myRay = new Ray(transform.position,Vector3.down); //射線方向
//射線由myRay射出長度為DownHeight 碰到的物件為hit
if(Physics.Raycast (myRay, out hit ,DownHeight) ){
//hit
}
| mit | C# | |
de92d818a852266d28d090bb74c0adb7f6ef81f0 | Create initial attributes for attribute-driven Worksheet.FromData | mstum/Simplexcel,mstum/Simplexcel | src/Simplexcel/Cells/XlsxColumnAttribute.cs | src/Simplexcel/Cells/XlsxColumnAttribute.cs | using System;
namespace Simplexcel.Cells
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
internal class XlsxColumnAttribute : Attribute
{
/// <summary>
/// The name of the Column, used as the Header row
/// </summary>
public string Name { get; set; }
}
/// <summary>
/// This attribute causes <see cref="Worksheet.FromData"/> to ignore the property completely
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
internal class XlsxIgnoreColumnAttribute : Attribute
{
}
}
| mit | C# | |
f3da8b522fc191ea6fa75bc79b1bbd6e89cf036f | remove unnecessary duplication | assaframan/MoviesRestForAppHarbor,ServiceStack/ServiceStack.Examples,zhaokunfay/ServiceStack.Examples,ServiceStack/ServiceStack.Examples,ServiceStack/ServiceStack.Examples,assaframan/MoviesRestForAppHarbor,ServiceStack/ServiceStack.Examples,zhaokunfay/ServiceStack.Examples,zhaokunfay/ServiceStack.Examples,assaframan/MoviesRestForAppHarbor,zhaokunfay/ServiceStack.Examples | src/ServiceStack.Northwind/ServiceStack.Northwind.ServiceInterface/CustomersService.cs | src/ServiceStack.Northwind/ServiceStack.Northwind.ServiceInterface/CustomersService.cs | using ServiceStack.Northwind.ServiceModel.Operations;
using ServiceStack.Northwind.ServiceModel.Types;
using ServiceStack.OrmLite;
using ServiceStack.ServiceInterface;
namespace ServiceStack.Northwind.ServiceInterface
{
public class CustomersService : RestServiceBase<Customers>
{
public IDbConnectionFactory DbFactory { get; set; }
public override object OnGet(Customers request)
{
return new CustomersResponse { Customers = DbFactory.Exec(dbCmd => dbCmd.Select<Customer>()) };
}
}
}
| using ServiceStack.Northwind.ServiceModel.Operations;
using ServiceStack.Northwind.ServiceModel.Types;
using ServiceStack.OrmLite;
using ServiceStack.ServiceInterface;
namespace ServiceStack.Northwind.ServiceInterface
{
public class CustomersService : RestServiceBase<Customers>
{
public IDbConnectionFactory DbFactory { get; set; }
public override object OnGet(Customers request)
{
return new CustomersResponse { Customers = DbFactory.Exec(dbCmd => dbCmd.Select<Customer>()) };
}
}
public class CustomerService : RestServiceBase<Customer>
{
public IDbConnectionFactory DbFactory { get; set; }
public override object OnPost(Customer request)
{
return new CustomersResponse { Customers = DbFactory.Exec(dbCmd => dbCmd.Select<Customer>()) };
}
}
}
| bsd-3-clause | C# |
13ccad3a5bae4b9e8bf0630080c4d0d1448b2bbb | update context | mikebarker/Plethora.NET | src/Plethora.Context/Action/IUiActionTemplate.cs | src/Plethora.Context/Action/IUiActionTemplate.cs | using System.Drawing;
namespace Plethora.Context.Action
{
/// <summary>
/// A template used to create <see cref="IUiAction"/> instances to operate on
/// a single <see cref="ContextInfo"/> item.
/// </summary>
/// <seealso cref="IActionTemplate"/>
/// <seealso cref="IUiAction"/>
/// <seealso cref="IUiMultiActionTemplate"/>
public interface IUiActionTemplate : IActionTemplate
{
string GetActionText(ContextInfo context);
string GetActionDescription(ContextInfo context);
Image GetImage(ContextInfo context);
string GetGroup(ContextInfo context);
int GetRank(ContextInfo context);
}
/// <summary>
/// A template used to create <see cref="IUiAction"/> instances to operate on
/// multiple <see cref="ContextInfo"/> items.
/// </summary>
/// <example>
/// This is used when, for example, multiple trades are selected in a grid.
/// The list of actions which must be presented should differ from that when
/// a single trade is selected.
/// </example>>
/// <seealso cref="IMultiActionTemplate"/>
/// <seealso cref="IUiAction"/>
/// <seealso cref="IUiActionTemplate"/>
public interface IUiMultiActionTemplate : IMultiActionTemplate
{
string GetActionText(ContextInfo[] context);
string GetActionDescription(ContextInfo[] context);
Image GetImage(ContextInfo[] context);
string GetGroup(ContextInfo[] context);
int GetRank(ContextInfo[] context);
}
}
| mit | C# | |
1def7b15b165bfd6a2ea15d37207d24ad77bcf05 | add callback message sende tests. | ouraspnet/cap,dotnetcore/CAP,dotnetcore/CAP,dotnetcore/CAP | test/DotNetCore.CAP.Test/CallbackMessageSenderTest.cs | test/DotNetCore.CAP.Test/CallbackMessageSenderTest.cs | using System;
using System.Threading.Tasks;
using DotNetCore.CAP.Abstractions;
using DotNetCore.CAP.Internal;
using DotNetCore.CAP.Models;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Xunit;
namespace DotNetCore.CAP.Test
{
public class CallbackMessageSenderTest
{
private IServiceProvider _provider;
private Mock<ICallbackPublisher> _mockCallbackPublisher;
private Mock<IContentSerializer> _mockContentSerializer;
private Mock<IMessagePacker> _mockMessagePack;
public CallbackMessageSenderTest()
{
_mockCallbackPublisher = new Mock<ICallbackPublisher>();
_mockContentSerializer = new Mock<IContentSerializer>();
_mockMessagePack = new Mock<IMessagePacker>();
var services = new ServiceCollection();
services.AddTransient<CallbackMessageSender>();
services.AddLogging();
services.AddSingleton(_mockCallbackPublisher.Object);
services.AddSingleton(_mockContentSerializer.Object);
services.AddSingleton(_mockMessagePack.Object);
_provider = services.BuildServiceProvider();
}
[Fact]
public async void SendAsync_CanSend()
{
// Arrange
_mockCallbackPublisher
.Setup(x => x.PublishAsync(It.IsAny<CapPublishedMessage>()))
.Returns(Task.CompletedTask).Verifiable();
_mockContentSerializer
.Setup(x => x.Serialize(It.IsAny<object>()))
.Returns("").Verifiable();
_mockMessagePack
.Setup(x => x.Pack(It.IsAny<CapMessage>()))
.Returns("").Verifiable();
var fixture = Create();
// Act
await fixture.SendAsync(null, null, Mock.Of<object>());
// Assert
_mockCallbackPublisher.VerifyAll();
_mockContentSerializer.Verify();
_mockMessagePack.Verify();
}
private CallbackMessageSender Create()
=> _provider.GetService<CallbackMessageSender>();
}
}
namespace Samples
{
public interface IFoo
{
int Age { get; set; }
string Name { get; set; }
}
public class FooTest
{
[Fact]
public void CanSetProperty()
{
var mockFoo = new Mock<IFoo>();
mockFoo.Setup(x => x.Name).Returns("NameProerties");
Assert.Equal("NameProerties", mockFoo.Object.Name);
}
}
}
| mit | C# | |
0a1335aa668a036f9f05fa31965f4c3b221151ac | Add stub issuer enumeration | jcolag/CreditCardValidator | CreditCardRange/CreditCardRange/CreditCardType.cs | CreditCardRange/CreditCardRange/CreditCardType.cs | namespace CreditCardProcessing
{
public enum CreditCardType
{
Unknown,
}
}
| agpl-3.0 | C# | |
74e683b256eafc8abc4ca3cf65c470b3ca7b0a35 | Add missing file | michael-reichenauer/GitMind | GitMind/Features/Branching/CreateBranchService.cs | GitMind/Features/Branching/CreateBranchService.cs | using System.Threading.Tasks;
using System.Windows;
using GitMind.Common.ProgressHandling;
using GitMind.Git;
using GitMind.Git.Private;
using GitMind.GitModel;
using GitMind.RepositoryViews;
namespace GitMind.Features.Branching
{
internal class CreateBranchService : ICreateBranchService
{
private readonly IGitService gitService;
public CreateBranchService()
: this(new GitService())
{
}
public CreateBranchService(IGitService gitService)
{
this.gitService = gitService;
}
public Task CreateBranchAsync(RepositoryViewModel viewModel, Branch branch)
{
string workingFolder = viewModel.WorkingFolder;
Window owner = viewModel.Owner;
viewModel.SetIsInternalDialog(true);
CrateBranchDialog dialog = new CrateBranchDialog(owner);
if (dialog.ShowDialog() == true)
{
Progress.ShowDialog(owner, $"Create branch {dialog.BranchName} ...", async () =>
{
string branchName = dialog.BranchName;
string commitId = branch.TipCommit.Id;
if (commitId == Commit.UncommittedId)
{
commitId = branch.TipCommit.FirstParent.Id;
}
bool isPublish = dialog.IsPublish;
await gitService.CreateBranchAsync(workingFolder, branchName, commitId, isPublish);
viewModel.AddSpecifiedBranch(branchName);
await viewModel.RefreshAfterCommandAsync(true);
});
}
owner.Focus();
viewModel.SetIsInternalDialog(false);
return Task.CompletedTask;
}
}
} | mit | C# | |
ade39614ceeff091a2d8b2df37a3a2279fe7b753 | Fix insetion sort test | vitohk/AlRecall | tests/test.Alrecall/TestInsertingSort.cs | tests/test.Alrecall/TestInsertingSort.cs | using System;
using Alrecall.Structures.Arrays;
using Xunit;
namespace test.Alrecall
{
public class TestInsertingSort
{
public TestInsertingSort()
{
}
[Fact]
public void TestShortArray()
{
int[] inArray={0,23,589,76,589,5,6,7};
Console.WriteLine($"\n running inserting for array:\n {TestUtils.convertToString(inArray)}");
inArray.InsertionSort();
bool isSorted=inArray.IsSorted();
Assert.True(isSorted);
}
[Fact]
private void TestLongArray()
{
int[] inArray=new int[int.MaxValue/100];
var rnd=new Random();
for(int i=0;i<inArray.Length;i++)
{
inArray[i]=rnd.Next(int.MaxValue);
}
Console.WriteLine($"\n running inserting sort for a long array of {inArray.Length} integers.{(inArray.Length*4)/(1024*1024)} MB's");
inArray.InsertionSort();
bool isSorted=inArray.IsSorted();
Assert.True(isSorted);
}
}
} | mit | C# | |
d7b231af196cef4f5446f0ebf2b7c9ce50c20581 | Create FullscreenShader.cs | scmcom/unitycode | FullscreenShader.cs | FullscreenShader.cs | //pulled from UnityNativeAudioPlugins
using UnityEngine;
using System.Collections;
public class FullscreenShader : MonoBehaviour
{
public Material mat;
void Awake()
{
Application.targetFrameRate = 3000;
}
void Start(){}
void Update(){}
void OnRenderImage(RenderTexture src, RenderTexture dest)
{
Graphics.Blit(src, dest, mat);
}
}
| mit | C# | |
68a7ead0161320780b1b741851692d3c24df2728 | Create Anim.Sprite.cs | kinifi/2Dtools | Anim.Sprite.cs | Anim.Sprite.cs | using UnityEngine;
using System.Collections;
[RequireComponent (typeof (SpriteRenderer))]
public class Anim_Sprite : MonoBehaviour {
//The current animation playing
private Sprite[] currentAnimation;
//we also want to multiply the counter by a number to get a specific framerate
private float frameRate = 12.0f;
//Set a counter so the animation can be based on time
private float counter = 0.0f;
//The current frame counter that isn't time based but sprite based
//Example: 0 = first sprite
private int currentFrameCounter = 0;
//Is the animation playing
private bool playAnimation = false;
//Should we loop the animation
private bool Loop = false;
//the sprite render attached to this object
private SpriteRenderer _rend = null;
//Debug the animator
public bool DebugAnimator = false;
#region event bools
#endregion
/// <summary>
/// Start this instance.
/// </summary>
private void Start()
{
_rend = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
private void Update () {
if(playAnimation)
{
//keeping track of time with counter
counter += Time.deltaTime*frameRate;
//change the frames and calls all Event Methods
animationControl();
//Check to see if the animation is done so we can loop it
frameCompleteCheck();
}
}
#region Public API for consumption and manipulation
/// <summary>
/// Play the specified Animation
/// </summary>
/// <param name="_animation">_animation.</param>
/// <param name="loopAnimation">If set to <c>true</c> loop animation.</param>
public void PlayMultiple(Sprite[] _animation, bool loopAnimation)
{
Loop = loopAnimation;
currentAnimation = _animation;
playAnimation = true;
}
/// <summary>
/// Play the specified Single Sprite Animation
/// </summary>
/// <param name="_animation">_animation.</param>
public void PlaySingle(Sprite[] _animation)
{
Loop = true;
currentAnimation = _animation;
playAnimation = true;
}
/// <summary>
/// Continues playing the Current Animation
/// </summary>
public void ContinuePlaying()
{
playAnimation = true;
}
/// <summary>
/// Stops playing the Current Animation
/// </summary>
public void StopPlaying()
{
playAnimation = false;
}
/// <summary>
/// Checks if the animation is playing or not
/// </summary>
/// <returns><c>true</c>, if playing was ised, <c>false</c> otherwise.</returns>
public bool isPlaying()
{
return playAnimation;
}
#endregion
#region Animation System Methods
/// <summary>
/// Animates the GameObject using the Sprite Renderer attached
/// </summary>
private void animationControl()
{
//check to see if we have any frames left to play
if(counter > currentFrameCounter && currentFrameCounter < currentAnimation.Length)
{
//check to see if this is the start of the animation
if(currentFrameCounter == 0)
{
onAnimationEnter();
}
else if(counter > currentAnimation.Length - 1)
{
onAnimationComplete();
}
//change the sprite render to reflect the
_rend.sprite = currentAnimation[currentFrameCounter];
//increment the frame count so we can continue the animation and change frames
currentFrameCounter += 1;
}
}
/// <summary>
/// checks to see if the animation is on the last frame and loops it if it needs to
/// </summary>
private void frameCompleteCheck()
{
//If animation finishes, we destroy the object
if(counter > currentAnimation.Length)
{
if(Loop)
{
currentFrameCounter = 0;
counter = 0.0f;
}
}
}
#endregion
#region Event Methods
/// <summary>
/// Calls the OnEnter Animation to let your method know it has started
/// </summary>
public void onAnimationEnter()
{
SendMessage("OnSpriteEnter", SendMessageOptions.DontRequireReceiver);
}
/// <summary>
/// Calls the OnComplete Animation to let your method know its done
/// </summary>
public void onAnimationComplete()
{
SendMessage("OnSpriteExit", SendMessageOptions.DontRequireReceiver);
}
#endregion
}
| mit | C# | |
bd9720090d7cd0847b92ee49e4f467c6970c63cf | Create Exercise_09.cs | jesushilarioh/Questions-and-Exercises-in-C-Sharp | Exercise_09.cs | Exercise_09.cs | using System;
public class Exercise_09
{
public static void Main()
{
/********************************************************************
*
* 9. Write a program that takes four numbers as input to calculate
* calculate and print the average.
*
*
* By: Jesus Hilario Hernandez
* Last Updated: October 4th 2017
*
********************************************************************/
Console.WriteLine("Enter the First number: 10");
var num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the Second number: 15");
var num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the Third number: 20");
var num3 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the Fourth number: 30");
var num4 = Convert.ToInt32(Console.ReadLine());
Console.Write("The average of ");
Console.Write("{0}, {1}, {2}, and {3} is: ", num1, num2, num3, num4);
Console.WriteLine("{0}", (num1 + num2 + num3 + num4) / 4);
}
}
| mit | C# | |
61b0ed21904fdaa5fb63695ad62f442d593d7b82 | Add GenerateAudio.cs test. | eylvisaker/AgateLib | Tests/AudioTests/GenerateAudio.cs | Tests/AudioTests/GenerateAudio.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using AgateLib;
using AgateLib.AudioLib;
using AgateLib.DisplayLib;
namespace Tests.AudioTests
{
class GenerateAudio : IAgateTest
{
public string Name
{
get { return "Generate Audio"; }
}
public string Category
{
get { return "Audio"; }
}
public void Main(string[] args)
{
using (AgateSetup setup = new AgateSetup())
{
setup.AskUser = true;
setup.Initialize(true, true, false);
if (setup.WasCanceled)
return;
DisplayWindow wind = DisplayWindow.CreateWindowed("Generate Audio", 640, 480);
short[] s = new short[22050];
int frequency = 100;
FillSoundBuffer(s, frequency);
SoundBuffer buf = new SoundBuffer(s);
buf.Loop = true;
SoundBufferSession ses = buf.Play();
Stopwatch w = new Stopwatch();
w.Start();
while (wind.IsClosed == false)
{
Display.BeginFrame();
Display.Clear();
FontSurface.AgateSans14.Color = AgateLib.Geometry.Color.White;
FontSurface.AgateSans14.DrawText(0, 0, string.Format("Frequency: {0}", frequency));
Display.EndFrame();
Core.KeepAlive();
if (w.ElapsedMilliseconds > 800)
{
frequency += 50;
FillSoundBuffer(s, frequency);
buf.Write(s, 0, 0, s.Length);
w.Reset();
w.Start();
}
}
}
}
private void FillSoundBuffer(short[] s, double frequency)
{
for (int i = 0; i < s.Length; i++)
{
double index = i / (double)s.Length;
index *= 2 * Math.PI * frequency;
s[i] = (short)(Math.Sin(index) * short.MaxValue);
}
}
}
}
| mit | C# | |
d045c9e050529c88c1487094becfe87bca83e3a3 | add CBLoggerBuilder | CloudBreadProject/CloudBread-Admin-Web,yshong93/CloudBread-Admin-Web,yshong93/CloudBread-Admin-Web,CloudBreadProject/CloudBread-Admin-Web,yshong93/CloudBread-Admin-Web,CloudBreadProject/CloudBread-Admin-Web | CBLoggerBuilder.cs | CBLoggerBuilder.cs | using CloudBreadAdminWebAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Web;
namespace CloudBread_Admin_Web
{
public class CBLoggerBuilder
{
public enum LoggerType { GET, GETbyIID, PUT, POST, PATCH, DELETE };
public enum LevelType { INFO };
public static void Build(ref Logging.CBLoggers logMsg, ClaimsPrincipal claims,
string controllerName, LevelType levelType, LoggerType loggerType, string message)
{
logMsg.memberID = CBAuth.getMemberID(claims);
logMsg.Level = levelType.ToString();
logMsg.Logger = controllerName + "-" + loggerType.ToString();
logMsg.Message = message;
}
}
} | mit | C# | |
bede132142670d12bf6a8fb290a6a1409d2b006d | Add F.Property | farity/farity | Farity/Property.cs | Farity/Property.cs | using System;
using System.Linq.Expressions;
namespace Farity
{
public static partial class F
{
/// <summary>
/// Returns a function that when supplied an object returns the indicated property of that object.
/// </summary>
/// <typeparam name="T">The type of object on which to work.</typeparam>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="propertyExpression">The property expression.</param>
/// <returns>A function that when supplied an object returns the indicated property of that object.</returns>
public static Func<T, TProperty> Property<T, TProperty>(Expression<Func<T, TProperty>> propertyExpression)
{
return propertyExpression.Compile();
}
/// <summary>
/// Returns a function that when supplied an object returns the indicated property of that object.
/// </summary>
/// <typeparam name="T">The type of object on which to work.</typeparam>
/// <param name="propertyExpression">The property expression.</param>
/// <returns>A function that when supplied an object returns the indicated property of that object.</returns>
public static Func<T, object> Property<T>(Expression<Func<T, object>> propertyExpression)
{
return propertyExpression.Compile();
}
}
} | mit | C# | |
001485f310e7980d7109ab2dba0e0a69d022388c | add test for repository | wilcommerce/Wilcommerce.Core.Data.EFCore | Wilcommerce.Core.Data.EFCore.Test/Repository/RepositoryTest.cs | Wilcommerce.Core.Data.EFCore.Test/Repository/RepositoryTest.cs | using System.Linq;
using Wilcommerce.Core.Common.Domain.Models;
using Wilcommerce.Core.Data.EFCore.ReadModels;
using Wilcommerce.Core.Data.EFCore.Test.Fixtures;
using Xunit;
namespace Wilcommerce.Core.Data.EFCore.Test.Repository
{
public class RepositoryTest : IClassFixture<CommonContextFixture>
{
private CommonContextFixture _fixture;
private EFCore.Repository.Repository _repository;
private CommonDatabase _database;
public RepositoryTest(CommonContextFixture fixture)
{
_fixture = fixture;
_repository = new EFCore.Repository.Repository(_fixture.Context);
_database = new CommonDatabase(_fixture.Context);
}
[Fact]
public void Add_New_User_Should_Increment_Users_Number()
{
int usersCount = _database.Users.Count();
var user = User.CreateAsAdministrator("Administrator2", "admin2@wilcommerce.com", "456");
_repository.Add(user);
_repository.SaveChanges();
int newUsersCount = _database.Users.Count();
Assert.Equal(usersCount + 1, newUsersCount);
}
[Fact]
public void GetByKey_Should_Return_The_User_Found()
{
var userId = _database.Users.FirstOrDefault(u => u.Email == "admin@wilcommerce.com").Id;
var user = _repository.GetByKey<User>(userId);
Assert.NotNull(user);
Assert.Equal(userId, user.Id);
Assert.Equal("admin@wilcommerce.com", user.Email);
}
}
}
| mit | C# | |
5fa5b648300e5777c9d0036d9c819c6427edda10 | Create IMongoUnitOfWork.cs | tiksn/TIKSN-Framework | TIKSN.Core/Data/Mongo/IMongoUnitOfWork.cs | TIKSN.Core/Data/Mongo/IMongoUnitOfWork.cs | using System;
namespace TIKSN.Data.Mongo
{
public interface IMongoUnitOfWork : IUnitOfWork
{
public IServiceProvider Services { get; }
}
} | mit | C# | |
01b87947579c417395458c2832ba730d331d6e6b | Add abstract `Section` class | UselessToucan/osu,ppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu-new,smoogipoo/osu,ppy/osu,peppy/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu | osu.Game/Screens/Edit/Verify/Section.cs | osu.Game/Screens/Edit/Verify/Section.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.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics.Sprites;
using osu.Game.Overlays;
using osuTK;
namespace osu.Game.Screens.Edit.Verify
{
public abstract class Section : CompositeDrawable
{
private const int header_height = 50;
protected readonly IssueList IssueList;
protected FillFlowContainer Flow;
protected abstract string Header { get; }
protected Section(IssueList issueList)
{
IssueList = issueList;
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colours)
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Masking = true;
InternalChildren = new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.X,
Height = header_height,
Padding = new MarginPadding { Horizontal = 20 },
Child = new OsuSpriteText
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Text = Header,
Font = new FontUsage(size: 25, weight: "bold")
}
},
new Container
{
Y = header_height,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Child = Flow = new FillFlowContainer
{
Padding = new MarginPadding { Horizontal = 20 },
Spacing = new Vector2(10),
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
}
}
};
}
}
}
| mit | C# | |
121d6f99be297e83192c6304b84f8e87e5851e8f | Create Settings.cs | Magion/WernherChecker,Kerbas-ad-astra/WernherChecker,linuxgurugamer/WernherChecker | Source/Settings.cs | Source/Settings.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace WernherChecker
{
class WCSettings
{
public ConfigNode cfg = ConfigNode.Load(WernherChecker.DataPath + "WernherChecker.cfg");
public bool j_sugg = true;
public bool lockOnHover = true;
public bool checkCrewAssignment = true;
public bool cfgFound;
public WernherChecker.toolbarType activeToolbar;
public void Load()
{
if (System.IO.File.Exists(WernherChecker.DataPath + "WernherChecker.cfg"))
{
cfgFound = true;
Debug.Log("[WernherChecker]: Config file found at " + WernherChecker.DataPath + "WernherChecker.cfg");
//-----------------------------------------------------------------------------
try
{
this.j_sugg = bool.Parse(cfg.GetValue("j_sugg"));
Debug.Log("[WernherChecker]: SETTINGS - Jeb's suggestion enabled: " + this.j_sugg);
}
catch { Debug.LogWarning("[WernherChecker]: SETTINGS - j_sugg field has an invalid value assigned (" + cfg.GetValue("j_sugg") + "). Please assign valid boolean value."); }
//------------------------------------------------------------------------------
try
{
this.lockOnHover = bool.Parse(cfg.GetValue("lockOnHover"));
Debug.Log("[WernherChecker]: SETTINGS - Lock editor while hovering over window: " + this.lockOnHover);
}
catch { Debug.LogWarning("[WernherChecker]: SETTINGS - lockOnHover field has an invalid value assigned (" + cfg.GetValue("lockOnHover") + "). Please assign valid boolean value."); }
//----------------------------------------------------------------------------
try
{
this.checkCrewAssignment = bool.Parse(cfg.GetValue("checkCrewAssignment"));
Debug.Log("[WernherChecker]: SETTINGS - Check crew assignment before launch: " + this.checkCrewAssignment);
}
catch { Debug.LogWarning("[WernherChecker]: SETTINGS - checkCrewAssignment field has an invalid value assigned (" + cfg.GetValue("checkCrewAssignment") + "). Please assign valid boolean value."); }
//--------------------------------------------------------------------------
try
{
this.activeToolbar = (WernherChecker.toolbarType)Enum.Parse(typeof(WernherChecker.toolbarType), cfg.GetValue("toolbarType"));
Debug.Log("[WernherChecker]: SETTINGS - Active toolbar: " + this.activeToolbar.ToString());
}
catch { Debug.LogWarning("[WernherChecker]: SETTINGS - toolbarType field has an invalid value assigned (" + cfg.GetValue("toolbarType") + "). Please assign valid value (BLIZZY / STOCK)."); }
}
else
{
Debug.LogWarning("[WernherChecker]: Missing config file!");
cfgFound = false;
}
}
}
}
| mit | C# | |
d63df0f271e87fa927416e900382ac8fceefcf90 | Add Brandon Olin as author | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/BrandonOlin.cs | src/Firehose.Web/Authors/BrandonOlin.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class BrandonOlin : IFilterMyBlogPosts, IAmACommunityMember
{
public string FirstName => "Brandon";
public string LastName => "Olin";
public string ShortBioOrTagLine => "Cloud Architect and veteran Systems Engineer with a penchant for PowerShell, DevOps processes, and open-source software.";
public string StateOrRegion => "Portland, Oregon";
public string EmailAddress => "brandon@devblackops.io";
public string TwitterHandle => "devblackops";
public string GitHubHandle => "devblackops";
public string GravatarHash => "07f265f8f921b6876ce9ea65902f0480";
public GeoPosition Position => new GeoPosition(45.5131063, -122.670492);
public Uri WebSite => new Uri("https://devblackops.io/");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://devblackops.io/feed.xml"); }
}
public bool Filter(SyndicationItem item)
{
return item.Categories.Where(i => i.Name.Equals("powershell", StringComparison.OrdinalIgnoreCase)).Any();
}
}
}
| mit | C# | |
9b8c8b0112faabc70e8991a1e7ed61b46c608740 | Add Post Type resource. | maxcutler/wp-api-csharp | PortableWordPressApi/Resources/PostType.cs | PortableWordPressApi/Resources/PostType.cs | using System.Collections.Generic;
namespace PortableWordPressApi.Resources
{
public class PostType
{
public string Name { get; set; }
public string Slug { get; set; }
public string Description { get; set; }
public bool Hierarchical { get; set; }
public bool Queryable { get; set; }
public bool Searchable { get; set; }
public Dictionary<string, string> Labels { get; set; }
public Meta Meta { get; set; }
}
}
| mit | C# | |
4032361ff247232e68ef00728e35edf15b1a99d1 | Create program.cs | UnstableMutex/ANTFECControl | program.cs | program.cs | using ANT_Managed_Library;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
// static byte[] networkKey = { 0xB9, 0xA5, 0x21, 0xFB, 0xBD, 0x72, 0xC3, 0x45};
static byte[] networkKey = { 0xE8, 0xE4, 0x21, 0x3B, 0x55, 0x7A, 0x67, 0xC1 };
// static byte[] networkKey = { 0xA8, 0xA4, 0x23, 0xB9, 0xF5, 0x5E, 0x63, 0xC1 };
static void Main(string[] args)
{
Console.WriteLine("Connecting to HRM, PRESS ENTER TO TERMINATE PROGRAM");
var device = new ANT_Device();
var ressnk = device.setNetworkKey(0, networkKey, 500);
ANT_Channel channel0 = device.getChannel(0);
channel0.assignChannel(ANT_ReferenceLibrary.ChannelType.BASE_Slave_Receive_0x00, 0, 500);
channel0.setChannelID(0, false, 120, 0, 500);
channel0.setChannelPeriod((ushort)8070, 500);
channel0.setChannelSearchTimeout(15);
channel0.setChannelFreq(57, 500);
channel0.setProximitySearch(10, 500); //Is set to limit the search range
channel0.channelResponse += Channel_channelResponse;
var oc = channel0.openChannel(500);
Console.ReadKey();
}
private static void Channel_channelResponse(ANT_Response response)
{
var rid = response.getMessageID();
Console.WriteLine(rid);
var m = response.messageContents;
string s = "";
var ev = response.getChannelEventCode();
Console.WriteLine(ev);
var d = response.timeReceived;
foreach (var item in m)
{
s += item.ToString() + " ";
}
Console.WriteLine(s);
}
}
}
| unlicense | C# | |
4f9f30e165fc47e2f1627d6980833c537d88b6e5 | Create MaximilianLærum.cs | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/MaximilianLærum.cs | src/Firehose.Web/Authors/MaximilianLærum.cs | public class MaximilianLærum : IAmACommunityMember
{
public string FirstName => "Maximilian";
public string LastName => "Lærum";
public string ShortBioOrTagLine => "PowerShell enthusiast";
public string StateOrRegion => "Norway";
public string TwitterHandle => "tr4psec";
public string GravatarHash => "0e45a9759e36d29ac45cf020882cdf5c";
public string GitHubHandle => "Tr4pSec";
public Uri WebSite => new Uri("https://get-help.guru/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://get-help.guru/rss"); } }
}
| mit | C# | |
9e8e847e304b3652b9bd655fb9f08d4956bafa6d | Create Encryption.cs | vikekh/hacker-rank-cs | Freestyle/Encryption.cs | Freestyle/Encryption.cs | mit | C# | ||
1d7cab6f69154544dc612355916d273ebe8d2c9c | Build fix. AomicIntegerArray inclusion | szKarlen/atomics.net | src/System.Threading.Atomics/AtomicIntegerArray.cs | src/System.Threading.Atomics/AtomicIntegerArray.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System.Threading.Atomics
{
public class AtomicIntegerArray : IAtomicRefArray<int>
{
private readonly int[] _data;
private readonly MemoryOrder _order;
public AtomicIntegerArray(int[] source, MemoryOrder order = MemoryOrder.SeqCst)
: this(source.Length)
{
source.CopyTo(_data, 0);
}
public AtomicIntegerArray(int length, MemoryOrder order = MemoryOrder.SeqCst)
{
if (!order.IsSpported()) throw new ArgumentException(string.Format("{0} is not supported", order.ToString()));
_data = new int[length];
_order = order;
}
public void Store(int index, ref int value, MemoryOrder order)
{
switch (order)
{
case MemoryOrder.Relaxed:
this._data[index] = value;
break;
case MemoryOrder.Consume:
throw new NotSupportedException();
case MemoryOrder.Acquire:
throw new InvalidOperationException("Cannot set (store) value with Acquire semantics");
case MemoryOrder.Release:
case MemoryOrder.AcqRel:
#if ARM_CPU || ITANIUM_CPU
Platform.MemoryBarrier();
#else
this._data[index] = value;
#endif
break;
case MemoryOrder.SeqCst:
#if ARM_CPU || ITANIUM_CPU
Platform.MemoryBarrier();
this._data[index] = value;
Platform.MemoryBarrier();
#else
Interlocked.Exchange(ref this._data[index], value);
#endif
break;
default:
throw new ArgumentOutOfRangeException("order");
}
}
public int this[int i]
{
get { return Load(i, _order); }
set { Store(i, ref value, _order); }
}
public void Store(int index, int value, MemoryOrder order)
{
Store(index, ref value, order);
}
public int Load(int index, MemoryOrder order)
{
if (order == MemoryOrder.Consume)
throw new NotSupportedException();
if (order == MemoryOrder.Release)
throw new InvalidOperationException("Cannot get (load) value with Release semantics");
switch (order)
{
case MemoryOrder.Relaxed:
return this._data[index];
case MemoryOrder.Acquire:
case MemoryOrder.AcqRel:
case MemoryOrder.SeqCst:
#if ARM_CPU || ITANIUM_CPU
var tmp = this._data[index];
Platform.MemoryBarrier();
return tmp;
#else
return this._data[index];
#endif
default:
throw new ArgumentOutOfRangeException("order");
}
}
public bool IsLockFree
{
get { return true; }
}
public int CompareExchange(int index, int value, int comparand)
{
return Interlocked.CompareExchange(ref this._data[index], value, comparand);
}
}
}
| bsd-3-clause | C# | |
1a632d66a9857f2714e784c3e3df1b0293693712 | Include SendKeysUtilities (should have been in previous commit) | jskeet/DemoCode,jskeet/DemoCode,jskeet/DemoCode,jskeet/DemoCode | Drums/VDrumExplorer.Console/SendKeysUtilities.cs | Drums/VDrumExplorer.Console/SendKeysUtilities.cs | // Copyright 2020 Jon Skeet. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using System.IO;
using System.Reflection;
namespace VDrumExplorer.Console
{
/// <summary>
/// Utility methods to work with the SendKeys class.
/// </summary>
public static class SendKeysUtilities
{
private static readonly Type sendKeysClass = GetSendKeysClass();
public static bool HasSendKeys => sendKeysClass is object;
private static Type GetSendKeysClass()
{
try
{
var assembly = Assembly.Load("System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
return assembly?.GetType("System.Windows.Forms.SendKeys");
}
catch (IOException)
{
return null;
}
}
public static void SendWait(string keys)
{
if (sendKeysClass is null)
{
throw new InvalidOperationException($"Cannot use SendKeys on this platform.");
}
var method = sendKeysClass.GetMethod("SendWait", new[] { typeof(string) });
method.Invoke(null, new object[] { keys });
}
}
}
| apache-2.0 | C# | |
f0b82876b467897a1e440eb530b0255b127809c4 | Create strategy.cs | Skookum/design-patterns,Skookum/design-patterns,Skookum/design-patterns,Skookum/design-patterns,Skookum/design-patterns | patterns/strategy/strategy.cs | patterns/strategy/strategy.cs | using System;
namespace StrategyPattern
{
//context
public abstract class Company
{
public abstract double Calculate(Package package);
}
//context
public class Shipping
{
private Company company;
public void SetStrategy(Company company)
{
this.company = company;
}
public double Calculate(Package package)
{
return company.Calculate(package);
}
}
//dependent
public class Package
{
public int From { get; set; }
public int To { get; set; }
public string Weight { get; set; }
}
//concreteStrategy
public class UPS : Company
{
public override double Calculate(Package package)
{
// calculations...
return 45.95;
}
}
//concreteStrategy
public class USPS : Company
{
public override double Calculate(Package package)
{
// calculations...
return 39.40;
}
}
//concreteStrategy
public class Fedex : Company
{
public override double Calculate(Package package)
{
// calculations...
return 43.20;
}
}
//client Participant
internal class Program
{
static void Main(string[] args)
{
Package package = new Package()
{ From = 76712, To = 10012, Weight = "1kg"};
// the 3 strategies
UPS ups = new UPS();
USPS usps = new USPS();
Fedex fedex = new Fedex();
Shipping shipping = new Shipping();
shipping.SetStrategy(ups);
Console.WriteLine("UPS Strategy: " + shipping.Calculate(package));
shipping.SetStrategy(usps);
Console.WriteLine("USPS Strategy: " + shipping.Calculate(package));
shipping.SetStrategy(fedex);
Console.WriteLine("Fedex Strategy: " + shipping.Calculate(package));
}
}
}
| mit | C# | |
8bae538af93957b15f9233b68266d09081f37ce7 | Create SetBoxColliderToUI.cs | UnityCommunity/UnityLibrary | Assets/Scripts/Editor/ContextMenu/SetBoxColliderToUI.cs | Assets/Scripts/Editor/ContextMenu/SetBoxColliderToUI.cs | // Tries to move BoxCollider(3D)-component to match UI panel/image position, by adjusting collider pivot value
using UnityEngine;
using UnityEditor;
namespace UnityLibrary
{
public class SetBoxColliderToUI : MonoBehaviour
{
[MenuItem("CONTEXT/BoxCollider/Match Position to UI")]
static void FixPosition(MenuCommand command)
{
BoxCollider b = (BoxCollider)command.context;
// record undo
Undo.RecordObject(b.transform, "Set Box Collider To UI");
// fix pos from Pivot
var r = b.gameObject.GetComponent<RectTransform>();
if (r == null) return;
//Debug.Log("pivot "+r.pivot);
var center = b.center;
center.x = 0.5f - r.pivot.x;
center.y = 0.5f - r.pivot.y;
b.center = center;
}
}
}
| mit | C# | |
3c57ce2721c0d0eee953b14506a60fa71f5ea1cd | add initial implementation of Enviroment class | MrBadge/NeutronDiffusion | NeutronDiffusion/Enviroment.cs | NeutronDiffusion/Enviroment.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NeutronDiffusion
{
class Enviroment
{
public double SigmaS { get; }
public double SigmaA { get; }
public double CosFi { get; }
public int NeutronNums { get; set; }
private List<Neutron> neutrons = new List<Neutron>();
public Enviroment(double SigmaS, double SigmaA, double CosFi)
{
this.SigmaS = SigmaS;
this.SigmaA = SigmaA;
this.CosFi = CosFi;
}
public static void Main()
{
Enviroment env = new Enviroment(2, 2, 0.1);
env.NeutronNums = 2;
env.StartSimulation();
}
public void StartSimulation()
{
for (int i = 0; i < NeutronNums; i++)
neutrons.Add(new Neutron(new CustomPoint3D(), SigmaA, SigmaS, CosFi));
neutrons.ForEach(neutron => neutron.Move());
Console.WriteLine("HERE");
}
private double MeanFreePathBeforeAbsorption()
{
return neutrons.Aggregate(
0.0,
(res, neutron) => res + neutron.AverageFreePathLength * neutron.FreePathLength.Count
) / NeutronNums;
}
private double MeanSquareOffsetBeforeAbsorption()
{
return 0;
}
}
}
| mit | C# | |
93a6345205241c661b02fc0282760287634fa64e | Add tests for F.Drop | farity/farity | Farity.Tests/DropTests.cs | Farity.Tests/DropTests.cs | using Xunit;
using System.Linq;
namespace Farity.Tests
{
public class DropTests
{
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
public void DropDropsNElements(int n)
{
Assert.True(n <= 5 && n >= 0);
var data = new[] { 1, 2, 3, 4, 5 };
var expected = data.Length - n;
var dropped = F.Drop(n, data).ToList();
var actual = dropped.Count;
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
public void DropDropsFirstNElements(int n)
{
Assert.True(n <= 5 && n >= 0);
var data = new[] { 1, 2, 3, 4, 5 };
var expected = data.Skip(n).ToList();
var actual = F.Drop(n, data).ToList();
Assert.Equal(expected, actual);
}
[Fact]
public void DropReturnsSameSequenceIfCountIsZero()
{
var expected = new[] { 1, 2, 3, 4, 5 };
var actual = F.Drop(0, expected);
Assert.Equal(expected, actual);
}
[Fact]
public void DropReturnsEmptySequenceIfCountIsGreaterThanOrEqualToLengthOfSequence()
{
var expected = Enumerable.Empty<int>();
var data = new[] { 1, 2, 3, 4, 5 };
var actual = F.Drop(5, expected);
Assert.Equal(expected, actual);
actual = F.Drop(9, expected);
Assert.Equal(expected, actual);
}
}
}
| mit | C# | |
65b0e9a45b172b74663ee2318c4ec6db43f467b1 | Add FileSelector control | tzachshabtay/MonoAGS | Source/Editor/AGS.Editor/Components/FileSelector/FileSelector.cs | Source/Editor/AGS.Editor/Components/FileSelector/FileSelector.cs | using System;
using AGS.API;
using AGS.Engine;
namespace AGS.Editor
{
public class FileSelector : AGSComponent
{
private readonly IGameFactory _factory;
private ISplitPanelComponent _splitter;
private FolderTree _folderTree;
private FilesView _filesView;
const float _gutterSize = 15f;
public FileSelector(IGameFactory factory)
{
_factory = factory;
}
public override void Init()
{
base.Init();
Entity.Bind<ISplitPanelComponent>(c => { _splitter = c; configureSplitter(); }, c => _splitter = null);
}
public override void Dispose()
{
base.Dispose();
_folderTree.OnFolderSelected.Unsubscribe(onFolderSelected);
}
private void configureSplitter()
{
_splitter.IsHorizontal = true;
var leftPanel = _factory.UI.GetPanel("FolderTree", 300f, 600f, 100f, 100f);
leftPanel.AddComponent<ICropChildrenComponent>();
//var contentsPanel = _factory.UI.CreateScrollingPanel(leftPanel);
leftPanel.Tint = GameViewColors.Panel;
leftPanel.Border = _factory.Graphics.Borders.SolidColor(GameViewColors.Border, 3f);
leftPanel.RenderLayer = new AGSRenderLayer(AGSLayers.UI.Z - 1000);
var tree = leftPanel.AddComponent<ITreeViewComponent>();
tree.LeftPadding = 10f;
tree.TopPadding = 30f;
_folderTree = leftPanel.AddComponent<FolderTree>();
_folderTree.DefaultFolder = "../../../../../Demo";
_splitter.TopPanel = leftPanel;
var rightPanel = _factory.UI.GetPanel("FilesView", 800f, 600f, 400f, 100f);
rightPanel.Tint = GameViewColors.Panel;
rightPanel.Border = _factory.Graphics.Borders.SolidColor(GameViewColors.Border, 3f);
rightPanel.RenderLayer = new AGSRenderLayer(AGSLayers.UI.Z - 1000);
var inv = rightPanel.AddComponent<IInventoryWindowComponent>();
inv.Inventory = new AGSInventory();
inv.ItemSize = (120f, 120f);
inv.PaddingLeft = 20f;
inv.PaddingRight = 20f;
_filesView = rightPanel.AddComponent<FilesView>();
_filesView.Folder = "../../../../../Demo/DemoQuest/Assets/Sounds";
_folderTree.OnFolderSelected.Subscribe(folder => _filesView.Folder = folder);
_splitter.BottomPanel = rightPanel;
}
private void onFolderSelected(string folder)
{
_filesView.Folder = folder;
}
}
}
| artistic-2.0 | C# | |
9302762e49f9d8618b419b76ef0bd18b9e66f4ad | Make NFig internals visible to Tests | NFig/NFig | NFig/AssemblyInfo.cs | NFig/AssemblyInfo.cs | using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("NFig.Tests")] | mit | C# | |
b1bad6162a2204702ec41247f07a0a5eb0cae5e1 | Add RestVideo object | Aux/NTwitch,Aux/NTwitch | src/NTwitch.Rest/Entities/Videos/RestVideo.cs | src/NTwitch.Rest/Entities/Videos/RestVideo.cs | using System;
namespace NTwitch.Rest
{
public class RestVideo : RestEntity, IVideo
{
public ulong BroadcastId { get; }
public RestChannelSummary Channel { get; }
public DateTime CreatedAt { get; }
public string Description { get; }
public string DescriptionRaw { get; }
public string Game { get; }
public string Language { get; }
public int Length { get; }
public TwitchImage Preview { get; }
public DateTime PublishedAt { get; }
public string Status { get; }
public string[] Tags { get; }
public string Title { get; }
public BroadcastType Type { get; }
public string Url { get; }
public string Viewable { get; }
public int Views { get; }
public RestVideo(TwitchRestClient client, ulong id) : base(client, id) { }
//IVideo
IChannelSummary IVideo.Channel
=> Channel;
}
}
| mit | C# | |
bcc7c4ba26d66b665dc9905763984777635df43d | Add IWin32Resource | Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver | src/AsmResolver.PE.Win32Resources/IWin32Resource.cs | src/AsmResolver.PE.Win32Resources/IWin32Resource.cs | namespace AsmResolver.PE.Win32Resources
{
/// <summary>
/// Provides a high level view of a native win32 resource that can be stored in the resources data directory of a
/// portable executable (PE) image.
/// </summary>
public interface IWin32Resource
{
/// <summary>
/// Serializes the win32 resource to the provided root win32 resource data directory.
/// </summary>
/// <param name="rootDirectory">The root directory to submit the changes to.</param>
void WriteToDirectory(IResourceDirectory rootDirectory);
}
} | mit | C# | |
9b679431e2b95e947e18fc76f8c0b58313b22b5b | Add ZipArchive test for full roundtrip ExternAttr | elijah6/corefx,jlin177/corefx,twsouthwick/corefx,tijoytom/corefx,MaggieTsang/corefx,shimingsg/corefx,nbarbettini/corefx,krytarowski/corefx,stone-li/corefx,gkhanna79/corefx,parjong/corefx,dotnet-bot/corefx,dotnet-bot/corefx,stone-li/corefx,dhoehna/corefx,mmitche/corefx,krytarowski/corefx,parjong/corefx,wtgodbe/corefx,Jiayili1/corefx,dhoehna/corefx,wtgodbe/corefx,nbarbettini/corefx,ericstj/corefx,rubo/corefx,zhenlan/corefx,the-dwyer/corefx,ravimeda/corefx,stephenmichaelf/corefx,the-dwyer/corefx,cydhaselton/corefx,nchikanov/corefx,jlin177/corefx,nbarbettini/corefx,axelheer/corefx,Jiayili1/corefx,weltkante/corefx,Ermiar/corefx,tijoytom/corefx,twsouthwick/corefx,zhenlan/corefx,shimingsg/corefx,JosephTremoulet/corefx,ptoonen/corefx,axelheer/corefx,dhoehna/corefx,seanshpark/corefx,JosephTremoulet/corefx,YoupHulsebos/corefx,YoupHulsebos/corefx,krk/corefx,Jiayili1/corefx,Ermiar/corefx,MaggieTsang/corefx,MaggieTsang/corefx,DnlHarvey/corefx,stephenmichaelf/corefx,mmitche/corefx,jlin177/corefx,weltkante/corefx,Petermarcu/corefx,stone-li/corefx,richlander/corefx,axelheer/corefx,ptoonen/corefx,mmitche/corefx,elijah6/corefx,ptoonen/corefx,Jiayili1/corefx,jlin177/corefx,wtgodbe/corefx,Petermarcu/corefx,krk/corefx,dotnet-bot/corefx,MaggieTsang/corefx,mmitche/corefx,rubo/corefx,Ermiar/corefx,ravimeda/corefx,rubo/corefx,ericstj/corefx,parjong/corefx,seanshpark/corefx,dhoehna/corefx,alexperovich/corefx,krk/corefx,fgreinacher/corefx,ViktorHofer/corefx,YoupHulsebos/corefx,rjxby/corefx,dotnet-bot/corefx,ViktorHofer/corefx,nchikanov/corefx,nchikanov/corefx,fgreinacher/corefx,shimingsg/corefx,mazong1123/corefx,mazong1123/corefx,richlander/corefx,gkhanna79/corefx,ptoonen/corefx,the-dwyer/corefx,cydhaselton/corefx,billwert/corefx,mazong1123/corefx,cydhaselton/corefx,alexperovich/corefx,DnlHarvey/corefx,the-dwyer/corefx,weltkante/corefx,shimingsg/corefx,Jiayili1/corefx,tijoytom/corefx,dotnet-bot/corefx,axelheer/corefx,ptoonen/corefx,ravimeda/corefx,dhoehna/corefx,gkhanna79/corefx,gkhanna79/corefx,the-dwyer/corefx,cydhaselton/corefx,nbarbettini/corefx,alexperovich/corefx,richlander/corefx,stone-li/corefx,shimingsg/corefx,rjxby/corefx,shimingsg/corefx,wtgodbe/corefx,ericstj/corefx,BrennanConroy/corefx,ViktorHofer/corefx,cydhaselton/corefx,twsouthwick/corefx,billwert/corefx,tijoytom/corefx,ericstj/corefx,twsouthwick/corefx,cydhaselton/corefx,parjong/corefx,billwert/corefx,mmitche/corefx,seanshpark/corefx,ViktorHofer/corefx,stephenmichaelf/corefx,billwert/corefx,mazong1123/corefx,rjxby/corefx,tijoytom/corefx,fgreinacher/corefx,wtgodbe/corefx,DnlHarvey/corefx,yizhang82/corefx,nchikanov/corefx,JosephTremoulet/corefx,billwert/corefx,JosephTremoulet/corefx,Petermarcu/corefx,twsouthwick/corefx,weltkante/corefx,axelheer/corefx,JosephTremoulet/corefx,nchikanov/corefx,parjong/corefx,rjxby/corefx,ericstj/corefx,BrennanConroy/corefx,cydhaselton/corefx,krytarowski/corefx,fgreinacher/corefx,DnlHarvey/corefx,ptoonen/corefx,stephenmichaelf/corefx,ravimeda/corefx,mazong1123/corefx,nbarbettini/corefx,ViktorHofer/corefx,Ermiar/corefx,Jiayili1/corefx,Jiayili1/corefx,JosephTremoulet/corefx,twsouthwick/corefx,zhenlan/corefx,krk/corefx,krytarowski/corefx,nbarbettini/corefx,the-dwyer/corefx,zhenlan/corefx,mmitche/corefx,zhenlan/corefx,elijah6/corefx,billwert/corefx,seanshpark/corefx,ericstj/corefx,richlander/corefx,stephenmichaelf/corefx,twsouthwick/corefx,mmitche/corefx,weltkante/corefx,dotnet-bot/corefx,nchikanov/corefx,elijah6/corefx,MaggieTsang/corefx,YoupHulsebos/corefx,gkhanna79/corefx,gkhanna79/corefx,jlin177/corefx,richlander/corefx,the-dwyer/corefx,stone-li/corefx,nchikanov/corefx,Ermiar/corefx,rjxby/corefx,tijoytom/corefx,gkhanna79/corefx,parjong/corefx,dhoehna/corefx,dotnet-bot/corefx,ViktorHofer/corefx,krk/corefx,nbarbettini/corefx,ravimeda/corefx,Petermarcu/corefx,zhenlan/corefx,stephenmichaelf/corefx,yizhang82/corefx,weltkante/corefx,krytarowski/corefx,krk/corefx,wtgodbe/corefx,zhenlan/corefx,seanshpark/corefx,Ermiar/corefx,krytarowski/corefx,axelheer/corefx,krk/corefx,seanshpark/corefx,mazong1123/corefx,YoupHulsebos/corefx,stone-li/corefx,BrennanConroy/corefx,ravimeda/corefx,yizhang82/corefx,seanshpark/corefx,DnlHarvey/corefx,yizhang82/corefx,yizhang82/corefx,richlander/corefx,krytarowski/corefx,billwert/corefx,weltkante/corefx,rjxby/corefx,MaggieTsang/corefx,tijoytom/corefx,stephenmichaelf/corefx,ptoonen/corefx,shimingsg/corefx,mazong1123/corefx,MaggieTsang/corefx,ViktorHofer/corefx,parjong/corefx,alexperovich/corefx,yizhang82/corefx,ericstj/corefx,rubo/corefx,wtgodbe/corefx,elijah6/corefx,dhoehna/corefx,ravimeda/corefx,alexperovich/corefx,richlander/corefx,JosephTremoulet/corefx,Petermarcu/corefx,jlin177/corefx,Petermarcu/corefx,jlin177/corefx,YoupHulsebos/corefx,yizhang82/corefx,DnlHarvey/corefx,Petermarcu/corefx,rubo/corefx,rjxby/corefx,alexperovich/corefx,YoupHulsebos/corefx,alexperovich/corefx,elijah6/corefx,elijah6/corefx,Ermiar/corefx,DnlHarvey/corefx,stone-li/corefx | src/System.IO.Compression/tests/ZipArchive/zip_netcoreappTests.cs | src/System.IO.Compression/tests/ZipArchive/zip_netcoreappTests.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.Runtime.InteropServices;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Compression.Tests
{
public class zip_netcoreappTests : ZipFileTestBase
{
[Theory]
[InlineData("sharpziplib.zip", 0)]
[InlineData("Linux_RW_RW_R__.zip", 0x8000 + 0x0100 + 0x0080 + 0x0020 + 0x0010 + 0x0004)]
[InlineData("Linux_RWXRW_R__.zip", 0x8000 + 0x01C0 + 0x0020 + 0x0010 + 0x0004)]
[InlineData("OSX_RWXRW_R__.zip", 0x8000 + 0x01C0 + 0x0020 + 0x0010 + 0x0004)]
public static async Task Read_UnixFilePermissions(string zipName, uint expectedAttr)
{
using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(compat(zipName)), ZipArchiveMode.Read))
{
foreach (ZipArchiveEntry e in archive.Entries)
{
Assert.Equal(expectedAttr, ((uint)e.ExternalAttributes) >> 16);
}
}
}
[Theory]
[InlineData(int.MaxValue)]
[InlineData(int.MinValue)]
[InlineData(0)]
[InlineData((0x8000 + 0x01C0 + 0x0020 + 0x0010 + 0x0004) << 16)]
public static async Task RoundTrips_UnixFilePermissions(int expectedAttr)
{
using (var stream = await StreamHelpers.CreateTempCopyStream(zfile("normal.zip")))
{
using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Update, true))
{
foreach (ZipArchiveEntry e in archive.Entries)
{
e.ExternalAttributes = expectedAttr;
Assert.Equal(expectedAttr, e.ExternalAttributes);
}
}
using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Read))
{
foreach (ZipArchiveEntry e in archive.Entries)
{
Assert.Equal(expectedAttr, e.ExternalAttributes);
}
}
}
}
}
}
| // 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.Runtime.InteropServices;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Compression.Tests
{
public class zip_netcoreappTests : ZipFileTestBase
{
[Theory]
[InlineData("sharpziplib.zip", 0)]
[InlineData("Linux_RW_RW_R__.zip", 0x8000 + 0x0100 + 0x0080 + 0x0020 + 0x0010 + 0x0004)]
[InlineData("Linux_RWXRW_R__.zip", 0x8000 + 0x01C0 + 0x0020 + 0x0010 + 0x0004)]
[InlineData("OSX_RWXRW_R__.zip", 0x8000 + 0x01C0 + 0x0020 + 0x0010 + 0x0004)]
public static async Task Read_UnixFilePermissions(string zipName, uint expectedAttr)
{
using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(compat(zipName)), ZipArchiveMode.Read))
{
foreach (ZipArchiveEntry e in archive.Entries)
{
Assert.Equal(expectedAttr, ((uint)e.ExternalAttributes) >> 16);
}
}
}
[Theory]
[InlineData(int.MaxValue)]
[InlineData(int.MinValue)]
[InlineData(0)]
public static async Task RoundTrips_UnixFilePermissions(int expectedAttr)
{
using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(zfile("normal.zip")), ZipArchiveMode.Update))
{
foreach (ZipArchiveEntry e in archive.Entries)
{
e.ExternalAttributes = expectedAttr;
Assert.Equal(expectedAttr, e.ExternalAttributes);
}
}
}
}
}
| mit | C# |
a7bfae689f59b8f4a99535a5831ebb77d95a648b | Add benchmark coverage of `Scheduler` | peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework | osu.Framework.Benchmarks/BenchmarkScheduler.cs | osu.Framework.Benchmarks/BenchmarkScheduler.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 BenchmarkDotNet.Attributes;
using osu.Framework.Threading;
namespace osu.Framework.Benchmarks
{
public class BenchmarkScheduler : BenchmarkTest
{
private Scheduler scheduler = null!;
private Scheduler schedulerWithEveryUpdate = null!;
private Scheduler schedulerWithManyDelayed = null!;
public override void SetUp()
{
base.SetUp();
scheduler = new Scheduler();
schedulerWithEveryUpdate = new Scheduler();
schedulerWithEveryUpdate.AddDelayed(() => { }, 0, true);
schedulerWithManyDelayed = new Scheduler();
for (int i = 0; i < 1000; i++)
schedulerWithManyDelayed.AddDelayed(() => { }, int.MaxValue);
}
[Benchmark]
public void UpdateEmptyScheduler()
{
for (int i = 0; i < 1000; i++)
scheduler.Update();
}
[Benchmark]
public void UpdateSchedulerWithManyDelayed()
{
for (int i = 0; i < 1000; i++)
schedulerWithManyDelayed.Update();
}
[Benchmark]
public void UpdateSchedulerWithEveryUpdate()
{
for (int i = 0; i < 1000; i++)
schedulerWithEveryUpdate.Update();
}
[Benchmark]
public void UpdateSchedulerWithManyAdded()
{
for (int i = 0; i < 1000; i++)
{
scheduler.Add(() => { });
scheduler.Update();
}
}
}
}
| mit | C# | |
180fe00fb9c85606f1900d434a45fa674f642b0f | Add dump PSI for file internal action | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | resharper/resharper-unity/src/Internal/DumpPsiForFileAction.cs | resharper/resharper-unity/src/Internal/DumpPsiForFileAction.cs | using System.Diagnostics;
using System.IO;
using System.Text;
using JetBrains.Application.DataContext;
using JetBrains.Application.UI.Actions;
using JetBrains.Application.UI.ActionsRevised.Menu;
using JetBrains.Application.UI.ActionSystem.ActionsRevised.Menu;
using JetBrains.ProjectModel;
using JetBrains.ProjectModel.DataContext;
using JetBrains.ReSharper.Features.Internal.PsiModules;
using JetBrains.ReSharper.Features.Internal.resources;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.ExtensionsAPI;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Unity.Internal
{
[Action("Dump PSI for Current File")]
public class DumpPsiForFileAction : IExecutableAction, IInsertBefore<InternalPsiMenu, DumpPsiSourceFilePropertiesAction>
{
public bool Update(IDataContext context, ActionPresentation presentation, DelegateUpdate nextUpdate)
{
var projectFile = context.GetData(ProjectModelDataConstants.PROJECT_MODEL_ELEMENT) as IProjectFile;
return projectFile?.ToSourceFile() != null;
}
public void Execute(IDataContext context, DelegateExecute nextExecute)
{
var projectFile = context.GetData(ProjectModelDataConstants.PROJECT_MODEL_ELEMENT) as IProjectFile;
var sourceFile = projectFile?.ToSourceFile();
if (sourceFile == null)
return;
var path = CompanySpecificFolderLocations.TempFolder / (Path.GetRandomFileName() + ".txt");
using (var sw = new StreamWriter(path.OpenFileForWriting(), Encoding.UTF8))
{
foreach (var psiFile in sourceFile.EnumerateDominantPsiFiles())
{
sw.WriteLine("Language: {0}", psiFile.Language.Name);
DebugUtil.DumpPsi(sw, psiFile);
}
}
Process.Start(path.FullPath);
}
}
}
| apache-2.0 | C# | |
dd68b1830842020ebe301980f65ef7bffe14d7f4 | Add request class | DevChampsBR/MeDaUmFilme | src/MeDaUmFilme.Consulta/MeDaUmFilmeRequest.cs | src/MeDaUmFilme.Consulta/MeDaUmFilmeRequest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace MeDaUmFilme {
public static class Ramdons
{
public static IEnumerable<string> Get()
{
return new List<string>()
{
"Batman",
"Frozen",
};
}
}
public class MeDaUmFilmeRequest
{
private readonly string REQUEST_API = "http://www.omdbapi.com/?";
public string Title { get; set; }
public string Year { get; set; }
public string SearchUri
{
get
{
var uri = $"{REQUEST_API}s={Title}";
if (string.IsNullOrWhiteSpace(Title))
uri = $"{REQUEST_API}s={Ramdons.Get().FirstOrDefault()}";
if (!string.IsNullOrWhiteSpace(Year))
uri = $"{uri}&y={Year}";
return uri;
}
}
}
public class MeDaUmFilmeSearch
{
public async Task<string> GetMovie(MeDaUmFilmeRequest request)
{
string json = null;
using (var client = new HttpClient())
{
var response = await client.GetAsync(request.SearchUri);
if (response.IsSuccessStatusCode)
json = await response.Content.ReadAsStringAsync();
return json;
}
}
}
} | mit | C# | |
72ffa8edd24d55cde4da20f465a29729435edbcb | Add dev-only class GUIDebug for debugging GUI API related issues | zwcloud/ImGui,zwcloud/ImGui,zwcloud/ImGui | src/ImGui/Development/GUIDebug.cs | src/ImGui/Development/GUIDebug.cs | namespace ImGui.Development
{
public class GUIDebug
{
public static void SetWindowPosition(string windowName, Point position)
{
var possibleWindow = Application.ImGuiContext.WindowManager.Windows.Find(window => window.Name == windowName);
if (possibleWindow != null)
{
possibleWindow.Position = position;
}
}
}
} | agpl-3.0 | C# | |
cd8f7f35d2712cc8429efe7e152afe957a3b6c0d | Add DateTimeExtensions | imasm/CSharpExtensions | CSharpEx/DateTimeEx.cs | CSharpEx/DateTimeEx.cs | using System;
namespace CSharpEx
{
/// <summary>
/// DateTime Extensions
/// </summary>
public static class DateTimeEx
{
/// <summary>
/// Gets the day of the week represented by this instance.
/// According to the international standard ISO 8601, Monday shall be the
/// first day of the week ending with Sunday as the last day of the week
/// </summary>
public static int DayOfWeekEU(this DateTime dateTime)
{
int day = ((int) dateTime.DayOfWeek) - 1;
if (day < 0)
day = 6;
return day;
}
}
}
| apache-2.0 | C# | |
c568a449e991d5576ce7cb75c98a20bc6543abfd | Add Instagram | jetebusiness/NEO-Default_Theme,jetebusiness/NEO-Default_Theme | Views/Shared/Blocks/Instagram/_InstagramMedia.cshtml | Views/Shared/Blocks/Instagram/_InstagramMedia.cshtml | @model IList<DomainCompany.Entities.InstagramMedia>
@if (Model != null && Model.Count() > 0)
{
var userName = @Model.FirstOrDefault().username;
<div class="ui container">
<div class="ui horizontal divider">
<a href="https://www.instagram.com/@userName/?hl=pt-br" title="@userName" target="_blank">@Html.Raw("@"+userName)</a>
</div>
<div class="ui grid">
<div class="row one column">
<div class="column">
<div class="ui equal width grid margin none images middle aligned center aligned stackable slideshow insta_feed" data-qtd="6">
@foreach (var media in Model.Where(c => c.media_type.ToLower() == "image").Take(10))
{
<div class="column slideshow-item">
<a href="@media.permalink" target="_blank">
<img class="ui image centered fluid " src="@media.media_url" alt="" title="" onerror="imgError(this)">
</a>
</div>
}
</div>
</div>
</div>
</div>
<div class="ui divider hidden"></div>
</div>
} | mpl-2.0 | C# | |
a75f25ae869040aca731d6045d840d602e874fe1 | index changed | Abedoy/abedoy.github.io,Abedoy/abedoy.github.io | index.cshtml | index.cshtml | @{
Layout = "_Layout";
}
@section header{
<h1>Explore our world your way</h1>
<a href="/tours.htm" title="Find your tour!"><h2>Find your tour</h2></a>
}
<article id="mainArticle">
<h1>Tour Spotlight</h1>
<p class="spotlight">This month's spotlight package is Cycle California. Whether you are looking for some serious downhill thrills to a relaxing ride along the coast, you'll find something to love in Cycle California.<br /> <span class="accent"><a href="/tours_cycle.htm" title="Cycle California">tour details</a></span></p>
<h1>Explorer's Podcast</h1>
<video controls poster="/images/podcast_poster.jpg" width="512" height="288" preload="none">
<source src="_video/podcast_teaser.mp4" type="video/mp4" />
<source src="_video/podcast_teaser.webm" type="video/webm" />
<source src="_video/podcast_teaser.theora.ogv" type="video/ogg" />
</video>
<p class="videoText">Join us each month as we publish a new Explore California video podcast, with featured tours, customer photos, and some exctiing new features!<span class="accent"><a href="explorers/video.htm" title="Video Podcast">Watch the full video</a></span></p>
</article> | mit | C# | |
d38f2ff857e4b29940cfa40cd1c9c3f614e9075f | Create test.cs | cloudymatrix/ALRD | test.cs | test.cs | hi
| apache-2.0 | C# | |
950ce36119a8da0fbf8c25f653065dbdb90a6293 | Add Extensions.cs | dv-lebedev/statistics | Statistics/Extensions.cs | Statistics/Extensions.cs | /*
Copyright 2015 Denis Lebedev
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.
*/
namespace Statistics
{
public static class Extensions
{
public static double ToDouble(this decimal value)
{
return (double)value;
}
public static decimal ToDecimal(this double value)
{
return (decimal)value;
}
public static double[] ToDouble(this decimal[] array)
{
int size = array.Length;
double[] result = new double[size];
for (int i = 0; i < size; i++)
{
result[i] = (double)array[i];
}
return result;
}
public static decimal[] ToDecimal(this double[] array)
{
int size = array.Length;
decimal[] result = new decimal[size];
for (int i = 0; i < size; i++)
{
result[i] = (decimal)array[i];
}
return result;
}
}
}
| apache-2.0 | C# | |
b3de2003d0cf7f866275e6ae5b70d0a3c23d7aa2 | Add ShutdownHandler unit test. | jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr | test/HelloCoreClrApp.Test/ShutdownHandlerTest.cs | test/HelloCoreClrApp.Test/ShutdownHandlerTest.cs | using System.Threading;
using FluentAssertions;
using Xunit;
namespace HelloCoreClrApp.Test
{
public class ShutdownHandlerTest
{
[Fact]
public void ConfigureShouldNotFailTest()
{
var cts = new CancellationTokenSource();
ShutdownHandler.Configure(cts);
cts.IsCancellationRequested.Should().Be(false);
}
}
}
| mit | C# | |
387f824809f7217bbee53600b1375f8efd940ff3 | Create Deneme.cs | archifux/TestRepos | Deneme.cs | Deneme.cs | Test Sayfasi
| unlicense | C# | |
f8488372e252a864a9849340abf160cc85a3216a | Fix commit cb14631a3a211008f2a64282633dd2876ace717d | StockSharp/StockSharp | Localization.Generator/Properties/AssemblyInfo.cs | Localization.Generator/Properties/AssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("S#.Localization generator")]
[assembly: AssemblyDescription("Localization generator.")] | apache-2.0 | C# | |
2cbdbc5aae1c03e5f13b9bc0280cc0bd7bb3e143 | Create array.cs | wchild30/asterisk,ashoktandan007/csharp | array.cs | array.cs | using System;
class Program
{
static int i, j;
static void Main(string[] args)
{
Console.WriteLine("enter no of students");
i = int.Parse(Console.ReadLine());
Console.WriteLine("enter no of subjects");
j = int.Parse(Console.ReadLine());
int[,] arr = new int[i, j];
for (int w = 0; w < i; w++)
{
Console.WriteLine("for " + (w+1) + " student");
for (int x = 0; x < j; x++)
{
Console.Write("enter " + (x+1) + " subject marks= ");
arr[w, x] = int.Parse(Console.ReadLine());
}
}
for (int u = 0; u < i; u++)
{
Console.WriteLine("student "+(u+1)+" marks are: ");
for (int y = 0; y < j; y++)
{
Console.WriteLine(arr[u, y]);
}
}
Console.ReadLine();
}
}
| apache-2.0 | C# | |
167a3e2cf842455db9bf20d7defa2c1d2f36eee2 | Add another file. | KirillOsenkov/MSBuildStructuredLog,KirillOsenkov/MSBuildStructuredLog | src/StructuredLogViewer/WelcomeScreen.cs | src/StructuredLogViewer/WelcomeScreen.cs | namespace Microsoft.Build.Logging.StructuredLogger
{
public class WelcomeScreen
{
}
}
| mit | C# | |
17872356d6c40cad8cdfdcd91c8cda4938c6fc2b | add Latch | itsuart/cs-goodies | Latch.cs | Latch.cs | public class Latch
{
private long _lockCount = 0;
public IDisposable Lock()
{
_lockCount += 1;
return new Helper(this);
}
public bool Unlocked { get { return _lockCount == 0; } }
public bool Locked { get { return !Unlocked; } }
private class Helper : IDisposable
{
private Latch _parent;
public Helper(Latch parent)
{
_parent = parent;
}
public void Dispose()
{
_parent._lockCount -= 1;
_parent = null;
}
}
}
| unlicense | C# | |
e19e4557973b25f0e0e214d4498e2e022d0459c9 | Create abstract base class for a HttpServer | SnowflakePowered/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,RonnChyran/snowflake,faint32/snowflake-1,RonnChyran/snowflake,SnowflakePowered/snowflake,faint32/snowflake-1,faint32/snowflake-1 | Snowflake.API/Core/Server/BaseHttpServer.cs | Snowflake.API/Core/Server/BaseHttpServer.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Threading;
namespace Snowflake.Core.Server
{
public abstract class BaseHttpServer
{
HttpListener serverListener;
Thread serverThread;
bool cancel;
public BaseHttpServer(int port)
{
serverListener = new HttpListener();
serverListener.Prefixes.Add("http://localhost:" + port.ToString() + "/");
}
public void StartServer()
{
this.serverThread = new Thread(
() =>
{
serverListener.Start();
while (!this.cancel)
{
HttpListenerContext context = serverListener.GetContext();
Task.Run(() => this.Process(context));
}
}
);
this.serverThread.IsBackground = true;
this.serverThread.Start();
}
public void StopServer()
{
this.cancel = true;
this.serverThread.Join();
this.serverListener.Stop();
}
public abstract void Process(HttpListenerContext context);
}
}
| mpl-2.0 | C# | |
301d7f1123a323ab55a64cdc92344cd9d243168d | Fix build error for XCode | NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity | ncmb_unity/Assets/Editor/UpdateXcodeProject.cs | ncmb_unity/Assets/Editor/UpdateXcodeProject.cs | using System;
using System.IO;
using UnityEngine;
using UnityEditor;
using UnityEditor.iOS.Xcode;
using UnityEditor.Callbacks;
using System.Collections;
public class UpdateXcodeProject
{
[PostProcessBuildAttribute (0)]
public static void OnPostprocessBuild (BuildTarget buildTarget, string pathToBuiltProject)
{
// Stop processing if targe is NOT iOS
if (buildTarget != BuildTarget.iOS)
return;
UpdateXcode(pathToBuiltProject);
}
static void UpdateXcode(string pathToBuiltProject)
{
var projectPath = pathToBuiltProject + "/Unity-iPhone.xcodeproj/project.pbxproj";
if (!File.Exists(projectPath))
{
throw new Exception(string.Format("projectPath is null {0}", projectPath));
}
// Initialize PbxProject
PBXProject pbxProject = new PBXProject();
pbxProject.ReadFromFile(projectPath);
string targetGuid = pbxProject.TargetGuidByName("Unity-iPhone");
// Adding required framework
pbxProject.AddFrameworkToProject(targetGuid, "UserNotifications.framework", false);
// Apply settings
File.WriteAllText (projectPath, pbxProject.WriteToString());
}
}
| apache-2.0 | C# | |
b1725c9d1a130afaf443447ca27ed4bad13bd775 | Add tests for F.TakeFrom | farity/farity | Farity.Tests/TakeFromTests.cs | Farity.Tests/TakeFromTests.cs | using Xunit;
using System.Linq;
namespace Farity.Tests
{
public class TakeFromTests
{
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
public void TakeFromTakesElementsFromIndexN(int n)
{
Assert.True(n <= 5 && n >= 0);
var data = new[] { 1, 2, 3, 4, 5 };
var expected = data.Skip(n).ToList();
var actual = F.TakeFrom(n, data).ToList();
Assert.Equal(expected, actual);
}
[Fact]
public void TakeFromReturnsSameSequenceIfIndexIsZero()
{
var expected = new[] { 1, 2, 3, 4, 5 };
var actual = F.TakeFrom(0, expected);
Assert.Equal(expected, actual);
}
[Fact]
public void TakeFromReturnsEmptySequenceIfIndexIsGreaterThanOrEqualToLengthOfSequence()
{
var expected = new int[] { };
var data = new[] { 1, 2, 3, 4, 5 };
var actual = F.TakeFrom(5, expected);
Assert.Equal(expected, actual);
actual = F.TakeFrom(9, expected);
Assert.Equal(expected, actual);
}
}
}
| mit | C# | |
196f47c1ab7013d033bb6ad795743e007f01f209 | Add `FileWriterTests ` | jlennox/HeartRate | Lennox.HeartRate.Tests/FileWriterTests.cs | Lennox.HeartRate.Tests/FileWriterTests.cs | using System.IO;
using System.Linq;
using HeartRate;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Lennox.HeartRate.Tests
{
[TestClass]
public class FileWriterTests
{
[TestMethod]
public void IBIFormatsCorrectly()
{
using var tmp = new TempFile();
var ibi = new IBIFile(tmp);
ibi.Reading(new HeartRateReading
{
RRIntervals = new int[] {
4 * 1024,
4 * 1024 + (1024 / 2 + 4), // Ensure the rounding is working.
6 * 1024 + 4
}
});
ibi.Reading(new HeartRateReading
{
RRIntervals = new int[] {
7 * 1024,
8 * 1024,
9 * 1024
}
});
var actual = File.ReadAllLines(tmp);
var expected = Enumerable.Range(4, 6)
.Select(t => t.ToString()).ToArray();
CollectionAssert.AreEqual(expected, actual);
}
}
}
| mit | C# | |
dc9250ca04c106936018275decc5b3392921221b | add json dispatcher. | dotnetcore/CAP,ouraspnet/cap,dotnetcore/CAP,dotnetcore/CAP | src/DotNetCore.CAP/Dashboard/JsonDispatcher.cs | src/DotNetCore.CAP/Dashboard/JsonDispatcher.cs | using System;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
namespace DotNetCore.CAP.Dashboard
{
internal class JsonDispatcher : IDashboardDispatcher
{
private readonly Func<DashboardContext, object> _command;
public JsonDispatcher(Func<DashboardContext, object> command)
{
_command = command;
}
public async Task Dispatch(DashboardContext context)
{
var request = context.Request;
var response = context.Response;
object result = _command(context);
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new JsonConverter[] { new StringEnumConverter { CamelCaseText = true } }
};
var serialized = JsonConvert.SerializeObject(result, settings);
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(serialized);
}
}
}
| mit | C# | |
031f21175e5cfde7c6a5e5ab219e7c32a24456d8 | Create run.csx | vunvulear/Stuff,vunvulear/Stuff,vunvulear/Stuff | Azure/azure-function-extractgpslocation-onedrive-drawwatermark/run.csx | Azure/azure-function-extractgpslocation-onedrive-drawwatermark/run.csx | #r "Microsoft.Azure.WebJobs.Extensions.ApiHub" // Don't forget to blog about it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExifLib;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
public static void Run(Stream inputFile, TraceWriter log, Stream outputFile)
{
log.Info("Image Process Starts");
log.Info("Extract location information");
ExifReader exifReader = new ExifReader(inputFile);
double[] latitudeComponents;
exifReader.GetTagValue(ExifTags.GPSLatitude, out latitudeComponents);
double[] longitudeComponents;
exifReader.GetTagValue(ExifTags.GPSLongitude, out longitudeComponents);
log.Info("Prepare string content");
string location = string.Empty;
if (latitudeComponents == null ||
longitudeComponents == null)
{
location = "No GPS location";
}
else
{
double latitude = 0;
double longitude = 0;
latitude = latitudeComponents[0] + latitudeComponents[1] / 60 + latitudeComponents[2] / 3600;
longitude = longitudeComponents[0] + longitudeComponents[1] / 60 + longitudeComponents[2] / 3600;
location = $"Latitude: '{latitude}' | Longitude: '{longitude}'";
}
log.Info($"Text to be written: '{location}'");
// Reset position. After Exif operations the cursor location is not on position 0 anymore;
inputFile.Position = 0;
log.Info("Write text to picture");
using (Image inputImage = Image.FromStream(inputFile, true))
{
using (Graphics graphic = Graphics.FromImage(inputImage))
{
graphic.SmoothingMode = SmoothingMode.HighQuality;
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphic.DrawString(location, new Font("Tahoma", 100, FontStyle.Bold), Brushes.Red, 200, 200);
graphic.Flush();
log.Info("Write to the output stream");
inputImage.Save(outputFile, ImageFormat.Jpeg);
}
}
log.Info("Image Process Ends");
}
| apache-2.0 | C# | |
a3d302a81da3ff7275076fcf40334ba49ae68a86 | Create rot13.cs | HeyIamJames/Learning-C-,HeyIamJames/Learning-C- | rot13.cs | rot13.cs | static string Rot13(string input)
{
if(input == null)
return null;
Tuple<int, int>[] ranges = { Tuple.Create(65, 90), Tuple.Create(97, 122) };
var chars = input.Select(x =>
{
var range = ranges.SingleOrDefault(y => x >= y.Item1 && x <= y.Item2);
if(range == null)
return x;
return (char)((x - range.Item1 + 13) % 26) + range.Item1;
});
return string.Concat(chars);
}
| mit | C# | |
9ebdef12a89d38f432acbb8898126786dac9fc77 | add path measure example | jkoritzinsky/Avalonia,Perspex/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,grokys/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,Perspex/Perspex,SuperJMN/Avalonia | samples/RenderDemo/Pages/PathMeasurementPage.cs | samples/RenderDemo/Pages/PathMeasurementPage.cs | using System.Diagnostics;
using System.Drawing.Drawing2D;
using Avalonia;
using Avalonia.Controls;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using Avalonia.Visuals.Media.Imaging;
namespace RenderDemo.Pages
{
public class PathMeasurementPage : Control
{
private RenderTargetBitmap _bitmap;
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
_bitmap = new RenderTargetBitmap(new PixelSize(500, 500), new Vector(96, 96));
base.OnAttachedToLogicalTree(e);
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
_bitmap.Dispose();
_bitmap = null;
base.OnDetachedFromLogicalTree(e);
}
readonly Stopwatch _st = Stopwatch.StartNew();
readonly IPen strokePen = new ImmutablePen(Brushes.DarkBlue, 10d, null, PenLineCap.Round, PenLineJoin.Round);
readonly IPen strokePen1 = new ImmutablePen(Brushes.Purple, 10d, null, PenLineCap.Round, PenLineJoin.Round);
readonly IPen strokePen2 = new ImmutablePen(Brushes.Green, 10d, null, PenLineCap.Round, PenLineJoin.Round);
readonly IPen strokePen3 = new ImmutablePen(Brushes.LightBlue, 10d, null, PenLineCap.Round, PenLineJoin.Round);
public override void Render(DrawingContext context)
{
using (var ctxi = _bitmap.CreateDrawingContext(null))
using (var ctx = new DrawingContext(ctxi, false))
{
ctxi.Clear(default);
var x = new PathGeometry();
using (var xsad = x.Open())
{
xsad.BeginFigure(new Point(20, 20), false);
xsad.LineTo(new Point(400, 50));
xsad.LineTo(new Point(80, 100));
xsad.LineTo(new Point(300, 150));
xsad.EndFigure(false);
}
ctx.DrawGeometry(null, strokePen, x);
var length = x.PlatformImpl.ContourLength;
if (x.PlatformImpl.TryGetSegment(length * 0.05, length * 0.2, true, out var dst1))
ctx.DrawGeometry(null, strokePen1, (Geometry)dst1);
if (x.PlatformImpl.TryGetSegment(length * 0.2, length * 0.8, true, out var dst2))
ctx.DrawGeometry(null, strokePen2, (Geometry)dst2);
if (x.PlatformImpl.TryGetSegment(length * 0.8, length * 0.95, true, out var dst3))
ctx.DrawGeometry(null, strokePen3, (Geometry)dst3);
/*
* paint.Style = SKPaintStyle.Stroke;z
paint.StrokeWidth = 10;z
paint.IsAntialias = true;z
paint.StrokeCap = SKStrokeCap.Round;z
paint.StrokeJoin = SKStrokeJoin.Round;x
path.MoveTo(20, 20);
path.LineTo(400, 50);
path.LineTo(80, 100);
path.LineTo(300, 150);
paint.Color = SampleMedia.Colors.XamarinDarkBlue;
canvas.DrawPath(path, paint);
using (var measure = new SKPathMeasure(path, false))
using (var dst = new SKPath())
{
var length = measure.Length;
dst.Reset();
measure.GetSegment(length * 0.05f, length * 0.2f, dst, true);
paint.Color = SampleMedia.Colors.XamarinPurple;
canvas.DrawPath(dst, paint);
dst.Reset();
measure.GetSegment( dst, true);
paint.Color = SampleMedia.Colors.XamarinGreen;
canvas.DrawPath(dst, paint);
dst.Reset();
measure.GetSegment(length * 0.8f, length * 0.95f, dst, true);
paint.Color = SampleMedia.Colors.XamarinLightBlue;
canvas.DrawPath(dst, paint);
}
*/
//
// ctx.FillRectangle(Brushes.Fuchsia, new Rect(50, 50, 100, 100));
}
context.DrawImage(_bitmap,
new Rect(0, 0, 500, 500),
new Rect(0, 0, 500, 500));
Dispatcher.UIThread.Post(InvalidateVisual, DispatcherPriority.Background);
base.Render(context);
}
}
}
| mit | C# | |
1f8c472db3ac17ef2814fe45b1c4e65223975d04 | Add UNIX missing plug | CosmosOS/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos | source/Cosmos.System2_Plugs/Interop/UnixImpl.cs | source/Cosmos.System2_Plugs/Interop/UnixImpl.cs | using IL2CPU.API.Attribs;
using System;
using System.IO;
namespace Cosmos.System_Plugs.Interop
{
[Plug("Interop+Sys", IsOptional = true)]
internal class SysImpl
{
[PlugMethod(Signature = "System_Void__Interop_Sys_GetNonCryptographicallySecureRandomBytes_System_Byte__System_Int32_")]
internal static unsafe void GetNonCryptographicallySecureRandomBytes(byte* buffer, int length)
{
throw new NotImplementedException();
}
}
}
| bsd-3-clause | C# | |
ccc13555e84c25eb06591c15e755f3e57f79c271 | Create Details.cshtml | CarmelSoftware/Generic-Data-Repository-With-Caching | Views/Blogs/Details.cshtml | Views/Blogs/Details.cshtml | @model GenericRepositoryWithCatching.Models.Blog
@{
ViewBag.Title = "Details";
}
<div class="jumbotron">
<h2>Generic Repository With Memory Caching - @ViewBag.Title</h2>
<h4>By Carmel</h4>
</div>
<div class="jumbotron">
<fieldset>
<legend>Blog</legend>
<div class="display-label">
@Html.DisplayNameFor(model => model.Title)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Title)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.Text)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Text)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.DatePosted)
</div>
<div class="display-field">
@String.Format("{0:yyyy-MM-dd}", @Model.DatePosted)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.MainPicture)
</div>
<div class="display-field">
<img src="/Content/Images/@Model.MainPicture" />
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.Blogger.Name)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Blogger.Name)
</div>
</fieldset>
<p>
@Html.ActionLink("Edit", "Edit", new { id = Model.BlogID }, new { @class="btn btn-success" }) |
@Html.ActionLink("Back to List", "Index", null, new { @class="btn btn-success" })
</p>
</div>
| mit | C# | |
7b9da556fb7dc83d10e0ebd2ce1771a54935cd27 | Add `HttpRequestRewindExtensions` - aspnet/Home#2684 - makes the `BufferingHelper` methods used in MVC and WebHooks `public` | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNetCore.Http/Extensions/HttpRequestRewindExtensions.cs | src/Microsoft.AspNetCore.Http/Extensions/HttpRequestRewindExtensions.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNetCore.Http.Internal;
namespace Microsoft.AspNetCore.Http
{
/// <summary>
/// Extension methods for enabling buffering in an <see cref="HttpRequest"/>.
/// </summary>
public static class HttpRequestRewindExtensions
{
/// <summary>
/// Ensure the <paramref name="request"/> <see cref="HttpRequest.Body"/> can be read multiple times. Normally
/// buffers request bodies in memory; writes requests larger than 30K bytes to disk.
/// </summary>
/// <param name="request">The <see cref="HttpRequest"/> to prepare.</param>
/// <remarks>
/// Temporary files for larger requests are written to the location named in the <c>ASPNETCORE_TEMP</c>
/// environment variable, if any. If that environment variable is not defined, these files are written to the
/// current user's temporary folder. Files are automatically deleted at the end of their associated requests.
/// </remarks>
public static void EnableBuffering(this HttpRequest request)
{
BufferingHelper.EnableRewind(request);
}
/// <summary>
/// Ensure the <paramref name="request"/> <see cref="HttpRequest.Body"/> can be read multiple times. Normally
/// buffers request bodies in memory; writes requests larger than <paramref name="bufferThreshold"/> bytes to
/// disk.
/// </summary>
/// <param name="request">The <see cref="HttpRequest"/> to prepare.</param>
/// <param name="bufferThreshold">
/// The maximum size in bytes of the in-memory <see cref="System.Buffers.ArrayPool{Byte}"/> used to buffer the
/// stream. Larger request bodies are written to disk.
/// </param>
/// <remarks>
/// Temporary files for larger requests are written to the location named in the <c>ASPNETCORE_TEMP</c>
/// environment variable, if any. If that environment variable is not defined, these files are written to the
/// current user's temporary folder. Files are automatically deleted at the end of their associated requests.
/// </remarks>
public static void EnableBuffering(this HttpRequest request, int bufferThreshold)
{
BufferingHelper.EnableRewind(request, bufferThreshold);
}
/// <summary>
/// Ensure the <paramref name="request"/> <see cref="HttpRequest.Body"/> can be read multiple times. Normally
/// buffers request bodies in memory; writes requests larger than 30K bytes to disk.
/// </summary>
/// <param name="request">The <see cref="HttpRequest"/> to prepare.</param>
/// <param name="bufferLimit">
/// The maximum size in bytes of the request body. An attempt to read beyond this limit will cause an
/// <see cref="System.IO.IOException"/>.
/// </param>
/// <remarks>
/// Temporary files for larger requests are written to the location named in the <c>ASPNETCORE_TEMP</c>
/// environment variable, if any. If that environment variable is not defined, these files are written to the
/// current user's temporary folder. Files are automatically deleted at the end of their associated requests.
/// </remarks>
public static void EnableBuffering(this HttpRequest request, long bufferLimit)
{
BufferingHelper.EnableRewind(request, bufferLimit: bufferLimit);
}
/// <summary>
/// Ensure the <paramref name="request"/> <see cref="HttpRequest.Body"/> can be read multiple times. Normally
/// buffers request bodies in memory; writes requests larger than <paramref name="bufferThreshold"/> bytes to
/// disk.
/// </summary>
/// <param name="request">The <see cref="HttpRequest"/> to prepare.</param>
/// <param name="bufferThreshold">
/// The maximum size in bytes of the in-memory <see cref="System.Buffers.ArrayPool{Byte}"/> used to buffer the
/// stream. Larger request bodies are written to disk.
/// </param>
/// <param name="bufferLimit">
/// The maximum size in bytes of the request body. An attempt to read beyond this limit will cause an
/// <see cref="System.IO.IOException"/>.
/// </param>
/// <remarks>
/// Temporary files for larger requests are written to the location named in the <c>ASPNETCORE_TEMP</c>
/// environment variable, if any. If that environment variable is not defined, these files are written to the
/// current user's temporary folder. Files are automatically deleted at the end of their associated requests.
/// </remarks>
public static void EnableBuffering(this HttpRequest request, int bufferThreshold, long bufferLimit)
{
BufferingHelper.EnableRewind(request, bufferThreshold, bufferLimit);
}
}
}
| apache-2.0 | C# | |
ba5e32472de015442534144d32d5fb71904f2d45 | Create tjs_podRadiation.cs | tatjam/Radiation-Mod | Source/tjs_podRadiation.cs | Source/tjs_podRadiation.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace tjs_radMod
{
class tjs_podRadiation : PartModule //A class for checking the radiation of individual pods (Manned)
{
//Variables
[KSPField(isPersistant = true)]
public double radAmmount = 0f; //Internal, manages how much radiation is applied to a certin pod (Before maths)
[KSPField(isPersistant = false)]
public double radShield = 1f; //Configurable, is a DIVISOR of radAmmount, basically, shield ammount.
[KSPField(isPersistant = true)]
public double radShieldExtra = 0f; //Internal, adds to radShield. Is dependant of protective fluid on the part
private int safetyWait = 25; //Ammount of ticks to wait before the radiation stuff starts to happen (Safety first)
private int safetyWaited = 0; //Ammount of ticks that have been already waited :P
private string activePlanet = "NO_DATA"; //Active SOI. Set to "NO_DATA" to not damage crew on load.
private double altitude = 0; //Used in radiation calculation.
private double latitude = 0; //There tends to be more radiation at the poles.
//onStart:
public override void onStart(StartState state) //Runs when the part spawns
{
if(HighLogic.LoadedSceneIsFlight == true) //Check whenever the part is on flight
{
Debug.Log("[Radiation Manager] Pod radiation manager started!");
Debug.Log("[Radiation Manager] Make sure i'm not starting before physics load!");
}
}
public override void OnUpdate()
{
if(safetyWait == safetyWaited)
{
//All code goes here!
//HOPE IT WILL WORK!!!
activePlanet = vessel.orbit.referenceBody.bodyName;
altitude = vessel.altitude;
latitude = vessel.latitude;
Debug.Log("[Useless Spam] Vessel's active planet is: " + activePlanet + ", active altitude is: " + altitude + " and latitude is: " + latitude);
}
else //Safety first!
{
safetyWaited = safetyWaited + 1;
}
}
//Simple function, it does some magic and converts three input values into the final radiation dose!
//The magic behind this: radiationAmmount / (radiationShield + radiationShieldExtra)
public float cRadiation(float radiationAmmount, float radiationShield, float radiationShieldExtra)
{
float finRadiation = radiationAmmount / (radiationShield + radiationShieldExtra);
return finRadiation;
}
}
}
| mit | C# | |
5ed935f30aa0322ec6d3ed816cd172f2cc64c7e9 | Add entity list prototype (#3720) | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Shared/Prototypes/EntityList/EntityListPrototype.cs | Content.Shared/Prototypes/EntityList/EntityListPrototype.cs | using System.Collections.Generic;
using System.Collections.Immutable;
using Robust.Shared.IoC;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype.List;
using Robust.Shared.ViewVariables;
namespace Content.Shared.Prototypes.EntityList
{
[Prototype("entityList")]
public class EntityListPrototype : IPrototype
{
[ViewVariables]
[field: DataField("id", required: true)]
public string ID { get; } = default!;
[ViewVariables]
[field: DataField("entities", customTypeSerializer: typeof(PrototypeIdListSerializer<EntityPrototype>))]
public ImmutableList<string> EntityIds { get; } = ImmutableList<string>.Empty;
public IEnumerable<EntityPrototype> Entities(IPrototypeManager? prototypeManager = null)
{
prototypeManager ??= IoCManager.Resolve<IPrototypeManager>();
foreach (var entityId in EntityIds)
{
yield return prototypeManager.Index<EntityPrototype>(entityId);
}
}
}
}
| mit | C# | |
746e99a59b17578675c388bc90a92ac1c17e1b7b | Create InsertionSort.cs | BBoldenow/Algorithms,BBoldenow/Introduction-to-Algorithms,BBoldenow/Introduction-to-Algorithms,BBoldenow/Algorithms,BBoldenow/Introduction-to-Algorithms,BBoldenow/Algorithms | Insertion-Sort/InsertionSort.cs | Insertion-Sort/InsertionSort.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algorithms
{
class InsertionSort
{
public static void InsertSort(ref List<int> arr)
{
for (int i = 0; i < arr.Count; ++i)
{
int current = arr[i];
int pos = i;
while (pos > 0 && current < arr[pos - 1])
{
arr[pos] = arr[pos - 1];
arr[pos - 1] = current;
--pos;
}
}
}
}
}
| mit | C# | |
9bd7c4c0e59909bd0795f2fd02de75996266a21a | Create Planet.cs | jon-lad/Battlefleet-Gothic | Planet.cs | Planet.cs | using UnityEngine;
using System.Collections;
public class Planet : MonoBehaviour {
public int type;
public bool asteroidField;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| mit | C# | |
12e0c53b141d969f20f117c8b490d9f24b0877a7 | Fix ILC compilation failure for S.R.InteropServices.Test (#21633) | nbarbettini/corefx,axelheer/corefx,stone-li/corefx,krk/corefx,cydhaselton/corefx,yizhang82/corefx,cydhaselton/corefx,zhenlan/corefx,rubo/corefx,shimingsg/corefx,the-dwyer/corefx,ravimeda/corefx,JosephTremoulet/corefx,DnlHarvey/corefx,ericstj/corefx,Ermiar/corefx,Ermiar/corefx,cydhaselton/corefx,jlin177/corefx,parjong/corefx,Ermiar/corefx,billwert/corefx,zhenlan/corefx,nchikanov/corefx,shimingsg/corefx,wtgodbe/corefx,Jiayili1/corefx,shimingsg/corefx,nchikanov/corefx,Ermiar/corefx,zhenlan/corefx,fgreinacher/corefx,axelheer/corefx,the-dwyer/corefx,the-dwyer/corefx,the-dwyer/corefx,cydhaselton/corefx,krk/corefx,rubo/corefx,stone-li/corefx,zhenlan/corefx,Jiayili1/corefx,mmitche/corefx,MaggieTsang/corefx,wtgodbe/corefx,mmitche/corefx,jlin177/corefx,richlander/corefx,DnlHarvey/corefx,DnlHarvey/corefx,krk/corefx,JosephTremoulet/corefx,jlin177/corefx,the-dwyer/corefx,DnlHarvey/corefx,ptoonen/corefx,ericstj/corefx,jlin177/corefx,seanshpark/corefx,ravimeda/corefx,fgreinacher/corefx,billwert/corefx,yizhang82/corefx,JosephTremoulet/corefx,Ermiar/corefx,cydhaselton/corefx,seanshpark/corefx,shimingsg/corefx,fgreinacher/corefx,ptoonen/corefx,tijoytom/corefx,jlin177/corefx,JosephTremoulet/corefx,ericstj/corefx,mmitche/corefx,seanshpark/corefx,wtgodbe/corefx,nbarbettini/corefx,ViktorHofer/corefx,ericstj/corefx,shimingsg/corefx,nbarbettini/corefx,parjong/corefx,yizhang82/corefx,ptoonen/corefx,mmitche/corefx,mazong1123/corefx,BrennanConroy/corefx,Ermiar/corefx,tijoytom/corefx,tijoytom/corefx,Jiayili1/corefx,MaggieTsang/corefx,JosephTremoulet/corefx,parjong/corefx,ericstj/corefx,richlander/corefx,seanshpark/corefx,nbarbettini/corefx,cydhaselton/corefx,stone-li/corefx,yizhang82/corefx,rubo/corefx,yizhang82/corefx,MaggieTsang/corefx,mazong1123/corefx,yizhang82/corefx,parjong/corefx,ViktorHofer/corefx,billwert/corefx,wtgodbe/corefx,nchikanov/corefx,mmitche/corefx,stone-li/corefx,MaggieTsang/corefx,krk/corefx,stone-li/corefx,nchikanov/corefx,Jiayili1/corefx,twsouthwick/corefx,ericstj/corefx,Jiayili1/corefx,nbarbettini/corefx,DnlHarvey/corefx,Ermiar/corefx,seanshpark/corefx,rubo/corefx,zhenlan/corefx,billwert/corefx,krk/corefx,fgreinacher/corefx,twsouthwick/corefx,stone-li/corefx,mmitche/corefx,DnlHarvey/corefx,the-dwyer/corefx,ravimeda/corefx,twsouthwick/corefx,axelheer/corefx,mazong1123/corefx,mazong1123/corefx,parjong/corefx,mazong1123/corefx,MaggieTsang/corefx,billwert/corefx,ViktorHofer/corefx,MaggieTsang/corefx,seanshpark/corefx,axelheer/corefx,ptoonen/corefx,billwert/corefx,parjong/corefx,twsouthwick/corefx,rubo/corefx,axelheer/corefx,ViktorHofer/corefx,ViktorHofer/corefx,DnlHarvey/corefx,wtgodbe/corefx,shimingsg/corefx,krk/corefx,ravimeda/corefx,yizhang82/corefx,mazong1123/corefx,tijoytom/corefx,JosephTremoulet/corefx,nchikanov/corefx,ericstj/corefx,shimingsg/corefx,ptoonen/corefx,zhenlan/corefx,twsouthwick/corefx,richlander/corefx,ravimeda/corefx,nbarbettini/corefx,richlander/corefx,twsouthwick/corefx,zhenlan/corefx,stone-li/corefx,nchikanov/corefx,tijoytom/corefx,tijoytom/corefx,twsouthwick/corefx,ravimeda/corefx,ViktorHofer/corefx,MaggieTsang/corefx,axelheer/corefx,ravimeda/corefx,krk/corefx,jlin177/corefx,the-dwyer/corefx,jlin177/corefx,nbarbettini/corefx,mmitche/corefx,parjong/corefx,seanshpark/corefx,ptoonen/corefx,cydhaselton/corefx,ptoonen/corefx,richlander/corefx,ViktorHofer/corefx,nchikanov/corefx,wtgodbe/corefx,BrennanConroy/corefx,billwert/corefx,wtgodbe/corefx,BrennanConroy/corefx,richlander/corefx,richlander/corefx,JosephTremoulet/corefx,mazong1123/corefx,Jiayili1/corefx,Jiayili1/corefx,tijoytom/corefx | src/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/MarshalTests.Windows.cs | src/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/MarshalTests.Windows.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.Collections.Generic;
using Xunit;
namespace System.Runtime.InteropServices
{
public partial class MarshalTests
{
public static IEnumerable<object[]> IsComImport_Windows_ReturnsExpected()
{
yield return new object[] { new ComImportObject(), true };
yield return new object[] { new SubComImportObject(), true };
yield return new object[] { new InterfaceAndComImportObject(), true };
yield return new object[] { new InterfaceComImportObject(), false };
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
[MemberData(nameof(IsComImport_Windows_ReturnsExpected))]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not approved COM object for app")]
public void IsComObject_Windows_ReturnsExpected(object value, bool expected)
{
Assert.Equal(expected, Marshal.IsComObject(value));
}
}
[ComImport]
[Guid("927971f5-0939-11d1-8be1-00c04fd8d503")]
public interface IComImportObject { }
public class InterfaceComImportObject : IComImportObject { }
[ComImport]
[Guid("927971f5-0939-11d1-8be1-00c04fd8d503")]
public class InterfaceAndComImportObject : IComImportObject { }
[ComImport]
[Guid("927971f5-0939-11d1-8be1-00c04fd8d503")]
public class ComImportObject { }
public class SubComImportObject : ComImportObject { }
}
| // 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.Collections.Generic;
using Xunit;
namespace System.Runtime.InteropServices
{
public partial class MarshalTests
{
public static IEnumerable<object[]> IsComImport_Windows_ReturnsExpected()
{
yield return new object[] { new ComImportObject(), true };
yield return new object[] { new SubComImportObject(), true };
yield return new object[] { new InterfaceAndComImportObject(), true };
yield return new object[] { new InterfaceComImportObject(), false };
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
[MemberData(nameof(IsComImport_Windows_ReturnsExpected))]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not approved COM object for app")]
public void IsComObject_Windows_ReturnsExpected(object value, bool expected)
{
Assert.Equal(expected, Marshal.IsComObject(value));
}
[ComImport]
[Guid("927971f5-0939-11d1-8be1-00c04fd8d503")]
public interface IComImportObject { }
public class InterfaceComImportObject : IComImportObject { }
[ComImport]
[Guid("927971f5-0939-11d1-8be1-00c04fd8d503")]
public class InterfaceAndComImportObject : IComImportObject { }
[ComImport]
[Guid("927971f5-0939-11d1-8be1-00c04fd8d503")]
public class ComImportObject { }
public class SubComImportObject : ComImportObject { }
}
}
| mit | C# |
c3c605ac7ab72697cddee1a925a81335c448419c | Add serialize atributes for Employee | 23S163PR/system-programming | Novak.Andriy/parallel-extension-demo/Employee.cs | Novak.Andriy/parallel-extension-demo/Employee.cs | using System;
using System.Xml.Serialization;
namespace parallel_extension_demo
{
[Serializable]
[XmlRoot("employee")]
public class Employee
{
[XmlElement(ElementName = "identity")]
public Guid Identity { get; set; }
[XmlElement(ElementName = "name")]
public string Name { get; set; }
[XmlElement(ElementName = "email")]
public string Email { get; set; }
[XmlElement(ElementName = "ageInYears")]
public int AgeInYears { get; set; }
[XmlElement(ElementName = "gender")]
public Gender Gender { get; set; }
[XmlElement(ElementName = "salary")]
public decimal Salary { get; set; }
}
public enum Gender
{
Men,
Woman,
Transgender
}
}
| cc0-1.0 | C# | |
d08dcd9c743b56b0546c4d1572e5ece7b298b513 | Add test for #781 (#1824) | graphql-dotnet/graphql-dotnet,joemcbride/graphql-dotnet,graphql-dotnet/graphql-dotnet,graphql-dotnet/graphql-dotnet,joemcbride/graphql-dotnet | src/GraphQL.Tests/Bugs/Bug781UnobservedTasks.cs | src/GraphQL.Tests/Bugs/Bug781UnobservedTasks.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using GraphQL.SystemTextJson;
using GraphQL.Types;
using Shouldly;
using Xunit;
namespace GraphQL.Tests.Bugs
{
public class Bug781UnobservedTasks
{
private bool _unobserved;
[Theory(Skip = "for demonstration purposes only, unreliable results")]
[InlineData("{ do(throwCanceled: false) cancellation never }", true)]
[InlineData("{ do(throwCanceled: true) cancellation never }", false)]
public async Task cancel_execution_with_different_error_types(string query, bool unobserved)
{
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
var cts = new CancellationTokenSource();
ISchema schema = new Bug781Schema(cts);
string result = null;
try
{
result = await schema.ExecuteAsync(options =>
{
options.Query = query;
options.CancellationToken = cts.Token;
options.ThrowOnUnhandledException = true; // required
});
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
GC.Collect(); // GC causes UnobservedTaskException event
await Task.Delay(1000); // Wait some time for GC to complete
TaskScheduler.UnobservedTaskException -= TaskScheduler_UnobservedTaskException;
_unobserved.ShouldBe(unobserved);
}
private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
_unobserved = true;
Console.WriteLine("Unobserved exception: " + e.Exception);
}
}
public class Bug781Schema : Schema
{
public Bug781Schema(CancellationTokenSource cts)
{
Query = new Bug781Query(cts);
}
}
public class Bug781Query : ObjectGraphType
{
public Bug781Query(CancellationTokenSource cts)
{
// First field with long calculation emulation
FieldAsync<StringGraphType>(
"do",
arguments: new QueryArguments(new QueryArgument<BooleanGraphType> { Name = "throwCanceled" }),
resolve: async ctx =>
{
await Task.Delay(10);
cts.Token.WaitHandle.WaitOne();
if (ctx.GetArgument<bool>("throwCanceled"))
throw new OperationCanceledException(); // in this case the task will go into Canceled state and there will be no unobserved exception event
else
throw new Exception("Hello!"); // the task goes into Faulted state so unobserved exception event will arise
});
// Second field causes cancellation of execution
Field<StringGraphType>(
"cancellation",
resolve: ctx =>
{
cts.Cancel();
return "cancelled";
});
// The third field is necessary for the control to fall on the context.CancellationToken.ThrowIfCancellationRequested() instruction.
Field<StringGraphType>(
"never",
resolve: ctx => throw new Exception("Never called"));
}
}
}
| mit | C# | |
719587bf35841ff26557ddcace994ee75ebab04a | Reorder list | Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews | LeetCode/reorder_list.cs | LeetCode/reorder_list.cs | using System;
using System.Collections.Generic;
using System.Linq;
class Node {
public int Data { get; set; }
public Node Next { get; set; }
public override String ToString() {
return String.Format("{0} {1}", Data, (Next == null) ? String.Empty : Next.ToString());
}
}
class Program {
static void Main() {
Node head = null;
Enumerable.Range(1, 20).Reverse().ToList().ForEach(x => {
head = new Node {
Data = x,
Next = head
};
} );
Node mid = null;
Node end = head;
while (end != null && end.Next != null) {
mid = (mid == null)? head : mid.Next;
end = end.Next.Next;
}
Node head2 = mid.Next;
mid.Next = null;
Node first = head;
Node second = head2;
while (first != null && second != null) {
Node firstNext = first.Next;
Node secondNext = second.Next;
first.Next = second;
second.Next = firstNext;
second = secondNext;
first = firstNext;
}
Console.WriteLine(head);
}
}
| mit | C# | |
562280ced02ed9c570a7b56a8a6e4cd9dbd95507 | Add cursor trail test scene | peppy/osu,EVAST9919/osu,peppy/osu,smoogipooo/osu,ppy/osu,2yangk23/osu,EVAST9919/osu,UselessToucan/osu,peppy/osu-new,ZLima12/osu,smoogipoo/osu,NeoAdonis/osu,2yangk23/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,johnneijzen/osu,NeoAdonis/osu,johnneijzen/osu,ZLima12/osu,ppy/osu | osu.Game.Rulesets.Osu.Tests/TestSceneCursorTrail.cs | osu.Game.Rulesets.Osu.Tests/TestSceneCursorTrail.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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Textures;
using osu.Framework.Testing.Input;
using osu.Game.Audio;
using osu.Game.Rulesets.Osu.Skinning;
using osu.Game.Rulesets.Osu.UI.Cursor;
using osu.Game.Skinning;
using osu.Game.Tests.Visual;
using osuTK;
namespace osu.Game.Rulesets.Osu.Tests
{
public class TestSceneCursorTrail : OsuTestScene
{
[Test]
public void TestSmoothCursorTrail()
{
createTest(() => new CursorTrail());
}
[Test]
public void TestLegacySmoothCursorTrail()
{
createTest(() => new LegacySkinContainer(false)
{
Child = new LegacyCursorTrail()
});
}
[Test]
public void TestLegacyDisjointCursorTrail()
{
createTest(() => new LegacySkinContainer(true)
{
Child = new LegacyCursorTrail()
});
}
private void createTest(Func<Drawable> createContent) => AddStep("create trail", () =>
{
Clear();
Add(new Container
{
RelativeSizeAxes = Axes.Both,
Size = new Vector2(0.8f),
Child = new MovingCursorInputManager { Child = createContent?.Invoke() }
});
});
[Cached(typeof(ISkinSource))]
private class LegacySkinContainer : Container, ISkinSource
{
private readonly bool disjoint;
public LegacySkinContainer(bool disjoint)
{
this.disjoint = disjoint;
RelativeSizeAxes = Axes.Both;
}
public Drawable GetDrawableComponent(ISkinComponent component) => throw new NotImplementedException();
public Texture GetTexture(string componentName)
{
switch (componentName)
{
case "cursortrail":
var tex = new Texture(Texture.WhitePixel.TextureGL);
if (disjoint)
tex.ScaleAdjust = 1 / 25f;
return tex;
case "cursormiddle":
return disjoint ? null : Texture.WhitePixel;
}
return null;
}
public SampleChannel GetSample(ISampleInfo sampleInfo) => throw new NotImplementedException();
public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) => throw new NotImplementedException();
public event Action SourceChanged;
}
private class MovingCursorInputManager : ManualInputManager
{
public MovingCursorInputManager()
{
UseParentInput = false;
}
protected override void Update()
{
base.Update();
const double spin_duration = 1000;
double currentTime = Time.Current;
double angle = (currentTime % spin_duration) / spin_duration * 2 * Math.PI;
Vector2 rPos = new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle));
MoveMouseTo(ToScreenSpace(DrawSize / 2 + DrawSize / 3 * rPos));
}
}
}
}
| mit | C# | |
71b10a82ca7ccbf864270ccb4cc81983d4cd5039 | Create HaiTun.cs | daobude/- | HaiTun.cs | HaiTun.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LeagueSharp;
using LeagueSharp.Common;
using SharpDX;
namespace LSharp海豚防封 {
class Program {
public static Menu Config;
static void Main(string[] args) {
Config = new Menu("海豚防封:防封状态启动中","LSHARPSET",true);
Config.AddItem(new MenuItem("海豚", "官网:Www.Haoll.Cn"));
Config.AddToMainMenu();
Game.OnUpdate += Game_OnUpdate;
}
private static void Game_OnUpdate(EventArgs args) {
Hacks.DisableDrawings = false;
}
}
}
| isc | C# | |
e51444a99d11291b35de48ad84501f8933777a76 | Add helper extension methods for route data - Added RouteData.GetCurrentPage<T>() - Added RouteData.GetNavigationContext() | brickpile/brickpile,brickpile/brickpile,brickpile/brickpile | BrickPile.Core/Extensions/RouteDataExtensions.cs | BrickPile.Core/Extensions/RouteDataExtensions.cs | using System.Web;
using System.Web.Routing;
using BrickPile.Core.Routing;
namespace BrickPile.Core.Extensions
{
public static class RouteDataExtensions
{
public static T GetCurrentPage<T>(this RouteData data)
{
return (T)data.Values[PageRoute.CurrentPageKey];
}
public static NavigationContext GetNavigationContext(this RouteData data) {
return new NavigationContext(HttpContext.Current.Request.RequestContext);
}
}
}
| mit | C# | |
9e6994166c0eef43cb63b6d1d34e70e0cb324634 | Add helper to track ongoing operations in UI | ppy/osu,ppy/osu,UselessToucan/osu,peppy/osu,peppy/osu-new,smoogipoo/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu,ppy/osu | osu.Game/Screens/OnlinePlay/OngoingOperationTracker.cs | osu.Game/Screens/OnlinePlay/OngoingOperationTracker.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.Bindables;
namespace osu.Game.Screens.OnlinePlay
{
/// <summary>
/// Utility class to track ongoing online operations' progress.
/// Can be used to disable interactivity while waiting for a response from online sources.
/// </summary>
public class OngoingOperationTracker
{
/// <summary>
/// Whether there is an online operation in progress.
/// </summary>
public IBindable<bool> InProgress => inProgress;
private readonly Bindable<bool> inProgress = new BindableBool();
private LeasedBindable<bool> leasedInProgress;
/// <summary>
/// Begins tracking a new online operation.
/// </summary>
/// <exception cref="InvalidOperationException">An operation has already been started.</exception>
public void BeginOperation()
{
if (leasedInProgress != null)
throw new InvalidOperationException("Cannot begin operation while another is in progress.");
leasedInProgress = inProgress.BeginLease(true);
leasedInProgress.Value = true;
}
/// <summary>
/// Ends tracking an online operation.
/// Does nothing if an operation has not been begun yet.
/// </summary>
public void EndOperation()
{
leasedInProgress?.Return();
leasedInProgress = null;
}
}
}
| mit | C# | |
0cdaeb445edc9e9b7ffa6b2fcff769729e68cdd8 | Create VariableLengthBitVector.cs | GGG-KILLER/GUtils.NET | GUtils.Numerics/VariableLengthBitVector.cs | GUtils.Numerics/VariableLengthBitVector.cs | /*
* Copyright © 2019 GGG KILLER <gggkiller2@gmail.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 System;
using System.Collections.Generic;
using System.Linq;
using BitContainer = System.Byte;
namespace GUtils.Numerics
{
public class VariableLengthBitVector : IEquatable<VariableLengthBitVector>
{
private const int elementBitCount = sizeof(BitContainer) * 8;
private BitContainer[] containers;
public int Length => this.containers.Length;
public int Bits => this.Length * elementBitCount;
public VariableLengthBitVector()
{
this.containers = new BitContainer[1];
}
public VariableLengthBitVector(int bits)
{
var size = Math.DivRem(bits, elementBitCount, out var rem);
if ( rem > 0 )
{
size++;
}
this.containers = new BitContainer[size];
}
public VariableLengthBitVector(VariableLengthBitVector bitVector)
{
this.containers = (BitContainer[])bitVector.containers.Clone();
}
private void EnsureBitContainer(int index)
{
if (index >= this.containers.Length)
{
Array.Resize(ref this.containers, index + 1);
}
}
public void Clear() =>
Array.Clear(this.containers, 0, this.containers.Length);
public bool this[int offset]
{
set
{
var index = Math.DivRem(offset, elementBitCount, out offset);
this.EnsureBitContainer(index);
var mask = 1U << offset;
if (value)
{
this.containers[index] |= (BitContainer)mask;
}
else
{
this.containers[index] &= (BitContainer)~mask;
}
}
get
{
var index = Math.DivRem(offset, elementBitCount, out offset);
var mask = 1U << offset;
return (this.containers[index] & mask) == mask;
}
}
#region IEquatable<VariableLengthBitVector>
public bool Equals(VariableLengthBitVector other) =>
other != null
&& this.containers.SequenceEqual(other.containers);
#endregion IEquatable<VariableLengthBitVector>
#region Object
public override string ToString() =>
string.Join("", this.containers.Select(n => Convert.ToString(n, 2).PadLeft(elementBitCount, '0')).Reverse());
public override bool Equals(object obj) =>
this.Equals(obj as VariableLengthBitVector);
public override int GetHashCode()
{
var hashCode = -1534987273;
for (var i = 0; i < this.containers.Length; i++)
{
hashCode = unchecked(hashCode * -1521134295 + this.containers[i].GetHashCode());
}
return hashCode;
}
#endregion Object
#region Operators
public static bool operator ==(VariableLengthBitVector left, VariableLengthBitVector right) =>
EqualityComparer<VariableLengthBitVector>.Default.Equals(left, right);
public static bool operator !=(VariableLengthBitVector left, VariableLengthBitVector right) =>
!(left == right);
#endregion Operators
}
}
| mit | C# | |
2d2f2808093acd63e2ae0b7c02701c4c8853c381 | test executor | BigBabay/AsyncConverter,BigBabay/AsyncConverter | AsyncConverter.Tests/Highlightings/AsyncWaitTests.cs | AsyncConverter.Tests/Highlightings/AsyncWaitTests.cs | namespace AsyncConverter.Tests.Highlightings
{
public class AsyncWaitTests : HighlightingsTestsBase
{
protected override string Folder => "AsyncWait";
}
} | mit | C# | |
2716c6eb176dee2685b68e42b1cf113e113a3b5b | Update to version 1.1.0 | fvilers/WebApi.Contrib | src/AssemblyVersion.cs | src/AssemblyVersion.cs | using System.Reflection;
// 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.1.0.*")]
[assembly: AssemblyInformationalVersion("1.1.0-alpha")] | using System.Reflection;
// 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.*")]
[assembly: AssemblyInformationalVersion("1.0.0-alpha")] | mit | C# |
57bb983312f323399ab74f4274e0fd6dfe19f209 | Create AudioFileFormatConverter.cs | J3QQ4/Facebook-Messenger-Voice-Message-Converter | AudioFileFormatConverter.cs | AudioFileFormatConverter.cs | using Imago.Bots;
using MediaToolkit;
using MediaToolkit.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Configuration;
namespace Imago.Media
{
/// <summary>
/// Converts audio files between various formats using the open-source FFMPEG software.
/// </summary>
public class AudioFileFormatConverter
{
#region Properties
/// <summary>
/// Path + filename to the source file.
/// </summary>
public string SourceFileNameAndPath { get; private set; }
/// <summary>
/// Path + filename to the file which is the result of the conversion.
/// </summary>
public string ConvertedFileNameAndPath { get; private set; }
/// <summary>
/// The folder where the converted files will be stored.
/// </summary>
public string TargetPath { get; private set; }
#endregion
#region Constructors
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="sourceFileNameAndPath">Filename and path to the source file.</param>
/// <param name="targetPath">The folder where the converted files will be stored.</param>
public AudioFileFormatConverter(string sourceFileNameAndPath, string targetPath)
{
if (string.IsNullOrWhiteSpace(sourceFileNameAndPath))
{
throw new Exception("Empty source filename.");
}
else if (string.IsNullOrWhiteSpace(targetPath))
{
throw new Exception("Empty target path.");
}
else
{
this.SourceFileNameAndPath = sourceFileNameAndPath;
this.TargetPath = targetPath;
//create folder if it's not there
if (!Directory.Exists(TargetPath))
{
Directory.CreateDirectory(TargetPath);
}
}
}
#endregion
#region Public methods
/// <summary>
/// Converts a source MP4 file to a target WAV file and returns the path and filename of the converted file.
/// </summary>
/// <returns>The path and filename of the converted file.</returns>
public string ConvertMP4ToWAV()
{
ConvertedFileNameAndPath = TargetPath + @"\" + Path.GetFileNameWithoutExtension(SourceFileNameAndPath) + ".wav"; //use the same file name as original, but different folder and extension
var inputFile = new MediaFile { Filename = SourceFileNameAndPath };
var outputFile = new MediaFile { Filename = ConvertedFileNameAndPath };
using (var engine = new Engine(GetFFMPEGBinaryPath()))
{
engine.Convert(inputFile, outputFile);
}
return ConvertedFileNameAndPath;
}
/// <summary>
/// Removes the converted file from disk to free up space.
/// Doesn't remove the source file.
/// </summary>
/// <returns>True if file deleted successfully, false if cannot delete, exception if filename is empty.</returns>
public bool RemoveTargetFileFromDisk()
{
if (string.IsNullOrWhiteSpace(ConvertedFileNameAndPath))
{
throw new Exception("The file has not been converted yet, so it cannot be deleted.");
}
try
{
File.Delete(ConvertedFileNameAndPath);
return true;
}
catch
{
return false;
}
}
#endregion
#region Private methods
/// <summary>
/// Reads the config to determine the location of ffmpeg.exe.
/// </summary>
/// <returns>The full path and filename to the ffmpeg.exe program.</returns>
public string GetFFMPEGBinaryPath()
{
return Utils.GetHomeFolder() + WebConfigurationManager.AppSettings["FFMPEGBinaryLocation"];
}
#endregion
}
}
| mit | C# | |
c904950878f2134990e8fa6864312d4353298caf | Create Grading.cs | SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming | Kattis-Solutions/Grading.cs | Kattis-Solutions/Grading.cs | using System;
using System.Collections.Generic;
namespace Grading
{
class Program
{
static void Main(string[] args)
{
string[] arr = Console.ReadLine().Split(' ');
int num = int.Parse(Console.ReadLine());
List<int> li = new List<int>();
for(int i = 0; i < arr.Length; i++) { li.Add(int.Parse(arr[i])); }
string[] grade = new string[]{ "A", "B", "C", "D", "E"};
int x = 0;
bool found = false;
string res = "";
while (!found && x < li.Count)
{
if (num >= li[x])
{
found = true;
res = grade[x];
}
x++;
}
if (!found)
{
res = "F";
}
Console.WriteLine(res);
}
}
}
| mit | C# | |
84758b770872e8f332ae0e5503206c5a941c89bb | Add texture store interface | ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework | osu.Framework/Graphics/Textures/ITextureStore.cs | osu.Framework/Graphics/Textures/ITextureStore.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.Threading;
using System.Threading.Tasks;
using osu.Framework.Graphics.OpenGL.Textures;
using osu.Framework.IO.Stores;
namespace osu.Framework.Graphics.Textures
{
public interface ITextureStore : IResourceStore<Texture>
{
/// <summary>
/// Retrieves a texture from the store.
/// </summary>
/// <param name="name">The name of the texture.</param>
/// <param name="wrapModeS">The texture wrap mode in horizontal direction.</param>
/// <param name="wrapModeT">The texture wrap mode in vertical direction.</param>
/// <returns>The texture.</returns>
Texture Get(string name, WrapMode wrapModeS, WrapMode wrapModeT);
/// <summary>
/// Retrieves a texture from the store asynchronously.
/// </summary>
/// <param name="name">The name of the texture.</param>
/// <param name="wrapModeS">The texture wrap mode in horizontal direction.</param>
/// <param name="wrapModeT">The texture wrap mode in vertical direction.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>The texture.</returns>
Task<Texture> GetAsync(string name, WrapMode wrapModeS, WrapMode wrapModeT, CancellationToken cancellationToken = default);
}
}
| mit | C# | |
b33ba3b0070a808eb4fbb8f9ea75eea32c024c9f | Create ProductSeller.cs | daniela1991/hack4europecontest | ProductSeller.cs | ProductSeller.cs | namespace Cdiscount.OpenApi.ProxyClient.Contract.Common
{
/// <summary>
/// Product seller informations
/// </summary>
public class ProductSeller
{
/// <summary>
/// Seller identifier
/// </summary>
public string Id { get; set; }
/// <summary>
/// Product name
/// </summary>
public string Name { get; set; }
}
}
| mit | C# | |
d4478c7cbb2cb0580b2dee8ac34058ee3642e145 | rename to correct casing | fluffynuts/PeanutButter,fluffynuts/PeanutButter,fluffynuts/PeanutButter | source/EmailSpooler/EmailSpooler.Win32Service.Entity.Tests/TestEmailContext.cs | source/EmailSpooler/EmailSpooler.Win32Service.Entity.Tests/TestEmailContext.cs | using EmailSpooler.Win32Service.DB.Tests;
using NUnit.Framework;
using PeanutButter.TestUtils.Entity;
using PeanutButter.TestUtils.Generic;
namespace EmailSpooler.Win32Service.Entity.Tests
{
[TestFixture]
public class TestEmailContext: EntityPersistenceTestFixtureBase<EmailContext>
{
public TestEmailContext()
{
Configure(false, connectionString => new DbMigrationsRunnerSqlServer(connectionString));
}
[Test]
public void Type_ShouldImplement_IEmailContext()
{
//---------------Set up test pack-------------------
var sut = typeof (EmailContext);
//---------------Assert Precondition----------------
//---------------Execute Test ----------------------
sut.ShouldImplement<IEmailContext>();
//---------------Test Result -----------------------
}
[Test]
public void StaticConstructor_ShouldSetInitializerToNull()
{
using (GetContext())
{
//---------------Set up test pack-------------------
//---------------Assert Precondition----------------
//---------------Execute Test ----------------------
using (var connection = _tempDb.CreateConnection())
{
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = "select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = '__MigrationHistory';";
using (var reader = cmd.ExecuteReader())
{
Assert.IsFalse(reader.Read());
}
}
}
//---------------Test Result -----------------------
}
}
}
}
| bsd-3-clause | C# | |
8bb84570df904c9c55cc781e18cc13bfb13e834e | Introduce beatmap availability structure | smoogipoo/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu-new,smoogipooo/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,ppy/osu,peppy/osu,ppy/osu,UselessToucan/osu,ppy/osu | osu.Game/Online/Rooms/BeatmapAvailability.cs | osu.Game/Online/Rooms/BeatmapAvailability.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;
namespace osu.Game.Online.Rooms
{
/// <summary>
/// The local availability information about a certain beatmap for the client.
/// </summary>
public readonly struct BeatmapAvailability : IEquatable<BeatmapAvailability>
{
/// <summary>
/// The beatmap's availability state.
/// </summary>
public readonly DownloadState State;
/// <summary>
/// The beatmap's downloading progress, null when not in <see cref="DownloadState.Downloading"/> state.
/// </summary>
public readonly double? DownloadProgress;
/// <summary>
/// Constructs a new non-<see cref="DownloadState.Downloading"/> beatmap availability state.
/// </summary>
/// <param name="state">The beatmap availability state.</param>
/// <exception cref="ArgumentException">Throws if <see cref="DownloadState.Downloading"/> was specified in this constructor, as it has its own constructor (see <see cref="BeatmapAvailability(DownloadState, double)"/>.</exception>
public BeatmapAvailability(DownloadState state)
{
if (state == DownloadState.Downloading)
throw new ArgumentException($"{nameof(DownloadState.Downloading)} state has its own constructor, use it instead.");
State = state;
DownloadProgress = null;
}
/// <summary>
/// Constructs a new <see cref="DownloadState.Downloading"/>-specific beatmap availability state.
/// </summary>
/// <param name="state">The beatmap availability state (always <see cref="DownloadState.Downloading"/>).</param>
/// <param name="downloadProgress">The beatmap's downloading current progress.</param>
/// <exception cref="ArgumentException">Throws if non-<see cref="DownloadState.Downloading"/> was specified in this constructor, as they have their own constructor (see <see cref="BeatmapAvailability(DownloadState)"/>.</exception>
public BeatmapAvailability(DownloadState state, double downloadProgress)
{
if (state != DownloadState.Downloading)
throw new ArgumentException($"This is a constructor specific for {DownloadState.Downloading} state, use the regular one instead.");
State = DownloadState.Downloading;
DownloadProgress = downloadProgress;
}
public bool Equals(BeatmapAvailability other) => State == other.State && DownloadProgress == other.DownloadProgress;
public override string ToString() => $"{string.Join(", ", State, $"{DownloadProgress:0.00%}")}";
}
}
| mit | C# | |
8988b21e5721d97ee08f2eca4d45ec86ec768782 | add missing source Utils/Files.cs | PavelMaca/WoT-PogsIconSet | Utils/Files.cs | Utils/Files.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WotPogsIconSet.Utils
{
public class Files
{
public static void deleteDirectoryRecusivly(String path)
{
Console.WriteLine("Are you sure to delete " + path + " ?");
Console.ReadLine();
System.IO.DirectoryInfo di = new DirectoryInfo(path);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
}
}
}
| bsd-3-clause | C# | |
128e2ff59854541a7ee5d0b4fb266cabefc5bbfb | Create DummieObjects.cs | MingLu8/Nancy.WebApi.HelpPages | src/Nancy.WebApi.HelpPages.Demo/DummieObjects.cs | src/Nancy.WebApi.HelpPages.Demo/DummieObjects.cs | using System.Collections.Generic;
namespace Nancy.WebApi.Demo
{
/// <summary>
/// User Detail.
/// </summary>
public class User
{
/// <summary>
/// user Id.
/// </summary>
public int Id { get; set; }
/// <summary>
/// User Name.
/// </summary>
public Name Name { get; set; }
/// <summary>
/// User Gender.
/// </summary>
public Gender Gender { get; set; }
/// <summary>
/// User phones .
/// </summary>
public List<Phone> Phones { get; set; }
/// <summary>
/// User addresses.
/// </summary>
public List<Address> Addresses { get; set; }
}
/// <summary>
/// Address Detail.
/// </summary>
public class Address
{
/// <summary>
/// Address Type.
/// </summary>
public AddressType AddressType { get; set; }
/// <summary>
/// Street.
/// </summary>
public string Street { get; set; }
/// <summary>
/// This is City property.
/// </summary>
public string City { get; set; }
/// <summary>
/// Yes, it is state.
/// </summary>
public string State { get; set; }
/// <summary>
/// and zip code.
/// </summary>
public string Zip { get; set; }
}
/// <summary>
/// Address Type, primary or vacation.
/// </summary>
public enum AddressType
{
/// <summary>
/// Primary home address
/// </summary>
Primary,
/// <summary>
/// home for vacation.
/// </summary>
Vacation
}
/// <summary>
/// Phones, cell, home, or work phone.
/// </summary>
public class Phone
{
/// <summary>
/// phone type
/// </summary>
public PhoneType PhoneType { get; set; }
/// <summary>
/// phone number.
/// </summary>
public string Number { get; set; }
}
public enum PhoneType
{
/// <summary>
/// cell phone
/// </summary>
Cell,
/// <summary>
/// home phone
/// </summary>
Home,
/// <summary>
/// work phone.
/// </summary>
Work
}
/// <summary>
/// Gender male or female
/// </summary>
public enum Gender
{
/// <summary>
/// male
/// </summary>
Male,
/// <summary>
/// female
/// </summary>
Female
}
/// <summary>
/// User Name.
/// </summary>
public class Name
{
/// <summary>
/// user first name.
/// </summary>
public string FirstName { get; set; }
/// <summary>
/// user middle name.
/// </summary>
public string MiddleName { get; set; }
/// <summary>
/// user last name.
/// </summary>
public string LastName { get; set; }
}
}
| mit | C# | |
68f7cf341eac6f5b6391ccaf29bb225f73e38b9f | Add report model | Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training | src/AtomicChessPuzzles/Models/Report.cs | src/AtomicChessPuzzles/Models/Report.cs | using MongoDB.Bson.Serialization.Attributes;
namespace AtomicChessPuzzles.Models
{
public class Report
{
[BsonElement("_id")]
public string ID { get; set; }
[BsonElement("type")]
public string Type { get; set; }
[BsonElement("reporter")]
public string Reporter { get; set; }
[BsonElement("reported")]
public string Reported { get; set; }
[BsonElement("reason")]
public string Reason { get; set; }
[BsonElement("reasonExplanation")]
public string ReasonExplanation { get; set; }
public Report(string id, string type, string reporter, string reported, string reason, string reasonExplanation)
{
ID = id;
Type = type;
Reporter = reporter;
Reported = reported;
Reason = reason;
ReasonExplanation = reasonExplanation;
}
}
}
| agpl-3.0 | C# | |
163b8eb9b1e7e89a8e8996ceda3dfb976a96c279 | Implement insertion Sort | cschen1205/cs-algorithms,cschen1205/cs-algorithms | Algorithms/Sorting/InsertionSort.cs | Algorithms/Sorting/InsertionSort.cs | using System;
using Algorithms.Utils;
namespace Algorithms.Sorting
{
public class InsertionSort
{
public static void Sort<T>(T[] a, int lo, int hi, Comparison<T> compare)
{
for (var i = lo + 1; i <= hi; ++i)
{
for (var j = i-1; j >= lo; --j)
{
if (SortUtil.IsLessThan(a[j], a[j + 1], compare))
{
SortUtil.Exchange(a, j, j + 1);
}
else
{
break;
}
}
}
}
public static void Sort<T>(T[] a) where T : IComparable<T>
{
Sort(a, 0, a.Length-1, (a1, a2) => a1.CompareTo(a2));
}
}
} | mit | C# | |
1ca33ddf284ed46e8eb81af9cd1c6f3b68413345 | convert Unit as struct #4 | ic-sys/UniRx,saruiwa/UniRx,neuecc/UniRx,cruwel/UniRx,ataihei/UniRx,Useurmind/UniRx,juggernate/UniRx,Useurmind/UniRx,ic-sys/UniRx,kimsama/UniRx,OC-Leon/UniRx,zillakot/UniRx,zillakot/UniRx,cruwel/UniRx,m-ishikawa/UniRx,zillakot/UniRx,zhutaorun/UniRx,TORISOUP/UniRx,ufcpp/UniRx,zhutaorun/UniRx,cruwel/UniRx,endo0407/UniRx,OrangeCube/UniRx,ppcuni/UniRx,zhutaorun/UniRx,InvertGames/UniRx,juggernate/UniRx,Useurmind/UniRx,juggernate/UniRx,ic-sys/UniRx | Assets/UniRx/Scripts/System/Unit.cs | Assets/UniRx/Scripts/System/Unit.cs | using System;
namespace UniRx
{
// from Rx Official, but convert struct to class(for iOS AOT issue)
[Serializable]
public class Unit : IEquatable<Unit>
{
static readonly Unit @default = new Unit();
public static Unit Default { get { return @default; } }
public static bool operator ==(Unit first, Unit second)
{
return true;
}
public static bool operator !=(Unit first, Unit second)
{
return false;
}
public bool Equals(Unit other)
{
return true;
}
public override bool Equals(object obj)
{
return obj is Unit;
}
public override int GetHashCode()
{
return 0;
}
public override string ToString()
{
return "()";
}
}
} | using System;
namespace UniRx
{
// from Rx Official
[Serializable]
public struct Unit : IEquatable<Unit>
{
static readonly Unit @default = new Unit();
public static Unit Default { get { return @default; } }
public static bool operator ==(Unit first, Unit second)
{
return true;
}
public static bool operator !=(Unit first, Unit second)
{
return false;
}
public bool Equals(Unit other)
{
return true;
}
public override bool Equals(object obj)
{
return obj is Unit;
}
public override int GetHashCode()
{
return 0;
}
public override string ToString()
{
return "()";
}
}
} | mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.