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
08247e1b1f4c281152eba9a9d690c2b64db76edc
Increase version to 2.4.3
Azure/amqpnetlite
src/Properties/Version.cs
src/Properties/Version.cs
// ------------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation // All rights reserved. // // 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR // CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR // NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------------------ using System.Reflection; // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("2.1.0")] [assembly: AssemblyFileVersion("2.4.4")] [assembly: AssemblyInformationalVersion("2.4.4")]
// ------------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation // All rights reserved. // // 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR // CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR // NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------------------ using System.Reflection; // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("2.1.0")] [assembly: AssemblyFileVersion("2.4.3")] [assembly: AssemblyInformationalVersion("2.4.3")]
apache-2.0
C#
6e379f0646cb531798fa24243dc3a5e273cfd72c
Fix FocusedTextBox in line with framework changes
EVAST9919/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,2yangk23/osu,johnneijzen/osu,smoogipooo/osu,Frontear/osuKyzer,johnneijzen/osu,naoey/osu,peppy/osu,DrabWeb/osu,UselessToucan/osu,smoogipoo/osu,ZLima12/osu,DrabWeb/osu,Nabile-Rahmani/osu,UselessToucan/osu,EVAST9919/osu,DrabWeb/osu,ppy/osu,peppy/osu,NeoAdonis/osu,naoey/osu,ppy/osu,2yangk23/osu,smoogipoo/osu,ppy/osu,ZLima12/osu,naoey/osu,peppy/osu-new,peppy/osu,NeoAdonis/osu
osu.Game/Graphics/UserInterface/FocusedTextBox.cs
osu.Game/Graphics/UserInterface/FocusedTextBox.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using OpenTK.Graphics; using OpenTK.Input; using osu.Framework.Input; using System; namespace osu.Game.Graphics.UserInterface { /// <summary> /// A textbox which holds focus eagerly. /// </summary> public class FocusedTextBox : OsuTextBox { protected override Color4 BackgroundUnfocused => new Color4(10, 10, 10, 255); protected override Color4 BackgroundFocused => new Color4(10, 10, 10, 255); public Action Exit; private bool focus; public bool HoldFocus { get { return focus; } set { focus = value; if (!focus && HasFocus) GetContainingInputManager().ChangeFocus(null); } } public override bool HandleKeyboardInput => HoldFocus || base.HandleKeyboardInput; protected override void OnFocus(InputState state) { base.OnFocus(state); BorderThickness = 0; } protected override bool OnKeyDown(InputState state, KeyDownEventArgs args) { if (!args.Repeat && args.Key == Key.Escape) { if (Text.Length > 0) Text = string.Empty; else Exit?.Invoke(); return true; } return base.OnKeyDown(state, args); } public override bool RequestsFocus => HoldFocus; } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using OpenTK.Graphics; using OpenTK.Input; using osu.Framework.Input; using System; namespace osu.Game.Graphics.UserInterface { /// <summary> /// A textbox which holds focus eagerly. /// </summary> public class FocusedTextBox : OsuTextBox { protected override Color4 BackgroundUnfocused => new Color4(10, 10, 10, 255); protected override Color4 BackgroundFocused => new Color4(10, 10, 10, 255); public Action Exit; private bool focus; public bool HoldFocus { get { return focus; } set { focus = value; if (!focus && HasFocus) GetContainingInputManager().ChangeFocus(null); } } protected override void OnFocus(InputState state) { base.OnFocus(state); BorderThickness = 0; } protected override bool OnKeyDown(InputState state, KeyDownEventArgs args) { if (!args.Repeat && args.Key == Key.Escape) { if (Text.Length > 0) Text = string.Empty; else Exit?.Invoke(); return true; } return base.OnKeyDown(state, args); } public override bool RequestsFocus => HoldFocus; } }
mit
C#
2f2b0b3107898fe9a9927a6c00100580166804f5
Add exceptions during parse failures
kelleyma49/fasdr
Fasdr.Backend/Provider.cs
Fasdr.Backend/Provider.cs
using System; using System.Collections.Generic; using System.IO.Abstractions; using System.IO; namespace Fasdr.Backend { public class Provider { public static readonly char Separator = '|'; public Provider(string name) { Name = name; } public void Load(StreamReader stream) { Entries.Clear (); CurrentId = 0; while (!stream.EndOfStream) { var line = stream.ReadLine(); var split = line.Split(new char[] {Separator}, StringSplitOptions.RemoveEmptyEntries); // should be three entries - path name, weight, and if it's a leaf? if (split==null || split.Length!=3) { throw new Exception("Failed to parse line '" + line + "'"); } var path = split[0]; double weight; if (!Double.TryParse(split[1], out weight)) { throw new Exception ("Failed to parse weight"); } bool isLeaf; if (!Boolean.TryParse(split[2], out isLeaf)) { throw new Exception ("Failed to parse isLeaf flag"); } Add (path, isLeaf, weight); } } public void Save(string filePath,IFileSystem fileSystem) { var fileName = System.IO.Path.Combine(Path.GetTempPath(),Path.GetRandomFileName()); using (var s = fileSystem.File.CreateText(fileName)) { foreach(var p in Entries) { string line = $"{p.Value.FullPath}{Separator}{p.Value.Weight}{Separator}{p.Value.IsLeaf}"; s.WriteLine(line); } } fileSystem.File.Move(fileName, filePath); } public void Add(string fullPath,bool isLeaf,double weight = 1.0) { Entries.Add(CurrentId,new Entry(fullPath,weight,isLeaf)); var pathSplit = fullPath.Split (new char[]{ '\\'}); string lastElement = pathSplit [pathSplit.Length - 1].ToLower(); IList<int> ids; if (!LastEntries.TryGetValue (lastElement, out ids)) { LastEntries.Add(lastElement,ids = new List<int> ()); } ids.Add (CurrentId); CurrentId = CurrentId + 1; } public string Name { get; } public Dictionary<int,Entry> Entries { get; } = new Dictionary<int,Entry>(); public Dictionary<string,IList<int>> LastEntries { get; } = new Dictionary<string,IList<int>>(); private int CurrentId { get; set; } } public struct Entry { public Entry(string fullPath,double weight,bool isLeaf) { FullPath = fullPath; Weight = weight; IsLeaf = isLeaf; } public string FullPath { get; } public double Weight { get; } public bool IsLeaf { get; } } }
using System; using System.Collections.Generic; using System.IO.Abstractions; using System.IO; namespace Fasdr.Backend { public class Provider { public static readonly char Separator = '|'; public Provider(string name) { Name = name; } public void Load(StreamReader stream) { Entries.Clear (); CurrentId = 0; while (!stream.EndOfStream) { var line = stream.ReadLine(); var split = line.Split(new char[] {Separator}, StringSplitOptions.RemoveEmptyEntries); // should be three entries - path name, weight, and if it's a leaf? if (split==null || split.Length!=3) { throw new Exception("Failed to parse line '" + line + "'"); } var path = split[0]; double weight; if (!Double.TryParse(split[1], out weight)) { } bool isLeaf; if (!Boolean.TryParse(split[2], out isLeaf)) { } Add (path, isLeaf, weight); } } public void Save(string filePath,IFileSystem fileSystem) { var fileName = System.IO.Path.Combine(Path.GetTempPath(),Path.GetRandomFileName()); using (var s = fileSystem.File.CreateText(fileName)) { foreach(var p in Entries) { string line = $"{p.Value.FullPath}{Separator}{p.Value.Weight}{Separator}{p.Value.IsLeaf}"; s.WriteLine(line); } } fileSystem.File.Move(fileName, filePath); } public void Add(string fullPath,bool isLeaf,double weight = 1.0) { Entries.Add(CurrentId,new Entry(fullPath,weight,isLeaf)); var pathSplit = fullPath.Split (new char[]{ '\\'}); string lastElement = pathSplit [pathSplit.Length - 1].ToLower(); IList<int> ids; if (!LastEntries.TryGetValue (lastElement, out ids)) { LastEntries.Add(lastElement,ids = new List<int> ()); } ids.Add (CurrentId); CurrentId = CurrentId + 1; } public string Name { get; } public Dictionary<int,Entry> Entries { get; } = new Dictionary<int,Entry>(); public Dictionary<string,IList<int>> LastEntries { get; } = new Dictionary<string,IList<int>>(); private int CurrentId { get; set; } } public struct Entry { public Entry(string fullPath,double weight,bool isLeaf) { FullPath = fullPath; Weight = weight; IsLeaf = isLeaf; } public string FullPath { get; } public double Weight { get; } public bool IsLeaf { get; } } }
mit
C#
76f764e650f2e69dd4a08e74fdd3fc001258db66
Update Function.cs
gurmitteotia/guflow
Guflow.Lambda/Function.cs
Guflow.Lambda/Function.cs
using Amazon.Lambda.Core; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace Guflow.Lambda { public class Function { /// <summary> /// A simple function that takes a string return predefined result. /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public string BookHotelLambda(string input, ILambdaContext context) { return "hotelbooked"; } } }
using Amazon.Lambda.Core; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace Guflow.Lambda { public class Function { /// <summary> /// A simple function that takes a string and does a ToUpper /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public string BookHotelLambda(string input, ILambdaContext context) { return "hotelbooked"; } } }
apache-2.0
C#
6598c55f03189f1c06dbe2c5239e138a0a5cef0b
change a "should" phrase
ArcticEcho/Hatman
Hatman/Commands/Should.cs
Hatman/Commands/Should.cs
using System.Text.RegularExpressions; using ChatExchangeDotNet; namespace Hatman.Commands { class Should : ICommand { private readonly Regex ptn = new Regex(@"(?i)^((?<!why|how|wh(e(n|re)|at)).)*\?", Extensions.RegOpts); private readonly string[] phrases = new[] { "No.", "Yes.", "Yup", "Nope", "Indubitably.", "Never. Ever. *EVER*.", "I'll tell ya, only if I get my coffee.", "Nah.", "Ask The Skeet.", "... do I look like I know everything?", "Ask me no questions, and I shall tell no lies.", "*I'm sorry, the person you have called is away. Please leave a message after the \"beep\"...*", "Yeah.", "Ofc.", "NOOOOOOOOOOOOOOOO", "Sure..." }; public Regex CommandPattern { get { return ptn; } } public string Description { get { return "Decides whether or not something should happen."; } } public string Usage { get { return "(sh|[wc])ould|will|did and many words alike"; } } public void ProcessMessage(Message msg, ref Room rm) { rm.PostReplyFast(msg, phrases.PickRandom()); } } }
using System.Text.RegularExpressions; using ChatExchangeDotNet; namespace Hatman.Commands { class Should : ICommand { private readonly Regex ptn = new Regex(@"(?i)^((?<!why|how|wh(e(n|re)|at)).)*\?", Extensions.RegOpts); private readonly string[] phrases = new[] { "No.", "Yes.", "Yup.", "Nope.", "Indubitably", "Never. Ever. *EVER*.", "I'll tell ya, only if I get my coffee.", "Nah.", "Ask The Skeet.", "... do I look like I know everything?", "Ask me no questions, and I shall tell no lies.", "Sure, when it rains imaginary internet points.", "Yeah.", "Ofc.", "NOOOOOOOOOOOOOOOO", "Sure..." }; public Regex CommandPattern { get { return ptn; } } public string Description { get { return "Decides whether or not something should happen."; } } public string Usage { get { return "(sh|[wc])ould|will|did and many words alike"; } } public void ProcessMessage(Message msg, ref Room rm) { rm.PostReplyFast(msg, phrases.PickRandom()); } } }
isc
C#
26cc5624ae1afd68a8af6e46c906d9b7c5e4c6fa
convert build build list to generic as well & testing vs2015 CTP5!
ronin1/Demo.LinkedList.Reverse
LinkedListDemo/Program.cs
LinkedListDemo/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LinkedListDemo { class Program { static Node<T> BuildList<T>(T[] values) { if (values == null || values.Length == 0) return null; var last = new Node<T> { Value = values[0] }; Node<T> head = last; for (int i=1; i<values.Length; i++) { var n = new Node<T> { Value = values[i] }; last.Next = n; last = n; } return head; } static Node<T> Reverse<T>(Node<T> head) { if (head == null) return null; Node<T> last = null; Node<T> cur = head; while(cur != null) { Node<T> next = cur.Next; cur.Next = last; last = cur; cur = next; } return last; } static void PrintList<T>(Node<T> head, string msg = null) { Console.WriteLine(); if(!string.IsNullOrEmpty(msg)) Console.Write(msg); Node<T> cur = head; while (cur != null) { if (cur.Value == null) Console.Write("<null>"); else Console.Write(cur.Value); if (cur.Next != null) Console.Write(" ~~> "); cur = cur.Next; } Console.WriteLine(); } static void Main(string[] args) { Node<string> list = BuildList(args); PrintList(list, "Original: "); Node<string> reveresed = Reverse(list); PrintList(reveresed, "Reversed: "); PrintList(list, "Original: "); #if DEBUG Console.ReadKey(); #endif } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LinkedListDemo { class Program { static Node<string> BuildList(string[] values) { if (values == null || values.Length == 0) return null; var last = new Node<string> { Value = values[0] }; Node<string> head = last; for (int i=1; i<values.Length; i++) { var n = new Node<string> { Value = values[i] }; last.Next = n; last = n; } return head; } static Node<T> Reverse<T>(Node<T> head) { if (head == null) return null; Node<T> last = null; Node<T> cur = head; while(cur != null) { Node<T> next = cur.Next; cur.Next = last; last = cur; cur = next; } return last; } static void PrintList<T>(Node<T> head, string msg = null) { Console.WriteLine(); if(!string.IsNullOrEmpty(msg)) Console.Write(msg); Node<T> cur = head; while (cur != null) { if (cur.Value == null) Console.Write("<null>"); else Console.Write(cur.Value); if (cur.Next != null) Console.Write(" ~~> "); cur = cur.Next; } Console.WriteLine(); } static void Main(string[] args) { Node<string> list = BuildList(args); PrintList(list, "Original: "); Node<string> reveresed = Reverse(list); PrintList(reveresed, "Reversed: "); PrintList(list, "Original: "); #if DEBUG Console.ReadKey(); #endif } } }
unlicense
C#
a155af14e2990661aeb1cd23923db053c0842c21
Use throw expression to test C#7
NFig/NFig
NFig/OverridesSnapshot.cs
NFig/OverridesSnapshot.cs
using System; using System.Collections.Generic; using JetBrains.Annotations; namespace NFig { /// <summary> /// Represents the state of all overrides, and the last event, for an application. /// </summary> public class OverridesSnapshot<TTier, TDataCenter> where TTier : struct where TDataCenter : struct { /// <summary> /// The application name. /// </summary> [NotNull] public string AppName { get; } /// <summary> /// The commit ID at the time the snapshot was taken. /// </summary> [NotNull] public string Commit { get; } /// <summary> /// A list of overrides which existed at the time the snapshot was taken. /// </summary> [CanBeNull] public IList<OverrideValue<TTier, TDataCenter>> Overrides { get; } /// <summary> /// Initializes a new snapshot object. /// </summary> /// <param name="appName">The application name.</param> /// <param name="commit">The commit ID at the time of the snapshot.</param> /// <param name="overrides">A list of the overrides which exist at the time of the snapshot.</param> public OverridesSnapshot([NotNull] string appName, [NotNull] string commit, IList<OverrideValue<TTier, TDataCenter>> overrides) { AppName = appName ?? throw new ArgumentNullException(nameof(appName)); Commit = commit ?? throw new ArgumentNullException(nameof(commit)); Overrides = overrides; } } }
using System; using System.Collections.Generic; using JetBrains.Annotations; namespace NFig { /// <summary> /// Represents the state of all overrides, and the last event, for an application. /// </summary> public class OverridesSnapshot<TTier, TDataCenter> where TTier : struct where TDataCenter : struct { /// <summary> /// The application name. /// </summary> [NotNull] public string AppName { get; } /// <summary> /// The commit ID at the time the snapshot was taken. /// </summary> [NotNull] public string Commit { get; } /// <summary> /// A list of overrides which existed at the time the snapshot was taken. /// </summary> [CanBeNull] public IList<OverrideValue<TTier, TDataCenter>> Overrides { get; } /// <summary> /// Initializes a new snapshot object. /// </summary> /// <param name="appName">The application name.</param> /// <param name="commit">The commit ID at the time of the snapshot.</param> /// <param name="overrides">A list of the overrides which exist at the time of the snapshot.</param> public OverridesSnapshot([NotNull] string appName, [NotNull] string commit, IList<OverrideValue<TTier, TDataCenter>> overrides) { if (appName == null) throw new ArgumentNullException(nameof(appName)); if (commit == null) throw new ArgumentNullException(nameof(commit)); AppName = appName; Commit = commit; Overrides = overrides; } } }
mit
C#
202b7f9b29146312742f58b0efe2151ca617bbf5
remove redundant ApplyTo property
NServiceKit/NServiceKit,ZocDoc/ServiceStack,MindTouch/NServiceKit,timba/NServiceKit,NServiceKit/NServiceKit,MindTouch/NServiceKit,nataren/NServiceKit,MindTouch/NServiceKit,ZocDoc/ServiceStack,timba/NServiceKit,meebey/ServiceStack,NServiceKit/NServiceKit,nataren/NServiceKit,NServiceKit/NServiceKit,ZocDoc/ServiceStack,nataren/NServiceKit,nataren/NServiceKit,timba/NServiceKit,MindTouch/NServiceKit,timba/NServiceKit,meebey/ServiceStack,ZocDoc/ServiceStack
src/ServiceStack.ServiceInterface/RequiredPermissionAttribute.cs
src/ServiceStack.ServiceInterface/RequiredPermissionAttribute.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using ServiceStack.Common; using ServiceStack.ServiceHost; namespace ServiceStack.ServiceInterface { /// <summary> /// Indicates that the request dto, which is associated with this attribute, /// can only execute, if the user has specific permissions. /// </summary> [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)] public class RequiredPermissionAttribute : RequestFilterAttribute { public List<string> RequiredPermissions { get; set; } public RequiredPermissionAttribute(params string[] permissions) { this.RequiredPermissions = permissions.ToList(); this.ApplyTo = ApplyTo.All; } public RequiredPermissionAttribute(ApplyTo applyTo, params string[] permissions) { this.RequiredPermissions = permissions.ToList(); this.ApplyTo = applyTo; } public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto) { var session = req.GetSession(); foreach (string requiredPermission in this.RequiredPermissions) { if (session == null || !session.HasPermission(requiredPermission)) { res.StatusCode = (int)HttpStatusCode.Unauthorized; res.StatusDescription = "Invalid Permissions"; res.Close(); return; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using ServiceStack.Common; using ServiceStack.ServiceHost; namespace ServiceStack.ServiceInterface { /// <summary> /// Indicates that the request dto, which is associated with this attribute, /// can only execute, if the user has specific permissions. /// </summary> [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)] public class RequiredPermissionAttribute : RequestFilterAttribute { public List<string> RequiredPermissions { get; set; } public ApplyTo ApplyTo { get; set; } public RequiredPermissionAttribute(params string[] permissions) { this.RequiredPermissions = permissions.ToList(); this.ApplyTo = ApplyTo.All; } public RequiredPermissionAttribute(ApplyTo applyTo, params string[] permissions) { this.RequiredPermissions = permissions.ToList(); this.ApplyTo = applyTo; } public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto) { var session = req.GetSession(); foreach (string requiredPermission in this.RequiredPermissions) { if (session == null || !session.HasPermission(requiredPermission)) { res.StatusCode = (int)HttpStatusCode.Unauthorized; res.StatusDescription = "Invalid Permissions"; res.Close(); return; } } } } }
bsd-3-clause
C#
f1815b42bfdee9ac0a3d0e9f6b39ad1a674a3b9a
Add title/aria-label non-semantic global alert
smbc-digital/iag-webapp,smbc-digital/iag-webapp,smbc-digital/iag-webapp
src/StockportWebapp/Views/stockportgov/Shared/GlobalAlert.cshtml
src/StockportWebapp/Views/stockportgov/Shared/GlobalAlert.cshtml
@using StockportWebapp.Models @using StockportWebapp.Utils @inject ICookiesHelper CookiesHelper @model Alert @{ var alertCookies = CookiesHelper.GetCookies<Alert>("alerts"); var isDismissed = alertCookies != null && alertCookies.Contains(Model.Slug) && !Model.IsStatic; } @if (!isDismissed) { <div class="global-alert-@Model.Severity.ToLowerInvariant()"> <div class="grid-container grid-100 global-alert-container"> <div class="grid-100 mobile-grid-100 tablet-grid-100 global-alert grid-parent"> <div class="hide-on-mobile hide-on-tablet global-alert-icon global-alert-icon-@Model.Severity.ToLowerInvariant()"> <i></i> </div> <div class="grid-80 mobile-grid-95 global-alert-text-container"> <div class="global-alert-text-@Model.Severity.ToLowerInvariant()"> <h3>@Model.Title</h3> @Html.Raw(Model.Body) </div> </div> @if (!Model.IsStatic) { <div class="global-alert-close-container"> <a href="javascript:void(0)" Title="Close @Model.Title alert" aria-label="Close @Model.Title alert"> <div class="global-alert-close-@Model.Severity.ToLowerInvariant()"> <i class="close-alert" data-slug="@Model.Slug" data-parent="global-alert-@Model.Severity.ToLowerInvariant()"></i> </div> </a> </div> } </div> </div> </div> }
@using StockportWebapp.Models @using StockportWebapp.Utils @inject ICookiesHelper CookiesHelper @model Alert @{ var alertCookies = CookiesHelper.GetCookies<Alert>("alerts"); var isDismissed = alertCookies != null && alertCookies.Contains(Model.Slug) && !Model.IsStatic; } @if (!isDismissed) { <div class="global-alert-@Model.Severity.ToLowerInvariant()"> <div class="grid-container grid-100 global-alert-container"> <div class="grid-100 mobile-grid-100 tablet-grid-100 global-alert grid-parent"> <div class="hide-on-mobile hide-on-tablet global-alert-icon global-alert-icon-@Model.Severity.ToLowerInvariant()"> <i></i> </div> <div class="grid-80 mobile-grid-95 global-alert-text-container"> <div class="global-alert-text-@Model.Severity.ToLowerInvariant()"> <h3>@Model.Title</h3> @Html.Raw(Model.Body) </div> </div> @if (!Model.IsStatic) { <div class="global-alert-close-container"> <a href="javascript:void(0)"> <div class="global-alert-close-@Model.Severity.ToLowerInvariant()"> <i class="close-alert" data-slug="@Model.Slug" data-parent="global-alert-@Model.Severity.ToLowerInvariant()" aria-hidden="true"></i> </div> </a> </div> } </div> </div> </div> }
mit
C#
d5053c392cb2e24ecca0017a84453074da92a4a7
Increase version
Tunous/EEPhysics,cap9/EEPhysics
EEPhysics/Properties/AssemblyInfo.cs
EEPhysics/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("EEPhysics")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EEPhysics")] [assembly: AssemblyCopyright("MIT License")] [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("80820906-c3b5-43f6-9eac-97906f07f2f4")] // 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.4.0.0")] [assembly: AssemblyFileVersion("1.4.0.0")]
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("EEPhysics")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EEPhysics")] [assembly: AssemblyCopyright("MIT License")] [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("80820906-c3b5-43f6-9eac-97906f07f2f4")] // 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.3.4.0")] [assembly: AssemblyFileVersion("1.3.4.0")]
mit
C#
07a3b6cdd74060e97f56f833423358ffed811c69
allow single writer and multiple readers
davidfowl/XmlSettings
XmlSettings/XmlUtility.cs
XmlSettings/XmlUtility.cs
namespace XmlSettings { using System.IO; using System.Xml.Linq; internal static class XmlUtility { internal static XDocument GetDocument(XName rootName, string path, bool createIfNotExists) { if (File.Exists(path)) { try { return GetDocument(path); } catch (FileNotFoundException) { if (createIfNotExists) { return CreateDocument(rootName, path); } } } if (createIfNotExists) { return CreateDocument(rootName, path); } return null; } private static XDocument CreateDocument(XName rootName, string path) { XDocument document = new XDocument(new XElement(rootName)); // Add it to the file system // Note: document.Save internally opens file for FileAccess.Write // but does allow other dirty read (FileShare.Read). it is the most // optimal where write is infrequent and dirty read is acceptable. document.Save(path); return document; } internal static XDocument GetDocument(string path) { // opens file for FileAccess.Read but does allow other read/write (FileShare.ReadWrite). // it is the most optimal where write is infrequent and dirty read is acceptable. using (var configStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { return XDocument.Load(configStream); } } } }
namespace XmlSettings { using System.IO; using System.Xml.Linq; internal static class XmlUtility { internal static XDocument GetDocument(XName rootName, string path, bool createIfNotExists) { if (File.Exists(path)) { try { return GetDocument(path); } catch (FileNotFoundException) { if (createIfNotExists) { return CreateDocument(rootName, path); } } } if (createIfNotExists) { return CreateDocument(rootName, path); } return null; } private static XDocument CreateDocument(XName rootName, string path) { XDocument document = new XDocument(new XElement(rootName)); // Add it to the file system document.Save(path); return document; } internal static XDocument GetDocument(string path) { using (Stream configStream = File.OpenRead(path)) { return XDocument.Load(configStream); } } } }
mit
C#
c0b39b16af34498c57e5306e847e9097abad89d7
add error logging to taskbarnotifer
Enigmatrix/Cobalt
Cobalt.TaskbarNotifier/App.xaml.cs
Cobalt.TaskbarNotifier/App.xaml.cs
using System.Windows.Threading; using Cobalt.Common.UI; using Serilog; namespace Cobalt.TaskbarNotifier { /// <inheritdoc /> /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App { } public class AppBoostrapper : Bootstrapper<IMainViewModel> { protected override void PrepareApplication() { Log.Logger = new LoggerConfiguration() .WriteTo.File("./tn-log.txt") .CreateLogger(); Log.Information("NEW SESSION"); } protected override void OnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { Log.Information($"Exception raised in TaskbarNotifier: {e}"); } } }
using Cobalt.Common.UI; namespace Cobalt.TaskbarNotifier { /// <inheritdoc /> /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App { } public class AppBoostrapper : Bootstrapper<IMainViewModel> { } }
mit
C#
e871c05fb0d5340cf40061e085466bc09b5bc388
Update Notification class
one-signal/OneSignal-Xamarin-SDK,one-signal/OneSignal-Xamarin-SDK
Com.OneSignal.Core/Notification.cs
Com.OneSignal.Core/Notification.cs
using System; using System.Collections.Generic; namespace Com.OneSignal.Core { public class Notification { public string title; public string body; public string sound; public string launchUrl; public string rawPayload; public List<ActionButton> actionButtons; public Dictionary<string, object> additionalData; public string notificationId; public List<Notification> groupedNotifications; public BackgroundImageLayout backgroundImageLayout; // android only public string groupKey; public string groupMessage; public string ledColor; public int priority; public string smallIcon; public string largeIcon; public string bigPicture; public string CollapseId; public string fromProjectNumber; public string smallIconAccentColor; public int lockScreenVisibility; public int androidNotificationId; //ios only public string badge; public string badgeIncrement; public string category; public string threadId; public string subtitle; public string templateId; public string templateName; public float relevanceScore; public bool mutableContent; public bool contentAvailable; public string interruptionLevel; } public class ActionButton { public string id; public string text; public string icon; public ActionButton(string id, string text, string icon) { this.id = id; this.text = text; this.icon = icon; } } public class BackgroundImageLayout { public string image; public string titleTextColor; public string bodyTextColor; public BackgroundImageLayout(string image, string titleTextColor, string bodyTextColor) { this.image = image; this.titleTextColor = titleTextColor; this.bodyTextColor = bodyTextColor; } } }
using System; using System.Collections.Generic; namespace Com.OneSignal.Core { public class Notification { public int androidNotificationId; public List<Notification> groupedNotifications; public string notificationId; public string templateName; public string templateId; public string title; public string body; public Dictionary<string, object> additionalData; public string smallIcon; public string largeIcon; public string bigPicture; public string smallIconAccentColor; public string launchUrl; public string sound; public string ledColor; public int lockScreenVisibility; public string groupKey; public string groupMessage; public List<ActionButton> actionButtons; public string fromProjectNumber; public BackgroundImageLayout backgroundImageLayout; public string CollapseId; public int priority; public string rawPayload; public float relevanceScore; } public class ActionButton { public string id; public string text; public string icon; public ActionButton(string id, string text, string icon) { this.id = id; this.text = text; this.icon = icon; } } public class BackgroundImageLayout { public string image; public string titleTextColor; public string bodyTextColor; public BackgroundImageLayout(string image, string titleTextColor, string bodyTextColor) { this.image = image; this.titleTextColor = titleTextColor; this.bodyTextColor = bodyTextColor; } } }
mit
C#
052a76047d8a6a8a3faea003b77ea538ca71fe54
Fix to reflect new layout settings
Geroshabu/MatchGenerator
Application/MatchGenerator/LayoutConfigureWindow.xaml.cs
Application/MatchGenerator/LayoutConfigureWindow.xaml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using MatchGenerator.Core; namespace MatchGenerator { /// <summary> /// LayoutConfigureWindow.xaml の相互作用ロジック /// </summary> public partial class LayoutConfigureWindow : Window { LayoutInformation CourtLayout; public LayoutConfigureWindow(LayoutInformation courtLayout) { InitializeComponent(); CourtLayout = courtLayout; } private void Window_Loaded(object sender, RoutedEventArgs e) { SettingImporter importer = new SettingImporter(); LayoutInformation court_layout = importer.Import("Setting.ini"); courtCountRowTextBox.Text = court_layout.Row.ToString(); courtCountColumnTextBox.Text = court_layout.Column.ToString(); MatchCountTextBox.Text = court_layout.CourtCount.ToString(); } private void okButton_Click(object sender, RoutedEventArgs e) { int parsed_value; CourtLayout.Row = int.TryParse(courtCountRowTextBox.Text, out parsed_value) ? parsed_value : CourtLayout.Row; CourtLayout.Column = int.TryParse(courtCountColumnTextBox.Text, out parsed_value) ? parsed_value : CourtLayout.Column; CourtLayout.CourtCount = int.TryParse(MatchCountTextBox.Text, out parsed_value) ? parsed_value : CourtLayout.CourtCount; this.Close(); } private void cancelButton_Click(object sender, RoutedEventArgs e) { this.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using MatchGenerator.Core; namespace MatchGenerator { /// <summary> /// LayoutConfigureWindow.xaml の相互作用ロジック /// </summary> public partial class LayoutConfigureWindow : Window { LayoutInformation CourtLayout; LayoutInformation NewCourtLayout; public LayoutConfigureWindow(LayoutInformation courtLayout) { InitializeComponent(); CourtLayout = courtLayout; NewCourtLayout = new LayoutInformation(); } private void Window_Loaded(object sender, RoutedEventArgs e) { SettingImporter importer = new SettingImporter(); NewCourtLayout = importer.Import("Setting.ini"); courtCountRowTextBox.Text = NewCourtLayout.Row.ToString(); courtCountColumnTextBox.Text = NewCourtLayout.Column.ToString(); MatchCountTextBox.Text = NewCourtLayout.CourtCount.ToString(); } private void okButton_Click(object sender, RoutedEventArgs e) { CourtLayout.Row = NewCourtLayout.Row; CourtLayout.Column = NewCourtLayout.Column; CourtLayout.CourtCount = NewCourtLayout.CourtCount; this.Close(); } private void cancelButton_Click(object sender, RoutedEventArgs e) { this.Close(); } } }
mit
C#
7fc2ccea13db9b29be6599a35a4de7e5462a3c5f
Update GlobalVar.cs
IDEAL-Lab/CIM,IDEAL-Lab/CIM,IDEAL-Lab/CIM,IDEAL-Lab/CIM
InfluenceMaximization/InfluenceMaximization/GlobalVar.cs
InfluenceMaximization/InfluenceMaximization/GlobalVar.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace InfluenceMaximization { public static class GlobalVar { public static double epsilon = 1e-6; public static int MC = 80000; public static int mH = 5000000; public static int batch_num = 100; // number of batches of iterations in Coordinate Descent Algorithm public static double Alpha = 1.0; public static double b = 0.05; // St = 1 and End = 5 mean we set B = 10,20,30,40,50 and run CIM algorithms respectively public static int St = 1; public static int End = 5; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace InfluenceMaximization { public static class GlobalVar { public static double epsilon = 1e-6; public static int MC = 80000; public static int mH = 5000000; public static int batch_num = 100; // number of batches of iterations in Coordinate Descent Algorithm public static double Alpha = 1.0; // St = 1 and End = 5 mean we set B = 10,20,30,40,50 and run CIM algorithms respectively public static int St = 1; public static int End = 5; } }
mit
C#
f6024ca8c0657cab4eeda90ef9225f66654fd6be
disable automatic migration data loss
dpesheva/QuizFactory,dpesheva/QuizFactory
QuizFactory/QuizFactory.Data/Migrations/Configuration.cs
QuizFactory/QuizFactory.Data/Migrations/Configuration.cs
namespace QuizFactory.Data.Migrations { using System; using System.Data.Entity.Migrations; using System.Linq; using QuizFactory.Data; internal sealed class Configuration : DbMigrationsConfiguration<QuizFactoryDbContext> { public Configuration() { this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationDataLossAllowed = false; } protected override void Seed(QuizFactoryDbContext context) { if (!context.Roles.Any()) { var seedUsers = new SeedUsers(); seedUsers.Generate(context); } var seedData = new SeedData(context); if (!context.QuizDefinitions.Any()) { foreach (var item in seedData.Quizzes) { context.QuizDefinitions.Add(item); } } if (!context.Categories.Any()) { foreach (var item in seedData.Categories) { context.Categories.Add(item); } } context.SaveChanges(); } } }
namespace QuizFactory.Data.Migrations { using System; using System.Data.Entity.Migrations; using System.Linq; using QuizFactory.Data; internal sealed class Configuration : DbMigrationsConfiguration<QuizFactoryDbContext> { public Configuration() { this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationDataLossAllowed = true; } protected override void Seed(QuizFactoryDbContext context) { if (!context.Roles.Any()) { var seedUsers = new SeedUsers(); seedUsers.Generate(context); } var seedData = new SeedData(context); if (!context.QuizDefinitions.Any()) { foreach (var item in seedData.Quizzes) { context.QuizDefinitions.Add(item); } } if (!context.Categories.Any()) { foreach (var item in seedData.Categories) { context.Categories.Add(item); } } context.SaveChanges(); } } }
mit
C#
14f6a615470f6733b544842d19ecf09b170d8ea0
Copy to memory stream if the input stream does not support seek.
yufeih/Nine.Storage,studio-nine/Nine.Storage
src/Portable/Storage/ContentAddressableStorage.cs
src/Portable/Storage/ContentAddressableStorage.cs
namespace Nine.Storage { using System; using System.IO; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; public class ContentAddressableStorage : IContentAddressableStorage { private readonly IBlobStorage blob; public IBlobStorage Blob => blob; public ContentAddressableStorage(IBlobStorage blob) { if ((this.blob = blob) == null) throw new ArgumentNullException(nameof(blob)); } public Task<bool> Exists(string key) => blob.Exists(VerifySha1(key)); public Task<string> GetUri(string key) => blob.GetUri(VerifySha1(key)); public Task<Stream> Get(string key, IProgress<ProgressInBytes> progress = null, CancellationToken cancellationToken = default(CancellationToken)) => blob.Get(VerifySha1(key), progress, cancellationToken); public Task<string> Put(Stream stream, IProgress<ProgressInBytes> progress = null, CancellationToken cancellationToken = default(CancellationToken)) => Put(null, stream, progress, cancellationToken); public Task<string> Put(string key, Stream stream, IProgress<ProgressInBytes> progress = null, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(key)) { if (!stream.CanSeek) { var ms = new MemoryStream(); stream.CopyTo(ms); ms.Seek(0, SeekOrigin.Begin); stream = ms; } key = Sha1.ComputeHashString(stream); stream.Seek(0, SeekOrigin.Begin); } return blob.Put(key, stream, progress, cancellationToken); } private string VerifySha1(string key) { if (key == null) return null; if (key.Length != 40) throw new ArgumentException("key"); foreach (var c in key) { if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z'))) throw new ArgumentException("key"); } return key; } } }
namespace Nine.Storage { using System; using System.IO; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; public class ContentAddressableStorage : IContentAddressableStorage { private readonly IBlobStorage blob; public IBlobStorage Blob => blob; public ContentAddressableStorage(IBlobStorage blob) { if ((this.blob = blob) == null) throw new ArgumentNullException(nameof(blob)); } public Task<bool> Exists(string key) => blob.Exists(VerifySha1(key)); public Task<string> GetUri(string key) => blob.GetUri(VerifySha1(key)); public Task<Stream> Get(string key, IProgress<ProgressInBytes> progress = null, CancellationToken cancellationToken = default(CancellationToken)) => blob.Get(VerifySha1(key), progress, cancellationToken); public Task<string> Put(Stream stream, IProgress<ProgressInBytes> progress = null, CancellationToken cancellationToken = default(CancellationToken)) => Put(null, stream, progress, cancellationToken); public Task<string> Put(string key, Stream stream, IProgress<ProgressInBytes> progress = null, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(key)) { key = Sha1.ComputeHashString(stream); stream.Seek(0, SeekOrigin.Begin); } return blob.Put(key, stream, progress, cancellationToken); } private string VerifySha1(string key) { if (key == null) return null; if (key.Length != 40) throw new ArgumentException("key"); foreach (var c in key) { if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z'))) throw new ArgumentException("key"); } return key; } } }
mit
C#
2981a5b030ba916a3bc6606093d70dbb254f758c
Fix token.
Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex
src/Squidex.Infrastructure/Security/Extensions.cs
src/Squidex.Infrastructure/Security/Extensions.cs
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using System.Linq; using System.Security.Claims; namespace Squidex.Infrastructure.Security { public static class Extensions { public static RefToken Token(this ClaimsPrincipal principal) { var subjectId = principal.OpenIdSubject(); if (!string.IsNullOrWhiteSpace(subjectId)) { return new RefToken(RefTokenType.Subject, subjectId); } var clientId = principal.OpenIdClientId(); if (!string.IsNullOrWhiteSpace(clientId)) { return new RefToken(RefTokenType.Client, clientId); } return null; } public static string OpenIdSubject(this ClaimsPrincipal principal) { return principal.Claims.FirstOrDefault(x => x.Type == OpenIdClaims.Subject)?.Value; } public static string OpenIdClientId(this ClaimsPrincipal principal) { return principal.Claims.FirstOrDefault(x => x.Type == OpenIdClaims.ClientId)?.Value; } public static string UserOrClientId(this ClaimsPrincipal principal) { return principal.OpenIdSubject() ?? principal.OpenIdClientId(); } public static string OpenIdPreferredUserName(this ClaimsPrincipal principal) { return principal.Claims.FirstOrDefault(x => x.Type == OpenIdClaims.PreferredUserName)?.Value; } public static string OpenIdName(this ClaimsPrincipal principal) { return principal.Claims.FirstOrDefault(x => x.Type == OpenIdClaims.Name)?.Value; } public static string OpenIdNickName(this ClaimsPrincipal principal) { return principal.Claims.FirstOrDefault(x => x.Type == OpenIdClaims.NickName)?.Value; } public static string OpenIdEmail(this ClaimsPrincipal principal) { return principal.Claims.FirstOrDefault(x => x.Type == OpenIdClaims.Email)?.Value; } public static bool IsInClient(this ClaimsPrincipal principal, string client) { return principal.Claims.Any(x => x.Type == OpenIdClaims.ClientId && string.Equals(x.Value, client, StringComparison.OrdinalIgnoreCase)); } } }
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using System.Linq; using System.Security.Claims; namespace Squidex.Infrastructure.Security { public static class Extensions { public static RefToken Token(this ClaimsPrincipal principal) { var subjectId = principal.OpenIdSubject(); if (!string.IsNullOrWhiteSpace(subjectId)) { return new RefToken(subjectId, RefTokenType.Subject); } var clientId = principal.OpenIdClientId(); if (!string.IsNullOrWhiteSpace(clientId)) { return new RefToken(clientId, RefTokenType.Client); } return null; } public static string OpenIdSubject(this ClaimsPrincipal principal) { return principal.Claims.FirstOrDefault(x => x.Type == OpenIdClaims.Subject)?.Value; } public static string OpenIdClientId(this ClaimsPrincipal principal) { return principal.Claims.FirstOrDefault(x => x.Type == OpenIdClaims.ClientId)?.Value; } public static string UserOrClientId(this ClaimsPrincipal principal) { return principal.OpenIdSubject() ?? principal.OpenIdClientId(); } public static string OpenIdPreferredUserName(this ClaimsPrincipal principal) { return principal.Claims.FirstOrDefault(x => x.Type == OpenIdClaims.PreferredUserName)?.Value; } public static string OpenIdName(this ClaimsPrincipal principal) { return principal.Claims.FirstOrDefault(x => x.Type == OpenIdClaims.Name)?.Value; } public static string OpenIdNickName(this ClaimsPrincipal principal) { return principal.Claims.FirstOrDefault(x => x.Type == OpenIdClaims.NickName)?.Value; } public static string OpenIdEmail(this ClaimsPrincipal principal) { return principal.Claims.FirstOrDefault(x => x.Type == OpenIdClaims.Email)?.Value; } public static bool IsInClient(this ClaimsPrincipal principal, string client) { return principal.Claims.Any(x => x.Type == OpenIdClaims.ClientId && string.Equals(x.Value, client, StringComparison.OrdinalIgnoreCase)); } } }
mit
C#
b8149c6c1db2e4f07e828919bc25007c623198f9
implement Repository.AddRange test
SorenZ/Alamut.DotNet
test/Alamut.Data.Sql.EF.Test/RepositoryTest.cs
test/Alamut.Data.Sql.EF.Test/RepositoryTest.cs
using Alamut.Data.Sql.EF.Repositories; using Alamut.Data.Sql.EF.Test.Database; using Alamut.Data.SSOT; using Alamut.Data.Structure; using Xunit; namespace Alamut.Data.Sql.EF.Test { public class RepositoryTest { private readonly AppDbContext _context; public RepositoryTest() { _context = DbHelper.GetInMemoryInstance(); } [Fact] public void Repository_Create_Test() { // arrange var repository = new Repository<Blog,int>(_context); var entity = new Blog { Url = "https://github.com/SorenZ/Alamut.DotNet", Rating = 5 }; var expected = ServiceResult<int>.Okay(1, Messages.ItemCreated); // act var actual = repository.Create(entity); // assert Assert.Equal(expected.Data, actual.Data); } [Fact] public void Repository_AddRange() { // arrange var repository = new Repository<Blog,int>(_context); var entities = new [] { new Blog { Url = "https://github.com/SorenZ/Alamut.DotNet", Rating = 5 }, new Blog { Url = "https://github.com/SorenZ/DataFramework", Rating = 4 } }; var expected = ServiceResult.Okay(Messages.ItemsCreated); // act var actual = repository.AddRange(entities,commit:true); // assert Assert.Equal(expected, actual); } } }
using Alamut.Data.Sql.EF.Repositories; using Alamut.Data.Sql.EF.Test.Database; using Alamut.Data.SSOT; using Alamut.Data.Structure; using Xunit; namespace Alamut.Data.Sql.EF.Test { public class RepositoryTest { private readonly AppDbContext _context; public RepositoryTest() { _context = DbHelper.GetInMemoryInstance(); } [Fact] public void Repository_Create_Test() { // arrange var repository = new Repository<Blog,int>(_context); var entity = new Blog { Url = "https://github.com/SorenZ/Alamut.DotNet", Rating = 5 }; var expected = ServiceResult<int>.Okay(1, Messages.ItemCreated); // act var actual = repository.Create(entity); // assert Assert.Equal(expected.Data, actual.Data); } } }
mit
C#
2f27b1677223bf3dec6dadbcbff3417e7811d06a
Use ? instead of Nullable
wench/Ao3-Tracker,wench/Ao3-Tracker,wench/Ao3-Tracker,wench/Ao3-Tracker
Ao3tracksync/Models/Work.cs
Ao3tracksync/Models/Work.cs
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Ao3tracksync.Models { using System; using System.Collections.Generic; public partial class Work { public long userid { get; set; } public long id { get; set; } public long chapterid { get; set; } public long number { get; set; } public long timestamp { get; set; } public long? location { get; set; } public virtual User User { get; set; } } }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Ao3tracksync.Models { using System; using System.Collections.Generic; public partial class Work { public long userid { get; set; } public long id { get; set; } public long chapterid { get; set; } public long number { get; set; } public long timestamp { get; set; } public Nullable<long> location { get; set; } public virtual User User { get; set; } } }
apache-2.0
C#
34db734d026fc018eccf2cfd51f0fe914082f66d
Update OAuthTokenResponse.cs
pdcdeveloper/QpGoogleApi
OAuth/Models/OAuthTokenResponse.cs
OAuth/Models/OAuthTokenResponse.cs
/* Date : Monday, June 13, 2016 Author : pdcdeveloper (https://github.com/pdcdeveloper) Objective : Version : 1.0 */ using Newtonsoft.Json; /// /// <summary> /// Model for the token response from Google after a successful authorization request. /// </summary> /// namespace QPGoogleAPI.OAuth.Models { public class OAuthTokenResponse { [JsonProperty("access_token")] public string AccessToken { get; set; } [JsonProperty("token_type")] public string TokenType { get; set; } [JsonProperty("expires_in")] public int ExpiresIn { get; set; } [JsonProperty("refresh_token")] public string RefreshToken { get; set; } } }
/* Date : Monday, June 13, 2016 Author : QualiP (https://github.com/QualiP) Objective : Version : 1.0 */ using Newtonsoft.Json; /// /// <summary> /// Model for the token response from Google after a successful authorization request. /// </summary> /// namespace QPGoogleAPI.OAuth.Models { public class OAuthTokenResponse { [JsonProperty("access_token")] public string AccessToken { get; set; } [JsonProperty("token_type")] public string TokenType { get; set; } [JsonProperty("expires_in")] public int ExpiresIn { get; set; } [JsonProperty("refresh_token")] public string RefreshToken { get; set; } } }
mit
C#
e6fd46051dcbd46a65aad33662ae98e28f7c8f2f
Update user model
Branimir123/PhotoLife,Branimir123/PhotoLife,Branimir123/PhotoLife
PhotoLife/PhotoLife.Models/User.cs
PhotoLife/PhotoLife.Models/User.cs
using System.ComponentModel.DataAnnotations; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; namespace PhotoLife.Models { public class User : IdentityUser { public User() : base(string.Empty) { } public User(string username, string email, string name, string description, string profilePicUrl) { this.UserName = username; this.Email = email; this.UserName = name; this.Description = description; this.ProfilePicUrl = profilePicUrl; } public string Name { get; set; } public string Description { get; set; } public string ProfilePicUrl { get; set; } public Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager) { return manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); } } }
using System.ComponentModel.DataAnnotations; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; namespace PhotoLife.Models { public class User : IdentityUser { public User() : base(string.Empty) { } public User(string username, string email, string name, string description) { this.UserName = username; this.Email = email; this.UserName = name; this.Description = description; } public string Name { get; set; } public string Description { get; set; } public Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager) { return manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); } } }
mit
C#
6567f3a21c1c25636d119d8a01ef8a64aca7ebfc
Update AssemblyInfo
BluestoneEU/TypeGap,BluestoneEU/TypeGap,BluestoneEU/TypeGap,BluestoneEU/TypeGap
TypeGap/Properties/AssemblyInfo.cs
TypeGap/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("TypeGap")] [assembly: AssemblyDescription("A library to bridge the gap between C# (specifically asp.net) and typescript.")] [assembly: AssemblyCompany("Bluestone")] [assembly: AssemblyProduct("TypeGap")] [assembly: AssemblyCopyright("Copyright © BLUESTONE ADMINISTRATIVE SERVICES (UK) LIMITED 2017")] [assembly: ComVisible(false)] [assembly: Guid("a4f61c27-545f-4050-bce1-9d6ddcef7819")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
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("TypeBridge")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TypeBridge")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("a4f61c27-545f-4050-bce1-9d6ddcef7819")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
d317852745548e35295177a8db708b20fee3ce64
Fix canvas rendering issue
residuum/xwt,lytico/xwt,TheBrainTech/xwt,akrisiun/xwt,cra0zy/xwt,sevoku/xwt,antmicro/xwt,hwthomas/xwt,directhex/xwt,steffenWi/xwt,mminns/xwt,mono/xwt,iainx/xwt,hamekoz/xwt,mminns/xwt
Xwt.WPF/Xwt.WPFBackend/ExCanvas.cs
Xwt.WPF/Xwt.WPFBackend/ExCanvas.cs
// // ExCanvas.cs // // Author: // Eric Maupin <ermau@xamarin.com> // // Copyright (c) 2012 Xamarin, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Windows.Media; using WpfCanvas = System.Windows.Controls.Canvas; namespace Xwt.WPFBackend { internal class ExCanvas : WpfCanvas, IWpfWidget { public Action<System.Windows.Media.DrawingContext> RenderAction; protected override void OnRender (System.Windows.Media.DrawingContext dc) { base.OnRender (dc); var render = RenderAction; if (render != null) render (dc); } public WidgetBackend Backend { get; set; } protected override System.Windows.Size MeasureOverride (System.Windows.Size constraint) { var s = base.MeasureOverride (constraint); return Backend.MeasureOverride (constraint, s); } } }
// // ExCanvas.cs // // Author: // Eric Maupin <ermau@xamarin.com> // // Copyright (c) 2012 Xamarin, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Windows.Media; using WpfCanvas = System.Windows.Controls.Canvas; namespace Xwt.WPFBackend { internal class ExCanvas : WpfCanvas, IWpfWidget { public Action<System.Windows.Media.DrawingContext> RenderAction; protected override void OnRender (System.Windows.Media.DrawingContext dc) { var render = RenderAction; if (render != null) render (dc); base.OnRender (dc); } public WidgetBackend Backend { get; set; } protected override System.Windows.Size MeasureOverride (System.Windows.Size constraint) { var s = base.MeasureOverride (constraint); return Backend.MeasureOverride (constraint, s); } } }
mit
C#
876fe10a8572b80a6d956fbb4f6547535f723083
Update version to 1.0.3
gpailler/MegaApiClient,wojciech-urbanowski/MegaApiClient,PNSolutions/MegaApiClient
MegaApiClient/Properties/AssemblyInfo.cs
MegaApiClient/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("MegaApiClient")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Grégoire Pailler")] [assembly: AssemblyProduct("MegaApiClient")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("d4d9205c-f753-4694-8823-dac8a65729be")] // 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.3.0")] [assembly: AssemblyFileVersion("1.0.3.0")] [assembly: InternalsVisibleTo("MegaApiClient.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100592e623bfeb798f72e8e912283641da7e5b000a57c6d1ebaee470c3ec0fb4ebc6a4f643d02f41395e670276ec744e8d93667047d0cd04c5ad5c8015b53ceb4798ec1f8f0277d722e652a5a1aff7c2b502512c681988cffcd3cdbfdd56694fa5a518688a24cccdf52be4e47b271e4830162fbfbd3a85ed418f19c77c0fa1d498a")]
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("MegaApiClient")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Grégoire Pailler")] [assembly: AssemblyProduct("MegaApiClient")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("d4d9205c-f753-4694-8823-dac8a65729be")] // 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.2.0")] [assembly: AssemblyFileVersion("1.0.2.0")] [assembly: InternalsVisibleTo("MegaApiClient.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100592e623bfeb798f72e8e912283641da7e5b000a57c6d1ebaee470c3ec0fb4ebc6a4f643d02f41395e670276ec744e8d93667047d0cd04c5ad5c8015b53ceb4798ec1f8f0277d722e652a5a1aff7c2b502512c681988cffcd3cdbfdd56694fa5a518688a24cccdf52be4e47b271e4830162fbfbd3a85ed418f19c77c0fa1d498a")]
mit
C#
115f5963a962104b4c3b9246cbaa08e504510434
Fix issue with default image active behaviour
HelloKitty/317refactor
src/Rs317.Client.OpenTK/Rendering/OpenTKImageProducer.cs
src/Rs317.Client.OpenTK/Rendering/OpenTKImageProducer.cs
using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.CompilerServices; namespace Rs317.Sharp { public sealed class OpenTKImageProducer : BaseRsImageProducer<OpenTKRsGraphicsContext>, IOpenTKImageRenderable { private Bitmap image { get; } private FasterPixel FasterPixel { get; } public bool isDirty { get; private set; } = false; public IntPtr ImageDataPointer { get; } public Rectangle ImageLocation { get; private set; } public object SyncObject { get; } = new object(); private bool accessedPixelBuffer { get; set; } = false; public OpenTKImageProducer(int width, int height) : base(width, height) { image = new Bitmap(width, height); BitmapData data = image.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, image.PixelFormat); ImageDataPointer = data.Scan0; image.UnlockBits(data); FasterPixel = new FasterPixel(image); initDrawingArea(); ImageLocation = new Rectangle(0, 0, width, height); } public void ConsumeDirty() { lock (SyncObject) isDirty = false; } public override int[] pixels { get { lock (SyncObject) accessedPixelBuffer = true; return base.pixels; } } protected override void OnBeforeInternalDrawGraphics(int x, int z) { method239(); } protected override void InternalDrawGraphics(int x, int y, IRSGraphicsProvider<OpenTKRsGraphicsContext> rsGraphicsProvider) { ImageLocation = new Rectangle(x, y, width, height); //It's only dirty if they accessed the pixel buffer. //TODO: We can optimize around this in the client itself. lock (SyncObject) { if(accessedPixelBuffer) isDirty = true; accessedPixelBuffer = false; } } private void method239() { FasterPixel.Lock(); for(int y = 0; y < height; y++) { for(int x = 0; x < width; x++) { int value = pixels[x + y * width]; //fastPixel.SetPixel(x, y, Color.FromArgb((value >> 16) & 0xFF, (value >> 8) & 0xFF, value & 0xFF)); FasterPixel.SetPixel(x, y, (byte)(value >> 16), (byte)(value >> 8), (byte)value, 255); } } FasterPixel.Unlock(true); } } }
using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.CompilerServices; namespace Rs317.Sharp { public sealed class OpenTKImageProducer : BaseRsImageProducer<OpenTKRsGraphicsContext>, IOpenTKImageRenderable { private Bitmap image { get; } private FasterPixel FasterPixel { get; } public bool isDirty { get; private set; } = true; //Always initially dirty. public IntPtr ImageDataPointer { get; } public Rectangle ImageLocation { get; private set; } public object SyncObject { get; } = new object(); private bool accessedPixelBuffer { get; set; } = false; public OpenTKImageProducer(int width, int height) : base(width, height) { image = new Bitmap(width, height); BitmapData data = image.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, image.PixelFormat); ImageDataPointer = data.Scan0; image.UnlockBits(data); FasterPixel = new FasterPixel(image); initDrawingArea(); ImageLocation = new Rectangle(0, 0, width, height); } public void ConsumeDirty() { lock (SyncObject) isDirty = false; } public override int[] pixels { get { lock (SyncObject) accessedPixelBuffer = true; return base.pixels; } } protected override void OnBeforeInternalDrawGraphics(int x, int z) { method239(); } protected override void InternalDrawGraphics(int x, int y, IRSGraphicsProvider<OpenTKRsGraphicsContext> rsGraphicsProvider) { ImageLocation = new Rectangle(x, y, width, height); //It's only dirty if they accessed the pixel buffer. //TODO: We can optimize around this in the client itself. lock (SyncObject) { if(accessedPixelBuffer) isDirty = true; accessedPixelBuffer = false; } } private void method239() { FasterPixel.Lock(); for(int y = 0; y < height; y++) { for(int x = 0; x < width; x++) { int value = pixels[x + y * width]; //fastPixel.SetPixel(x, y, Color.FromArgb((value >> 16) & 0xFF, (value >> 8) & 0xFF, value & 0xFF)); FasterPixel.SetPixel(x, y, (byte)(value >> 16), (byte)(value >> 8), (byte)value, 255); } } FasterPixel.Unlock(true); } } }
mit
C#
fb98a70a89f9bb475bbce94ea8195f45feca95f3
Remove unused lines
pardeike/Harmony
Harmony/Tools/PatchTools.cs
Harmony/Tools/PatchTools.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Harmony { public static class PatchTools { // this holds all the objects we want to keep alive so they don't get garbage-collected static Dictionary<object, object> objectReferences = new Dictionary<object, object>(); public static void RememberObject(object key, object value) { objectReferences[key] = value; } public static MethodInfo GetPatchMethod<T>(Type patchType, string name, Type[] parameters = null) { var method = patchType.GetMethods(AccessTools.all) .FirstOrDefault(m => m.GetCustomAttributes(typeof(T), true).Count() > 0); if (method == null) method = AccessTools.Method(patchType, name, parameters); return method; } public static void GetPatches(Type patchType, out MethodInfo prefix, out MethodInfo postfix, out MethodInfo transpiler) { prefix = GetPatchMethod<HarmonyPrefix>(patchType, "Prefix"); postfix = GetPatchMethod<HarmonyPostfix>(patchType, "Postfix"); transpiler = GetPatchMethod<HarmonyTranspiler>(patchType, "Transpiler"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Harmony { public static class PatchTools { // this holds all the objects we want to keep alive so they don't get garbage-collected static Dictionary<object, object> objectReferences = new Dictionary<object, object>(); public static void RememberObject(object key, object value) { objectReferences[key] = value; } public static MethodInfo GetPatchMethod<T>(Type patchType, string name, Type[] parameters = null) { var method = patchType.GetMethods(AccessTools.all) .FirstOrDefault(m => m.GetCustomAttributes(typeof(T), true).Count() > 0); if (method == null) method = AccessTools.Method(patchType, name, parameters); return method; } public static void GetPatches(Type patchType, MethodBase original, out MethodInfo prefix, out MethodInfo postfix, out MethodInfo transpiler) { var type = original.DeclaringType; var methodName = original.Name; prefix = GetPatchMethod<HarmonyPrefix>(patchType, "Prefix"); postfix = GetPatchMethod<HarmonyPostfix>(patchType, "Postfix"); transpiler = GetPatchMethod<HarmonyTranspiler>(patchType, "Transpiler"); } } }
mit
C#
485090b40409bde68c3fe8f26ca94d843916a0ac
Implement Bootstrap's collapsible navbar
ShamsulAmry/Malaysia-GST-Checker
Amry.Gst.Web/Views/Shared/_Master.cshtml
Amry.Gst.Web/Views/Shared/_Master.cshtml
@functions { string BootstrapCssActive(PageTag current) { return current == ViewBag.PageTag ? "active" : null; } } <!DOCTYPE html> <html lang="en" ng-app="@ViewBag.AngularAppName"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>@ViewBag.Title</title> <!-- Bootstrap --> <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" /> <link href="~/Contents/app.min.css" rel="stylesheet" /> @RenderSection("Head", false) </head> <body ng-controller="@ViewBag.AngularControllerName" cg-busy="@ViewBag.AngularBusyPromise"> <nav class="navbar navbar-inverse"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="/" class="navbar-brand">Malaysia GST Checker</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li class="@BootstrapCssActive(PageTag.Home)"><a href="/">Home</a></li> <li class="@BootstrapCssActive(PageTag.About)"><a href="/about">About</a></li> </ul> </div> </div> </nav> <div class="container"> @RenderBody() </div> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> @RenderSection("BodyEnd", false) </body> </html>
@functions { string BootstrapCssActive(PageTag current) { return current == ViewBag.PageTag ? "active" : null; } } <!DOCTYPE html> <html lang="en" ng-app="@ViewBag.AngularAppName"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>@ViewBag.Title</title> <!-- Bootstrap --> <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" /> <link href="~/Contents/app.min.css" rel="stylesheet" /> @RenderSection("Head", false) </head> <body ng-controller="@ViewBag.AngularControllerName" cg-busy="@ViewBag.AngularBusyPromise"> <nav class="navbar navbar-inverse"> <div class="container"> <div class="navbar-header"> <a href="/" class="navbar-brand">Malaysia GST Checker</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li class="@BootstrapCssActive(PageTag.Home)"><a href="/">Home</a></li> <li class="@BootstrapCssActive(PageTag.About)"><a href="/about">About</a></li> </ul> </div> </div> </nav> <div class="container"> @RenderBody() </div> @RenderSection("BodyEnd", false) </body> </html>
mit
C#
abaa9f66cc9e2df27d447f1f475ced2cdffda2fa
Check crew transfer status
DMagic1/KSP_Vessel_Manager
Source/NoteUIObjects/Notes_CrewButton.cs
Source/NoteUIObjects/Notes_CrewButton.cs
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.UI; using BetterNotes.NoteClasses; namespace BetterNotes.NoteUIObjects { public class Notes_CrewButton : Notes_UIObjectBase { private Notes_CrewObject crewObject; private bool highlight; private void Start() { highlight = Notes_MainMenu.Settings.HighLightPart; } protected override bool assignObject(object obj) { if (obj == null || obj.GetType() != typeof(Notes_CrewObject)) { return false; } crewObject = (Notes_CrewObject)obj; return true; } protected override void OnLeftClick() { if (crewObject == null) return; if (crewObject.TransferActive) return; crewObject.RootPart.SetHighlight(false, false); crewObject.transferCrew(); } protected override void OnRightClick() { //Part Right-Click menu } protected override void OnMouseIn() { if (crewObject == null) return; if (crewObject.TransferActive) return; if (highlight) crewObject.RootPart.SetHighlight(true, false); } protected override void OnMouseOut() { if (crewObject == null) return; if (crewObject.TransferActive) return; if (highlight) crewObject.RootPart.SetHighlight(false, false); } protected override void ToolTip() { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.UI; using BetterNotes.NoteClasses; namespace BetterNotes.NoteUIObjects { public class Notes_CrewButton : Notes_UIObjectBase { private Notes_CrewObject crewObject; private bool highlight; private void Start() { highlight = Notes_MainMenu.Settings.HighLightPart; } protected override bool assignObject(object obj) { if (obj == null || obj.GetType() != typeof(Notes_CrewObject)) { return false; } crewObject = (Notes_CrewObject)obj; return true; } protected override void OnLeftClick() { if (crewObject == null) return; crewObject.RootPart.SetHighlight(false, false); crewObject.transferCrew(); } protected override void OnRightClick() { //Part Right-Click menu } protected override void OnMouseIn() { if (crewObject == null) return; if (crewObject.TransferActive) return; if (highlight) crewObject.RootPart.SetHighlight(true, false); } protected override void OnMouseOut() { if (crewObject == null) return; if (crewObject.TransferActive) return; if (highlight) crewObject.RootPart.SetHighlight(false, false); } protected override void ToolTip() { throw new NotImplementedException(); } } }
mit
C#
ce4a5a84246250bee58fb428588c1f30ede188f4
Fix PresentParameters to appear only in Win8 build
VirusFree/SharpDX,dazerdude/SharpDX,TigerKO/SharpDX,TigerKO/SharpDX,sharpdx/SharpDX,PavelBrokhman/SharpDX,PavelBrokhman/SharpDX,fmarrabal/SharpDX,RobyDX/SharpDX,TechPriest/SharpDX,weltkante/SharpDX,Ixonos-USA/SharpDX,VirusFree/SharpDX,RobyDX/SharpDX,sharpdx/SharpDX,fmarrabal/SharpDX,TigerKO/SharpDX,PavelBrokhman/SharpDX,manu-silicon/SharpDX,andrewst/SharpDX,waltdestler/SharpDX,VirusFree/SharpDX,shoelzer/SharpDX,mrvux/SharpDX,andrewst/SharpDX,fmarrabal/SharpDX,wyrover/SharpDX,andrewst/SharpDX,weltkante/SharpDX,davidlee80/SharpDX-1,Ixonos-USA/SharpDX,TechPriest/SharpDX,weltkante/SharpDX,fmarrabal/SharpDX,mrvux/SharpDX,wyrover/SharpDX,sharpdx/SharpDX,mrvux/SharpDX,PavelBrokhman/SharpDX,dazerdude/SharpDX,manu-silicon/SharpDX,waltdestler/SharpDX,VirusFree/SharpDX,waltdestler/SharpDX,dazerdude/SharpDX,dazerdude/SharpDX,Ixonos-USA/SharpDX,RobyDX/SharpDX,waltdestler/SharpDX,davidlee80/SharpDX-1,jwollen/SharpDX,TechPriest/SharpDX,TechPriest/SharpDX,shoelzer/SharpDX,shoelzer/SharpDX,wyrover/SharpDX,jwollen/SharpDX,manu-silicon/SharpDX,RobyDX/SharpDX,jwollen/SharpDX,wyrover/SharpDX,weltkante/SharpDX,TigerKO/SharpDX,manu-silicon/SharpDX,shoelzer/SharpDX,jwollen/SharpDX,Ixonos-USA/SharpDX,davidlee80/SharpDX-1,davidlee80/SharpDX-1,shoelzer/SharpDX
Source/SharpDX.DXGI/PresentParameters.cs
Source/SharpDX.DXGI/PresentParameters.cs
// Copyright (c) 2010-2011 SharpDX - Alexandre Mutel // // 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. #if WIN8 using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace SharpDX.DXGI { public partial struct PresentParameters { /// <summary> /// <para>A list of updated rectangles that you update in the back buffer for the presented frame. An application must update every single pixel in each rectangle that it reports to the runtime; the application cannot assume that the pixels are saved from the previous frame. For more information about updating dirty rectangles, see Remarks. You can set this member to <c>null</c> if DirtyRectsCount is 0. An application must not update any pixel outside of the dirty rectangles.</para> /// </summary> /// <unmanaged>RECT* pDirtyRects</unmanaged> public SharpDX.Rectangle[] DirtyRectangles; /// <summary> /// <para> A reference to the scrolled rectangle. The scrolled rectangle is the rectangle of the previous frame from which the runtime bit-block transfers (bitblts) content. The runtime also uses the scrolled rectangle to optimize presentation in terminal server and indirect display scenarios.</para> /// <para>The scrolled rectangle also describes the destination rectangle, that is, the region on the current frame that is filled with scrolled content. You can set this member to <c>null</c> to indicate that no content is scrolled from the previous frame.</para> /// </summary> /// <unmanaged>RECT* pScrollRect</unmanaged> public SharpDX.Rectangle? ScrollRectangle; /// <summary> /// <para>A reference to the offset of the scrolled area that goes from the source rectangle (of previous frame) to the destination rectangle (of current frame). You can set this member to <c>null</c> to indicate no offset.</para> /// </summary> /// <unmanaged>POINT* pScrollOffset</unmanaged> public SharpDX.DrawingPoint? ScrollOffset; // Internal native struct used for marshalling [StructLayout(LayoutKind.Sequential, Pack = 0)] internal partial struct __Native { public int DirtyRectsCount; public System.IntPtr PDirtyRects; public System.IntPtr PScrollRect; public System.IntPtr PScrollOffset; } } } #endif
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace SharpDX.DXGI { public partial struct PresentParameters { /// <summary> /// <para>A list of updated rectangles that you update in the back buffer for the presented frame. An application must update every single pixel in each rectangle that it reports to the runtime; the application cannot assume that the pixels are saved from the previous frame. For more information about updating dirty rectangles, see Remarks. You can set this member to <c>null</c> if DirtyRectsCount is 0. An application must not update any pixel outside of the dirty rectangles.</para> /// </summary> /// <unmanaged>RECT* pDirtyRects</unmanaged> public SharpDX.Rectangle[] DirtyRectangles; /// <summary> /// <para> A reference to the scrolled rectangle. The scrolled rectangle is the rectangle of the previous frame from which the runtime bit-block transfers (bitblts) content. The runtime also uses the scrolled rectangle to optimize presentation in terminal server and indirect display scenarios.</para> /// <para>The scrolled rectangle also describes the destination rectangle, that is, the region on the current frame that is filled with scrolled content. You can set this member to <c>null</c> to indicate that no content is scrolled from the previous frame.</para> /// </summary> /// <unmanaged>RECT* pScrollRect</unmanaged> public SharpDX.Rectangle? ScrollRectangle; /// <summary> /// <para>A reference to the offset of the scrolled area that goes from the source rectangle (of previous frame) to the destination rectangle (of current frame). You can set this member to <c>null</c> to indicate no offset.</para> /// </summary> /// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='DXGI_PRESENT_PARAMETERS::pScrollOffset']/*"/> /// <unmanaged>POINT* pScrollOffset</unmanaged> public SharpDX.DrawingPoint? ScrollOffset; // Internal native struct used for marshalling [StructLayout(LayoutKind.Sequential, Pack = 0)] internal partial struct __Native { public int DirtyRectsCount; public System.IntPtr PDirtyRects; public System.IntPtr PScrollRect; public System.IntPtr PScrollOffset; } } }
mit
C#
71e7533caf9c5f9edcb4ddcd193a3288c380c551
Use string interpolation
bcemmett/SurveyMonkeyApi-v3
SurveyMonkey/SurveyMonkeyApi.Webhooks.cs
SurveyMonkey/SurveyMonkeyApi.Webhooks.cs
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json.Linq; using SurveyMonkey.Containers; using SurveyMonkey.RequestSettings; namespace SurveyMonkey { public partial class SurveyMonkeyApi { public List<Webhook> GetWebhookList() { var settings = new PagingSettings(); return GetWebhookListPager(settings); } public List<Webhook> GetWebhookList(PagingSettings settings) { return GetWebhookListPager(settings); } private List<Webhook> GetWebhookListPager(PagingSettings settings) { string endPoint = "/webhooks"; const int maxResultsPerPage = 100; var results = Page(settings, endPoint, typeof(List<Webhook>), maxResultsPerPage); return results.ToList().ConvertAll(o => (Webhook)o); } public Webhook GetWebhookDetails(long webhookId) { string endPoint = $"/webhooks/{webhookId}"; var verb = Verb.GET; JToken result = MakeApiRequest(endPoint, verb, new RequestData()); var webhook = result.ToObject<Webhook>(); return webhook; } public Webhook CreateWebhook(Webhook webhook) { if (webhook.Id.HasValue) { throw new ArgumentException("An id can't be supplied when creating a webhook."); } string endPoint = "/webhooks"; var verb = Verb.POST; var requestData = Helpers.RequestSettingsHelper.GetPopulatedProperties(webhook); JToken result = MakeApiRequest(endPoint, verb, requestData); var createdWebhook = result.ToObject<Webhook>(); return createdWebhook; } } }
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json.Linq; using SurveyMonkey.Containers; using SurveyMonkey.RequestSettings; namespace SurveyMonkey { public partial class SurveyMonkeyApi { public List<Webhook> GetWebhookList() { var settings = new PagingSettings(); return GetWebhookListPager(settings); } public List<Webhook> GetWebhookList(PagingSettings settings) { return GetWebhookListPager(settings); } private List<Webhook> GetWebhookListPager(PagingSettings settings) { string endPoint = "/webhooks"; const int maxResultsPerPage = 100; var results = Page(settings, endPoint, typeof(List<Webhook>), maxResultsPerPage); return results.ToList().ConvertAll(o => (Webhook)o); } public Webhook GetWebhookDetails(long webhookId) { string endPoint = String.Format("/webhooks/{0}", webhookId); var verb = Verb.GET; JToken result = MakeApiRequest(endPoint, verb, new RequestData()); var webhook = result.ToObject<Webhook>(); return webhook; } public Webhook CreateWebhook(Webhook webhook) { if (webhook.Id.HasValue) { throw new ArgumentException("An id can't be supplied when creating a webhook."); } string endPoint = "/webhooks"; var verb = Verb.POST; var requestData = Helpers.RequestSettingsHelper.GetPopulatedProperties(webhook); JToken result = MakeApiRequest(endPoint, verb, requestData); var createdWebhook = result.ToObject<Webhook>(); return createdWebhook; } } }
mit
C#
2fcf7cae8a06236532f4c176740e0bdf44d70ddc
remove unecessary interface on blueprintIngredient
msarilar/EDEngineer,Psieonic/EDEngineer,Psieonic/EDEngineer,msarilar/EDEngineer
EDEngineer/Models/BlueprintIngredient.cs
EDEngineer/Models/BlueprintIngredient.cs
namespace EDEngineer.Models { public class BlueprintIngredient { public Entry Entry { get; } public BlueprintIngredient(Entry entry, int size) { Entry = entry; Size = size; } public int Size { get; } public override string ToString() { return $"{Entry.Kind} : {Entry.Name} ({Entry.Count} / {Size})"; } } }
using System.ComponentModel; using System.Runtime.CompilerServices; namespace EDEngineer.Models { public class BlueprintIngredient : INotifyPropertyChanged { public Entry Entry { get; } public BlueprintIngredient(Entry entry, int size) { Entry = entry; Size = size; } public int Size { get; } public event PropertyChangedEventHandler PropertyChanged; public override string ToString() { return $"{Entry.Kind} : {Entry.Name} ({Entry.Count} / {Size})"; } protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
mit
C#
fd02b3181e0fcb4a758964c10192c81d2bd877d4
Update comment.
CountrySideEngineer/Ev3Controller
dev/src/Ev3Controller/ViewModel/Ev3SafeStateViewModel.cs
dev/src/Ev3Controller/ViewModel/Ev3SafeStateViewModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ev3Controller.ViewModel { public class Ev3SafeStateViewModel : DeviceViewModelBase { #region Public Properties /// <summary> /// State that shows safe state. /// </summary> protected string _SafetyState; public string SafetyState { get { return _SafetyState; } set { this._SafetyState = value; this.RaisePropertyChanged("SafetyState"); } } #endregion #region Other methods and private properties in calling order /// <summary> /// Reset device data of safe state /// </summary> public override void ResetDevice() { base.ResetDevice(); this.SafetyState = ""; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ev3Controller.ViewModel { public class Ev3SafeStateViewModel : DeviceViewModelBase { #region Public Properties /// <summary> /// State that shows safe state. /// </summary> protected string _SafetyState; public string SafetyState { get { return _SafetyState; } set { this._SafetyState = value; this.RaisePropertyChanged("SafetyState"); } } #endregion #region Other methods and private properties in calling order public override void ResetDevice() { base.ResetDevice(); this.SafetyState = ""; } #endregion } }
mit
C#
0467760bd6611587680211da7b56e375b5aa29bc
fix hardcoded blog path
Wyamio/Wyam,Wyamio/Wyam,Wyamio/Wyam
themes/Docs/Samson/Shared/_BlogPostDetails.cshtml
themes/Docs/Samson/Shared/_BlogPostDetails.cshtml
@model IDocument <dl class="dl-horizontal"> <dt><i class="fa fa-calendar"></i> Published</dt> <dd>@(Model.Get<DateTime>(DocsKeys.Published).ToLongDateString(Context))</dd> @if(Model.ContainsKey(DocsKeys.Category)) { string link = Model.String(DocsKeys.Category).Replace(" ", "-").Replace("'", string.Empty); <dt><i class="fa fa-bookmark"></i> Category</dt> <dd><a href="@Context.GetLink($"/{@Context.String(DocsKeys.BlogPath)}/{link}")">@(Model.String(DocsKeys.Category))</a></dd> } @if(Model.ContainsKey(DocsKeys.Author)) { string link = Model.String(DocsKeys.Author).Replace(" ", "-").Replace("'", string.Empty); <dt><i class="fa fa-user"></i> Author</dt> <dd><a href="@Context.GetLink($"/{@Context.String(DocsKeys.BlogPath)}/author/{link}")">@(Model.String(DocsKeys.Author))</a></dd> } </dl>
@model IDocument <dl class="dl-horizontal"> <dt><i class="fa fa-calendar"></i> Published</dt> <dd>@(Model.Get<DateTime>(DocsKeys.Published).ToLongDateString(Context))</dd> @if(Model.ContainsKey(DocsKeys.Category)) { string link = Model.String(DocsKeys.Category).Replace(" ", "-").Replace("'", string.Empty); <dt><i class="fa fa-bookmark"></i> Category</dt> <dd><a href="@Context.GetLink("/blog/" + link)">@(Model.String(DocsKeys.Category))</a></dd> } @if(Model.ContainsKey(DocsKeys.Author)) { string link = Model.String(DocsKeys.Author).Replace(" ", "-").Replace("'", string.Empty); <dt><i class="fa fa-user"></i> Author</dt> <dd><a href="@Context.GetLink("/blog/author/" + link)">@(Model.String(DocsKeys.Author))</a></dd> } </dl>
mit
C#
23e243a1647339dfa5dc1cf0e04347da9f471d7d
Revert "Increase the maximum time we wait for long running tests from 5 to 10."
eric-davis/JustSaying,Intelliflo/JustSaying,Intelliflo/JustSaying
JustSaying.TestingFramework/Patiently.cs
JustSaying.TestingFramework/Patiently.cs
using System; using System.Threading; using NUnit.Framework; namespace JustSaying.TestingFramework { public static class Patiently { public static void VerifyExpectation(Action expression) { VerifyExpectation(expression, 5.Seconds()); } public static void VerifyExpectation(Action expression, TimeSpan timeout) { bool hasTimedOut; var started = DateTime.Now; do { try { expression.Invoke(); return; } catch { } hasTimedOut = timeout < DateTime.Now - started; Thread.Sleep(TimeSpan.FromMilliseconds(50)); Console.WriteLine("Waiting for {0} ms - Still Checking.", (DateTime.Now - started).TotalMilliseconds); } while (!hasTimedOut); expression.Invoke(); } public static void AssertThat(Func<bool> func) { AssertThat(func, 5.Seconds()); } public static void AssertThat(Func<bool> func, TimeSpan timeout) { bool result; bool hasTimedOut; var started = DateTime.Now; do { result = func.Invoke(); hasTimedOut = timeout < DateTime.Now - started; Thread.Sleep(TimeSpan.FromMilliseconds(50)); Console.WriteLine("Waiting for {0} ms - Still Checking.", (DateTime.Now - started).TotalMilliseconds); } while (!result && !hasTimedOut); Assert.True(result); } } public static class Extensions { public static TimeSpan Seconds(this int seconds) { return TimeSpan.FromSeconds(seconds); } } }
using System; using System.Threading; using NUnit.Framework; namespace JustSaying.TestingFramework { public static class Patiently { public static void VerifyExpectation(Action expression) { VerifyExpectation(expression, 5.Seconds()); } public static void VerifyExpectation(Action expression, TimeSpan timeout) { bool hasTimedOut; var started = DateTime.Now; do { try { expression.Invoke(); return; } catch { } hasTimedOut = timeout < DateTime.Now - started; Thread.Sleep(TimeSpan.FromMilliseconds(50)); Console.WriteLine("Waiting for {0} ms - Still Checking.", (DateTime.Now - started).TotalMilliseconds); } while (!hasTimedOut); expression.Invoke(); } public static void AssertThat(Func<bool> func) { AssertThat(func, 10.Seconds()); } public static void AssertThat(Func<bool> func, TimeSpan timeout) { bool result; bool hasTimedOut; var started = DateTime.Now; do { result = func.Invoke(); hasTimedOut = timeout < DateTime.Now - started; Thread.Sleep(TimeSpan.FromMilliseconds(50)); Console.WriteLine("Waiting for {0} ms - Still Checking.", (DateTime.Now - started).TotalMilliseconds); } while (!result && !hasTimedOut); Assert.True(result); } } public static class Extensions { public static TimeSpan Seconds(this int seconds) { return TimeSpan.FromSeconds(seconds); } } }
apache-2.0
C#
4e7f28f365132c5db52e6ff32bf73c4cf34f6459
Add parentheses within the conditional AND and OR expressions to declare the operator precedence
mike-rowley/XamarinMediaManager,martijn00/XamarinMediaManager,mike-rowley/XamarinMediaManager,martijn00/XamarinMediaManager
MediaManager/Media/MediaExtractorBase.cs
MediaManager/Media/MediaExtractorBase.cs
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; namespace MediaManager.Media { public abstract class MediaExtractorBase : IMediaExtractor { public virtual async Task<IMediaItem> CreateMediaItem(string url) { var mediaItem = new MediaItem(url); mediaItem.MediaLocation = GetMediaLocation(mediaItem); return await ExtractMetadata(mediaItem); } public virtual async Task<IMediaItem> CreateMediaItem(FileInfo file) { var mediaItem = new MediaItem(file.FullName); mediaItem.MediaLocation = GetMediaLocation(mediaItem); return await ExtractMetadata(mediaItem); } public virtual async Task<IMediaItem> CreateMediaItem(IMediaItem mediaItem) { mediaItem.MediaLocation = GetMediaLocation(mediaItem); return await ExtractMetadata(mediaItem); } public virtual Task<object> RetrieveMediaItemArt(IMediaItem mediaItem) { return null; } public abstract Task<IMediaItem> ExtractMetadata(IMediaItem mediaItem); public virtual MediaLocation GetMediaLocation(IMediaItem mediaItem) { if (mediaItem.MediaUri.StartsWith("http")) return MediaLocation.Remote; if (mediaItem.MediaUri.StartsWith("file") || mediaItem.MediaUri.StartsWith("/") || (mediaItem.MediaUri.Length > 1 && mediaItem.MediaUri[1] == ':')) return MediaLocation.FileSystem; return MediaLocation.Unknown; } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; namespace MediaManager.Media { public abstract class MediaExtractorBase : IMediaExtractor { public virtual async Task<IMediaItem> CreateMediaItem(string url) { var mediaItem = new MediaItem(url); mediaItem.MediaLocation = GetMediaLocation(mediaItem); return await ExtractMetadata(mediaItem); } public virtual async Task<IMediaItem> CreateMediaItem(FileInfo file) { var mediaItem = new MediaItem(file.FullName); mediaItem.MediaLocation = GetMediaLocation(mediaItem); return await ExtractMetadata(mediaItem); } public virtual async Task<IMediaItem> CreateMediaItem(IMediaItem mediaItem) { mediaItem.MediaLocation = GetMediaLocation(mediaItem); return await ExtractMetadata(mediaItem); } public virtual Task<object> RetrieveMediaItemArt(IMediaItem mediaItem) { return null; } public abstract Task<IMediaItem> ExtractMetadata(IMediaItem mediaItem); public virtual MediaLocation GetMediaLocation(IMediaItem mediaItem) { if (mediaItem.MediaUri.StartsWith("http")) return MediaLocation.Remote; if (mediaItem.MediaUri.StartsWith("file") || mediaItem.MediaUri.StartsWith("/") || mediaItem.MediaUri.Length > 1 && mediaItem.MediaUri[1] == ':') return MediaLocation.FileSystem; return MediaLocation.Unknown; } } }
mit
C#
1d0fc419496d16307bda5a2ef40c93db0fdc8d16
insert object sent from page
pako1337/Content_Man,pako1337/Content_Man
Content_Man.Web/api/ContentElementApiModule.cs
Content_Man.Web/api/ContentElementApiModule.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using ContentDomain; using ContentDomain.Dto; using ContentDomain.Repositories; using Nancy; using Nancy.ModelBinding; namespace Content_Man.Web.api { public class ContentElementApiModule : Nancy.NancyModule { public ContentElementApiModule() : base("api/ContentElement") { Get["/"] = _ => { var list = new ContentElementRepository().All().AsDto(); var serializer = new Nancy.Json.JavaScriptSerializer(); var ceString = serializer.Serialize(list); var bytes = System.Text.Encoding.UTF8.GetBytes(ceString); return new Response() { ContentType = "application/json", Contents = s => s.Write(bytes, 0, bytes.Length) }; }; Get["/{elementId}"] = arg => { var jsonModel = new ContentElementRepository().Get((int)arg.elementId).AsDto(); var serializer = new Nancy.Json.JavaScriptSerializer(); var ceString = serializer.Serialize(jsonModel); var bytes = System.Text.Encoding.UTF8.GetBytes(ceString); return new Response() { ContentType = "application/json", Contents = s => s.Write(bytes, 0, bytes.Length) }; }; Post["/"] = _ => { var repo = new ContentElementRepository(); var contentElement = this.Bind<ContentElementDto>(); repo.Insert(new ContentDomain.Factories.ContentElementFactory().Create(contentElement)); return HttpStatusCode.OK; }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using ContentDomain; using ContentDomain.Dto; using ContentDomain.Repositories; using Nancy; using Nancy.ModelBinding; namespace Content_Man.Web.api { public class ContentElementApiModule : Nancy.NancyModule { public ContentElementApiModule() : base("api/ContentElement") { Get["/"] = _ => { var list = new ContentElementRepository().All().AsDto(); var serializer = new Nancy.Json.JavaScriptSerializer(); var ceString = serializer.Serialize(list); var bytes = System.Text.Encoding.UTF8.GetBytes(ceString); return new Response() { ContentType = "application/json", Contents = s => s.Write(bytes, 0, bytes.Length) }; }; Get["/{elementId}"] = arg => { var jsonModel = new ContentElementRepository().Get((int)arg.elementId).AsDto(); var serializer = new Nancy.Json.JavaScriptSerializer(); var ceString = serializer.Serialize(jsonModel); var bytes = System.Text.Encoding.UTF8.GetBytes(ceString); return new Response() { ContentType = "application/json", Contents = s => s.Write(bytes, 0, bytes.Length) }; }; Post["/"] = _ => { var repo = new ContentElementRepository(); var contentElement = this.Bind<ContentElementDto>(); //repo.Insert(ce); return HttpStatusCode.OK; }; } } }
mit
C#
b2f4a05c8665eb79e037a0a78a025847263559c0
Revert accidental commit
bratsche/monotouch-samples,a9upam/monotouch-samples,hongnguyenpro/monotouch-samples,robinlaide/monotouch-samples,kingyond/monotouch-samples,nervevau2/monotouch-samples,albertoms/monotouch-samples,albertoms/monotouch-samples,W3SS/monotouch-samples,W3SS/monotouch-samples,markradacz/monotouch-samples,peteryule/monotouch-samples,nervevau2/monotouch-samples,labdogg1003/monotouch-samples,nelzomal/monotouch-samples,andypaul/monotouch-samples,nelzomal/monotouch-samples,davidrynn/monotouch-samples,markradacz/monotouch-samples,a9upam/monotouch-samples,andypaul/monotouch-samples,YOTOV-LIMITED/monotouch-samples,sakthivelnagarajan/monotouch-samples,xamarin/monotouch-samples,kingyond/monotouch-samples,labdogg1003/monotouch-samples,haithemaraissia/monotouch-samples,YOTOV-LIMITED/monotouch-samples,davidrynn/monotouch-samples,iFreedive/monotouch-samples,andypaul/monotouch-samples,peteryule/monotouch-samples,labdogg1003/monotouch-samples,nelzomal/monotouch-samples,nelzomal/monotouch-samples,davidrynn/monotouch-samples,kingyond/monotouch-samples,markradacz/monotouch-samples,hongnguyenpro/monotouch-samples,robinlaide/monotouch-samples,YOTOV-LIMITED/monotouch-samples,sakthivelnagarajan/monotouch-samples,davidrynn/monotouch-samples,xamarin/monotouch-samples,hongnguyenpro/monotouch-samples,iFreedive/monotouch-samples,xamarin/monotouch-samples,sakthivelnagarajan/monotouch-samples,albertoms/monotouch-samples,W3SS/monotouch-samples,haithemaraissia/monotouch-samples,bratsche/monotouch-samples,a9upam/monotouch-samples,nervevau2/monotouch-samples,andypaul/monotouch-samples,hongnguyenpro/monotouch-samples,haithemaraissia/monotouch-samples,peteryule/monotouch-samples,labdogg1003/monotouch-samples,robinlaide/monotouch-samples,nervevau2/monotouch-samples,YOTOV-LIMITED/monotouch-samples,iFreedive/monotouch-samples,sakthivelnagarajan/monotouch-samples,peteryule/monotouch-samples,a9upam/monotouch-samples,robinlaide/monotouch-samples,haithemaraissia/monotouch-samples
BubbleCell/BubbleCell/AppDelegate.cs
BubbleCell/BubbleCell/AppDelegate.cs
// // Sample shows how to use MonoTouch.Dialog to create an iPhone SMS-like // display of conversations // // Author: // Miguel de Icaza // using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Dialog; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace BubbleCell { [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { DialogViewController chat; UIWindow window; static void Main (string[] args) { UIApplication.Main (args, null, "AppDelegate"); } public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); var root = new RootElement ("Chat Sample") { new Section () { new ChatBubble (true, "This is the text on the left, what I find fascinating about this is how many lines can fit!"), new ChatBubble (false, "This is some text on the right"), new ChatBubble (true, "Wow, you are very intense!"), new ChatBubble (false, "oops"), new ChatBubble (true, "yes"), } }; chat = new DialogViewController (UITableViewStyle.Plain, root); chat.TableView.SeparatorStyle = UITableViewCellSeparatorStyle.None; window.RootViewController = chat; window.MakeKeyAndVisible (); return true; } } }
// // Sample shows how to use MonoTouch.Dialog to create an iPhone SMS-like // display of conversations // // Author: // Miguel de Icaza // using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Dialog; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace BubbleCell { [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { DialogViewController chat; UIWindow window; Section chatSection; static void Main (string[] args) { UIApplication.Main (args, null, "AppDelegate"); } public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); var root = new RootElement ("Chat Sample") { (chatSection = new Section () { new ChatBubble (false, " "), new ChatBubble (false, " "), new ChatBubble (false, " \n \n \n "), new ChatBubble (false, " \n "), new ChatBubble (true, "This is the text on the left, what I find fascinating about this is how many lines can fit!"), new ChatBubble (false, "This is some text on the right"), new ChatBubble (true, "Wow, you are very intense!"), new ChatBubble (false, "oops"), new ChatBubble (true, "yes"), }) }; chat = new DialogViewController (UITableViewStyle.Plain, root); chat.TableView.SeparatorStyle = UITableViewCellSeparatorStyle.None; window.RootViewController = chat; window.MakeKeyAndVisible (); return true; } } }
mit
C#
b24b7b15d41918aec2943322787b5737786dafcf
Update ValuesController.cs
bigfont/webapi-cors
CORS/Controllers/ValuesController.cs
CORS/Controllers/ValuesController.cs
using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Cors; namespace CORS.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "This is a CORS response. ", "It works from any origin." }; } // GET api/values/another [HttpGet] [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")] public IEnumerable<string> Another() { return new string[] { "This is a CORS response. ", "It works only from two origins: ", "1. www.bigfont.ca ", "2. the same origin." }; } } }
using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Cors; namespace CORS.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "This is a CORS response.", "It works from any origin." }; } // GET api/values/another [HttpGet] [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")] public IEnumerable<string> Another() { return new string[] { "This is a CORS response.", "It works only from www.bigfont.ca AND from the same origin." }; } } }
mit
C#
bf04ebd3f795ac8528d18dffed932e4e27d9184b
Use fieldset instead of div
mattgwagner/alert-roster
alert-roster.web/Views/Home/Index.cshtml
alert-roster.web/Views/Home/Index.cshtml
@model IEnumerable<alert_roster.web.Models.Message> @{ ViewBag.Title = "Messages"; } <div class="jumbotron"> <h1>@ViewBag.Title</h1> </div> @foreach (var message in Model) { <div class="row"> <div class="col-md-4"> <fieldset> <legend> <script>var d = moment.utc('@message.PostedDate').local(); document.write(d);</script> </legend> @message.Content </fieldset> </div> </div> }
@model IEnumerable<alert_roster.web.Models.Message> @{ ViewBag.Title = "Messages"; } <div class="jumbotron"> <h1>@ViewBag.Title</h1> </div> @foreach (var message in Model) { <div class="row"> <div class="col-md-4"> <h2> <script>var d = moment.utc('@message.PostedDate').local(); document.write(d);</script></h2> <p> @message.Content </p> </div> </div> }
mit
C#
83f0d611e0e667bdac743ad211ca311df12b1704
Add spacing
fredatgithub/UsefulFunctions
ConsoleAppPrimesByHundred/Program.cs
ConsoleAppPrimesByHundred/Program.cs
using System; using FonctionsUtiles.Fred.Csharp; namespace ConsoleAppPrimesByHundred { internal class Program { private static void Main() { Action<string> display = Console.WriteLine; display("Prime numbers by hundred:"); foreach (var kvp in FunctionsPrimes.NumberOfPrimesByHundred(1000)) { display($"{kvp.Key} - {kvp.Value}"); } display(string.Empty); display("Prime numbers by thousand:"); display(string.Empty); foreach (var kvp in FunctionsPrimes.NumberOfPrimesByNthHundred(9000, 1000)) { display($"{kvp.Key} - {kvp.Value}"); } display("Press any key to exit"); Console.ReadKey(); } } }
using System; using FonctionsUtiles.Fred.Csharp; namespace ConsoleAppPrimesByHundred { internal class Program { private static void Main() { Action<string> display = Console.WriteLine; display("Prime numbers by hundred:"); foreach (var kvp in FunctionsPrimes.NumberOfPrimesByHundred(1000)) { display($"{kvp.Key} - {kvp.Value}"); } foreach (var kvp in FunctionsPrimes.NumberOfPrimesByNthHundred(9000, 1000)) { display($"{kvp.Key} - {kvp.Value}"); } display("Press any key to exit"); Console.ReadKey(); } } }
mit
C#
c1d68bb66f8da7b0fcdb96970848ee0e501d785e
Add DoAsync method
sakapon/KLibrary-Labs
CoreLab/Core/Reactive/Observable2.cs
CoreLab/Core/Reactive/Observable2.cs
using KLibrary.Labs.Mathematics; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace KLibrary.Labs.Reactive { public static class Observable2 { public static IObservable<long> Interval(TimeSpan interval) { return new TimeTicker(interval); } public static IObservable<long> Interval(TimeSpan interval, bool forAsync) { return new TimeTicker(interval, forAsync); } public static IObservable<TSource> SetMaxFrequency<TSource>(this IObservable<TSource> source, double maxFrequency) { if (source == null) throw new ArgumentNullException("source"); var filter = new FrequencyFilter(maxFrequency); return new ChainNotifier<TSource, TSource>(source, (o, onNext) => { if (filter.CheckLap()) onNext(o); }); } public static IObservable<TSource> DoAsync<TSource>(this IObservable<TSource> source, Action<TSource> onNext) { if (source == null) throw new ArgumentNullException("source"); if (onNext == null) throw new ArgumentNullException("onNext"); return new ChainNotifier<TSource, TSource>(source, (o, onNext2) => Task.Run(() => { onNext(o); onNext2(o); })); } } }
using KLibrary.Labs.Mathematics; using System; using System.Collections.Generic; using System.Linq; namespace KLibrary.Labs.Reactive { public static class Observable2 { public static IObservable<long> Interval(TimeSpan interval) { return new TimeTicker(interval); } public static IObservable<long> Interval(TimeSpan interval, bool forAsync) { return new TimeTicker(interval, forAsync); } public static IObservable<T> SetMaxFrequency<T>(this IObservable<T> observable, double maxFrequency) { if (observable == null) throw new ArgumentNullException("observable"); var filter = new FrequencyFilter(maxFrequency); return new ChainNotifier<T, T>(observable, (o, onNext) => { if (filter.CheckLap()) onNext(o); }); } } }
mit
C#
549367727f0955674791285099b6eee0e36a08b4
fix compile error
guibec/rpgcraft,guibec/rpgcraft,guibec/rpgcraft,guibec/rpgcraft
unity/Assets/Scripts/Game/Player/Experience.cs
unity/Assets/Scripts/Game/Player/Experience.cs
using UnityEngine; using System.Collections; using UnityEngine.Assertions; public class Experience { public Experience() { XP = 0; } public int Level { get { for (int i = MaxLevel-1; i >= 0; --i) { if (XP >= NextLevels[i]) return i + 1; } Assert.IsTrue(false, "Invalid level state"); return 1; } } public int XP { get; private set; } public int MaxLevel { get { return NextLevels.Length; } } private int[] NextLevels = { 0, 50, 150, 375, 790, 1400, 2300, 3300}; }
using UnityEngine; using System.Collections; using UnityEngine.Assertions; public class Experience { public int Level { get { for (int i = MaxLevel-1; i >= 0; --i) { if (XP >= NextLevels[i]) return i + 1; } Assert.IsTrue(false, "Invalid level state"); return 1; } } public int XP { get; private set; } = 0; public int MaxLevel => NextLevels.Length; private int[] NextLevels = { 0, 50, 150, 375, 790, 1400, 2300, 3300}; }
mit
C#
4fc89ea30e25fb7def853c0aa1ab770781a28ebe
Trim un-necessarry char from aggregation variable
inohiro/LodViewProvider
LodViewProvider/LodViewProvider/Aggregation.cs
LodViewProvider/LodViewProvider/Aggregation.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LodViewProvider { public enum AggregationType { Min = 0, Max = 1, Sum = 2, Count = 3, Average = 4, // group by // order by } public class Aggregation : ICondition { public string Variable { get; private set; } public AggregationType AggregationType { get; private set; } public Aggregation( string variable, AggregationType aggregationType ) { Variable = variable.Trim( '\"' ); AggregationType = aggregationType; } public override string ToString() { var strBuild = new StringBuilder(); switch ( AggregationType ) { case LodViewProvider.AggregationType.Average: { } break; case LodViewProvider.AggregationType.Count: { } break; case LodViewProvider.AggregationType.Max: { } break; case LodViewProvider.AggregationType.Min: { } break; default: { throw new InvalidAggregationTypeException(); } break; } return strBuild.ToString(); } } public class InvalidAggregationTypeException : Exception { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LodViewProvider { public enum AggregationType { Min = 0, Max = 1, Sum = 2, Count = 3, Average = 4, // group by // order by } public class Aggregation : ICondition { public string Variable { get; private set; } public AggregationType AggregationType { get; private set; } public Aggregation( string variable, AggregationType aggregationType ) { Variable = variable; AggregationType = aggregationType; } public override string ToString() { var strBuild = new StringBuilder(); switch ( AggregationType ) { case LodViewProvider.AggregationType.Average: { } break; case LodViewProvider.AggregationType.Count: { } break; case LodViewProvider.AggregationType.Max: { } break; case LodViewProvider.AggregationType.Min: { } break; default: { throw new InvalidAggregationTypeException(); } break; } return strBuild.ToString(); } } public class InvalidAggregationTypeException : Exception { } }
mit
C#
d7219e321707ed71e07f990bde08c0205abbbeb0
clean up
RogerKratz/mbcache
MbCache/Logic/LogAndStatisticCacheDecorator.cs
MbCache/Logic/LogAndStatisticCacheDecorator.cs
using log4net; using MbCache.Core; namespace MbCache.Logic { public class LogAndStatisticCacheDecorator : ICache, IStatistics { private ILog log; private readonly ICache _cache; public LogAndStatisticCacheDecorator(ICache cache) { _cache = cache; log = LogManager.GetLogger(cache.GetType()); } public long CacheHits { get; private set; } public long CacheMisses { get; private set; } public object Get(string key) { log.Debug("Trying to find cache entry <" + key + ">"); var ret = _cache.Get(key); if(ret == null) { log.Debug("Cache miss for <" + key + ">"); CacheMisses++; } else { log.Debug("Cache hit for <" + key + ">"); CacheHits++; } return ret; } public void Put(string key, object value) { log.Debug("Put in cache entry <" + key + ">"); _cache.Put(key, value); } public void Delete(string keyStartingWith) { _cache.Delete(keyStartingWith); } public void Clear() { CacheHits = 0; CacheMisses = 0; } } }
using System; using log4net; using MbCache.Core; namespace MbCache.Logic { public class LogAndStatisticCacheDecorator : ICache, IStatistics { private ILog log; private readonly ICache _cache; private long _cacheHits; private long _cacheMisses; public LogAndStatisticCacheDecorator(ICache cache) { _cache = cache; log = LogManager.GetLogger(cache.GetType()); } public object Get(string key) { log.Debug("Trying to find cache entry <" + key + ">"); var ret = _cache.Get(key); if(ret == null) { log.Debug("Cache miss for <" + key + ">"); _cacheMisses++; } else { log.Debug("Cache hit for <" + key + ">"); _cacheHits++; } return ret; } public void Put(string key, object value) { log.Debug("Put in cache entry <" + key + ">"); _cache.Put(key, value); } public void Delete(string keyStartingWith) { _cache.Delete(keyStartingWith); } public void Clear() { _cacheHits = 0; _cacheMisses = 0; } public long CacheHits { get { return _cacheHits; } } public long CacheMisses { get { return _cacheMisses; } } } }
mit
C#
72c6d69789b80c3f729f2a5b4b17318572758b9a
Switch to v1.0.3
Abc-Arbitrage/Zebus,Abc-Arbitrage/Zebus.Persistence
src/SharedVersionInfo.cs
src/SharedVersionInfo.cs
using System.Reflection; [assembly: AssemblyVersion("1.0.3")] [assembly: AssemblyFileVersion("1.0.3")] [assembly: AssemblyInformationalVersion("1.0.3")]
using System.Reflection; [assembly: AssemblyVersion("1.0.2")] [assembly: AssemblyFileVersion("1.0.2")] [assembly: AssemblyInformationalVersion("1.0.2")]
mit
C#
714dd7486e52e36e657e2ebbf4c4359586ae8f47
Fix creation date
kcotugno/OpenARLog
OpenARLog.Data/TypeData.cs
OpenARLog.Data/TypeData.cs
/* * Copyright (C) 2015-2016 kcotugno * All rights reserved * * Distributed under the terms of the BSD 2 Clause software license. See the * accompanying LICENSE file or http://www.opensource.org/licenses/BSD-2-Clause. * * Author: kcotugno * Date: 4/8/2016 */ using System.Data; namespace OpenARLog.Data { public abstract class TypeData { protected dataTable; protected typeDataDb; protected Constants.TYPES type; public Load() { dataTable = typeDataDb.GetTable(type); } public DataTable GetTypeData() { return dataTable; } } }
/* * Copyright (C) 2015-2016 kcotugno * All rights reserved * * Distributed under the terms of the BSD 2 Clause software license. See the * accompanying LICENSE file or http://www.opensource.org/licenses/BSD-2-Clause. * * Author: kcotugno * Date: 4/6/2016 */ using System.Data; namespace OpenARLog.Data { public abstract class TypeData { protected dataTable; protected typeDataDb; protected Constants.TYPES type; public Load() { dataTable = typeDataDb.GetTable(type); } public DataTable GetTypeData() { return dataTable; } } }
mit
C#
41afe14be7f21ead740e59849760faaedb2513f5
Fix incorrect usage of Sldr API by SldrWritingSystemFactory
gmartin7/libpalaso,ddaspit/libpalaso,gtryus/libpalaso,mccarthyrb/libpalaso,gtryus/libpalaso,ermshiperete/libpalaso,ermshiperete/libpalaso,ermshiperete/libpalaso,gmartin7/libpalaso,mccarthyrb/libpalaso,sillsdev/libpalaso,tombogle/libpalaso,sillsdev/libpalaso,glasseyes/libpalaso,gtryus/libpalaso,andrew-polk/libpalaso,glasseyes/libpalaso,ddaspit/libpalaso,gmartin7/libpalaso,glasseyes/libpalaso,tombogle/libpalaso,glasseyes/libpalaso,sillsdev/libpalaso,mccarthyrb/libpalaso,andrew-polk/libpalaso,andrew-polk/libpalaso,ddaspit/libpalaso,tombogle/libpalaso,ermshiperete/libpalaso,mccarthyrb/libpalaso,gmartin7/libpalaso,andrew-polk/libpalaso,gtryus/libpalaso,tombogle/libpalaso,sillsdev/libpalaso,ddaspit/libpalaso
SIL.WritingSystems/SldrWritingSystemFactory.cs
SIL.WritingSystems/SldrWritingSystemFactory.cs
using System.IO; namespace SIL.WritingSystems { public class SldrWritingSystemFactory : SldrWritingSystemFactory<WritingSystemDefinition> { protected override WritingSystemDefinition ConstructDefinition() { return new WritingSystemDefinition(); } protected override WritingSystemDefinition ConstructDefinition(string ietfLanguageTag) { return new WritingSystemDefinition(ietfLanguageTag); } protected override WritingSystemDefinition ConstructDefinition(WritingSystemDefinition ws) { return new WritingSystemDefinition(ws); } } public abstract class SldrWritingSystemFactory<T> : WritingSystemFactoryBase<T> where T : WritingSystemDefinition { public override T Create(string ietfLanguageTag) { // check SLDR for template string sldrCachePath = Path.Combine(Path.GetTempPath(), "SldrCache"); string templatePath; string filename; switch (GetLdmlFromSldr(sldrCachePath, ietfLanguageTag, out filename)) { case SldrStatus.FileFromSldr: case SldrStatus.FileFromSldrCache: templatePath = Path.Combine(sldrCachePath, filename); break; default: templatePath = null; break; } // check template folder for template if (string.IsNullOrEmpty(templatePath) && !string.IsNullOrEmpty(TemplateFolder)) { templatePath = Path.Combine(TemplateFolder, ietfLanguageTag + ".ldml"); if (!File.Exists(templatePath)) templatePath = null; } T ws; if (!string.IsNullOrEmpty(templatePath)) { ws = ConstructDefinition(); var loader = new LdmlDataMapper(this); loader.Read(templatePath, ws); ws.Template = templatePath; } else { ws = ConstructDefinition(ietfLanguageTag); } return ws; } /// <summary> /// The folder in which the repository looks for template LDML files when a writing system is wanted /// that cannot be found in the local store, global store, or SLDR. /// </summary> public string TemplateFolder { get; set; } /// <summary> /// Gets the a LDML file from the SLDR. /// </summary> protected virtual SldrStatus GetLdmlFromSldr(string path, string id, out string filename) { return Sldr.GetLdmlFile(path, id, out filename); } } }
using System.IO; using System.Net; namespace SIL.WritingSystems { public class SldrWritingSystemFactory : SldrWritingSystemFactory<WritingSystemDefinition> { protected override WritingSystemDefinition ConstructDefinition() { return new WritingSystemDefinition(); } protected override WritingSystemDefinition ConstructDefinition(string ietfLanguageTag) { return new WritingSystemDefinition(ietfLanguageTag); } protected override WritingSystemDefinition ConstructDefinition(WritingSystemDefinition ws) { return new WritingSystemDefinition(ws); } } public abstract class SldrWritingSystemFactory<T> : WritingSystemFactoryBase<T> where T : WritingSystemDefinition { public override T Create(string ietfLanguageTag) { // check SLDR for template string sldrCachePath = Path.Combine(Path.GetTempPath(), "SldrCache"); Directory.CreateDirectory(sldrCachePath); string templatePath = Path.Combine(sldrCachePath, ietfLanguageTag + ".ldml"); string filename; if (GetLdmlFromSldr(templatePath, ietfLanguageTag, out filename) == SldrStatus.FileNotFound) { // check SLDR cache for template if (!File.Exists(templatePath)) templatePath = null; } // check template folder for template if (string.IsNullOrEmpty(templatePath) && !string.IsNullOrEmpty(TemplateFolder)) { templatePath = Path.Combine(TemplateFolder, ietfLanguageTag + ".ldml"); if (!File.Exists(templatePath)) templatePath = null; } T ws; if (!string.IsNullOrEmpty(templatePath)) { ws = ConstructDefinition(); var loader = new LdmlDataMapper(this); loader.Read(templatePath, ws); ws.Template = templatePath; } else { ws = ConstructDefinition(ietfLanguageTag); } return ws; } /// <summary> /// The folder in which the repository looks for template LDML files when a writing system is wanted /// that cannot be found in the local store, global store, or SLDR. /// </summary> public string TemplateFolder { get; set; } /// <summary> /// Gets the a LDML file from the SLDR. /// </summary> protected virtual SldrStatus GetLdmlFromSldr(string path, string id, out string filename) { return Sldr.GetLdmlFile(path, id, out filename); } } }
mit
C#
2384c4fa70235a1b8bc661d239028d5af4c40bf6
Update IUserSessionScopeStorage.cs
tiksn/TIKSN-Framework
TIKSN.Core/Session/IUserSessionScopeStorage.cs
TIKSN.Core/Session/IUserSessionScopeStorage.cs
using System; namespace TIKSN.Session { public interface IUserSessionScopeStorage<TIdentity> where TIdentity : IEquatable<TIdentity> { IServiceProvider GetOrAddServiceProvider(TIdentity id); bool TryRemoveServiceProvider(TIdentity id); } }
using System; namespace TIKSN.Session { public interface IUserSessionScopeStorage<TIdentity> where TIdentity : IEquatable<TIdentity> { IServiceProvider GetOrAddServiceProvider(TIdentity id); bool TryRemoveServiceProvider(TIdentity id); } }
mit
C#
558ce640c805a4f5016223d67770409cee74e60e
Sort out assembly metadata.
CamTechConsultants/CvsntGitImporter
Properties/AssemblyInfo.cs
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("CvsntGitConverter")] [assembly: AssemblyDescription("CVSNT to Git Importer")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Cambridge Technology Consultants")] [assembly: AssemblyProduct("CvsntGitConverter")] [assembly: AssemblyCopyright("Copyright © 2013 Cambridge Technology Consultants Ltd.")] [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("ec661d49-de7f-45ce-85a6-e1b2319499f4")] // 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")] [assembly: InternalsVisibleTo("CvsntGitImporterTest")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
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("CvsGitConverter")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CvsGitConverter")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("ec661d49-de7f-45ce-85a6-e1b2319499f4")] // 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")] [assembly: InternalsVisibleTo("CvsntGitImporterTest")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
mit
C#
332aba5b558b70b6595f46d8d1b67bbd83ba93fe
Add SongInfo.WebUrl
gyrosworkshop/Wukong,gyrosworkshop/Wukong
src/Wukong/Models/Song.cs
src/Wukong/Models/Song.cs
using System; using System.Reflection; namespace Wukong.Models { public class ClientSong { public string SiteId { get; set; } public string SongId { get; set; } // override object.Equals public override bool Equals(object obj) { var song = obj as ClientSong; if (null == song) { return false; } return SiteId == song.SiteId && SongId == song.SongId; } public override int GetHashCode() { var hash = 17; hash = hash * 23 + SongId.GetHashCode(); hash = hash * 23 + SiteId.GetHashCode(); return hash; } public static bool operator ==(ClientSong a, ClientSong b) { if (ReferenceEquals(a, b)) { return true; } if ((object) a == null || (object) b == null) { return false; } return a.Equals(b); } public static bool operator !=(ClientSong a, ClientSong b) { return !(a == b); } } public class ClientSongData : ClientSong { public ClientSongData() { } public ClientSongData(ClientSong song) { SiteId = song.SiteId; SongId = song.SongId; } public long SongListId { get; set; } public virtual SongListData SongList { get; set; } } public class Song : SongInfo { public Files Music; public double Length; public int Bitrate; } public class SongInfo : ClientSong { public string Artist; public string Album; public Files Artwork; public string Title; public Lyric[] Lyrics; public string WebUrl; } public class Lyric { public bool withTimeline; public bool translate; public string lyric; } public class Files { public string file; public string fileViaCdn; } }
using System; using System.Reflection; namespace Wukong.Models { public class ClientSong { public string SiteId { get; set; } public string SongId { get; set; } // override object.Equals public override bool Equals(object obj) { var song = obj as ClientSong; if (null == song) { return false; } return SiteId == song.SiteId && SongId == song.SongId; } public override int GetHashCode() { var hash = 17; hash = hash * 23 + SongId.GetHashCode(); hash = hash * 23 + SiteId.GetHashCode(); return hash; } public static bool operator ==(ClientSong a, ClientSong b) { if (ReferenceEquals(a, b)) { return true; } if ((object) a == null || (object) b == null) { return false; } return a.Equals(b); } public static bool operator !=(ClientSong a, ClientSong b) { return !(a == b); } } public class ClientSongData : ClientSong { public ClientSongData() { } public ClientSongData(ClientSong song) { SiteId = song.SiteId; SongId = song.SongId; } public long SongListId { get; set; } public virtual SongListData SongList { get; set; } } public class Song : SongInfo { public Files Music; public double Length; public int Bitrate; } public class SongInfo : ClientSong { public string Artist; public string Album; public Files Artwork; public string Title; public Lyric[] Lyrics; } public class Lyric { public bool withTimeline; public bool translate; public string lyric; } public class Files { public string file; public string fileViaCdn; } }
mit
C#
113f90e92e341f826926a1a3d2f4dcd9387df952
add back schedule is CurrentPath setter
UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,peppy/osu-new,smoogipooo/osu
osu.Game/Overlays/Wiki/Markdown/WikiMarkdownContainer.cs
osu.Game/Overlays/Wiki/Markdown/WikiMarkdownContainer.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.Linq; using Markdig.Extensions.Yaml; using Markdig.Syntax; using Markdig.Syntax.Inlines; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers.Markdown; using osu.Game.Graphics.Containers.Markdown; namespace osu.Game.Overlays.Wiki.Markdown { public class WikiMarkdownContainer : OsuMarkdownContainer { public string CurrentPath { set => Schedule(() => DocumentUrl = $"{DocumentUrl}wiki/{value}"); } protected override void AddMarkdownComponent(IMarkdownObject markdownObject, FillFlowContainer container, int level) { switch (markdownObject) { case YamlFrontMatterBlock yamlFrontMatterBlock: container.Add(new WikiNoticeContainer(yamlFrontMatterBlock)); break; case ParagraphBlock paragraphBlock: // Check if paragraph only contains an image if (paragraphBlock.Inline.Count() == 1 && paragraphBlock.Inline.FirstChild is LinkInline { IsImage: true } linkInline) { container.Add(new WikiMarkdownImageBlock(linkInline)); return; } break; } base.AddMarkdownComponent(markdownObject, container, level); } public override MarkdownTextFlowContainer CreateTextFlow() => new WikiMarkdownTextFlowContainer(); private class WikiMarkdownTextFlowContainer : OsuMarkdownTextFlowContainer { protected override void AddImage(LinkInline linkInline) => AddDrawable(new WikiMarkdownImage(linkInline)); } } }
// 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.Linq; using Markdig.Extensions.Yaml; using Markdig.Syntax; using Markdig.Syntax.Inlines; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers.Markdown; using osu.Game.Graphics.Containers.Markdown; namespace osu.Game.Overlays.Wiki.Markdown { public class WikiMarkdownContainer : OsuMarkdownContainer { public string CurrentPath { set => DocumentUrl = $"{DocumentUrl}wiki/{value}"; } protected override void AddMarkdownComponent(IMarkdownObject markdownObject, FillFlowContainer container, int level) { switch (markdownObject) { case YamlFrontMatterBlock yamlFrontMatterBlock: container.Add(new WikiNoticeContainer(yamlFrontMatterBlock)); break; case ParagraphBlock paragraphBlock: // Check if paragraph only contains an image if (paragraphBlock.Inline.Count() == 1 && paragraphBlock.Inline.FirstChild is LinkInline { IsImage: true } linkInline) { container.Add(new WikiMarkdownImageBlock(linkInline)); return; } break; } base.AddMarkdownComponent(markdownObject, container, level); } public override MarkdownTextFlowContainer CreateTextFlow() => new WikiMarkdownTextFlowContainer(); private class WikiMarkdownTextFlowContainer : OsuMarkdownTextFlowContainer { protected override void AddImage(LinkInline linkInline) => AddDrawable(new WikiMarkdownImage(linkInline)); } } }
mit
C#
3efd8b68e81ccffa2ccc3d67e3ac17773f4a2bc0
add support for zoom level based cache folders
brnkhy/MapzenGo,brnkhy/MapzenGo
Assets/MapzenGo/Models/CachedDynamicTileManager.cs
Assets/MapzenGo/Models/CachedDynamicTileManager.cs
using System.IO; using System.Text; using MapzenGo.Helpers; using UniRx; using UnityEngine; namespace MapzenGo.Models { public class CachedDynamicTileManager : DynamicTileManager { public string RelativeCachePath = "../MapzenGo/CachedTileData/{0}/"; protected string CacheFolderPath; public override void Start() { CacheFolderPath = Path.Combine(Application.dataPath, RelativeCachePath); CacheFolderPath = CacheFolderPath.Format(Zoom); if (!Directory.Exists(CacheFolderPath)) Directory.CreateDirectory(CacheFolderPath); base.Start(); } protected override void LoadTile(Vector2d tileTms, Tile tile) { var url = string.Format(_mapzenUrl, _mapzenLayers, Zoom, tileTms.x, tileTms.y, _mapzenFormat, _key); var tilePath = Path.Combine(CacheFolderPath, tileTms.x + "_" + tileTms.y); if (File.Exists(tilePath)) { var r = new StreamReader(tilePath, Encoding.Default); var mapData = r.ReadToEnd(); ConstructTile(mapData, tile); } else { ObservableWWW.Get(url).Subscribe( success => { var sr = File.CreateText(tilePath); sr.Write(success); sr.Close(); ConstructTile(success, tile); }, error => { Debug.Log(error); }); } } } }
using System.IO; using System.Text; using UniRx; using UnityEngine; namespace MapzenGo.Models { public class CachedDynamicTileManager : DynamicTileManager { public string RelativeCachePath = "../MapzenGo/CachedTileData/"; protected string CacheFolderPath; public override void Start() { CacheFolderPath = Path.Combine(Application.dataPath, RelativeCachePath); if (!Directory.Exists(CacheFolderPath)) Directory.CreateDirectory(CacheFolderPath); base.Start(); } protected override void LoadTile(Vector2d tileTms, Tile tile) { var url = string.Format(_mapzenUrl, _mapzenLayers, Zoom, tileTms.x, tileTms.y, _mapzenFormat, _key); var tilePath = Path.Combine(CacheFolderPath, Zoom + "_" + tileTms.x + "_" + tileTms.y); if (File.Exists(tilePath)) { var r = new StreamReader(tilePath, Encoding.Default); var mapData = r.ReadToEnd(); ConstructTile(mapData, tile); } else { ObservableWWW.Get(url).Subscribe( success => { var sr = File.CreateText(tilePath); sr.Write(success); sr.Close(); ConstructTile(success, tile); }, error => { Debug.Log(error); }); } } } }
mit
C#
4e944de0ca1170755b4d0ca09fda4a797402bb15
Fix for SSD rank filtering
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Controllers/SSDController.cs
Battery-Commander.Web/Controllers/SSDController.cs
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers { [Authorize, ApiExplorerSettings(IgnoreApi = true)] public class SSDController : Controller { private readonly Database db; public SSDController(Database db) { this.db = db; } public async Task<IActionResult> Index(SoldierSearchService.Query query) { // Ensure we're only displaying Soldiers we care about here if (!query.Ranks.Any()) query.OnlyEnlisted = true; return View("List", await SoldierSearchService.Filter(db, query)); } [HttpPost] public async Task<IActionResult> Update(int soldierId, SSD ssd, decimal completion) { // Take the models and pull the updated data var soldier = await SoldiersController.Get(db, soldierId); soldier .SSDSnapshots .Add(new Soldier.SSDSnapshot { SSD = ssd, PerecentComplete = completion / 100 // Convert to decimal percentage }); await db.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } } }
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers { [Authorize, ApiExplorerSettings(IgnoreApi = true)] public class SSDController : Controller { private readonly Database db; public SSDController(Database db) { this.db = db; } public async Task<IActionResult> Index(SoldierSearchService.Query query) { // Ensure we're only displaying Soldiers we care about here query.OnlyEnlisted = true; return View("List", await SoldierSearchService.Filter(db, query)); } [HttpPost] public async Task<IActionResult> Update(int soldierId, SSD ssd, decimal completion) { // Take the models and pull the updated data var soldier = await SoldiersController.Get(db, soldierId); soldier .SSDSnapshots .Add(new Soldier.SSDSnapshot { SSD = ssd, PerecentComplete = completion / 100 // Convert to decimal percentage }); await db.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } } }
mit
C#
7c4ff956e6844d1f58f450038bf32882347964c5
Make test functions static, add new test and optimize old tests.
Xevle/Tests
Tests.Xevle.Math/Tuples/Tuple3dcTests.cs
Tests.Xevle.Math/Tuples/Tuple3dcTests.cs
using NUnit.Framework; using System; using Xevle.Math.Tuples; namespace Tests.Xevle.Math { [TestFixture()] public static class Test { static double delta=0.0001; [Test()] public static void TestConstructor() { // Prepare test Tuple3dc tuple = new Tuple3dc(1, 2, 3); // Execute test Assert.AreEqual(1, tuple.x); Assert.AreEqual(2, tuple.y); Assert.AreEqual(3, tuple.z); } #region Test operators #region Unary operators [Test()] public static void TestUnaryOperatorPlus() { // Prepare test Tuple3dc tuple = new Tuple3dc(1, 2, 3); tuple = +tuple; // Execute test Assert.AreEqual(1, tuple.x); Assert.AreEqual(2, tuple.y); Assert.AreEqual(3, tuple.z); } [Test()] public static void TestUnaryOperatorMinus() { // Prepare test Tuple3dc tuple = new Tuple3dc(1, 2, 3); tuple = -tuple; // Execute test Assert.AreEqual(-1, tuple.x); Assert.AreEqual(-2, tuple.y); Assert.AreEqual(-3, tuple.z); } [Test()] public static void TestUnaryOperatorMagnitude() { // Prepare test Tuple3dc tuple = new Tuple3dc(1, 2, 3); double magnitude = !tuple; // Execute test Assert.AreEqual(3.74165738677394, magnitude, delta); } [Test()] public static void TestUnaryOperatorNormalize() { // Prepare test Tuple3dc tuple = new Tuple3dc(1, 2, 3); Tuple3dc normalizedTuple = ~tuple; // Execute test Assert.AreEqual(0.267261241912424, normalizedTuple.x, delta); Assert.AreEqual(0.534522483824849, normalizedTuple.y, delta); Assert.AreEqual(0.801783725737273, normalizedTuple.z, delta); } #endregion #region Binary operators [Test()] public static void TestAddition() { // Prepare test Tuple3dc a = new Tuple3dc(1, 2, 3); Tuple3dc b = new Tuple3dc(4, 5, 6); Tuple3dc c = a + b; // Execute test Assert.AreEqual(5, c.x, delta); Assert.AreEqual(7, c.y, delta); Assert.AreEqual(9, c.z, delta); } #endregion #endregion } }
using NUnit.Framework; using System; using Xevle.Math.Tuples; namespace Tests.Xevle.Math { [TestFixture()] public class Test { [Test()] public void TestConstructor() { // Prepare test Tuple3dc tuple = new Tuple3dc(1, 2, 3); // Execute test Assert.AreEqual(1, tuple.x); Assert.AreEqual(2, tuple.y); Assert.AreEqual(3, tuple.z); } #region Test operators #region Unary operators [Test()] public void TestUnaryOperatorPlus() { // Prepare test Tuple3dc tuple = new Tuple3dc(1, 2, 3); tuple = +tuple; // Execute test Assert.AreEqual(1, tuple.x); Assert.AreEqual(2, tuple.y); Assert.AreEqual(3, tuple.z); } [Test()] public void TestUnaryOperatorMinus() { // Prepare test Tuple3dc tuple = new Tuple3dc(1, 2, 3); tuple = -tuple; // Execute test Assert.AreEqual(-1, tuple.x); Assert.AreEqual(-2, tuple.y); Assert.AreEqual(-3, tuple.z); } [Test()] public void TestUnaryOperatorMagnitude() { // Prepare test Tuple3dc tuple = new Tuple3dc(1, 2, 3); double magnitude = !tuple; double diff = System.Math.Abs(3.74165738677394 - magnitude); // Execute test if (diff > 0.01) { Assert.Fail(); } } [Test()] public void TestUnaryOperatorNormalize() { // Prepare test Tuple3dc tuple = new Tuple3dc(1, 2, 3); Tuple3dc normalizedTuple = ~tuple; double diffX = System.Math.Abs(0.267261241912424 - normalizedTuple.x); double diffY = System.Math.Abs(0.534522483824849 - normalizedTuple.y); double diffZ = System.Math.Abs(0.801783725737273 - normalizedTuple.z); // Execute test if (diffX > 0.01) Assert.Fail(); if (diffY > 0.01) Assert.Fail(); if (diffZ > 0.01) Assert.Fail(); } #endregion #endregion } }
mit
C#
b6a458a07ec9518fb011782f2cceb8560f82a273
Cover seasonal backgrounds not resetting on inactivity in test
ppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu,ppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu
osu.Game.Tests/NonVisual/SessionStaticsTest.cs
osu.Game.Tests/NonVisual/SessionStaticsTest.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.Game.Configuration; using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Tests.NonVisual { [TestFixture] public class SessionStaticsTest { private SessionStatics sessionStatics; [Test] public void TestSessionStaticsReset() { sessionStatics = new SessionStatics(); sessionStatics.SetValue(Static.LoginOverlayDisplayed, true); sessionStatics.SetValue(Static.MutedAudioNotificationShownOnce, true); sessionStatics.SetValue(Static.LowBatteryNotificationShownOnce, true); sessionStatics.SetValue(Static.LastHoverSoundPlaybackTime, (double?)1d); sessionStatics.SetValue(Static.SeasonalBackgrounds, new APISeasonalBackgrounds { EndDate = new DateTimeOffset(2022, 1, 1, 0, 0, 0, TimeSpan.Zero) }); Assert.IsFalse(sessionStatics.GetBindable<bool>(Static.LoginOverlayDisplayed).IsDefault); Assert.IsFalse(sessionStatics.GetBindable<bool>(Static.MutedAudioNotificationShownOnce).IsDefault); Assert.IsFalse(sessionStatics.GetBindable<bool>(Static.LowBatteryNotificationShownOnce).IsDefault); Assert.IsFalse(sessionStatics.GetBindable<double?>(Static.LastHoverSoundPlaybackTime).IsDefault); Assert.IsFalse(sessionStatics.GetBindable<APISeasonalBackgrounds>(Static.SeasonalBackgrounds).IsDefault); sessionStatics.ResetAfterInactivity(); Assert.IsTrue(sessionStatics.GetBindable<bool>(Static.LoginOverlayDisplayed).IsDefault); Assert.IsTrue(sessionStatics.GetBindable<bool>(Static.MutedAudioNotificationShownOnce).IsDefault); Assert.IsTrue(sessionStatics.GetBindable<bool>(Static.LowBatteryNotificationShownOnce).IsDefault); // some statics should not reset despite inactivity. Assert.IsFalse(sessionStatics.GetBindable<double?>(Static.LastHoverSoundPlaybackTime).IsDefault); Assert.IsFalse(sessionStatics.GetBindable<APISeasonalBackgrounds>(Static.SeasonalBackgrounds).IsDefault); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Configuration; namespace osu.Game.Tests.NonVisual { [TestFixture] public class SessionStaticsTest { private SessionStatics sessionStatics; [Test] public void TestSessionStaticsReset() { sessionStatics = new SessionStatics(); sessionStatics.SetValue(Static.LoginOverlayDisplayed, true); sessionStatics.SetValue(Static.MutedAudioNotificationShownOnce, true); sessionStatics.SetValue(Static.LowBatteryNotificationShownOnce, true); sessionStatics.SetValue(Static.LastHoverSoundPlaybackTime, (double?)1d); Assert.IsFalse(sessionStatics.GetBindable<bool>(Static.LoginOverlayDisplayed).IsDefault); Assert.IsFalse(sessionStatics.GetBindable<bool>(Static.MutedAudioNotificationShownOnce).IsDefault); Assert.IsFalse(sessionStatics.GetBindable<bool>(Static.LowBatteryNotificationShownOnce).IsDefault); Assert.IsFalse(sessionStatics.GetBindable<double?>(Static.LastHoverSoundPlaybackTime).IsDefault); sessionStatics.ResetAfterInactivity(); Assert.IsTrue(sessionStatics.GetBindable<bool>(Static.LoginOverlayDisplayed).IsDefault); Assert.IsTrue(sessionStatics.GetBindable<bool>(Static.MutedAudioNotificationShownOnce).IsDefault); Assert.IsTrue(sessionStatics.GetBindable<bool>(Static.LowBatteryNotificationShownOnce).IsDefault); // some statics should not reset despite inactivity. Assert.IsFalse(sessionStatics.GetBindable<double?>(Static.LastHoverSoundPlaybackTime).IsDefault); } } }
mit
C#
c9d33122a2141976c9c5cdf99345687e9e78f591
Rewrite BaseViewModel's property resolution to keep dependency map in a static field and only resolve the dependencies once during the lifetime of an application.
Misza13/StarsReloaded
StarsReloaded.Client.ViewModel/BaseViewModel.cs
StarsReloaded.Client.ViewModel/BaseViewModel.cs
namespace StarsReloaded.Client.ViewModel { using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using GalaSoft.MvvmLight; using StarsReloaded.Client.ViewModel.Attributes; public class BaseViewModel : ViewModelBase { private static readonly Dictionary<Type, Dictionary<string, List<string>>> PropertyDependencies = new Dictionary<Type, Dictionary<string, List<string>>>(); public override void RaisePropertyChanged([CallerMemberName] string propertyName = null) { base.RaisePropertyChanged(propertyName); foreach (var property in GetDependentProperties(this.GetType(), propertyName)) { #if DEBUG Console.WriteLine($"{propertyName} -> {property}"); #endif this.RaisePropertyChanged(property); } } private static IEnumerable<string> GetDependentProperties(Type type, string propName) { lock (PropertyDependencies) { if (!PropertyDependencies.ContainsKey(type)) { PropertyDependencies[type] = ResolvePropertyDependencies(type); } var typeMap = PropertyDependencies[type]; if (!typeMap.ContainsKey(propName)) { return new string[0]; } return PropertyDependencies[type][propName]; } } private static Dictionary<string, List<string>> ResolvePropertyDependencies(Type type) { #if DEBUG Console.WriteLine($"Resolving property dependencies for {type.FullName}"); #endif var map = new Dictionary<string, List<string>>(); foreach (var property in type.GetProperties()) { foreach (var dependency in property.GetCustomAttributes(typeof(DependsUponAttribute))) { var dependsUpon = (dependency as DependsUponAttribute)?.PropertyName; if (dependsUpon != null && dependsUpon != property.Name) { RegisterDependency(map, dependsUpon, property.Name); } } } return map; } private static void RegisterDependency(IDictionary<string, List<string>> map, string fromProp, string toProp) { if (!map.ContainsKey(fromProp)) { map[fromProp] = new List<string>(); } if (!map[fromProp].Contains(toProp)) { map[fromProp].Add(toProp); } } } }
namespace StarsReloaded.Client.ViewModel { using System; using System.Reflection; using System.Runtime.CompilerServices; using GalaSoft.MvvmLight; using StarsReloaded.Client.ViewModel.Attributes; public class BaseViewModel : ViewModelBase { public override void RaisePropertyChanged([CallerMemberName] string propertyName = null) { base.RaisePropertyChanged(propertyName); foreach (var property in this.GetType().GetProperties()) { foreach (var baseProp in property.GetCustomAttributes(typeof(DependsUponAttribute))) { var dependentUpon = (baseProp as DependsUponAttribute)?.PropertyName; if (dependentUpon == propertyName) { #if DEBUG Console.WriteLine($"{propertyName} -> {property.Name}"); #endif this.RaisePropertyChanged(property.Name); } } } } } }
mit
C#
8ce9edaf8f9fa661669a846fe36df3701fdb217c
Initialize claims collection in InMemoryUser
IdentityServer/IdentityServer3,paulofoliveira/IdentityServer3,tonyeung/IdentityServer3,olohmann/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,buddhike/IdentityServer3,jonathankarsh/IdentityServer3,angelapper/IdentityServer3,remunda/IdentityServer3,delRyan/IdentityServer3,18098924759/IdentityServer3,wondertrap/IdentityServer3,IdentityServer/IdentityServer3,codeice/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,18098924759/IdentityServer3,roflkins/IdentityServer3,remunda/IdentityServer3,iamkoch/IdentityServer3,iamkoch/IdentityServer3,bestwpw/IdentityServer3,delloncba/IdentityServer3,kouweizhong/IdentityServer3,kouweizhong/IdentityServer3,tonyeung/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,kouweizhong/IdentityServer3,tuyndv/IdentityServer3,tonyeung/IdentityServer3,iamkoch/IdentityServer3,SonOfSam/IdentityServer3,bodell/IdentityServer3,mvalipour/IdentityServer3,jackswei/IdentityServer3,mvalipour/IdentityServer3,delloncba/IdentityServer3,codeice/IdentityServer3,roflkins/IdentityServer3,paulofoliveira/IdentityServer3,yanjustino/IdentityServer3,Agrando/IdentityServer3,charoco/IdentityServer3,delRyan/IdentityServer3,angelapper/IdentityServer3,olohmann/IdentityServer3,Agrando/IdentityServer3,openbizgit/IdentityServer3,ryanvgates/IdentityServer3,olohmann/IdentityServer3,chicoribas/IdentityServer3,bestwpw/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,chicoribas/IdentityServer3,uoko-J-Go/IdentityServer,tbitowner/IdentityServer3,bestwpw/IdentityServer3,wondertrap/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,yanjustino/IdentityServer3,delRyan/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,jackswei/IdentityServer3,SonOfSam/IdentityServer3,tuyndv/IdentityServer3,openbizgit/IdentityServer3,buddhike/IdentityServer3,buddhike/IdentityServer3,codeice/IdentityServer3,faithword/IdentityServer3,delloncba/IdentityServer3,jonathankarsh/IdentityServer3,angelapper/IdentityServer3,EternalXw/IdentityServer3,ryanvgates/IdentityServer3,faithword/IdentityServer3,faithword/IdentityServer3,roflkins/IdentityServer3,EternalXw/IdentityServer3,tuyndv/IdentityServer3,tbitowner/IdentityServer3,ryanvgates/IdentityServer3,charoco/IdentityServer3,charoco/IdentityServer3,tbitowner/IdentityServer3,paulofoliveira/IdentityServer3,remunda/IdentityServer3,uoko-J-Go/IdentityServer,SonOfSam/IdentityServer3,Agrando/IdentityServer3,bodell/IdentityServer3,jonathankarsh/IdentityServer3,18098924759/IdentityServer3,bodell/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,chicoribas/IdentityServer3,mvalipour/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,yanjustino/IdentityServer3,IdentityServer/IdentityServer3,openbizgit/IdentityServer3,uoko-J-Go/IdentityServer,EternalXw/IdentityServer3,jackswei/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,wondertrap/IdentityServer3
source/Core/Services/InMemory/InMemoryUser.cs
source/Core/Services/InMemory/InMemoryUser.cs
/* * Copyright 2014 Dominick Baier, Brock Allen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections.Generic; using System.Security.Claims; namespace Thinktecture.IdentityServer.Core.Services.InMemory { public class InMemoryUser { public string Subject { get; set; } public bool Enabled { get; set; } public string Username { get; set; } public string Password { get; set; } public string Provider { get; set; } public string ProviderId { get; set; } public IEnumerable<Claim> Claims { get; set; } public InMemoryUser() { Enabled = true; Claims = new List<Claim>(); } } }
/* * Copyright 2014 Dominick Baier, Brock Allen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections.Generic; using System.Security.Claims; namespace Thinktecture.IdentityServer.Core.Services.InMemory { public class InMemoryUser { public string Subject { get; set; } public bool Enabled { get; set; } public string Username { get; set; } public string Password { get; set; } public string Provider { get; set; } public string ProviderId { get; set; } public IEnumerable<Claim> Claims { get; set; } public InMemoryUser() { Enabled = true; } } }
apache-2.0
C#
ed0d29db3dfef54146e4e6dfe03f601b454df26f
remove comments
stanac/LiteApi,stanac/LiteApi,stanac/LiteApi
LiteApi/LiteApi.Demo/Controllers/TestController.cs
LiteApi/LiteApi.Demo/Controllers/TestController.cs
using System.Collections.Generic; using System.Linq; namespace LiteApi.Demo.Controllers { public class TestController : LiteController { readonly IDemoService _service; public TestController(IDemoService service) { _service = service; } public int Add(int a, int b) { return _service.Add(a, b); } public string Add(string a, string b) { return _service.Add(a, b); } public int SumInts(int[] ints) { return ints.Sum(); } public int Action1(int i) { return i; } public int Action1(int[] i) { return i.Sum(); } public int Action2(int i) { return i; } public int Action2(int? i) { return i ?? 0; } public int Action2(int[] i) { return i.Sum(); } public int Action2(int?[] i) { return i.Select(x => x ?? -0).Sum(); } public object SumNotNullable(List<int?> ints) { bool hasNulls = ints.Any(x => !x.HasValue); int sum = ints.Where(x => x.HasValue).Select(x => x.Value).Sum(); return new { hasNulls, sum }; } } }
using System.Collections.Generic; using System.Linq; namespace LiteApi.Demo.Controllers { public class TestController : LiteController { readonly IDemoService _service; public TestController(IDemoService service) { _service = service; } public int Add(int a, int b) { return _service.Add(a, b); } public string Add(string a, string b) { return _service.Add(a, b); } public int SumInts(int[] ints) { return ints.Sum(); } // will never be called, always DoIt(int[] i) will be called public int Action1(int i) { return i; } public int Action1(int[] i) { return i.Sum(); } // will never be called, always DoIt(int? i) will be called public int Action2(int i) { return i; } public int Action2(int? i) { return i ?? 0; } public int Action2(int[] i) { return i.Sum(); } public int Action2(int?[] i) { return i.Select(x => x ?? -0).Sum(); } public object SumNotNullable(List<int?> ints) { bool hasNulls = ints.Any(x => !x.HasValue); int sum = ints.Where(x => x.HasValue).Select(x => x.Value).Sum(); return new { hasNulls, sum }; } } }
mit
C#
cefbba1930aa85d129113374bedb4ccedc414cec
add trigger attribute to Routine
myxini/block-program
block-program/Detection/Routine.cs
block-program/Detection/Routine.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Myxini.Recognition { public class Routine { private IList<Instruction> list_instruction = new List<Instruction>(); public Routine(ControlBlock trigger) { Instructions = list_instruction; Trigger = trigger; } public IEnumerable<Instruction> Instructions { get; private set; } public ControlBlock Trigger { get; private set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Myxini.Recognition { public class Routine { private IList<Instruction> list_instruction = new List<Instruction>(); public Routine() { Instructions = list_instruction; } public IEnumerable<Instruction> Instructions { get; private set; } } }
mit
C#
45b7bcf1f97091fd764d43eccf0072e69135f178
Add check is transport work with webGL or not at transport factory
insthync/LiteNetLibManager,insthync/LiteNetLibManager
Scripts/Transports/WebSocket/WebSocketTransportFactory.cs
Scripts/Transports/WebSocket/WebSocketTransportFactory.cs
namespace LiteNetLibManager { public class WebSocketTransportFactory : BaseTransportFactory { public override bool CanUseWithWebGL { get { return true; } } public override ITransport Build() { return new WebSocketTransport(); } } }
namespace LiteNetLibManager { public class WebSocketTransportFactory : BaseTransportFactory { public override bool CanUseWithWebGL { get { return false; } } public override ITransport Build() { return new WebSocketTransport(); } } }
mit
C#
55df1f469e11e5fdba1304654e26b0833af46e5f
Fix the null reference exception coming from AutomaticPackageCurator when curatedFeed has been loaded without including Packages.
KuduApps/NuGetGallery,KuduApps/NuGetGallery,KuduApps/NuGetGallery,ScottShingler/NuGetGallery,skbkontur/NuGetGallery,projectkudu/SiteExtensionGallery,projectkudu/SiteExtensionGallery,skbkontur/NuGetGallery,KuduApps/NuGetGallery,JetBrains/ReSharperGallery,mtian/SiteExtensionGallery,grenade/NuGetGallery_download-count-patch,skbkontur/NuGetGallery,projectkudu/SiteExtensionGallery,JetBrains/ReSharperGallery,mtian/SiteExtensionGallery,ScottShingler/NuGetGallery,JetBrains/ReSharperGallery,ScottShingler/NuGetGallery,mtian/SiteExtensionGallery,grenade/NuGetGallery_download-count-patch,grenade/NuGetGallery_download-count-patch,KuduApps/NuGetGallery
Website/PackageCurators/WebMatrixPackageCurator.cs
Website/PackageCurators/WebMatrixPackageCurator.cs
using System.IO; using System.Linq; using NuGet; namespace NuGetGallery { public class WebMatrixPackageCurator : AutomaticPackageCurator { public override void Curate( Package galleryPackage, IPackage nugetPackage) { var curatedFeed = GetService<ICuratedFeedByNameQuery>().Execute("webmatrix", includePackages: true); if (curatedFeed == null) { return; } if (!galleryPackage.IsLatestStable) { return; } var shouldBeIncluded = galleryPackage.Tags != null && galleryPackage.Tags.ToLowerInvariant().Contains("aspnetwebpages"); if (!shouldBeIncluded) { shouldBeIncluded = true; foreach (var file in nugetPackage.GetFiles()) { var fi = new FileInfo(file.Path); if (fi.Extension == ".ps1" || fi.Extension == ".t4") { shouldBeIncluded = false; break; } } } if (shouldBeIncluded && DependenciesAreCurated(galleryPackage, curatedFeed)) { GetService<ICreateCuratedPackageCommand>().Execute( curatedFeed.Key, galleryPackage.PackageRegistration.Key, automaticallyCurated: true); } } } }
using System.IO; using System.Linq; using NuGet; namespace NuGetGallery { public class WebMatrixPackageCurator : AutomaticPackageCurator { public override void Curate( Package galleryPackage, IPackage nugetPackage) { var curatedFeed = GetService<ICuratedFeedByNameQuery>().Execute("webmatrix"); if (curatedFeed == null) { return; } if (!galleryPackage.IsLatestStable) { return; } var shouldBeIncluded = galleryPackage.Tags != null && galleryPackage.Tags.ToLowerInvariant().Contains("aspnetwebpages"); if (!shouldBeIncluded) { shouldBeIncluded = true; foreach (var file in nugetPackage.GetFiles()) { var fi = new FileInfo(file.Path); if (fi.Extension == ".ps1" || fi.Extension == ".t4") { shouldBeIncluded = false; break; } } } if (shouldBeIncluded && DependenciesAreCurated(galleryPackage, curatedFeed)) { GetService<ICreateCuratedPackageCommand>().Execute( curatedFeed.Key, galleryPackage.PackageRegistration.Key, automaticallyCurated: true); } } } }
apache-2.0
C#
4e38d043b810c98b1f99768a330f06b695a2d3af
add tool method for DictionaryExtension
yuanrui/Examples,yuanrui/Examples,yuanrui/Examples,yuanrui/Examples,yuanrui/Examples
Simple.Common/Extensions/DictionaryExtension.cs
Simple.Common/Extensions/DictionaryExtension.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Simple.Common.Extensions { public static class DictionaryExtension { /// <summary> /// try add key value for dictionary, if key not exists then add key value, else do nothing. /// Thread unsafe /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <param name="dict"></param> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public static bool TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value) { if (dict == null || dict.ContainsKey(key)) { return false; } dict.Add(key, value); return true; } public static TValue AddOrUpdate<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory) { if (dict == null) { throw new ArgumentNullException("dict"); } if (dict.ContainsKey(key)) { dict[key] = updateValueFactory(key, addValue); } else { dict[key] = addValue; } return dict[key]; } public static Dictionary<TKey, TValue> Merge<TKey, TValue>(this Dictionary<TKey, TValue> @thisDict, Dictionary<TKey, TValue> @thatDict) { if (@thisDict == null) { throw new ArgumentNullException("thisDict"); } if (@thatDict == null) { throw new ArgumentNullException("thatDict"); } var result = new Dictionary<TKey, TValue>(@thisDict.Count + @thatDict.Count); foreach (var pair in @thisDict) { result.Add(pair.Key, pair.Value); } foreach (var pair in @thatDict) { TryAdd(result, pair.Key, pair.Value); } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Simple.Common.Extensions { public static class DictionaryExtension { /// <summary> /// try add key value for dictionary, if key not exists then add key value, else do nothing. /// Thread unsafe /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <param name="dic"></param> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public static bool TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dic, TKey key, TValue value) { if (dic == null || dic.ContainsKey(key)) { return false; } dic.Add(key, value); return true; } } }
apache-2.0
C#
26adb3642b7ee6b6a0c2f50bcf0c6e7cedb285b7
Increment AssemblyInfo version number.
fox091/TournamentTeamMaker
TeamMaker/Properties/AssemblyInfo.cs
TeamMaker/Properties/AssemblyInfo.cs
using System.Reflection; 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("TeamMaker")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TeamMaker")] [assembly: AssemblyCopyright("")] [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("71703720-56ba-4e6a-9004-239a9836693b")] // 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: AssemblyFileVersion("1.1.0")]
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("TeamMaker")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TeamMaker")] [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("71703720-56ba-4e6a-9004-239a9836693b")] // 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.2")] [assembly: AssemblyFileVersion("1.0.2")]
mit
C#
0420a64b6b39e70d7d538ac655a16a1cb6675309
Bump version to 0.6.6
ar3cka/Journalist
src/SolutionInfo.cs
src/SolutionInfo.cs
// <auto-generated/> using System.Reflection; [assembly: AssemblyProductAttribute("Journalist")] [assembly: AssemblyVersionAttribute("0.6.6")] [assembly: AssemblyInformationalVersionAttribute("0.6.6")] [assembly: AssemblyFileVersionAttribute("0.6.6")] [assembly: AssemblyCompanyAttribute("Anton Mednonogov")] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.6.6"; } }
// <auto-generated/> using System.Reflection; [assembly: AssemblyProductAttribute("Journalist")] [assembly: AssemblyVersionAttribute("0.6.5")] [assembly: AssemblyInformationalVersionAttribute("0.6.5")] [assembly: AssemblyFileVersionAttribute("0.6.5")] [assembly: AssemblyCompanyAttribute("Anton Mednonogov")] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.6.5"; } }
apache-2.0
C#
e93fef3c3dfded6bebc773537c01ad0a490cef6a
Test for NH-2559 (does not fail)
fredericDelaporte/nhibernate-core,nhibernate/nhibernate-core,lnu/nhibernate-core,fredericDelaporte/nhibernate-core,alobakov/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,nhibernate/nhibernate-core,gliljas/nhibernate-core,lnu/nhibernate-core,ngbrown/nhibernate-core,nkreipke/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,ManufacturingIntelligence/nhibernate-core,alobakov/nhibernate-core,nkreipke/nhibernate-core,livioc/nhibernate-core,hazzik/nhibernate-core,nkreipke/nhibernate-core,ManufacturingIntelligence/nhibernate-core,livioc/nhibernate-core,RogerKratz/nhibernate-core,hazzik/nhibernate-core,hazzik/nhibernate-core,ManufacturingIntelligence/nhibernate-core,RogerKratz/nhibernate-core,ngbrown/nhibernate-core,hazzik/nhibernate-core,RogerKratz/nhibernate-core,livioc/nhibernate-core,gliljas/nhibernate-core,lnu/nhibernate-core,alobakov/nhibernate-core,ngbrown/nhibernate-core,gliljas/nhibernate-core
src/NHibernate.Test/Linq/ByMethod/AnyTests.cs
src/NHibernate.Test/Linq/ByMethod/AnyTests.cs
using System.Linq; using NUnit.Framework; namespace NHibernate.Test.Linq.ByMethod { [TestFixture] public class AnyTests : LinqTestCase { [Test] public void AnySublist() { var orders = db.Orders.Where(o => o.OrderLines.Any(ol => ol.Quantity == 5)).ToList(); Assert.AreEqual(61, orders.Count); orders = db.Orders.Where(o => o.OrderLines.Any(ol => ol.Order == null)).ToList(); Assert.AreEqual(0, orders.Count); } [Test] public void NestedAny() { var test = (from c in db.Customers where c.ContactName == "Bob" && (c.CompanyName == "NormalooCorp" || c.Orders.Any(o => o.OrderLines.Any(ol => ol.Discount < 20 && ol.Discount >= 10))) select c).ToList(); Assert.AreEqual(0, test.Count); } [Test] public void ManyToManyAny() { var test = db.Orders.Where(o => o.Employee.FirstName == "test"); var result = test.Where(o => o.Employee.Territories.Any(t => t.Description == "test")).ToList(); Assert.AreEqual(0, result.Count); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; namespace NHibernate.Test.Linq.ByMethod { [TestFixture] public class AnyTests : LinqTestCase { [Test] public void AnySublist() { var orders = db.Orders.Where(o => o.OrderLines.Any(ol => ol.Quantity == 5)).ToList(); Assert.AreEqual(61, orders.Count); orders = db.Orders.Where(o => o.OrderLines.Any(ol => ol.Order == null)).ToList(); Assert.AreEqual(0, orders.Count); } [Test] public void NestedAny() { var test = (from c in db.Customers where c.ContactName == "Bob" && (c.CompanyName == "NormalooCorp" || c.Orders.Any(o => o.OrderLines.Any(ol => ol.Discount < 20 && ol.Discount >= 10))) select c).ToList(); Assert.AreEqual(0, test.Count); } } }
lgpl-2.1
C#
c2e526400ff8282fbb5f17f332f1b6f1603b517b
Use IActor instead of Actor in UsingIFrame action
Galad/tranquire,Galad/tranquire,Galad/tranquire
src/Tranquire.Selenium/Actions/UsingIFrame.cs
src/Tranquire.Selenium/Actions/UsingIFrame.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Tranquire.Selenium.Actions { /// <summary> /// Allow to switch to a frame and go back to the parent frame /// </summary> public class UsingIFrame { private IActor _actor; /// <summary> /// Creates a new instance of <see cref="UsingIFrame"/> /// </summary> /// <param name="actor">The actor used to retrieve the <see cref="BrowseTheWeb"/> ability</param> public UsingIFrame(IActor actor) { Guard.ForNull(actor, "actor"); _actor = actor; } /// <summary> /// Define the actor to use when switching to the frame /// </summary> /// <param name="actor"></param> /// <returns>A <see cref="UsingIFrame"/> object that can be used to switch to a frame</returns> public static UsingIFrame For(IActor actor) { return new UsingIFrame(actor); } /// <summary> /// Switch to the frame located by the given <see cref="ITarget"/> /// </summary> /// <param name="target">The target representing the frame to switch to</param> /// <returns>A <see cref="IDisposable"/> object. When it is disposed, the browser will go back to the parent frame.</returns> public IDisposable LocatedBy(ITarget target) { var driver = _actor.BrowseTheWeb(); driver.SwitchTo().Frame(target.ResolveFor(_actor)); return new Disposable(() => driver.SwitchTo().ParentFrame()); } private class Disposable : IDisposable { private System.Action _action; public Disposable(System.Action action) { _action = action; } public void Dispose() { if(_action == null) { return; } var action = Interlocked.Exchange(ref _action, null); action(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Tranquire.Selenium.Actions { /// <summary> /// Allow to switch to a frame and go back to the parent frame /// </summary> public class UsingIFrame { private Actor _actor; /// <summary> /// Creates a new instance of <see cref="UsingIFrame"/> /// </summary> /// <param name="actor">The actor used to retrieve the <see cref="BrowseTheWeb"/> ability</param> public UsingIFrame(Actor actor) { Guard.ForNull(actor, "actor"); _actor = actor; } /// <summary> /// Define the actor to use when switching to the frame /// </summary> /// <param name="actor"></param> /// <returns>A <see cref="UsingIFrame"/> object that can be used to switch to a frame</returns> public static UsingIFrame For(Actor actor) { return new UsingIFrame(actor); } /// <summary> /// Switch to the frame located by the given <see cref="ITarget"/> /// </summary> /// <param name="target">The target representing the frame to switch to</param> /// <returns>A <see cref="IDisposable"/> object. When it is disposed, the browser will go back to the parent frame.</returns> public IDisposable LocatedBy(ITarget target) { var driver = _actor.BrowseTheWeb(); driver.SwitchTo().Frame(target.ResolveFor(_actor)); return new Disposable(() => driver.SwitchTo().ParentFrame()); } private class Disposable : IDisposable { private System.Action _action; public Disposable(System.Action action) { _action = action; } public void Dispose() { if(_action == null) { return; } var action = Interlocked.Exchange(ref _action, null); action(); } } } }
mit
C#
599b96bc524e791e2ba6b212ec4b922c583426d9
bump version
northwoodspd/UIA.Extensions,northwoodspd/UIA.Extensions
src/UIA.Extensions/Properties/AssemblyInfo.cs
src/UIA.Extensions/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("UIA.Extensions")] [assembly: AssemblyDescription(".NET library to expose controls to Automation")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Northwoods Consulting Partners")] [assembly: AssemblyProduct("UIA.Extensions")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("ae10cb98-b115-42f8-9a9b-2e572c767ccf")] // 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.7.2")] [assembly: AssemblyFileVersion("1.0.7.2")] [assembly: InternalsVisibleTo("UIA.Extensions.Units,PublicKey=002400000480000094000000060200000024000052534131000400000100010083671eb3742e62" + "427388c9e512020d945fa7ba10b5a1605d534ec7504c89ec99571c3ab023c04733fb0b15eedd1c" + "270f62b8519ddf44b5ba2f8045dca32ab054946aafe2734637409d0723aa186376f7b8b3a603c5" + "c1f578f3938ce3fc0166647a2c44d1f964f3ef48025455dacfc4c1c808ea5c3faeb325fff0d771" + "bf0da19c")]
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("UIA.Extensions")] [assembly: AssemblyDescription(".NET library to expose controls to Automation")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Northwoods Consulting Partners")] [assembly: AssemblyProduct("UIA.Extensions")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("ae10cb98-b115-42f8-9a9b-2e572c767ccf")] // 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.7.1")] [assembly: AssemblyFileVersion("1.0.7.1")] [assembly: InternalsVisibleTo("UIA.Extensions.Units,PublicKey=002400000480000094000000060200000024000052534131000400000100010083671eb3742e62" + "427388c9e512020d945fa7ba10b5a1605d534ec7504c89ec99571c3ab023c04733fb0b15eedd1c" + "270f62b8519ddf44b5ba2f8045dca32ab054946aafe2734637409d0723aa186376f7b8b3a603c5" + "c1f578f3938ce3fc0166647a2c44d1f964f3ef48025455dacfc4c1c808ea5c3faeb325fff0d771" + "bf0da19c")]
mit
C#
7b72c0635cb2cdcf4410b8e2a087e1125b001a1b
Allow getting UpgradeConfiguration from UpgradeEngineBuilder
DbUp/DbUp
src/dbup-core/Builder/UpgradeEngineBuilder.cs
src/dbup-core/Builder/UpgradeEngineBuilder.cs
using System; using System.Collections.Generic; using DbUp.Engine; namespace DbUp.Builder { /// <summary> /// Builds a UpgradeEngine by accepting a list of callbacks to execute. For custom configuration, you should /// implement extension methods on top of this class. /// </summary> public class UpgradeEngineBuilder { readonly List<Action<UpgradeConfiguration>> callbacks = new List<Action<UpgradeConfiguration>>(); /// <summary> /// Adds a callback that will be run to configure the upgrader when Build is called. /// </summary> /// <param name="configuration">The configuration.</param> public void Configure(Action<UpgradeConfiguration> configuration) { callbacks.Add(configuration); } /// <summary> /// Creates an UpgradeConfiguration based on this configuration. /// </summary> /// <returns></returns> public UpgradeConfiguration BuildConfiguration() { var config = new UpgradeConfiguration(); foreach (var callback in callbacks) { callback(config); } config.Validate(); return config; } /// <summary> /// Creates an UpgradeEngine based on this configuration. /// </summary> /// <returns></returns> public UpgradeEngine Build() { var config = BuildConfiguration(); return new UpgradeEngine(config); } } }
using System; using System.Collections.Generic; using DbUp.Engine; namespace DbUp.Builder { /// <summary> /// Builds a UpgradeEngine by accepting a list of callbacks to execute. For custom configuration, you should /// implement extension methods on top of this class. /// </summary> public class UpgradeEngineBuilder { readonly List<Action<UpgradeConfiguration>> callbacks = new List<Action<UpgradeConfiguration>>(); /// <summary> /// Adds a callback that will be run to configure the upgrader when Build is called. /// </summary> /// <param name="configuration">The configuration.</param> public void Configure(Action<UpgradeConfiguration> configuration) { callbacks.Add(configuration); } /// <summary> /// Creates an UpgradeEngine based on this configuration. /// </summary> /// <returns></returns> public UpgradeEngine Build() { var config = new UpgradeConfiguration(); foreach (var callback in callbacks) { callback(config); } config.Validate(); return new UpgradeEngine(config); } } }
mit
C#
26b54fab3d60805d8ba682e26412df18b80a0d10
update removed
murst/Blogifier.Core,murst/Blogifier.Core,blogifierdotnet/Blogifier.Core,murst/Blogifier.Core,blogifierdotnet/Blogifier.Core
samples/WebApp/Views/Blogifier/Admin/Custom/_Shared/_about.cshtml
samples/WebApp/Views/Blogifier/Admin/Custom/_Shared/_about.cshtml
<div class="modal modal-sm" id="aboutBlogifier"> <div class="modal-overlay modal-close"></div> <div class="modal-body"> <div class="bf-about"> <img class="item-logo" src="/embedded/lib/img/logo.png" alt="Blogifier" /> <h2 class="item-title">Blogifier @Blogifier.Core.Common.ApplicationSettings.Version</h2> <p class="item-desc">This project provides blogging features to ASP.NET Core applications</p> <p class="item-desc item-copyright">Copyright &copy; @DateTime.Now.Year</p> <ul class="item-social"> <li><a href="https://github.com/blogifierdotnet/Blogifier.Core/" target="_blank"><i class="fa fa-github"></i></a></li> <li><a href="https://twitter.com/blogifierdotnet/" target="_blank"><i class="fa fa-twitter"></i></a></li> <li><a href="https://facebook.com/blogifierdotnet/" target="_blank"><i class="fa fa-facebook-square"></i></a></li> <li><a href="https://instagram.com/blogifierdotnet/" target="_blank"><i class="fa fa-instagram"></i></a></li> </ul> </div> </div> </div>
<div class="modal modal-sm" id="aboutBlogifier"> <div class="modal-overlay modal-close"></div> <div class="modal-body"> <div class="bf-about"> <img class="item-logo" src="/embedded/lib/img/logo.png" alt="Blogifier" /> <h2 class="item-title">Blogifier @Blogifier.Core.Common.ApplicationSettings.Version</h2> <p class="item-desc">This project provides blogging features to ASP.NET Core applications</p> <p class="item-desc item-copyright">Copyright &copy; @DateTime.Now.Year</p> <ul class="item-social"> <li><a href="https://github.com/blogifierdotnet/Blogifier.Core/" target="_blank"><i class="fa fa-github"></i></a></li> <li><a href="https://twitter.com/blogifierdotnet/" target="_blank"><i class="fa fa-twitter"></i></a></li> <li><a href="https://facebook.com/blogifierdotnet/" target="_blank"><i class="fa fa-facebook-square"></i></a></li> <li><a href="https://instagram.com/blogifierdotnet/" target="_blank"><i class="fa fa-instagram"></i></a></li> </ul> <div class="item-notify"> <a href="#">Update Your Blogifier!</a> </div> </div> </div> </div>
mit
C#
c7ef248a5ba8e6076a7c2412860edfa4d2b0221a
Update IArgbColor.cs
Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D/Model/Style/IArgbColor.cs
src/Core2D/Model/Style/IArgbColor.cs
 namespace Core2D.Style { /// <summary> /// Defines ARGB color contract. /// </summary> public interface IArgbColor : IColor, IStringExporter { /// <summary> /// Alpha color channel. /// </summary> byte A { get; set; } /// <summary> /// Red color channel. /// </summary> byte R { get; set; } /// <summary> /// Green color channel. /// </summary> byte G { get; set; } /// <summary> /// Blue color channel. /// </summary> byte B { get; set; } } }
 namespace Core2D.Style { /// <summary> /// Defines ARGB color contract. /// </summary> public interface IArgbColor : IColor { /// <summary> /// Alpha color channel. /// </summary> byte A { get; set; } /// <summary> /// Red color channel. /// </summary> byte R { get; set; } /// <summary> /// Green color channel. /// </summary> byte G { get; set; } /// <summary> /// Blue color channel. /// </summary> byte B { get; set; } } }
mit
C#
25ed491f8a37dad3dcfcc7484414276d4e7521a5
Add broken test to testproj
JetBrains/teamcity-dotmemory,JetBrains/teamcity-dotmemory
testproj/UnitTest1.cs
testproj/UnitTest1.cs
namespace testproj { using System; using System.Collections.Generic; using JetBrains.dotMemoryUnit; using NUnit.Framework; [TestFixture] public class UnitTest1 { [Test] public void TestMethod1() { var strs = new List<string>(); var memoryCheckPoint = dotMemory.Check(); strs.Add(GenStr()); strs.Add(GenStr()); strs.Add(GenStr()); dotMemory.Check( memory => { var strCount = memory .GetDifference(memoryCheckPoint) .GetNewObjects() .GetObjects(i => i.Type == typeof(string)) .ObjectsCount; Assert.LessOrEqual(strCount, 2); }); strs.Clear(); } [Test] public void TestMethod2() { var strs = new List<string>(); var memoryCheckPoint = dotMemory.Check(); strs.Add(GenStr()); strs.Add(GenStr()); dotMemory.Check( memory => { var strCount = memory .GetDifference(memoryCheckPoint) .GetNewObjects() .GetObjects(i => i.Type == typeof(string)) .ObjectsCount; Assert.LessOrEqual(strCount, 2); }); strs.Clear(); } private static string GenStr() { return Guid.NewGuid().ToString(); } } }
namespace testproj { using System; using JetBrains.dotMemoryUnit; using NUnit.Framework; [TestFixture] public class UnitTest1 { [Test] public void TestMethod1() { dotMemory.Check( memory => { var str1 = "1"; var str2 = "2"; var str3 = "3"; Assert.LessOrEqual(2, memory.ObjectsCount); Console.WriteLine(str1 + str2 + str3); }); } } }
apache-2.0
C#
3fde470e6ed03afa24414cf053479030035626a7
Remove steps from part 1 that have been moved to part 2.
JohnRush/File-Encryption-Tutorial
source/Tutorial01/Tutorial01.cs
source/Tutorial01/Tutorial01.cs
using System; using System.IO; using System.Security.Cryptography; namespace Tutorial { class Program { static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine("You must provide the name of a file to read and the name of a file to write."); return; } var sourceFilename = args[0]; var destinationFilename = args[1]; using (var sourceStream = File.OpenRead(sourceFilename)) using (var destinationStream = File.Create(destinationFilename)) using (var provider = new AesCryptoServiceProvider()) using (var cryptoTransform = provider.CreateEncryptor()) using (var cryptoStream = new CryptoStream(destinationStream, cryptoTransform, CryptoStreamMode.Write)) { sourceStream.CopyTo(cryptoStream); } } } }
using System; using System.IO; using System.Security.Cryptography; namespace Tutorial { class Program { static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine("You must provide the name of a file to read and the name of a file to write."); return; } var sourceFilename = args[0]; var destinationFilename = args[1]; using (var sourceStream = File.OpenRead(sourceFilename)) using (var destinationStream = File.Create(destinationFilename)) using (var provider = new AesCryptoServiceProvider()) using (var cryptoTransform = provider.CreateEncryptor()) using (var cryptoStream = new CryptoStream(destinationStream, cryptoTransform, CryptoStreamMode.Write)) { destinationStream.Write(provider.IV, 0, provider.IV.Length); sourceStream.CopyTo(cryptoStream); Console.WriteLine(System.Convert.ToBase64String(provider.Key)); } } } }
mit
C#
d535f5e06c4569027929d30a66674c6ecfd92b35
Remove a non-test 'test' accidentally added in revision 16233f163778.
BenJenkinson/nodatime,malcolmr/nodatime,jskeet/nodatime,zaccharles/nodatime,zaccharles/nodatime,zaccharles/nodatime,malcolmr/nodatime,malcolmr/nodatime,jskeet/nodatime,zaccharles/nodatime,nodatime/nodatime,malcolmr/nodatime,BenJenkinson/nodatime,nodatime/nodatime,zaccharles/nodatime,zaccharles/nodatime
src/NodaTime.Test/Calendars/HebrewEcclesiasticalCalculatorTest.cs
src/NodaTime.Test/Calendars/HebrewEcclesiasticalCalculatorTest.cs
// Copyright 2014 The Noda Time Authors. 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.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using NodaTime.Calendars; using NUnit.Framework; namespace NodaTime.Test.Calendars { [TestFixture] public class HebrewScripturalCalculatorTest { [Test] public void DaysInYear() { var bcl = new HebrewCalendar(); var minYear = bcl.GetYear(bcl.MinSupportedDateTime); var maxYear = bcl.GetYear(bcl.MaxSupportedDateTime); for (int year = minYear; year <= maxYear; year++) { Assert.AreEqual(bcl.GetDaysInYear(year), HebrewScripturalCalculator.DaysInYear(year)); } } [Test] public void DaysInMonth() { var bcl = new HebrewCalendar(); // Not all months in the min/max years are supported var minYear = bcl.GetYear(bcl.MinSupportedDateTime) + 1; var maxYear = bcl.GetYear(bcl.MaxSupportedDateTime) - 1; for (int year = minYear; year <= maxYear; year++) { int months = bcl.GetMonthsInYear(year); for (int month = 1; month <= months; month++) { int scripturalMonth = HebrewMonthConverter.CivilToScriptural(year, month); int bclDays = bcl.GetDaysInMonth(year, month); int nodaDays = HebrewScripturalCalculator.DaysInMonth(year, scripturalMonth); Assert.AreEqual(bclDays, nodaDays); } } } } }
// Copyright 2014 The Noda Time Authors. 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.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using NodaTime.Calendars; using NUnit.Framework; namespace NodaTime.Test.Calendars { [TestFixture] public class HebrewScripturalCalculatorTest { [Test] public void DaysInYear() { var bcl = new HebrewCalendar(); var minYear = bcl.GetYear(bcl.MinSupportedDateTime); var maxYear = bcl.GetYear(bcl.MaxSupportedDateTime); for (int year = minYear; year <= maxYear; year++) { Assert.AreEqual(bcl.GetDaysInYear(year), HebrewScripturalCalculator.DaysInYear(year)); } } [Test] public void DaysInMonth() { var bcl = new HebrewCalendar(); // Not all months in the min/max years are supported var minYear = bcl.GetYear(bcl.MinSupportedDateTime) + 1; var maxYear = bcl.GetYear(bcl.MaxSupportedDateTime) - 1; for (int year = minYear; year <= maxYear; year++) { int months = bcl.GetMonthsInYear(year); for (int month = 1; month <= months; month++) { int scripturalMonth = HebrewMonthConverter.CivilToScriptural(year, month); int bclDays = bcl.GetDaysInMonth(year, month); int nodaDays = HebrewScripturalCalculator.DaysInMonth(year, scripturalMonth); Assert.AreEqual(bclDays, nodaDays); } } } [Test] public void ElapsedDays() { Console.WriteLine(HebrewScripturalCalculator.ElapsedDays(1)); Console.WriteLine(HebrewScripturalCalculator.ElapsedDays(5730)); Console.WriteLine(HebrewScripturalCalculator.ElapsedDays(5731)); } } }
apache-2.0
C#
2508a910ab24fa303f992089b7ea467a41a174fe
Update MultipleRequest tests
pardahlman/RawRabbit,northspb/RawRabbit
src/RawRabbit.IntegrationTests/SimpleUse/MultipleRequestsTests.cs
src/RawRabbit.IntegrationTests/SimpleUse/MultipleRequestsTests.cs
using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using RawRabbit.Common; using RawRabbit.IntegrationTests.TestMessages; using RawRabbit.vNext; using Xunit; namespace RawRabbit.IntegrationTests.SimpleUse { public class MultipleRequestsTests { [Fact] public async void Should_Just_Work() { /* Setup */ const int numberOfCalls = 10000; var array = new Task[numberOfCalls]; var requester = BusClientFactory.CreateDefault(); var responder = BusClientFactory.CreateDefault(); responder.RespondAsync<FirstRequest, FirstResponse>((req, i) => Task.FromResult(new FirstResponse { Infered = Guid.NewGuid() }) ); /* Test */ var sw = new Stopwatch(); sw.Start(); for (var i = 0; i < numberOfCalls; i++) { var response = requester.RequestAsync<FirstRequest, FirstResponse>(); array[i] =response; } Task.WaitAll(array); sw.Stop(); var ids = array .OfType<Task<FirstResponse>>() .Select(b => b.Result.Infered) .Where(id => id != Guid.Empty) .Distinct() .ToList(); /* Assert */ Assert.Equal(numberOfCalls, ids.Count); } } }
using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using RawRabbit.Common; using RawRabbit.IntegrationTests.TestMessages; using RawRabbit.vNext; using Xunit; namespace RawRabbit.IntegrationTests.SimpleUse { public class MultipleRequestsTests { [Fact] public async void Should_Just_Work() { /* Setup */ const int numberOfCalls = 10000; var bag = new ConcurrentBag<Guid>(); var requester = BusClientFactory.CreateDefault(); var responder = BusClientFactory.CreateDefault(); responder.RespondAsync<FirstRequest, FirstResponse>((req, i) => Task.FromResult(new FirstResponse { Infered = Guid.NewGuid() }) ); /* Test */ var sw = new Stopwatch(); sw.Start(); for (var i = 0; i < numberOfCalls; i++) { var response = await requester.RequestAsync<FirstRequest, FirstResponse>(); bag.Add(response.Infered); } sw.Stop(); /* Assert */ Assert.Equal(numberOfCalls, bag.Count); } } }
mit
C#
d8bd2f0a7d6e3fd1895beb14f820ce43aa83689d
Fix the called parameter being incorrect
ppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework
osu.Framework.Tests/Primitives/TriangleTest.cs
osu.Framework.Tests/Primitives/TriangleTest.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Graphics.Primitives; using osuTK; using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace osu.Framework.Tests.Primitives { [TestFixture] class TriangleTest { [TestCaseSource(typeof(AreaTestData), nameof(AreaTestData.TestCases))] [DefaultFloatingPointTolerance(0.1f)] public float TestArea(Triangle testTriangle) => testTriangle.Area; private class AreaTestData { public static IEnumerable TestCases { get { // Point yield return new TestCaseData(new Triangle(Vector2.Zero, Vector2.Zero, Vector2.Zero)).Returns(0); // Angled yield return new TestCaseData(new Triangle(Vector2.Zero, new Vector2(10, 0), new Vector2(10))).Returns(50); yield return new TestCaseData(new Triangle(Vector2.Zero, new Vector2(0, 10), new Vector2(10))).Returns(50); yield return new TestCaseData(new Triangle(Vector2.Zero, new Vector2(10, -10), new Vector2(10))).Returns(100); yield return new TestCaseData(new Triangle(Vector2.Zero, new Vector2(10, -10), new Vector2(10))).Returns(100); } } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Graphics.Primitives; using osuTK; using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace osu.Framework.Tests.Primitives { [TestFixture] class TriangleTest { [TestCaseSource(typeof(AreaTestData), nameof(AreaTestData.TestCases))] [DefaultFloatingPointTolerance(0.1f)] public float TestArea(Triangle testTriangle) => testTriangle.AreaNew; private class AreaTestData { public static IEnumerable TestCases { get { // Point yield return new TestCaseData(new Triangle(Vector2.Zero, Vector2.Zero, Vector2.Zero)).Returns(0); // Angled yield return new TestCaseData(new Triangle(Vector2.Zero, new Vector2(10, 0), new Vector2(10))).Returns(50); yield return new TestCaseData(new Triangle(Vector2.Zero, new Vector2(0, 10), new Vector2(10))).Returns(50); yield return new TestCaseData(new Triangle(Vector2.Zero, new Vector2(10, -10), new Vector2(10))).Returns(100); yield return new TestCaseData(new Triangle(Vector2.Zero, new Vector2(10, -10), new Vector2(10))).Returns(100); } } } } }
mit
C#
329fae6450e772c1d36d4a248ccf0ecd1062d55c
Add marquee, logo and adjustments to IVideoManagement
xue-blood/wpfVlc,RickyGAkl/Vlc.DotNet,marcomeyer/Vlc.DotNet,someonehan/Vlc.DotNet,raydtang/Vlc.DotNet,RickyGAkl/Vlc.DotNet,briancowan/Vlc.DotNet,someonehan/Vlc.DotNet,thephez/Vlc.DotNet,agherardi/Vlc.DotNet,jeremyVignelles/Vlc.DotNet,agherardi/Vlc.DotNet,briancowan/Vlc.DotNet,marcomeyer/Vlc.DotNet,xue-blood/wpfVlc,thephez/Vlc.DotNet,raydtang/Vlc.DotNet,ZeBobo5/Vlc.DotNet
src/Vlc.DotNet.Core/IVideoManagement.cs
src/Vlc.DotNet.Core/IVideoManagement.cs
namespace Vlc.DotNet.Core { public interface IVideoManagement { string CropGeometry { get; set; } int Teletext { get; set; } ITracksManagement Tracks { get; } string Deinterlace { set; } IMarqueeManagement Marquee { get; } ILogoManagement Logo { get; } IAdjustmentsManagement Adjustments { get; } } }
namespace Vlc.DotNet.Core { public interface IVideoManagement { string CropGeometry { get; set; } int Teletext { get; set; } ITracksManagement Tracks { get; } string Deinterlace { set; } } }
mit
C#
2f61d93ea479ee09fb91c1ff2d899f2ffdcd5303
correct method name to "Recognition()"
myxini/block-program
block-program/Execution/BlockProgramExecuter.cs
block-program/Execution/BlockProgramExecuter.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Myxini.Execution { class BlockProgramExecuter : IBlockProgramExecuter { /// <summary> /// 通信するやつ /// </summary> private Communication.CommunicationService service; /// <summary> /// ホワイトボードを撮るカメラ /// </summary> private Recognition.Image.ICamera camera = new Recognition.Image.Kinect(); public BlockProgramExecuter(Communication.CommunicationService service) { this.service = service; } /// <summary> /// ホワイトボード上に構成されたプログラムを1回読んで実行する /// </summary> public void Execute() { // カメラでホワイトボードをパシャリ Recognition.Image.IImage image_whiteboard = camera.Capture(); // 写真からScriptを作る Recognition.Recognizer recognizer = new Recognition.Recognizer(); Recognition.Script script = recognizer.Recognition(image_whiteboard); // 通信するやつを使ってScriptを実行 service.Run(script); } /// <summary> /// 実行中のプログラムがあれば停止する /// </summary> public void Stop() { // 通信するやつを使って実行を停止 service.Stop(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Myxini.Execution { class BlockProgramExecuter : IBlockProgramExecuter { /// <summary> /// 通信するやつ /// </summary> private Communication.CommunicationService service; /// <summary> /// ホワイトボードを撮るカメラ /// </summary> private Recognition.Image.ICamera camera = new Recognition.Image.Kinect(); public BlockProgramExecuter(Communication.CommunicationService service) { this.service = service; } /// <summary> /// ホワイトボード上に構成されたプログラムを1回読んで実行する /// </summary> public void Execute() { // カメラでホワイトボードをパシャリ Recognition.Image.IImage image_whiteboard = camera.Capture(); // 写真からScriptを作る Recognition.Recognizer recognizer = new Recognition.Recognizer(); Recognition.Script script = recognizer.Recognize(image_whiteboard); // 通信するやつを使ってScriptを実行 service.Run(script); } /// <summary> /// 実行中のプログラムがあれば停止する /// </summary> public void Stop() { // 通信するやつを使って実行を停止 service.Stop(); } } }
mit
C#
645f9d529c2451211ec14260c518b9f32fb8adec
Make AddClasses() only include public classes
khellang/Scrutor
src/Scrutor/ImplementationTypeSelector.cs
src/Scrutor/ImplementationTypeSelector.cs
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.DependencyInjection; namespace Scrutor { internal class ImplementationTypeSelector : TypeSourceSelector, IImplementationTypeSelector, ISelector { protected ImplementationTypeSelector(IEnumerable<Type> types) { Types = types; } protected IEnumerable<Type> Types { get; } public IServiceTypeSelector AddClasses() { return AddClasses(publicOnly: true); } public IServiceTypeSelector AddClasses(bool publicOnly) { var classes = GetNonAbstractClasses(publicOnly); return AddSelector(classes); } public IServiceTypeSelector AddClasses(Action<IImplementationTypeFilter> action) { return AddClasses(action, publicOnly: false); } public IServiceTypeSelector AddClasses(Action<IImplementationTypeFilter> action, bool publicOnly) { Preconditions.NotNull(action, nameof(action)); var classes = GetNonAbstractClasses(publicOnly); var filter = new ImplementationTypeFilter(classes); action(filter); return AddSelector(filter.Types); } void ISelector.Populate(IServiceCollection services, RegistrationStrategy registrationStrategy) { if (Selectors.Count == 0) { AddClasses(); } foreach (var selector in Selectors) { selector.Populate(services, registrationStrategy); } } private IServiceTypeSelector AddSelector(IEnumerable<Type> types) { var selector = new ServiceTypeSelector(types); Selectors.Add(selector); return selector; } private IEnumerable<Type> GetNonAbstractClasses(bool publicOnly) { return Types.Where(t => t.IsNonAbstractClass(publicOnly)); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.DependencyInjection; namespace Scrutor { internal class ImplementationTypeSelector : TypeSourceSelector, IImplementationTypeSelector, ISelector { protected ImplementationTypeSelector(IEnumerable<Type> types) { Types = types; } protected IEnumerable<Type> Types { get; } public IServiceTypeSelector AddClasses() { return AddClasses(publicOnly: false); } public IServiceTypeSelector AddClasses(bool publicOnly) { var classes = GetNonAbstractClasses(publicOnly); return AddSelector(classes); } public IServiceTypeSelector AddClasses(Action<IImplementationTypeFilter> action) { return AddClasses(action, publicOnly: false); } public IServiceTypeSelector AddClasses(Action<IImplementationTypeFilter> action, bool publicOnly) { Preconditions.NotNull(action, nameof(action)); var classes = GetNonAbstractClasses(publicOnly); var filter = new ImplementationTypeFilter(classes); action(filter); return AddSelector(filter.Types); } void ISelector.Populate(IServiceCollection services, RegistrationStrategy registrationStrategy) { if (Selectors.Count == 0) { AddClasses(); } foreach (var selector in Selectors) { selector.Populate(services, registrationStrategy); } } private IServiceTypeSelector AddSelector(IEnumerable<Type> types) { var selector = new ServiceTypeSelector(types); Selectors.Add(selector); return selector; } private IEnumerable<Type> GetNonAbstractClasses(bool publicOnly) { return Types.Where(t => t.IsNonAbstractClass(publicOnly)); } } }
mit
C#
edccdfe968ca83e9c41ad44e2c78415137632589
add IsWindowsRuntimeType()
tibel/Weakly,huoxudong125/Weakly
src/Weakly/Reflection/ReflectionHelper.cs
src/Weakly/Reflection/ReflectionHelper.cs
using System; using System.Reflection; using System.Runtime.CompilerServices; namespace Weakly { /// <summary> /// Some useful helpers for <see cref="System.Reflection"/>. /// </summary> public static class ReflectionHelper { /// <summary> /// Determines whether the specified method is a lambda. /// </summary> /// <param name="methodInfo">The method to examine.</param> /// <returns>True, if the method is a lambda; otherwise false.</returns> public static bool IsLambda(this MethodInfo methodInfo) { return methodInfo.IsStatic && methodInfo.GetCustomAttribute<CompilerGeneratedAttribute>() != null; } /// <summary> /// Determines whether the specified method is closure. /// </summary> /// <param name="methodInfo">The method to examine.</param> /// <returns>True, if the method is a closure; otherwise false.</returns> public static bool IsClosure(this MethodInfo methodInfo) { return !methodInfo.IsStatic && methodInfo.DeclaringType.GetTypeInfo().GetCustomAttribute<CompilerGeneratedAttribute>() != null; } /// <summary> /// Determines whether the specified method is an async method. /// </summary> /// <param name="methodInfo">The method to examine.</param> /// <returns>True, if the method is an async method; otherwise false.</returns> public static bool IsAsync(this MethodInfo methodInfo) { return methodInfo.GetCustomAttribute<AsyncStateMachineAttribute>() != null; } /// <summary> /// Determines wether the specified type is a Windows Runtime Type. /// </summary> /// <param name="type">The type to examine.</param> /// <returns>True, if the type is a Windows Runtime Type; otherwise false.</returns> public static bool IsWindowsRuntimeType(this Type type) { return type != null && type.AssemblyQualifiedName.EndsWith("ContentType=WindowsRuntime", StringComparison.Ordinal); } } }
using System.Reflection; using System.Runtime.CompilerServices; namespace Weakly { /// <summary> /// Some useful helpers for <see cref="System.Reflection"/>. /// </summary> public static class ReflectionHelper { /// <summary> /// Determines whether the specified method is a lambda. /// </summary> /// <param name="methodInfo">The method to examine.</param> /// <returns>True, if the method is a lambda; otherwise false.</returns> public static bool IsLambda(this MethodInfo methodInfo) { return methodInfo.IsStatic && methodInfo.GetCustomAttribute<CompilerGeneratedAttribute>() != null; } /// <summary> /// Determines whether the specified method is closure. /// </summary> /// <param name="methodInfo">The method to examine.</param> /// <returns>True, if the method is a closure; otherwise false.</returns> public static bool IsClosure(this MethodInfo methodInfo) { return !methodInfo.IsStatic && methodInfo.DeclaringType.GetTypeInfo().GetCustomAttribute<CompilerGeneratedAttribute>() != null; } /// <summary> /// Determines whether the specified method is an async method. /// </summary> /// <param name="methodInfo">The method to examine.</param> /// <returns>True, if the method is an async method; otherwise false.</returns> public static bool IsAsync(this MethodInfo methodInfo) { return methodInfo.GetCustomAttribute<AsyncStateMachineAttribute>() != null; } } }
mit
C#
d918446c8a0e9964286cda45ce77f912c7259838
add static factory method
kreeben/resin,kreeben/resin
src/Sir.Store/AnalyzedString.cs
src/Sir.Store/AnalyzedString.cs
using System.Collections.Generic; namespace Sir { /// <summary> /// An analyzed (tokenized) string. /// </summary> public class AnalyzedString { public IList<(int offset, int length)> Tokens { get; private set; } public IList<SortedList<long, int>> Embeddings { get; private set; } public string Original { get; private set; } public AnalyzedString(IList<(int offset, int length)> tokens, IList<SortedList<long, int>> embeddings, string original) { Tokens = tokens; Embeddings = embeddings; Original = original; } public override string ToString() { return Original; } public static AnalyzedString AsSingleToken(string text) { var tokens = new List<(int, int)> { (0, text.Length) }; var vectors = new List<SortedList<long, int>> { text.ToVector(0, text.Length) }; return new AnalyzedString(tokens, vectors, text); } } }
using System.Collections.Generic; namespace Sir { /// <summary> /// An analyzed (tokenized) string. /// </summary> public class AnalyzedString { public IList<(int offset, int length)> Tokens { get; private set; } public IList<SortedList<long, int>> Embeddings { get; private set; } public string Original { get; private set; } public AnalyzedString(IList<(int offset, int length)> tokens, IList<SortedList<long, int>> embeddings, string original) { Tokens = tokens; Embeddings = embeddings; Original = original; } public override string ToString() { return Original; } } }
mit
C#
e0abd0b2c19d198b250c0c86a5003c5ceaaca1fe
fix comment
peppy/osu,ppy/osu,johnneijzen/osu,peppy/osu-new,ppy/osu,smoogipooo/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,EVAST9919/osu,NeoAdonis/osu,ZLima12/osu,NeoAdonis/osu,peppy/osu,ZLima12/osu,2yangk23/osu,UselessToucan/osu,johnneijzen/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,EVAST9919/osu,smoogipoo/osu,peppy/osu,2yangk23/osu
osu.Game/Rulesets/Mods/ModHidden.cs
osu.Game/Rulesets/Mods/ModHidden.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.Configuration; using osu.Game.Graphics; using osu.Game.Rulesets.Objects.Drawables; using System.Collections.Generic; using System.Linq; using osu.Framework.Bindables; using osu.Framework.Graphics.Sprites; using osu.Game.Rulesets.Scoring; using osu.Game.Scoring; namespace osu.Game.Rulesets.Mods { public abstract class ModHidden : Mod, IReadFromConfig, IApplicableToDrawableHitObjects, IApplicableToScoreProcessor { public override string Name => "Hidden"; public override string Acronym => "HD"; public override IconUsage Icon => OsuIcon.ModHidden; public override ModType Type => ModType.DifficultyIncrease; public override bool Ranked => true; protected Bindable<bool> IncreaseFirstObjectVisibility = new Bindable<bool>(); public void ReadFromConfig(OsuConfigManager config) { IncreaseFirstObjectVisibility = config.GetBindable<bool>(OsuSetting.IncreaseFirstObjectVisibility); } public virtual void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables) { foreach (var d in drawables.Skip(IncreaseFirstObjectVisibility.Value ? 1 : 0)) d.ApplyCustomUpdateState += ApplyHiddenState; } public void ApplyToScoreProcessor(ScoreProcessor scoreProcessor) { // Default value of ScoreProcessor's Rank in Hidden Mod should be SS+ scoreProcessor.Rank.Value = ScoreRank.XH; } public ScoreRank AdjustRank(ScoreRank rank, double accuracy) { switch (rank) { case ScoreRank.X: return ScoreRank.XH; case ScoreRank.S: return ScoreRank.SH; default: return rank; } } protected virtual void ApplyHiddenState(DrawableHitObject hitObject, ArmedState state) { } } }
// 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.Configuration; using osu.Game.Graphics; using osu.Game.Rulesets.Objects.Drawables; using System.Collections.Generic; using System.Linq; using osu.Framework.Bindables; using osu.Framework.Graphics.Sprites; using osu.Game.Rulesets.Scoring; using osu.Game.Scoring; namespace osu.Game.Rulesets.Mods { public abstract class ModHidden : Mod, IReadFromConfig, IApplicableToDrawableHitObjects, IApplicableToScoreProcessor { public override string Name => "Hidden"; public override string Acronym => "HD"; public override IconUsage Icon => OsuIcon.ModHidden; public override ModType Type => ModType.DifficultyIncrease; public override bool Ranked => true; protected Bindable<bool> IncreaseFirstObjectVisibility = new Bindable<bool>(); public void ReadFromConfig(OsuConfigManager config) { IncreaseFirstObjectVisibility = config.GetBindable<bool>(OsuSetting.IncreaseFirstObjectVisibility); } public virtual void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables) { foreach (var d in drawables.Skip(IncreaseFirstObjectVisibility.Value ? 1 : 0)) d.ApplyCustomUpdateState += ApplyHiddenState; } public void ApplyToScoreProcessor(ScoreProcessor scoreProcessor) { // Default value of <see ScoreProcessor's Rank in Hidden Mod should be SS+ scoreProcessor.Rank.Value = ScoreRank.XH; } public ScoreRank AdjustRank(ScoreRank rank, double accuracy) { switch (rank) { case ScoreRank.X: return ScoreRank.XH; case ScoreRank.S: return ScoreRank.SH; default: return rank; } } protected virtual void ApplyHiddenState(DrawableHitObject hitObject, ArmedState state) { } } }
mit
C#
089736a01378dff4d5251aafa4fcd7104fa52f6b
Update Trooper.cs (#29)
BosslandGmbH/BuddyWing.DefaultCombat
trunk/DefaultCombat/Routines/Basic/Trooper.cs
trunk/DefaultCombat/Routines/Basic/Trooper.cs
// Copyright (C) 2011-2016 Bossland GmbH // See the file LICENSE for the source code's detailed license using Buddy.BehaviorTree; using DefaultCombat.Core; using DefaultCombat.Helpers; namespace DefaultCombat.Routines { public class Trooper : RotationBase { public override string Name { get { return "Basic Trooper"; } } public override Composite Buffs { get { return new PrioritySelector( Spell.Buff("Fortification") ); } } public override Composite Cooldowns { get { return new PrioritySelector(); } } public override Composite SingleTarget { get { return new PrioritySelector( CombatMovement.CloseDistance(Distance.Ranged), Spell.Cast("High Impact Bolt"), Spell.Cast("Ion Pulse", ret => Me.ResourcePercent() >= 50), Spell.Cast("Hammer Shot") ); } } public override Composite AreaOfEffect { get { return new Decorator(ret => Targeting.ShouldAoe, new PrioritySelector()); } } } }
// Copyright (C) 2011-2016 Bossland GmbH // See the file LICENSE for the source code's detailed license using Buddy.BehaviorTree; using DefaultCombat.Core; using DefaultCombat.Helpers; namespace DefaultCombat.Routines { public class Trooper : RotationBase { public override string Name { get { return "Basic Trooper"; } } public override Composite Buffs { get { return new PrioritySelector( Spell.Buff("Fortification") ); } } public override Composite Cooldowns { get { return new PrioritySelector(); } } public override Composite SingleTarget { get { return new PrioritySelector( CombatMovement.CloseDistance(Distance.Ranged), Spell.Cast("Sticky Grenade"), Spell.CastOnGround("Mortar Volley", ret => Me.CurrentTarget.Distance > .5f), Spell.Cast("High Impact Bolt"), Spell.Cast("Recharge Cells", ret => Me.ResourcePercent() <= 50), Spell.Cast("Stockstrike", ret => Me.CurrentTarget.Distance <= .4f), Spell.Cast("Pulse Cannon", ret => Me.CurrentTarget.Distance <= 1f), Spell.Cast("Ion Pulse", ret => Me.ResourcePercent() >= 50), Spell.Cast("Hammer Shot") ); } } public override Composite AreaOfEffect { get { return new Decorator(ret => Targeting.ShouldAoe, new PrioritySelector()); } } } }
apache-2.0
C#
cd13787bd95654f227218e1a53789d099b3bde56
implement IsDirty interface (unused) for shell document tabs.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/ViewModels/WasabiDocumentTabViewModel.cs
WalletWasabi.Gui/ViewModels/WasabiDocumentTabViewModel.cs
using AvalonStudio.Documents; using AvalonStudio.Extensibility; using AvalonStudio.Shell; using Dock.Model; using ReactiveUI; namespace WalletWasabi.Gui.ViewModels { public abstract class WasabiDocumentTabViewModel : ViewModelBase, IDocumentTabViewModel { public WasabiDocumentTabViewModel(string title) { Title = title; } public WasabiDocumentTabViewModel() { } public string Id { get; set; } public virtual string Title { get; set; } public object Context { get; set; } public double Width { get; set; } public double Height { get; set; } public IView Parent { get; set; } private bool _isSelected; public bool IsSelected { get { return _isSelected; } set { this.RaiseAndSetIfChanged(ref _isSelected, value); } } public bool IsDirty { get; set; } public virtual void Close() { IoC.Get<IShell>().RemoveDocument(this); IsSelected = false; } public virtual void OnSelected() { IsSelected = true; } public virtual void OnDeselected() { IsSelected = false; } public bool OnClose() { return false; } } }
using AvalonStudio.Documents; using AvalonStudio.Extensibility; using AvalonStudio.Shell; using Dock.Model; using ReactiveUI; namespace WalletWasabi.Gui.ViewModels { public abstract class WasabiDocumentTabViewModel : ViewModelBase, IDocumentTabViewModel { public WasabiDocumentTabViewModel(string title) { Title = title; } public WasabiDocumentTabViewModel() { } public string Id { get; set; } public virtual string Title { get; set; } public object Context { get; set; } public double Width { get; set; } public double Height { get; set; } public IView Parent { get; set; } private bool _isSelected; public bool IsSelected { get { return _isSelected; } set { this.RaiseAndSetIfChanged(ref _isSelected, value); } } public virtual void Close() { IoC.Get<IShell>().RemoveDocument(this); this.IsSelected = false; } public virtual void OnSelected() { this.IsSelected = true; } public virtual void OnDeselected() { this.IsSelected = false; } } }
mit
C#
4ad8664d13d7c7bcf91d6bd9b3d121ce09414a2b
Fix code to return LanguageCode not CountryCode
AlexStefan/template-app
Internationalization/Internationalization.Touch/Helpers/AppInfo.cs
Internationalization/Internationalization.Touch/Helpers/AppInfo.cs
using Foundation; using Internationalization.Core.Helpers; namespace Internationalization.Touch.Helpers { public class AppInfo : IAppInfo { public string CurrentLanguage { get { return NSLocale.CurrentLocale.LanguageCode.ToLower(); } } } }
using Foundation; using Internationalization.Core.Helpers; namespace Internationalization.Touch.Helpers { public class AppInfo : IAppInfo { public string CurrentLanguage => NSLocale.CurrentLocale.CountryCode.ToLower(); } }
mit
C#
90bb401978d4d3ae0dc9a149361d2d82a0f195ad
Update SqlExpressionBuilder.cs
PowerMogli/Rabbit.Db
src/RabbitDB/Expression/SqlExpressionBuilder.cs
src/RabbitDB/Expression/SqlExpressionBuilder.cs
using System; using System.Data.SqlClient; using System.Linq.Expressions; using System.Text; using RabbitDB.Mapping; using RabbitDB.Storage; namespace RabbitDB.Expressions { internal class SqlExpressionBuilder<T> { private readonly IDbProvider _dbProvider; private readonly TableInfo _tableInfo; private readonly StringBuilder _sqlBuilder = new StringBuilder(); private readonly ExpressionWriter<T> _expressionWriter; internal SqlExpressionBuilder(IDbProvider dbProvider) { _dbProvider = dbProvider; _tableInfo = TableInfo<T>.GetTableInfo; _expressionWriter = new ExpressionWriter<T>(dbProvider.BuilderHelper, this.Parameters); } private static string SortToString(SortOrder sort) { return sort == SortOrder.Descending ? "desc" : "asc"; } internal SqlExpressionBuilder<T> OrderBy(Expression<Func<T, object>> selector, SortOrder sort = SortOrder.Ascending) { if (_order) { _sqlBuilder.Append(", "); } else { _sqlBuilder.Append(" order by "); } var column = selector.Body.GetPropertyName(); _sqlBuilder.AppendFormat("{0} {1}", _dbProvider.EscapeName(column), SortToString(sort)); _order = true; return this; } internal void Append(string text) { _sqlBuilder.Append(text); } internal SqlExpressionBuilder<T> WriteSelectColumn<R>(Expression<Func<T, R>> selector, string alias = null) { var name = selector.Body.GetPropertyName(); if (_hasColumn) { _sqlBuilder.Append(", "); } _sqlBuilder.Append(_dbProvider.EscapeName(_tableInfo.ResolveColumnName(name))); _hasColumn = true; if (alias != null) { _sqlBuilder.AppendFormat(" as {0}", alias); } return this; } private bool _where; private bool _hasColumn; private bool _order; internal SqlExpressionBuilder<T> Where(Expression<Func<T, bool>> criteria) { if (!_where) { _sqlBuilder.Append(" where "); _where = true; } else { _sqlBuilder.Append(" and "); } Write(criteria); return this; } internal void CreateSelect(Expression<Func<T, bool>> criteria) { WriteSelectAllColumns(); Write(criteria); } private void WriteSelectAllColumns() { _sqlBuilder.Append(_tableInfo.GetBaseSelect(_dbProvider)); } internal void Write(Expression<Func<T, bool>> criteria) { _sqlBuilder.Append(_expressionWriter.Write(criteria)); } internal void Write(Expression<Func<T, object>> statement) { _sqlBuilder.Append(_expressionWriter.Write(statement)); } internal ExpressionParameterCollection Parameters { get; private set; } public override string ToString() { return _sqlBuilder.ToString(); } } }
using System; using System.Linq.Expressions; using System.Text; using RabbitDB.Mapping; namespace RabbitDB.Expressions { internal class ExpressionSqlBuilder<T> { } }
apache-2.0
C#
bdd2753fb11cc7472f60ff6b97b30401a6919d53
Bump webapi from 5.2.0 to 5.2.1
Brightspace/D2L.Security.OAuth2
src/D2L.Security.OAuth2.WebApi/Properties/AssemblyInfo.cs
src/D2L.Security.OAuth2.WebApi/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle( "D2L.Security.WebApi" )] [assembly: AssemblyDescription( "A library that implements Web API components for authenticating D2L services." )] [assembly: AssemblyCompany( "Desire2Learn" )] [assembly: AssemblyProduct( "Brightspace" )] [assembly: AssemblyInformationalVersion( "5.2.1.0" )] [assembly: AssemblyVersion( "5.2.1.0" )] [assembly: AssemblyFileVersion( "5.2.1.0" )] [assembly: AssemblyCopyright( "Copyright © Desire2Learn" )] [assembly: InternalsVisibleTo( "D2L.Security.OAuth2.WebApi.UnitTests" )] [assembly: InternalsVisibleTo( "D2L.Security.OAuth2.WebApi.IntegrationTests" )]
using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle( "D2L.Security.WebApi" )] [assembly: AssemblyDescription( "A library that implements Web API components for authenticating D2L services." )] [assembly: AssemblyCompany( "Desire2Learn" )] [assembly: AssemblyProduct( "Brightspace" )] [assembly: AssemblyInformationalVersion( "5.2.0.0" )] [assembly: AssemblyVersion( "5.2.0.0" )] [assembly: AssemblyFileVersion( "5.2.0.0" )] [assembly: AssemblyCopyright( "Copyright © Desire2Learn" )] [assembly: InternalsVisibleTo( "D2L.Security.OAuth2.WebApi.UnitTests" )] [assembly: InternalsVisibleTo( "D2L.Security.OAuth2.WebApi.IntegrationTests" )]
apache-2.0
C#
2a0cd5785e7ae9318f39ade9a86bcfadfde9782f
Add missing documentation for CloudEventAdapter
GoogleCloudPlatform/functions-framework-dotnet,GoogleCloudPlatform/functions-framework-dotnet
src/Google.Cloud.Functions.Framework/CloudEventAdapter.cs
src/Google.Cloud.Functions.Framework/CloudEventAdapter.cs
// Copyright 2020, Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Microsoft.AspNetCore.Http; using System.Threading.Tasks; using CloudNative.CloudEvents; using System.Diagnostics.CodeAnalysis; namespace Google.Cloud.Functions.Framework { /// <summary> /// An adapter to implement an HTTP Function based on a Cloud Event Function. /// </summary> public sealed class CloudEventAdapter : IHttpFunction { private readonly ICloudEventFunction _function; /// <summary> /// Constructs a new instance based on the given Cloud Event Function. /// </summary> /// <param name="function">The Cloud Event Function to invoke.</param> public CloudEventAdapter(ICloudEventFunction function) => _function = Preconditions.CheckNotNull(function, nameof(function)); /// <summary> /// Handles an HTTP request by extracting the Cloud Event from it and passing it to the /// original Cloud Event Function. The request fails if it does not contain a Cloud Event. /// </summary> /// <param name="context">The HTTP context containing the request and response.</param> /// <returns>A task representing the asynchronous operation.</returns> public async Task HandleAsync(HttpContext context) { var cloudEvent = await context.Request.ReadCloudEventAsync(); // Note: ReadCloudEventAsync appears never to actually return null as it's documented to. // Instead, we use the presence of properties required by the spec to determine validity. if (!IsValidEvent(cloudEvent)) { context.Response.StatusCode = 400; await context.Response.WriteAsync("Request is expected to contain a Cloud Event.", context.RequestAborted); return; } await _function.HandleAsync(cloudEvent); } private static bool IsValidEvent([NotNullWhen(true)] CloudEvent? cloudEvent) => cloudEvent is object && !string.IsNullOrEmpty(cloudEvent.Id) && cloudEvent.Source is object && !string.IsNullOrEmpty(cloudEvent.Type); } }
// Copyright 2020, Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Microsoft.AspNetCore.Http; using System.Threading.Tasks; using CloudNative.CloudEvents; using System.Diagnostics.CodeAnalysis; namespace Google.Cloud.Functions.Framework { /// <summary> /// An adapter to implement an HTTP Function based on a Cloud Event Function. /// </summary> public sealed class CloudEventAdapter : IHttpFunction { private readonly ICloudEventFunction _function; /// <summary> /// Constructs a new instance based on the given Cloud Event Function. /// </summary> /// <param name="function">The Cloud Event Function to invoke.</param> public CloudEventAdapter(ICloudEventFunction function) => _function = Preconditions.CheckNotNull(function, nameof(function)); /// <summary> /// Handles an HTTP request by extracting the Cloud Event from it and passing it to the /// original Cloud Event Function. The request fails if it does not contain a Cloud Event. /// </summary> /// <param name="context">The HTTP context containing the request and response.</param> /// <returns></returns> public async Task HandleAsync(HttpContext context) { var cloudEvent = await context.Request.ReadCloudEventAsync(); // Note: ReadCloudEventAsync appears never to actually return null as it's documented to. // Instead, we use the presence of properties required by the spec to determine validity. if (!IsValidEvent(cloudEvent)) { context.Response.StatusCode = 400; await context.Response.WriteAsync("Request is expected to contain a Cloud Event.", context.RequestAborted); return; } await _function.HandleAsync(cloudEvent); } private static bool IsValidEvent([NotNullWhen(true)] CloudEvent? cloudEvent) => cloudEvent is object && !string.IsNullOrEmpty(cloudEvent.Id) && cloudEvent.Source is object && !string.IsNullOrEmpty(cloudEvent.Type); } }
apache-2.0
C#
fa3f6bb52f4f780b6f4db5e70f423790c4cce5e7
Send SSDP UDP Packets out on all external IPs explicitly
itamar82/simpleDLNA,antonio-bakula/simpleDLNA,bra1nb3am3r/simpleDLNA,nmaier/simpleDLNA
server/Ssdp/Datagram.cs
server/Ssdp/Datagram.cs
using System; using System.Net; using System.Net.Sockets; using System.Text; using NMaier.SimpleDlna.Utilities; namespace NMaier.SimpleDlna.Server.Ssdp { internal sealed class Datagram : Logging { public readonly IPEndPoint EndPoint; public readonly string Message; public readonly bool Sticky; public Datagram(IPEndPoint aEndPoint, string aMessage, bool sticky) { EndPoint = aEndPoint; Message = aMessage; Sticky = sticky; SendCount = 0; } public uint SendCount { get; private set; } public void Send(int port) { var msg = Encoding.ASCII.GetBytes(Message); foreach (var external in IP.ExternalAddresses) { try { var client = new UdpClient(new IPEndPoint(external, port)); client.BeginSend(msg, msg.Length, EndPoint, SendCallback, client); } catch (Exception ex) { Error(ex); } } ++SendCount; } private void SendCallback(IAsyncResult result) { using (var client = result.AsyncState as UdpClient) { try { client.EndSend(result); } catch (Exception ex) { Error(ex); } } } } }
using System.Net; using System.Net.Sockets; using System.Text; namespace NMaier.SimpleDlna.Server.Ssdp { internal sealed class Datagram { public readonly IPEndPoint EndPoint; public readonly string Message; public readonly bool Sticky; public Datagram(IPEndPoint aEndPoint, string aMessage, bool sticky) { EndPoint = aEndPoint; Message = aMessage; Sticky = sticky; SendCount = 0; } public uint SendCount { get; private set; } public void Send(int port) { using (var udp = new UdpClient(port, AddressFamily.InterNetwork)) { var msg = Encoding.ASCII.GetBytes(Message); udp.Send(msg, msg.Length, EndPoint); } ++SendCount; } } }
bsd-2-clause
C#
78a2c86f8258d31e501d623cf16c1ee09e5deb62
설정 변경시 기존 스크린샷 폴더 경로를 반영하여 보여줌
FreyYa/GranBlueHelper
GranBlueHelper/ViewModels/SettingsViewModel.cs
GranBlueHelper/ViewModels/SettingsViewModel.cs
using Grandcypher; using Livet; using Livet.Messaging; using GranBlueHelper.Models; using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Threading; using System.Windows; namespace GranBlueHelper.ViewModels { public class SettingsViewModel : ViewModel { #region Fiddler On/Off 스위치 private bool _StartFiddler; public bool StartFiddler { get { return this._StartFiddler; } set { if (this._StartFiddler != value) { this._StartFiddler = value; this.RaisePropertyChanged(); } } } private bool _StopFiddler; public bool StopFiddler { get { return this._StopFiddler; } set { if (this._StopFiddler != value) { this._StopFiddler = value; this.RaisePropertyChanged(); } } } #endregion public SettingsViewModel() { StartFiddler = false; StopFiddler = true; } public void SetScreenShotFolder() { string output; if (Settings.Current.ScreenShotFolder == "") output = "기본 사진 폴더"; else output = Settings.Current.ScreenShotFolder; System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog(); dialog.Description = "스크린샷을 저장할 폴더를 선택해주세요.\n현재폴더: " + output; dialog.ShowNewFolderButton = true; dialog.SelectedPath = Settings.Current.ScreenShotFolder; dialog.ShowDialog(); string selected = dialog.SelectedPath; Settings.Current.ScreenShotFolder = selected; } public void Startup() { StartFiddler = false; StopFiddler = true; GrandcypherClient.Current.Proxy.StartUp(Settings.Current.portNum); GrandcypherClient.Current.PostMan("FiddlerCore 작동시작. Port: " + Settings.Current.portNum.ToString()); } public void Shutdown() { StopFiddler = false; StartFiddler = true; GrandcypherClient.Current.Proxy.Quit(); GrandcypherClient.Current.PostMan("FiddlerCore 작동중지"); } } }
using Grandcypher; using Livet; using Livet.Messaging; using GranBlueHelper.Models; using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Threading; using System.Windows; namespace GranBlueHelper.ViewModels { public class SettingsViewModel : ViewModel { #region Fiddler On/Off 스위치 private bool _StartFiddler; public bool StartFiddler { get { return this._StartFiddler; } set { if (this._StartFiddler != value) { this._StartFiddler = value; this.RaisePropertyChanged(); } } } private bool _StopFiddler; public bool StopFiddler { get { return this._StopFiddler; } set { if (this._StopFiddler != value) { this._StopFiddler = value; this.RaisePropertyChanged(); } } } #endregion public SettingsViewModel() { StartFiddler = false; StopFiddler = true; } public void SetScreenShotFolder() { string output; if (Settings.Current.ScreenShotFolder == "") output = "기본 사진 폴더"; else output = Settings.Current.ScreenShotFolder; System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog(); dialog.Description = "스크린샷을 저장할 폴더를 선택해주세요.\n현재폴더: " + output; dialog.ShowNewFolderButton = false; dialog.ShowDialog(); string selected = dialog.SelectedPath; Settings.Current.ScreenShotFolder = selected; } public void Startup() { StartFiddler = false; StopFiddler = true; GrandcypherClient.Current.Proxy.StartUp(Settings.Current.portNum); GrandcypherClient.Current.PostMan("FiddlerCore 작동시작. Port: " + Settings.Current.portNum.ToString()); } public void Shutdown() { StopFiddler = false; StartFiddler = true; GrandcypherClient.Current.Proxy.Quit(); GrandcypherClient.Current.PostMan("FiddlerCore 작동중지"); } } }
mit
C#
b9628dffcf7001f47970fa17621937ee565f0960
Bump version
o11c/WebMConverter,nixxquality/WebMConverter,Yuisbean/WebMConverter
Properties/AssemblyInfo.cs
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("WebM for Retards")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebM for Retards")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")] // 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("2.16.6")]
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("WebM for Retards")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebM for Retards")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")] // 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("2.16.5")]
mit
C#
b055f32e075e05919a614b4b13d84a9ba4b47d6b
Fix test
Cyberboss/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server
tests/Tgstation.Server.Host.Tests/Core/TestApplication.cs
tests/Tgstation.Server.Host.Tests/Core/TestApplication.cs
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Tgstation.Server.Host.IO; namespace Tgstation.Server.Host.Core.Tests { [TestClass] public sealed class TestApplication : IServerControl { public Task<bool> ApplyUpdate(byte[] updateZipData, IIOManager ioManager, CancellationToken cancellationToken) => throw new NotImplementedException(); public void RegisterForRestart(Action action) { } public bool Restart() => throw new NotImplementedException(); [TestMethod] public async Task TestSuccessfulStartup() { var dbName = Path.GetTempFileName(); try { using (var webHost = WebHost.CreateDefaultBuilder(new string[] { "Database:DatabaseType=Sqlite", "Database:ConnectionString=Data Source=" + dbName }) //force it to use sqlite .UseStartup<Application>() .ConfigureServices((serviceCollection) => serviceCollection.AddSingleton<IServerControl>(this)) .Build() ) { await webHost.StartAsync().ConfigureAwait(false); await webHost.StopAsync().ConfigureAwait(false); } } finally { File.Delete(dbName); } } } }
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Tgstation.Server.Host.IO; namespace Tgstation.Server.Host.Core.Tests { [TestClass] public sealed class TestApplication : IServerControl { public Task<bool> ApplyUpdate(byte[] updateZipData, IIOManager ioManager, CancellationToken cancellationToken) => throw new NotImplementedException(); public void RegisterForRestart(Action action) => throw new NotImplementedException(); public bool Restart() => throw new NotImplementedException(); [TestMethod] public async Task TestSuccessfulStartup() { var dbName = Path.GetTempFileName(); try { using (var webHost = WebHost.CreateDefaultBuilder(new string[] { "Database:DatabaseType=Sqlite", "Database:ConnectionString=Data Source=" + dbName }) //force it to use sqlite .UseStartup<Application>() .ConfigureServices((serviceCollection) => serviceCollection.AddSingleton<IServerControl>(this)) .Build() ) { await webHost.StartAsync().ConfigureAwait(false); await webHost.StopAsync().ConfigureAwait(false); } } finally { File.Delete(dbName); } } } }
agpl-3.0
C#
17d0839620fe5d6dc412339be3517e2e77395a83
Fix for Issue #1562 (#1563)
exercism/xcsharp,exercism/xcsharp
exercises/practice/robot-name/RobotNameTests.cs
exercises/practice/robot-name/RobotNameTests.cs
using System.Collections.Generic; using Xunit; public class RobotNameTests { private readonly Robot robot = new Robot(); [Fact] public void Robot_has_a_name() { Assert.Matches(@"^[A-Z]{2}\d{3}$", robot.Name); } [Fact(Skip = "Remove this Skip property to run this test")] public void Name_is_the_same_each_time() { Assert.Equal(robot.Name, robot.Name); } [Fact(Skip = "Remove this Skip property to run this test")] public void Different_robots_have_different_names() { var robot2 = new Robot(); Assert.NotEqual(robot2.Name, robot.Name); } [Fact(Skip = "Remove this Skip property to run this test")] public void Can_reset_the_name() { var originalName = robot.Name; robot.Reset(); Assert.NotEqual(originalName, robot.Name); } [Fact(Skip = "Remove this Skip property to run this test")] public void After_reset_the_name_is_valid() { robot.Reset(); Assert.Matches(@"^[A-Z]{2}\d{3}$", robot.Name); } [Fact(Skip = "Remove this Skip property to run this test")] public void Robot_names_are_unique() { const int robotsCount = 10_000; var robots = new List<Robot>(robotsCount); // Needed to keep a reference to the robots as IDs of recycled robots may be re-issued var names = new HashSet<string>(robotsCount); for (int i = 0; i < robotsCount; i++) { var robot = new Robot(); robots.Add(robot); Assert.True(names.Add(robot.Name)); Assert.Matches(@"^[A-Z]{2}\d{3}$", robot.Name); } } }
using System.Collections.Generic; using Xunit; public class RobotNameTests { private readonly Robot robot = new Robot(); [Fact] public void Robot_has_a_name() { Assert.Matches(@"^[A-Z]{2}\d{3}$", robot.Name); } [Fact(Skip = "Remove this Skip property to run this test")] public void Name_is_the_same_each_time() { Assert.Equal(robot.Name, robot.Name); } [Fact(Skip = "Remove this Skip property to run this test")] public void Different_robots_have_different_names() { var robot2 = new Robot(); Assert.NotEqual(robot2.Name, robot.Name); } [Fact(Skip = "Remove this Skip property to run this test")] public void Can_reset_the_name() { var originalName = robot.Name; robot.Reset(); Assert.NotEqual(originalName, robot.Name); } [Fact(Skip = "Remove this Skip property to run this test")] public void After_reset_the_name_is_valid() { robot.Reset(); Assert.Matches(@"^[A-Z]{2}\d{3}$", robot.Name); } [Fact(Skip = "Remove this Skip property to run this test")] public void Robot_names_are_unique() { var names = new HashSet<string>(); for (int i = 0; i < 10_000; i++) { var robot = new Robot(); Assert.True(names.Add(robot.Name)); Assert.Matches(@"^[A-Z]{2}\d{3}$", robot.Name); } } }
mit
C#
545697031f285fc6f54f39d59fdccea0d4907397
Update ShoppingList.cs
SW3-P3/ProjectFood,SW3-P3/ProjectFood
ProjectFood/ProjectFood/Models/ShoppingList.cs
ProjectFood/ProjectFood/Models/ShoppingList.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity; namespace ProjectFood.Models { public class ShoppingList { public int ID { get; set; } public string Title { get; set; } public ICollection<Item> Items { get; set;} public ShoppingList() { Items = new List<Item>(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity; namespace ProjectFood.Models { public class ShoppingList { public int ID { get; set; } public string Title { get; set; } public ICollection<Item> Items { get; set;} public ShoppingList() { Items = new List<Item>(); //Items.Add(new Item("Havregryn")); } } }
mit
C#
3ca96d21756543eebe285e4a8ef1ecc5da84fbf5
Fix Environment class logic
escamilla/squirrel
squirrel/Environment.cs
squirrel/Environment.cs
using System.Collections.Generic; namespace squirrel { public class Environment { private readonly Environment _parent; private readonly Dictionary<string, AstNode> _definitions = new Dictionary<string, AstNode>(); public Environment(Environment parent) { _parent = parent; } public Environment() : this(null) { } public void Put(string key, AstNode value) => _definitions.Add(key, value); public AstNode? Get(string key) { if (_parent == null) { return GetShallow(key); } return GetShallow(key) ?? _parent.Get(key); } private AstNode? GetShallow(string key) { if (_definitions.ContainsKey(key)) { return _definitions[key]; } return null; } } }
using System.Collections.Generic; namespace squirrel { public class Environment { private readonly Environment _parent; private readonly Dictionary<string, AstNode> _definitions = new Dictionary<string, AstNode>(); public Environment(Environment parent) { _parent = parent; } public Environment() : this(null) { } public void Add(string name, AstNode value) => _definitions.Add(name, value); public AstNode? Get(string name) => GetShallow(name) ?? _parent.Get(name); private AstNode? GetShallow(string name) { if (_definitions.ContainsKey(name)) { return _definitions[name]; } return null; } } }
mit
C#
49e92b6747260346ca79890c7a722c08124c17eb
Update WalletWasabi/Services/SingleInstanceChecker.cs
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Services/SingleInstanceChecker.cs
WalletWasabi/Services/SingleInstanceChecker.cs
using NBitcoin; using Nito.AsyncEx; using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace WalletWasabi.Services { public class SingleInstanceChecker : IDisposable { /// <summary>Unique prefix for global mutex name.</summary> private const string MutexString = "WalletWasabiSingleInstance"; private bool _disposedValue; public SingleInstanceChecker(Network network) { Network = network; } private IDisposable? SingleApplicationLockHolder { get; set; } private Network Network { get; } public async Task CheckAsync() { if (_disposedValue) { throw new ObjectDisposedException(nameof(SingleInstanceChecker)); } // The disposal of this mutex handled by AsyncMutex.WaitForAllMutexToCloseAsync(). var mutex = new AsyncMutex($"{MutexString}-{Network}"); try { using CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.Zero); SingleApplicationLockHolder = await mutex.LockAsync(cts.Token).ConfigureAwait(false); } catch (IOException ex) { throw new InvalidOperationException($"Wasabi is already running on {Network}!", ex); } } /// <summary> /// <list type="bullet"> /// <item>Unmanaged resources need to be released regardless of the value of the <paramref name="disposing"/> parameter.</item> /// <item>Managed resources need to be released if the value of <paramref name="disposing"/> is <c>true</c>.</item> /// </list> /// </summary> /// <param name="disposing"> /// Indicates whether the method call comes from a <see cref="Dispose()"/> method /// (its value is <c>true</c>) or from a finalizer (its value is <c>false</c>). /// </param> protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { SingleApplicationLockHolder?.Dispose(); } _disposedValue = true; } } /// <summary> /// Do not change this code. /// </summary> public void Dispose() { // Dispose of unmanaged resources. Dispose(true); // Suppress finalization. GC.SuppressFinalize(this); } } }
using NBitcoin; using Nito.AsyncEx; using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace WalletWasabi.Services { public class SingleInstanceChecker : IDisposable { /// <summary>Unique prefix for global mutex name.</summary> private const string MutexString = "WalletWasabiSingleInstance"; private bool _disposedValue; public SingleInstanceChecker(Network network) { Network = network; } private IDisposable? SingleApplicationLockHolder { get; set; } private Network Network { get; } public async Task CheckAsync() { if (_disposedValue) { throw new ObjectDisposedException(nameof(SingleInstanceChecker)); } // The disposal of this mutex handled by AsyncMutex.WaitForAllMutexToCloseAsync(). var mutex = new AsyncMutex($"{MutexString}-{Network}"); try { using CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.Zero); SingleApplicationLockHolder = await mutex.LockAsync(cts.Token).ConfigureAwait(false); } catch (IOException ex) { throw new InvalidOperationException($"Wasabi is already running on {Network}!", ex); } } /// <summary> /// <list type="bullet"> /// <item>Unmanaged resources needs to be released regardless of the value of the <paramref name="disposing"/> parameter.</item> /// <item>Managed resources needs to be released if the value of <paramref name="disposing"/> is <c>true</c>.</item> /// </list> /// </summary> /// <param name="disposing"> /// Indicates whether the method call comes from a <see cref="Dispose()"/> method /// (its value is <c>true</c>) or from a finalizer (its value is <c>false</c>). /// </param> protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { SingleApplicationLockHolder?.Dispose(); } _disposedValue = true; } } /// <summary> /// Do not change this code. /// </summary> public void Dispose() { // Dispose of unmanaged resources. Dispose(true); // Suppress finalization. GC.SuppressFinalize(this); } } }
mit
C#
bf595df0ebd756e1c7d4619f23853d501ee491ec
Bump version
Fody/Costura,Fody/Costura
src/MethodTimeLogger.cs
src/MethodTimeLogger.cs
using System.Reflection; using System; using System.Globalization; /// <summary> /// Note: do not rename this class or put it inside a namespace. /// </summary> internal static class MethodTimeLogger { #region Methods public static void Log(MethodBase methodBase, long milliseconds, string message) { Log(methodBase.DeclaringType ?? typeof(object), methodBase.Name, milliseconds, message); } public static void Log(Type type, string methodName, long milliseconds, string message) { // if (type is null) // { // return; // } // if (milliseconds == 0) // { // // Don't log superfast methods // return; // } // var finalMessage = $"[METHODTIMER] {type.Name}.{methodName} took '{milliseconds.ToString(CultureInfo.InvariantCulture)}' ms"; // if (!string.IsNullOrWhiteSpace(message)) // { // finalMessage += $" | {message}"; // } // var logger = LogManager.GetLogger(type); // logger.Debug(finalMessage); } #endregion }
using System.Reflection; using System; using System.Globalization; /// <summary> /// Note: do not rename this class or put it inside a namespace. /// </summary> internal static class MethodTimeLogger { #region Methods public static void Log(MethodBase methodBase, long milliseconds, string message) { Log(methodBase.DeclaringType ?? typeof(object), methodBase.Name, milliseconds, message); } public static void Log(Type type, string methodName, long milliseconds, string message) { // if (type is null) // { // return; // } // if (milliseconds == 0) // { // // Don't log superfast methods // return; // } // var finalMessage = $"[METHODTIMER] {type.Name}.{methodName} took '{milliseconds.ToString(CultureInfo.InvariantCulture)}' ms"; // if (!string.IsNullOrWhiteSpace(message)) // { // finalMessage += $" | {message}"; // } // var logger = LogManager.GetLogger(type); // logger.Debug(finalMessage); } #endregion }
mit
C#
1b25f2385536f2ae5a9ced00632c29c9ad2386d7
Add docs
CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,mavasani/roslyn,mavasani/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn
src/Workspaces/Core/Portable/Workspace/Host/HostProjectServices.cs
src/Workspaces/Core/Portable/Workspace/Host/HostProjectServices.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; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// Per language services provided by the host environment. /// </summary> internal sealed class HostProjectServices { private readonly HostLanguageServices _services; public SolutionServices SolutionServices => _services.WorkspaceServices.SolutionServices; // This ensures a single instance of this type associated with each HostLanguageServices. [Obsolete("Do not call directly. Use HostLanguageServices.ProjectServices to acquire an instance")] internal HostProjectServices(HostLanguageServices services) { _services = services; } /// <inheritdoc cref="HostLanguageServices.Language"/> public string Language => _services.Language; /// <inheritdoc cref="HostLanguageServices.GetService"/> public TLanguageService? GetService<TLanguageService>() where TLanguageService : ILanguageService => _services.GetService<TLanguageService>(); /// <inheritdoc cref="HostLanguageServices.GetRequiredService"/> public TLanguageService GetRequiredService<TLanguageService>() where TLanguageService : ILanguageService => _services.GetRequiredService<TLanguageService>(); } }
// 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; namespace Microsoft.CodeAnalysis.Host { // TODO(cyrusn): Make public. Tracked through https://github.com/dotnet/roslyn/issues/62914 internal sealed class HostProjectServices { private readonly HostLanguageServices _services; public SolutionServices SolutionServices => _services.WorkspaceServices.SolutionServices; // This ensures a single instance of this type associated with each HostLanguageServices. [Obsolete("Do not call directly. Use HostLanguageServices.ProjectServices to acquire an instance")] internal HostProjectServices(HostLanguageServices services) { _services = services; } /// <inheritdoc cref="HostLanguageServices.Language"/> public string Language => _services.Language; /// <inheritdoc cref="HostLanguageServices.GetService"/> public TLanguageService? GetService<TLanguageService>() where TLanguageService : ILanguageService => _services.GetService<TLanguageService>(); /// <inheritdoc cref="HostLanguageServices.GetRequiredService"/> public TLanguageService GetRequiredService<TLanguageService>() where TLanguageService : ILanguageService => _services.GetRequiredService<TLanguageService>(); } }
mit
C#
44d054ada634e0128d2a629222ecf003782ae6c0
Add 'getAppInfo' and 'getIdentifier' to WP8 as well
danmichaelo/cordova-plugin-appinfo,vash15/cordova-plugin-appinfo,danmichaelo/cordova-plugin-appinfo,vash15/cordova-plugin-appinfo,vash15/cordova-plugin-appinfo,danmichaelo/cordova-plugin-appinfo
src/wp8/AppInfo.cs
src/wp8/AppInfo.cs
using System; using System.Xml.Linq; using WPCordovaClassLib.Cordova; using WPCordovaClassLib.Cordova.Commands; using WPCordovaClassLib.Cordova.JSON; namespace Cordova.Extension.Commands { public class AppInfo : BaseCommand { public void getAppInfo(string options) { Dictionary<string, string> appInfo = new Dictionary<string, string>() { {"identifier", ""}, {"version", ""}, {"build", ""} }; XElement manifestAppElement = XDocument.Load("WMAppManifest.xml").Root.Element("App"); if (manifestAppElement != null && manifestAppElement.Attribute("ProductID") != null) { appInfo["identifier"] = manifestAppElement.Attribute("ProductID").Value; } if (manifestAppElement != null && manifestAppElement.Attribute("Version") != null) { appInfo["version"] = manifestAppElement.Attribute("Version").Value; } string jsonString = JsonHelper.Serialize(keys); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, jsonString)); } public void getVersion(string options) { string version = "unknown"; XElement manifestAppElement = XDocument.Load("WMAppManifest.xml").Root.Element("App"); if (manifestAppElement != null && manifestAppElement.Attribute("Version") != null) { version = manifestAppElement.Attribute("Version").Value; } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, version)); } public void getIdentifier(string options) { string productID = "unknown"; XElement manifestAppElement = XDocument.Load("WMAppManifest.xml").Root.Element("App"); if (manifestAppElement != null && manifestAppElement.Attribute("ProductID") != null) { productID = manifestAppElement.Attribute("ProductID").Value; } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, productID)); } } }
using System; using System.Xml.Linq; using WPCordovaClassLib.Cordova; using WPCordovaClassLib.Cordova.Commands; using WPCordovaClassLib.Cordova.JSON; namespace Cordova.Extension.Commands { public class AppInfo : BaseCommand { public void getVersion(string options) { string version = "unknown"; XElement manifestAppElement = XDocument.Load("WMAppManifest.xml").Root.Element("App"); if (manifestAppElement != null && manifestAppElement.Attribute("Version") != null) { version = manifestAppElement.Attribute("Version").Value; } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, version)); } } }
mit
C#
524c6b7eaff2cee0246b20a943ff318bf5e5777e
Remove name limit test
bugsnag/bugsnag-dotnet,bugsnag/bugsnag-dotnet
tests/Bugsnag.Tests/Payload/BreadcrumbTests.cs
tests/Bugsnag.Tests/Payload/BreadcrumbTests.cs
using System; using System.Collections.Generic; using Bugsnag.Payload; using Xunit; namespace Bugsnag.Tests.Payload { public class BreadcrumbTests { [Fact] public void BreadcrumbIncludesTimestamp() { var breadcrumb = new Breadcrumb("test", BreadcrumbType.Manual); Assert.IsType<DateTime>(breadcrumb["timestamp"]); } [Fact] public void BreadcrumbWithNoMetadataDoesNotIncludeKey() { var breadcrumb = new Breadcrumb("test", BreadcrumbType.Manual); Assert.DoesNotContain("metaData", breadcrumb.Keys); } [Fact] public void FromReportIncludesExpectedKeys() { var configuration = new Configuration("123456"); var report = new Report(configuration, new System.Exception(), Bugsnag.Payload.HandledState.ForHandledException(), new Breadcrumb[0], new Session()); var breadcrumb = Breadcrumb.FromReport(report); Assert.Equal("error", breadcrumb["type"]); Assert.NotNull(breadcrumb["metaData"]); Assert.IsType<DateTime>(breadcrumb["timestamp"]); } [Fact] public void NullNameProvidesDefault() { var breadcrumb = new Breadcrumb(null, BreadcrumbType.Manual); Assert.NotNull(breadcrumb.Name); } } }
using System; using System.Collections.Generic; using Bugsnag.Payload; using Xunit; namespace Bugsnag.Tests.Payload { public class BreadcrumbTests { [Fact] public void BreadcrumbIncludesTimestamp() { var breadcrumb = new Breadcrumb("test", BreadcrumbType.Manual); Assert.IsType<DateTime>(breadcrumb["timestamp"]); } [Fact] public void BreadcrumbWithNoMetadataDoesNotIncludeKey() { var breadcrumb = new Breadcrumb("test", BreadcrumbType.Manual); Assert.DoesNotContain("metaData", breadcrumb.Keys); } [Fact] public void FromReportIncludesExpectedKeys() { var configuration = new Configuration("123456"); var report = new Report(configuration, new System.Exception(), Bugsnag.Payload.HandledState.ForHandledException(), new Breadcrumb[0], new Session()); var breadcrumb = Breadcrumb.FromReport(report); Assert.Equal("error", breadcrumb["type"]); Assert.NotNull(breadcrumb["metaData"]); Assert.IsType<DateTime>(breadcrumb["timestamp"]); } [Fact] public void NullNameProvidesDefault() { var breadcrumb = new Breadcrumb(null, BreadcrumbType.Manual); Assert.NotNull(breadcrumb.Name); } [Fact] public void LongNamesAreTrimmed() { var name = new String('a', 500); var breadcrumb = new Breadcrumb(name, BreadcrumbType.Manual); Assert.Equal(name.Substring(0, 30), breadcrumb.Name); } } }
mit
C#