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
c75406a00fa97dfa518e73d933f8c24a4f61d4e2
Correct value when registry value does not exist
emoacht/Monitorian
Source/ScreenFrame/Painter/ThemeInfo.cs
Source/ScreenFrame/Painter/ThemeInfo.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Win32; namespace ScreenFrame.Painter { /// <summary> /// Windows themes information /// </summary> public static class ThemeInfo { /// <summary> /// Gets the color theme for Windows. /// </summary> /// <returns>Color theme</returns> public static ColorTheme GetWindowsTheme() => GetTheme(SystemValueName); /// <summary> /// Gets the color theme for applications. /// </summary> /// <returns>Color theme</returns> public static ColorTheme GetAppTheme() => GetTheme(AppValueName); private const string SystemValueName = "SystemUsesLightTheme"; private const string AppValueName = "AppsUseLightTheme"; private static ColorTheme GetTheme(string valueName) { const string keyName = @"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"; // HKCU using var key = Registry.CurrentUser.OpenSubKey(keyName); return key?.GetValue(valueName) switch { 0 => ColorTheme.Dark, 1 => ColorTheme.Light, _ => ColorTheme.Unknown }; } } /// <summary> /// Color theme /// </summary> public enum ColorTheme { /// <summary> /// Unknown /// </summary> Unknown = 0, /// <summary> /// Dark mode /// </summary> Dark, /// <summary> /// Light mode /// </summary> Light } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Win32; namespace ScreenFrame.Painter { /// <summary> /// Windows themes information /// </summary> public static class ThemeInfo { /// <summary> /// Gets the color theme for Windows. /// </summary> /// <returns>Color theme</returns> public static ColorTheme GetWindowsTheme() => GetTheme(SystemValueName); /// <summary> /// Gets the color theme for applications. /// </summary> /// <returns>Color theme</returns> public static ColorTheme GetAppTheme() => GetTheme(AppValueName); private const string SystemValueName = "SystemUsesLightTheme"; private const string AppValueName = "AppsUseLightTheme"; private static ColorTheme GetTheme(string valueName) { const string keyName = @"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"; // HKCU using var key = Registry.CurrentUser.OpenSubKey(keyName); return key?.GetValue(valueName, 1) switch { 0 => ColorTheme.Dark, 1 => ColorTheme.Light, _ => ColorTheme.Unknown }; } } /// <summary> /// Color theme /// </summary> public enum ColorTheme { /// <summary> /// Unknown /// </summary> Unknown = 0, /// <summary> /// Dark mode /// </summary> Dark, /// <summary> /// Light mode /// </summary> Light } }
mit
C#
b26fdddf3f10fec3bed969b336e13d032a906219
Define 'System.{SystemException,InvalidOperationException}'
jonathanvdc/flame-llvm,jonathanvdc/flame-llvm,jonathanvdc/flame-llvm
stdlib/corlib/Exception.cs
stdlib/corlib/Exception.cs
// This file makes use of the LeMP 'unroll' macro to avoid copy-pasting code. // See http://ecsharp.net/lemp/avoid-tedium-with-LeMP.html for an explanation. #importMacros(LeMP); namespace System { /// <summary> /// Represents errors that occur during program execution. /// </summary> public class Exception : Object { /// <summary> /// Creates an exception. /// </summary> public Exception() : this("An exception occurred.") { } /// <summary> /// Creates an exception from an error message. /// </summary> /// <param name="message">An error message.</param> public Exception(string message) : this(message, null) { } /// <summary> /// Creates an exception from an error message and an inner /// exception. /// </summary> /// <param name="message">An error message.</param> /// <param name="innerException">An exception that gives rise to this exception.</param> public Exception(string message, Exception innerException) { this.Message = message; this.InnerException = innerException; } /// <summary> /// Gets the inner exception that gave rise to this exception. /// </summary> /// <returns>The inner exception.</returns> public Exception InnerException { get; private set; } /// <summary> /// Gets a message that describes the current exception. /// </summary> /// <returns>A message that describes why the exception occurred.</returns> public string Message { get; private set; } } unroll ((TYPE, BASE_TYPE, DEFAULT_MESSAGE) in ( (SystemException, Exception, "System error."), (InvalidOperationException, SystemException, "Operation is not valid due to the current state of the object."))) { public class TYPE : BASE_TYPE { /// <summary> /// Creates an exception. /// </summary> public TYPE() : base(DEFAULT_MESSAGE) { } /// <summary> /// Creates an exception from an error message. /// </summary> /// <param name="message">An error message.</param> public TYPE(string message) : base(message) { } /// <summary> /// Creates an exception from an error message and an inner /// exception. /// </summary> /// <param name="message">An error message.</param> /// <param name="innerException">An exception that gives rise to this exception.</param> public TYPE(string message, Exception innerException) : base(message, innerException) { } } } }
namespace System { /// <summary> /// Represents errors that occur during program execution. /// </summary> public class Exception : Object { /// <summary> /// Creates an exception. /// </summary> public Exception() : this("An exception occurred.") { } /// <summary> /// Creates an exception from an error message. /// </summary> /// <param name="message">An error message.</param> public Exception(string message) : this(message, null) { } /// <summary> /// Creates an exception from an error message and an inner /// exception. /// </summary> /// <param name="message">An error message.</param> /// <param name="innerException">An exception that gives rise to this exception.</param> public Exception(string message, Exception innerException) { this.Message = message; this.InnerException = innerException; } /// <summary> /// Gets the inner exception that gave rise to this exception. /// </summary> /// <returns>The inner exception.</returns> public Exception InnerException { get; private set; } /// <summary> /// Gets a message that describes the current exception. /// </summary> /// <returns>A message that describes why the exception occurred.</returns> public string Message { get; private set; } } }
mit
C#
38b5066a32278de2dd8cb63a850929d86a89a8dd
Add license to new file
Newsworthy/Huxley,jpsingleton/Huxley,Newsworthy/Huxley,jpsingleton/Huxley,mjanthony/Huxley,mjanthony/Huxley
src/Huxley/Models/DelaysResponse.cs
src/Huxley/Models/DelaysResponse.cs
/* Huxley - a JSON proxy for the UK National Rail Live Departure Board SOAP API Copyright (C) 2015 James Singleton * http://huxley.unop.uk * https://github.com/jpsingleton/Huxley This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; namespace Huxley.Models { public class DelaysResponse { public DateTime GeneratedAt { get; set; } public string LocationName { get; set; } public string Crs { get; set; } public string FilterLocationName { get; set; } // Yes this is a typo but it matches StationBoard public string Filtercrs { get; set; } public bool Delays { get; set; } public int TotalTrainsDelayed { get; set; } public int TotalDelayMinutes { get; set; } public int TotalTrains { get; set; } } }
using System; namespace Huxley.Models { public class DelaysResponse { public DateTime GeneratedAt { get; set; } public string LocationName { get; set; } public string Crs { get; set; } public string FilterLocationName { get; set; } // Yes this is a typo but it matches StationBoard public string Filtercrs { get; set; } public bool Delays { get; set; } public int TotalTrainsDelayed { get; set; } public int TotalDelayMinutes { get; set; } public int TotalTrains { get; set; } } }
agpl-3.0
C#
005222ff4555ef98b1d2ae202ed84b3190f068f7
update valueController #1
adamstephensen/test-api-publish-1221,adamstephensen/test-api-publish-1221
TestApi/Controllers/ValuesController.cs
TestApi/Controllers/ValuesController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Mvc; namespace TestApi.Controllers { [Route("api/[controller]")] public class ValuesController : Controller { // GET: api/values [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1-updated", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public string Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody]string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Mvc; namespace TestApi.Controllers { [Route("api/[controller]")] public class ValuesController : Controller { // GET: api/values [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public string Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody]string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
mit
C#
678f0fc0b9ed76a981888b205699513477ce259b
Update AssemblyInfo
danielchalmers/WpfAboutView
WpfAboutView/Properties/AssemblyInfo.cs
WpfAboutView/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("WpfAboutView")] [assembly: AssemblyDescription("Simple About control with app name, icon, version, and credits")] [assembly: AssemblyCompany("Daniel Chalmers")] [assembly: AssemblyProduct("WpfAboutView")] [assembly: AssemblyCopyright("© Daniel Chalmers 2017")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.0.0.0")]
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // 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("WpfAboutView")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Daniel Chalmers")] [assembly: AssemblyProduct("WpfAboutView")] [assembly: AssemblyCopyright("© Daniel Chalmers 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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.0.0.0")]
mit
C#
d5dda3035fdd42a625039f76f3274810fb2e5eb5
Test Positioned.Value.
Faithlife/Parsing
tests/Faithlife.Parsing.Tests/CommonTests.cs
tests/Faithlife.Parsing.Tests/CommonTests.cs
using Xunit; namespace Faithlife.Parsing.Tests; public class CommonTests { [Fact] public void ResultShouldAlwaysSucceed() { Parser.Success(true).TryParse("").ShouldSucceed(true, 0); Parser.Success(true).TryParse("x").ShouldSucceed(true, 0); Parser.Success(true).TryParse("xabc").ShouldSucceed(true, 0); } [Fact] public void EndShouldSucceedAtEnd() { Parser.Success(true).End().TryParse("x", 1).ShouldSucceed(true, 1); } [Fact] public void EndShouldFailNotAtEnd() { Parser.Success(true).End().TryParse("xabc", 1).ShouldFail(1); } [Fact] public void ParseThrowsOnFailure() { try { Parser.Success(true).End().Parse("xabc", 1); Assert.True(false); } catch (ParseException exception) { exception.Result.NextPosition.Index.ShouldBe(1); } } [Fact] public void NamedShouldNameFailure() { var namedFailure = Parser.String("abc").Named("epic").TryParse("xabc").GetNamedFailures().Single(); namedFailure.Name.ShouldBe("epic"); namedFailure.Position.Index.ShouldBe(0); } [Fact] public void PositionedShouldPositionSuccess() { var positioned = Parser.String("ab").Positioned().Parse("xabc", 1); positioned.Position.Index.ShouldBe(1); positioned.Value.ShouldBe("ab"); positioned.Length.ShouldBe(2); } [Fact] public void LineColumnEquality() { var a1 = new LineColumn(1, 2); var a2 = new LineColumn(1, 2); var b = new LineColumn(2, 1); (a1 == a2).ShouldBe(true); (a1 != b).ShouldBe(true); Equals(a1, b).ShouldBe(false); a1.GetHashCode().ShouldBe(a2.GetHashCode()); } [Fact] public void TextPositionEquality() { var values = Parser.String("ab").Positioned().Repeat(2).Parse("abab"); Equals(values[0].Position, values[1].Position).ShouldBe(false); Equals(values[0].Position.GetHashCode(), values[1].Position.GetHashCode()).ShouldBe(false); (values[0].Position == values[1].Position).ShouldBe(false); (values[0].Position != values[1].Position).ShouldBe(true); } [Fact] public void ParseResult_GetValueOrDefault() { ParseResult.Success(1, default).GetValueOrDefault().ShouldBe(1); ParseResult.Success(1, default).GetValueOrDefault(2).ShouldBe(1); ParseResult.Failure<int>(default).GetValueOrDefault().ShouldBe(0); ParseResult.Failure<int>(default).GetValueOrDefault(2).ShouldBe(2); } [Fact] public void ParseResult_ToMessage() { Parser.Char('a').TryParse("a").ToMessage().ShouldBe("success at 1,2"); Parser.Char('a').TryParse("b").ToMessage().ShouldBe("failure at 1,1"); Parser.Char('a').Named("'a'").TryParse("b").ToMessage().ShouldBe("failure at 1,1; expected 'a' at 1,1"); } }
using Xunit; namespace Faithlife.Parsing.Tests; public class CommonTests { [Fact] public void ResultShouldAlwaysSucceed() { Parser.Success(true).TryParse("").ShouldSucceed(true, 0); Parser.Success(true).TryParse("x").ShouldSucceed(true, 0); Parser.Success(true).TryParse("xabc").ShouldSucceed(true, 0); } [Fact] public void EndShouldSucceedAtEnd() { Parser.Success(true).End().TryParse("x", 1).ShouldSucceed(true, 1); } [Fact] public void EndShouldFailNotAtEnd() { Parser.Success(true).End().TryParse("xabc", 1).ShouldFail(1); } [Fact] public void ParseThrowsOnFailure() { try { Parser.Success(true).End().Parse("xabc", 1); Assert.True(false); } catch (ParseException exception) { exception.Result.NextPosition.Index.ShouldBe(1); } } [Fact] public void NamedShouldNameFailure() { var namedFailure = Parser.String("abc").Named("epic").TryParse("xabc").GetNamedFailures().Single(); namedFailure.Name.ShouldBe("epic"); namedFailure.Position.Index.ShouldBe(0); } [Fact] public void PositionedShouldPositionSuccess() { var positioned = Parser.String("ab").Positioned().Parse("xabc", 1); positioned.Position.Index.ShouldBe(1); positioned.Length.ShouldBe(2); } [Fact] public void LineColumnEquality() { var a1 = new LineColumn(1, 2); var a2 = new LineColumn(1, 2); var b = new LineColumn(2, 1); (a1 == a2).ShouldBe(true); (a1 != b).ShouldBe(true); Equals(a1, b).ShouldBe(false); a1.GetHashCode().ShouldBe(a2.GetHashCode()); } [Fact] public void TextPositionEquality() { var values = Parser.String("ab").Positioned().Repeat(2).Parse("abab"); Equals(values[0].Position, values[1].Position).ShouldBe(false); Equals(values[0].Position.GetHashCode(), values[1].Position.GetHashCode()).ShouldBe(false); (values[0].Position == values[1].Position).ShouldBe(false); (values[0].Position != values[1].Position).ShouldBe(true); } [Fact] public void ParseResult_GetValueOrDefault() { ParseResult.Success(1, default).GetValueOrDefault().ShouldBe(1); ParseResult.Success(1, default).GetValueOrDefault(2).ShouldBe(1); ParseResult.Failure<int>(default).GetValueOrDefault().ShouldBe(0); ParseResult.Failure<int>(default).GetValueOrDefault(2).ShouldBe(2); } [Fact] public void ParseResult_ToMessage() { Parser.Char('a').TryParse("a").ToMessage().ShouldBe("success at 1,2"); Parser.Char('a').TryParse("b").ToMessage().ShouldBe("failure at 1,1"); Parser.Char('a').Named("'a'").TryParse("b").ToMessage().ShouldBe("failure at 1,1; expected 'a' at 1,1"); } }
mit
C#
22b7060e63e2b98dd24ef60b6190c158e0ac63a4
Fix the license
googleapis/doc-templates,googleapis/doc-templates
java/yaml_navtree.cs
java/yaml_navtree.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. <?cs set longestWordLength = 0 ?><?cs set wideStyleCharacterLimit = 20 ?><?cs set pathPrefix = devsite.path ?><?cs # walk the children pages and print them nested below the parent page: the node to insert a label, link and check for children whitespace: Whitespace to insert before any text in the structure, which helps with nesting children on recursion. isRoot: treat this node as if it has children and insert a section node. ?><?cs def:write_child_nodes(page,whitespace,isRoot) ?><?cs if:longestWordLength < string.length(page.label)?><?cs set longestWordLength = string.length(page.label)?><?cs /if?> <?cs var:whitespace ?>- title: "<?cs var:page.label ?>" <?cs var:whitespace ?> path: <?cs var:pathPrefix+page.link ?><?cs if:subcount(page.children) || isRoot ?> <?cs var:whitespace ?> section: <?cs /if?><?cs each:child = page.children?><?cs if:!subcount(child.children) ?> <?cs var:whitespace ?> - title: "<?cs var:child.shortname ?>" <?cs var:whitespace ?> path: <?cs var:pathPrefix+child.link ?><?cs /if ?><?cs if:subcount(child.children) ?><?cs call:write_child_nodes(child,whitespace + " ",0) ?><?cs /if ?><?cs /each ?><?cs /def ?><?cs # print out the yaml nav starting with the toc entry and using the first item, which is generally the package summary as the root element with the rest of the pages as children beneath the package summary. ?> toc:<?cs each:page = docs.pages?><?cs if:page.type == "package"?><?cs call:write_child_nodes(page,"",1) ?><?cs else?> <?cs call:write_child_nodes(page," ",0) ?><?cs /if?><?cs /each ?>
<!-- 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. --> <?cs set longestWordLength = 0 ?><?cs set wideStyleCharacterLimit = 20 ?><?cs set pathPrefix = devsite.path ?><?cs # walk the children pages and print them nested below the parent page: the node to insert a label, link and check for children whitespace: Whitespace to insert before any text in the structure, which helps with nesting children on recursion. isRoot: treat this node as if it has children and insert a section node. ?><?cs def:write_child_nodes(page,whitespace,isRoot) ?><?cs if:longestWordLength < string.length(page.label)?><?cs set longestWordLength = string.length(page.label)?><?cs /if?> <?cs var:whitespace ?>- title: "<?cs var:page.label ?>" <?cs var:whitespace ?> path: <?cs var:pathPrefix+page.link ?><?cs if:subcount(page.children) || isRoot ?> <?cs var:whitespace ?> section: <?cs /if?><?cs each:child = page.children?><?cs if:!subcount(child.children) ?> <?cs var:whitespace ?> - title: "<?cs var:child.shortname ?>" <?cs var:whitespace ?> path: <?cs var:pathPrefix+child.link ?><?cs /if ?><?cs if:subcount(child.children) ?><?cs call:write_child_nodes(child,whitespace + " ",0) ?><?cs /if ?><?cs /each ?><?cs /def ?><?cs # print out the yaml nav starting with the toc entry and using the first item, which is generally the package summary as the root element with the rest of the pages as children beneath the package summary. ?> toc:<?cs each:page = docs.pages?><?cs if:page.type == "package"?><?cs call:write_child_nodes(page,"",1) ?><?cs else?> <?cs call:write_child_nodes(page," ",0) ?><?cs /if?><?cs /each ?>
apache-2.0
C#
057516d72024e3d034d464c4b7b26985345d7472
Resolve #25
Seaal/disclose
src/Disclose/Handler.cs
src/Disclose/Handler.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Disclose.DiscordClient; namespace Disclose { /// <summary> /// A base class for all Handlers. Extend this to create your own Handlers. /// </summary> public abstract class Handler : IHandler { protected IDiscloseSettings Disclose { get; private set; } protected IDiscordCommands Discord { get; private set; } protected IDataStore DataStore { get; private set; } /// <inheritdoc /> public virtual void Init(IDiscloseSettings disclose, IDiscordCommands discord, IDataStore dataStore) { Disclose = disclose; Discord = discord; DataStore = dataStore; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Disclose.DiscordClient; namespace Disclose { /// <summary> /// A base class for all Handlers. Extend this to create your own Handlers. /// </summary> public abstract class Handler : IHandler { protected IDiscloseSettings Disclose { get; private set; } protected IDiscordCommands Discord { get; private set; } protected IDataStore DataStore { get; private set; } public void Init(IDiscloseSettings disclose, IDiscordCommands discord, IDataStore dataStore) { Disclose = disclose; Discord = discord; DataStore = dataStore; } } }
mit
C#
7839e76f9bb8ba2b2cc4ec21566c14acce8faa44
Add ThrowIfAny method
Archie-Yang/PcscDotNet
src/PcscDotNet/SCardErrorExtensions.cs
src/PcscDotNet/SCardErrorExtensions.cs
using System; using System.ComponentModel; using System.Linq; namespace PcscDotNet { public static class SCardErrorExtensions { public static void Throw(this SCardError error) { throw new PcscException(error); } public static void ThrowIfAny(this SCardError error, params SCardError[] errors) { if (errors?.Contains(error) == true) { throw new PcscException(error); } } public static void ThrowIfNotSuccess(this SCardError error) { if (error != SCardError.Successs) { throw new PcscException(error); } } } }
using System; using System.ComponentModel; namespace PcscDotNet { public static class SCardErrorExtensions { public static void Throw(this SCardError error) { throw new PcscException(error); } public static void ThrowIfNotSuccess(this SCardError error) { if (error != SCardError.Successs) { throw new PcscException(error); } } } }
mit
C#
dab5288aaa4c775826d9cfd317684bd1537d76f7
Bump version
dylanplecki/KeycloakOwinAuthentication,joelnet/KeycloakOwinAuthentication,dylanplecki/BasicOidcAuthentication
src/Owin.Security.Keycloak/Properties/AssemblyInfo.cs
src/Owin.Security.Keycloak/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("Keycloak OWIN Authentication")] [assembly: AssemblyDescription("Keycloak Authentication Middleware for ASP.NET OWIN")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("OWIN")] [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("fcac3105-3e81-49c4-9d8e-0fc9e608e87c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.1.2")] [assembly: AssemblyFileVersion("1.0.1.2")]
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("Keycloak OWIN Authentication")] [assembly: AssemblyDescription("Keycloak Authentication Middleware for ASP.NET OWIN")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("OWIN")] [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("fcac3105-3e81-49c4-9d8e-0fc9e608e87c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.1.1")] [assembly: AssemblyFileVersion("1.0.1.1")]
mit
C#
94e46996d280e1803669dad3e9385037fd73c3f3
Update SkillController.cs - add "Edit" action - add "GetSkillByIdQueryHandler"
NinjaVault/NinjaHive,NinjaVault/NinjaHive
NinjaHive.WebApp/Controllers/SkillsController.cs
NinjaHive.WebApp/Controllers/SkillsController.cs
using System; using System.Web.Mvc; using NinjaHive.Contract.Commands; using NinjaHive.Contract.DTOs; using NinjaHive.Contract.Queries; using NinjaHive.Core; using NinjaHive.WebApp.Services; namespace NinjaHive.WebApp.Controllers { public class SkillsController : Controller { private readonly IQueryHandler<GetAllSkillsQuery, Skill[]> skillsQueryHandler; private readonly ICommandHandler<AddSkillCommand> addSkillCommandHandler; private readonly IQueryHandler<GetSkillByIdQuery, Skill> getSkillByIdCommandHandler; public SkillsController(IQueryHandler<GetAllSkillsQuery, Skill[]> skillsQueryHandler, ICommandHandler<AddSkillCommand> addSkillCommandHandler, IQueryHandler<GetSkillByIdQuery, Skill> getSkillByIdCommandHandler) { this.skillsQueryHandler = skillsQueryHandler; this.addSkillCommandHandler = addSkillCommandHandler; this.getSkillByIdCommandHandler = getSkillByIdCommandHandler; } // GET: Skills public ActionResult Index() { var skills = this.skillsQueryHandler.Handle(new GetAllSkillsQuery()); return View(skills); } public ActionResult Create() { return View(); } public ActionResult Edit(Guid skillId) { var skill = this.getSkillByIdCommandHandler.Handle(new GetSkillByIdQuery { SkillId = skillId }); return View(skill); } [HttpPost] public ActionResult Create(Skill skill) { skill.Id = Guid.NewGuid(); var command = new AddSkillCommand { Skill = skill, }; this.addSkillCommandHandler.Handle(command); var redirectUri = UrlProvider<SkillsController>.GetRouteValues(c => c.Index()); return RedirectToRoute(redirectUri); } } }
using System; using System.Web.Mvc; using NinjaHive.Contract.Commands; using NinjaHive.Contract.DTOs; using NinjaHive.Contract.Queries; using NinjaHive.Core; using NinjaHive.WebApp.Services; namespace NinjaHive.WebApp.Controllers { public class SkillsController : Controller { private readonly IQueryHandler<GetAllSkillsQuery, Skill[]> skillsQueryHandler; private readonly ICommandHandler<AddSkillCommand> addSkillCommandHandler; public SkillsController(IQueryHandler<GetAllSkillsQuery, Skill[]> skillsQueryHandler, ICommandHandler<AddSkillCommand> addSkillCommandHandler) { this.skillsQueryHandler = skillsQueryHandler; this.addSkillCommandHandler = addSkillCommandHandler; } // GET: Skills public ActionResult Index() { var skills = this.skillsQueryHandler.Handle(new GetAllSkillsQuery()); return View(skills); } public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(Skill skill) { skill.Id = Guid.NewGuid(); var command = new AddSkillCommand { Skill = skill, }; this.addSkillCommandHandler.Handle(command); var redirectUri = UrlProvider<SkillsController>.GetRouteValues(c => c.Index()); return RedirectToRoute(redirectUri); } } }
apache-2.0
C#
fb082f70c9daebdf1e75d651e398d59d713a79ea
remove lingering code
elastic/elasticsearch-net,elastic/elasticsearch-net
src/Tests/Reproduce/GithubIssue2788.cs
src/Tests/Reproduce/GithubIssue2788.cs
using System; using System.Collections.Generic; using System.Linq; using Elasticsearch.Net; using FluentAssertions; using FluentAssertions.Common; using Nest; using Tests.Framework; using Tests.Framework.ManagedElasticsearch.Clusters; using Xunit; namespace Tests.Reproduce { public class GithubIssue2788 : IClusterFixture<WritableCluster> { private readonly WritableCluster _cluster; public GithubIssue2788(WritableCluster cluster) { _cluster = cluster; } // sample mapping with nested objects with TimeSpan field class Root { [Nested] public Child[] Children { get; set; } } class Child { public TimeSpan StartTime { get; set; } public TimeSpan EndTime { get; set; } } [SkipVersion("6.0.0-rc1", "inner hits will return to their old representation with rc2")] public void CanDeserializeNumberToTimeSpanInInnerHits() { var indexName = "sample"; var client = _cluster.Client; //create index with automapping client.CreateIndex(indexName, create => create .Mappings(mappings => mappings .Map<Root>(map => map .AutoMap() ) ) ); var startTime = new TimeSpan(1, 2, 3); var endTime = new TimeSpan(2, 3, 4); client.Index(new Root { Children = new[] { new Child { StartTime = startTime, EndTime = endTime } } }, index => index .Index(indexName) .Refresh(Refresh.WaitFor) ); var result = client.Search<Root>(search => search .Query(query => query .Nested(nested => nested .Query(nestedQuery => nestedQuery .MatchAll() ) .Path(i => i.Children) .InnerHits() ) ) .Index(indexName) ); var child = result.Hits.First().InnerHits.Single().Value.Documents<Child>().Single(); child.Should().NotBeNull(); child.StartTime.Should().Be(startTime); child.EndTime.Should().Be(endTime); } } }
using System; using System.Collections.Generic; using System.Linq; using Elasticsearch.Net; using FluentAssertions; using FluentAssertions.Common; using Nest; using Tests.Framework; using Tests.Framework.ManagedElasticsearch.Clusters; using Xunit; namespace Tests.Reproduce { public class GithubIssue2788 : IClusterFixture<WritableCluster> { private readonly WritableCluster _cluster; public GithubIssue2788(WritableCluster cluster) { _cluster = cluster; } // sample mapping with nested objects with TimeSpan field class Root { [Nested] public Child[] Children { get; set; } } class Child { public TimeSpan StartTime { get; set; } public TimeSpan EndTime { get; set; } } [SkipVersion("6.0.0-rc1", "inner hits will return to their old representation with rc2")] public void CanDeserializeNumberToTimeSpanInInnerHits() { var indexName = "sample"; var client = _cluster.Client; //create index with automapping client.CreateIndex(indexName, create => create .Mappings(mappings => mappings .Map<Root>(map => map .AutoMap() ) ) ); var startTime = new TimeSpan(1, 2, 3); var endTime = new TimeSpan(2, 3, 4); client.Index(new Root { Children = new[] { new Child { StartTime = startTime, EndTime = endTime } } }, index => index .Index(indexName) .Refresh(Refresh.WaitFor) ); var result = client.Search<Root>(search => search .Query(query => query .Nested(nested => nested .Query(nestedQuery => nestedQuery .MatchAll() ) .Path(i => i.Children) .InnerHits() ) ) .Index(indexName) ); var child = result.Hits.First().InnerHits.Single().Value.Documents<Child>().Single(); IReadOnlyCollection<IHit<Root>> hits = result.Hits; InnerHitsMetaData innerHitsMetaData = hits.First().InnerHits["children"].Hits; innerHitsMetaData. child.Should().NotBeNull(); child.StartTime.Should().Be(startTime); child.EndTime.Should().Be(endTime); } } }
apache-2.0
C#
d45940fd7ce9940c6324020c17c59963b8dd62a4
Update ValuesOut.cs
EricZimmerman/RegistryPlugins
RegistryPlugin.TerminalServerClient/ValuesOut.cs
RegistryPlugin.TerminalServerClient/ValuesOut.cs
using System; using RegistryPluginBase.Interfaces; namespace RegistryPlugin.TerminalServerClient { public class ValuesOut:IValueOut { public ValuesOut(int mru, string host, string user, DateTimeOffset lastmod) { MRUPosition = mru; HostName = host; Username = user; LastModified = lastmod.UtcDateTime; } public string HostName { get; } public string Username { get; } public int MRUPosition { get; } public DateTime LastModified { get; } public string BatchKeyPath { get; set; } public string BatchValueName { get; set; } public string BatchValueData1 => HostName; public string BatchValueData2 => $"User: {Username}, MRU: {MRUPosition}"; public string BatchValueData3 => $"Last modified: {LastModified.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff} "; } }
using System; using RegistryPluginBase.Interfaces; namespace RegistryPlugin.TerminalServerClient { public class ValuesOut:IValueOut { public ValuesOut(int mru, string host, string user, DateTimeOffset lastmod) { MRUPosition = mru; HostName = host; Username = user; LastModified = lastmod.UtcDateTime; } public string HostName { get; } public string Username { get; } public int MRUPosition { get; } public DateTime LastModified { get; } public string BatchKeyPath { get; set; } public string BatchValueName { get; set; } public string BatchValueData1 => HostName; public string BatchValueData2 => $"User: {Username}, Mru: {MRUPosition}"; public string BatchValueData3 => $"Last modified: {LastModified.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff} "; } }
mit
C#
f3ae10c9e3d202a8a87e44b0735aaa988e6a41f8
Update build.cake
xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents
Android/Kotlin/build.cake
Android/Kotlin/build.cake
var TARGET = Argument("t", Argument("target", "Default")); Task("binderate") .Does(() => { var configFile = MakeAbsolute(new FilePath("./config.json")).FullPath; var basePath = MakeAbsolute(new DirectoryPath("./")).FullPath; var exit = StartProcess("xamarin-android-binderator", $"--config=\"{configFile}\" --basepath=\"{basePath}\""); if (exit != 0) throw new Exception($"xamarin-android-binderator exited with code {exit}."); }); Task("native") .Does(() => { var fn = IsRunningOnWindows() ? "gradlew.bat" : "gradlew"; var gradlew = MakeAbsolute((FilePath)("./native/KotlinSample/" + fn)); var exit = StartProcess(gradlew, new ProcessSettings { Arguments = "assemble", WorkingDirectory = "./native/KotlinSample/" }); if (exit != 0) throw new Exception($"Gradle exited with exit code {exit}."); }); Task("externals") .IsDependentOn("binderate") .IsDependentOn("native"); Task("libs") .IsDependentOn("externals") .Does(() => { var settings = new MSBuildSettings() .SetConfiguration("Release") .SetVerbosity(Verbosity.Minimal) .WithRestore() .WithProperty("DesignTimeBuild", "false") .WithProperty("PackageOutputPath", MakeAbsolute((DirectoryPath)"./output/").FullPath) .WithTarget("Pack"); MSBuild("./generated/Xamarin.Kotlin.sln", settings); }); Task("nuget") .IsDependentOn("libs"); Task("samples") .IsDependentOn("libs") .Does(() => { var settings = new MSBuildSettings() .SetConfiguration("Release") .SetVerbosity(Verbosity.Minimal) .WithRestore() .WithProperty("DesignTimeBuild", "false"); MSBuild("./samples/KotlinSample.sln", settings); }); Task("clean") .Does(() => { CleanDirectories("./generated/*/bin"); CleanDirectories("./generated/*/obj"); CleanDirectories("./externals/"); CleanDirectories("./generated/"); CleanDirectories("./native/.gradle"); CleanDirectories("./native/**/build"); }); Task("Default") .IsDependentOn("externals") .IsDependentOn("libs") .IsDependentOn("nuget") .IsDependentOn("samples"); RunTarget(TARGET);
var TARGET = Argument("t", Argument("target", "Default")); Task("binderate") .Does(() => { var configFile = MakeAbsolute(new FilePath("./config.json")).FullPath; var basePath = MakeAbsolute(new DirectoryPath("./")).FullPath; var exit = StartProcess("xamarin-android-binderator", $"--config=\"{configFile}\" --basepath=\"{basePath}\""); if (exit != 0) throw new Exception($"xamarin-android-binderator exited with code {exit}."); }); Task("native") .Does(() => { var fn = IsRunningOnWindows() ? "gradlew.bat" : "gradlew"; var gradlew = MakeAbsolute((FilePath)("./native/" + fn)); var exit = StartProcess(gradlew, new ProcessSettings { Arguments = "assemble", WorkingDirectory = "./native/KotlinSample/" }); if (exit != 0) throw new Exception($"Gradle exited with exit code {exit}."); }); Task("externals") .IsDependentOn("binderate") .IsDependentOn("native"); Task("libs") .IsDependentOn("externals") .Does(() => { var settings = new MSBuildSettings() .SetConfiguration("Release") .SetVerbosity(Verbosity.Minimal) .WithRestore() .WithProperty("DesignTimeBuild", "false") .WithProperty("PackageOutputPath", MakeAbsolute((DirectoryPath)"./output/").FullPath) .WithTarget("Pack"); MSBuild("./generated/Xamarin.Kotlin.sln", settings); }); Task("nuget") .IsDependentOn("libs"); Task("samples") .IsDependentOn("libs") .Does(() => { var settings = new MSBuildSettings() .SetConfiguration("Release") .SetVerbosity(Verbosity.Minimal) .WithRestore() .WithProperty("DesignTimeBuild", "false"); MSBuild("./samples/KotlinSample.sln", settings); }); Task("clean") .Does(() => { CleanDirectories("./generated/*/bin"); CleanDirectories("./generated/*/obj"); CleanDirectories("./externals/"); CleanDirectories("./generated/"); CleanDirectories("./native/.gradle"); CleanDirectories("./native/**/build"); }); Task("Default") .IsDependentOn("externals") .IsDependentOn("libs") .IsDependentOn("nuget") .IsDependentOn("samples"); RunTarget(TARGET);
mit
C#
39cfda05167673898faeda0403c2047a2917cd94
Update FileItem.cs
thijse/DSPhotoSorter
DSPhotoSorter/FileItem.cs
DSPhotoSorter/FileItem.cs
#region DS Photosorter - MIT - (c) 2017 Thijs Elenbaas. /* DS Photosorter - tool that processes photos captured with Synology DS Photo 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. Copyright 2017 - Thijs Elenbaas */ #endregion using System; namespace PhotoSorter { public class FileItem { public string FileName { get; set; } public DateTime ModifiedTime { get; set; } // Determine uniqueness public long Size { get; set; } public string QuickHash { get; set; } public string FullHash { get; set; } } }
using System; namespace PhotoSorter { public class FileItem { public string FileName { get; set; } public DateTime ModifiedTime { get; set; } // Determine uniqueness public long Size { get; set; } public string QuickHash { get; set; } public string FullHash { get; set; } } }
mit
C#
6278f3d5c4297814d425afa23fa421715800db45
bump version
QuintSys/Five9ApiClient
src/Five9ApiClient/Five9ApiClient/Properties/AssemblyInfo.cs
src/Five9ApiClient/Five9ApiClient/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Quintsys.Five9ApiClient")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Quintero Systems, Inc.")] [assembly: AssemblyProduct("Quintsys.Five9ApiClient")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("0e06c791-5550-4c02-9125-bcfc605fb9fc")] [assembly: AssemblyVersion("1.0.4")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Quintsys.Five9ApiClient")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Quintero Systems, Inc.")] [assembly: AssemblyProduct("Quintsys.Five9ApiClient")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("0e06c791-5550-4c02-9125-bcfc605fb9fc")] [assembly: AssemblyVersion("1.0.3")]
mit
C#
00ffd9ad709a5a46f6c366bbe3bcb79ca7be92ea
Fix on breakable body
pavelkouril/ld38,pavelkouril/ld38
Assets/Scripts/BreakableBody.cs
Assets/Scripts/BreakableBody.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace RUF { public class BreakableBody : MonoBehaviour { public GameObject OriginalObject; public GameObject ReplaceObject; private List<Rigidbody> mBodies; private List<float> mOffsets; private void OnTriggerExit(Collider other) { if (other.CompareTag("Destroyer")) { if (tag == "Wall") { ApplyGravityOnBody(GetComponent<Rigidbody>()); } else { mBodies = new List<Rigidbody>(); mOffsets = new List<float>(); OriginalObject.SetActive(false); ReplaceObject.SetActive(true); foreach (var rb in GetComponentsInChildren<Rigidbody>()) { if (rb.gameObject != gameObject) { rb.isKinematic = true; rb.useGravity = false; mBodies.Add(rb); mOffsets.Add(Time.time + Random.value * 2.5f); } } } } } private void ApplyGravityOnBody(Rigidbody body) { body.isKinematic = false; body.useGravity = true; } private void Update() { if (mBodies != null && mBodies.Count > 0) { List<int> remove = new List<int>(); for (int i = 0; i < mBodies.Count; i++) { if (mOffsets[i] <= Time.time) { ApplyGravityOnBody(mBodies[i]); remove.Add(i); } } if (remove.Count == mBodies.Count) { mBodies = null; } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace RUF { public class BreakableBody : MonoBehaviour { public GameObject OriginalObject; public GameObject ReplaceObject; private void OnTriggerExit(Collider other) { if (other.CompareTag("Destroyer")) { if (tag == "Wall") { ApplyGravityOnBody(GetComponent<Rigidbody>()); } else { OriginalObject.SetActive(false); ReplaceObject.SetActive(true); foreach (var rb in GetComponentsInChildren<Rigidbody>()) { ApplyGravityOnBody(rb); } } } } private void ApplyGravityOnBody(Rigidbody body) { body.isKinematic = false; body.useGravity = true; body.AddForce(new Vector3(0, Random.value * 100f, 0)); } } }
mit
C#
14389b4f6fc7f8a00d5c3704de9baace92a02684
Allow app to be hosted in a virtual directory via IIS, e.g. /docs/
RaynaldM/autohelp,RaynaldM/autohelp,RaynaldM/autohelp,RaynaldM/autohelp,RaynaldM/autohelp,RaynaldM/autohelp
AutoHelp/Views/Dll/Index.cshtml
AutoHelp/Views/Dll/Index.cshtml
@{ ViewBag.Title = "Assembly Docs"; } @using aspnet_mvc_helpers @using AutoHelp.Helpers @model AutoHelp.domain.Models.Assembly @section scripts { @Html.CompressedPartial("_Namespaces") @Html.CompressedPartial("_Typebaselist") @Html.CompressedPartial("_Typebase-Classes") @Html.CompressedPartial("_Typebase-Enumerations") @Html.CompressedPartial("_Typebase-Delegates") @Html.CompressedPartial("_Typebase-Interfaces") @Html.CompressedPartial("_Typebase-Structures") @Html.CompressedPartial("_PopOver") @Html.TypeScript("~/Typescripts/Dll.ts", true) @*<script src="~/Scripts/ts/Dll.js"></script>*@ <script> var CurrentBasePage = new DllIndexPage( { DllId: '@Model.Id', urlGet: '@Url.Content("~/api/Assemblies")' }); </script> } <h2>@Model.Name &nbsp;<small>@Model.FullName</small></h2> <div class="row" style="height:85%;min-height: 85%;"> <div class="col-md-3 fullheight"> <h3>Namespaces</h3> <div class="divScroll"> <ul id="nmlist" class="list-group"></ul> </div> </div> <div class="col-md-3 fullheight"> <h3 id="typebasetitle"></h3> <div class="divScroll"> <div id="nmsublist"></div> </div> </div> <div id="typebase" class="col-md-6 row fullheight"> </div> </div>
@{ ViewBag.Title = "Assembly Docs"; } @using aspnet_mvc_helpers @using AutoHelp.Helpers @model AutoHelp.domain.Models.Assembly @section scripts { @Html.CompressedPartial("_Namespaces") @Html.CompressedPartial("_Typebaselist") @Html.CompressedPartial("_Typebase-Classes") @Html.CompressedPartial("_Typebase-Enumerations") @Html.CompressedPartial("_Typebase-Delegates") @Html.CompressedPartial("_Typebase-Interfaces") @Html.CompressedPartial("_Typebase-Structures") @Html.CompressedPartial("_PopOver") @Html.TypeScript("~/Typescripts/Dll.ts", true) @*<script src="~/Scripts/ts/Dll.js"></script>*@ <script> var CurrentBasePage = new DllIndexPage( { DllId: '@Model.Id', urlGet: '@Url.RootUrl()/api/Assemblies' }); </script> } <h2>@Model.Name &nbsp;<small>@Model.FullName</small></h2> <div class="row" style="height:85%;min-height: 85%;"> <div class="col-md-3 fullheight"> <h3>Namespaces</h3> <div class="divScroll"> <ul id="nmlist" class="list-group"></ul> </div> </div> <div class="col-md-3 fullheight"> <h3 id="typebasetitle"></h3> <div class="divScroll"> <div id="nmsublist"></div> </div> </div> <div id="typebase" class="col-md-6 row fullheight"> </div> </div>
mit
C#
026078645330107b0d07166677e9212aa79fcac6
Add methods to get the overriden values, or use a default value if not overridden. Make them extension methods so that we can call them on null objects.
izrik/ChamberLib,izrik/ChamberLib,izrik/ChamberLib
Overrides.cs
Overrides.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ChamberLib { public class Overrides { public LightingData? Lighting; public IMaterial Material; public IShaderProgram ShaderProgram; public IShaderStage VertexShader; public IShaderStage FragmentShader; } public static class OverridesHelper { public static LightingData? GetLighting(this Overrides overrides, LightingData? defaultValue) { if (overrides == null) return defaultValue; return overrides.Lighting ?? defaultValue; } public static IMaterial GetMaterial(this Overrides overrides, IMaterial defaultValue) { if (overrides == null) return defaultValue; return overrides.Material ?? defaultValue; } public static IShaderProgram GetShaderProgram(this Overrides overrides, IShaderProgram defaultValue) { if (overrides == null) return defaultValue; return overrides.ShaderProgram ?? defaultValue; } public static IShaderStage GetVertexShader(this Overrides overrides, IShaderStage defaultValue) { if (overrides == null) return defaultValue; return overrides.VertexShader ?? defaultValue; } public static IShaderStage GetFragmentShader(this Overrides overrides, IShaderStage defaultValue) { if (overrides == null) return defaultValue; return overrides.FragmentShader ?? defaultValue; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ChamberLib { public class Overrides { public LightingData? Lighting; public IMaterial Material; public IShaderProgram ShaderProgram; public IShaderStage VertexShader; public IShaderStage FragmentShader; } }
lgpl-2.1
C#
99d053ef81aca0291a9ad752185172490dbf1b10
Return a copy of the route values in functional tests.
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
test/WebSites/RoutingWebSite/TestResponseGenerator.cs
test/WebSites/RoutingWebSite/TestResponseGenerator.cs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNet.Mvc; using Microsoft.Framework.DependencyInjection; namespace RoutingWebSite { // Generates a response based on the expected URL and action context public class TestResponseGenerator { private readonly ActionContext _actionContext; public TestResponseGenerator(IContextAccessor<ActionContext> contextAccessor) { _actionContext = contextAccessor.Value; if (_actionContext == null) { throw new InvalidOperationException("ActionContext should not be null here."); } } public JsonResult Generate(params string[] expectedUrls) { var link = (string)null; var query = _actionContext.HttpContext.Request.Query; if (query.ContainsKey("link")) { var values = query .Where(kvp => kvp.Key != "link" && kvp.Key != "link_action" && kvp.Key != "link_controller") .ToDictionary(kvp => kvp.Key.Substring("link_".Length), kvp => (object)kvp.Value[0]); var urlHelper = _actionContext.HttpContext.RequestServices.GetService<IUrlHelper>(); link = urlHelper.Action(query["link_action"], query["link_controller"], values); } return new JsonResult(new { expectedUrls = expectedUrls, actualUrl = _actionContext.HttpContext.Request.Path.Value, routeValues = new Dictionary<string, object>(_actionContext.RouteData.Values), action = _actionContext.ActionDescriptor.Name, controller = ((ReflectedActionDescriptor)_actionContext.ActionDescriptor).ControllerDescriptor.Name, link, }); } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using Microsoft.AspNet.Mvc; using Microsoft.Framework.DependencyInjection; namespace RoutingWebSite { // Generates a response based on the expected URL and action context public class TestResponseGenerator { private readonly ActionContext _actionContext; public TestResponseGenerator(IContextAccessor<ActionContext> contextAccessor) { _actionContext = contextAccessor.Value; if (_actionContext == null) { throw new InvalidOperationException("ActionContext should not be null here."); } } public JsonResult Generate(params string[] expectedUrls) { var link = (string)null; var query = _actionContext.HttpContext.Request.Query; if (query.ContainsKey("link")) { var values = query .Where(kvp => kvp.Key != "link" && kvp.Key != "link_action" && kvp.Key != "link_controller") .ToDictionary(kvp => kvp.Key.Substring("link_".Length), kvp => (object)kvp.Value[0]); var urlHelper = _actionContext.HttpContext.RequestServices.GetService<IUrlHelper>(); link = urlHelper.Action(query["link_action"], query["link_controller"], values); } return new JsonResult(new { expectedUrls = expectedUrls, actualUrl = _actionContext.HttpContext.Request.Path.Value, routeValues = _actionContext.RouteData.Values, action = _actionContext.ActionDescriptor.Name, controller = ((ReflectedActionDescriptor)_actionContext.ActionDescriptor).ControllerDescriptor.Name, link, }); } } }
apache-2.0
C#
46b379899e0d7299ff8ebb37d3de83701414b9aa
add taiko hd mod (2nd attempt)
NeoAdonis/osu,ppy/osu,ppy/osu,peppy/osu-new,smoogipoo/osu,smoogipooo/osu,peppy/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu
osu.Game.Rulesets.Taiko/Mods/TaikoModHidden.cs
osu.Game.Rulesets.Taiko/Mods/TaikoModHidden.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Configuration; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Taiko.Objects.Drawables; namespace osu.Game.Rulesets.Taiko.Mods { public class TaikoModHidden : ModHidden, IApplicableToDifficulty { public override string Description => @"Beats fade out before you hit them!"; public override double ScoreMultiplier => 1.06; // In stable Taiko, hit position is 160, so playfield is essentially 160 pixels shorter // than actual screen width. Normalized screen height is 480, so on a 4:3 screen the // playfield ratio will actually be (640 - 160) / 480 = 1 // For 16:9 resolutions, screen width with normalized height becomes 853.33333 instead, // meaning 16:9 playfield ratio is (853.333 - 160) / 480 = 1.444444. // Thus, 4:3 ratio / 16:9 ratio = 1 / 1.4444 = 9 / 13 private const double hd_sv_scale = 9.0 / 13.0; private BeatmapDifficulty difficulty; private ControlPointInfo controlPointInfo; [SettingSource("Hide Time", "Multiplies the time the note stays hidden")] public BindableNumber<double> VisibilityMod { get; } = new BindableDouble { MinValue = 0.5, // Max visibility is only to be used with max playfield size MaxValue = 1.5, Default = 1.0, Value = 1.0, Precision = 0.01, }; protected override void ApplyIncreasedVisibilityState(DrawableHitObject hitObject, ArmedState state) { ApplyNormalVisibilityState(hitObject, state); } protected double MultiplierAt(double position) { var beatLength = controlPointInfo.TimingPointAt(position)?.BeatLength; var speedMultiplier = controlPointInfo.DifficultyPointAt(position)?.SpeedMultiplier; return difficulty.SliderMultiplier * (speedMultiplier ?? 1.0) * TimingControlPoint.DEFAULT_BEAT_LENGTH / (beatLength ?? TimingControlPoint.DEFAULT_BEAT_LENGTH); } protected override void ApplyNormalVisibilityState(DrawableHitObject hitObject, ArmedState state) { switch (hitObject) { case DrawableDrumRollTick _: break; case DrawableHit _: break; default: return; } // I *think* it's like this because stable's default velocity multiplier is 1.4 var preempt = 14000 / MultiplierAt(hitObject.HitObject.StartTime) * VisibilityMod.Value; var start = hitObject.HitObject.StartTime - preempt * 0.6; var duration = preempt * 0.3; using (hitObject.BeginAbsoluteSequence(start)) { // With 0 opacity the object is dying, and if I set a lifetime other issues appear... // Ideally these need to be fixed, but I lack the knowledge to do it, and this is good enough anyway. hitObject.FadeTo(0.0005f, duration); } } public void ReadFromDifficulty(BeatmapDifficulty difficulty) { } public void ApplyToDifficulty(BeatmapDifficulty difficulty) { this.difficulty = difficulty; difficulty.SliderMultiplier /= hd_sv_scale; } public override void ApplyToBeatmap(IBeatmap beatmap) { controlPointInfo = beatmap.ControlPointInfo; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects.Drawables; namespace osu.Game.Rulesets.Taiko.Mods { public class TaikoModHidden : ModHidden { public override string Description => @"Beats fade out before you hit them!"; public override double ScoreMultiplier => 1.06; public override bool HasImplementation => false; protected override void ApplyIncreasedVisibilityState(DrawableHitObject hitObject, ArmedState state) { } protected override void ApplyNormalVisibilityState(DrawableHitObject hitObject, ArmedState state) { } } }
mit
C#
4ff5310473b38e82244c0bdf2b240c16a5438922
Fix editor crashing when loading a beatmap for an unsupported r… (#7261)
johnneijzen/osu,UselessToucan/osu,ppy/osu,peppy/osu,2yangk23/osu,2yangk23/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu-new,ppy/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,johnneijzen/osu,EVAST9919/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,EVAST9919/osu,smoogipoo/osu,NeoAdonis/osu
osu.Game/Screens/Edit/Compose/ComposeScreen.cs
osu.Game/Screens/Edit/Compose/ComposeScreen.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Edit; using osu.Game.Screens.Edit.Compose.Components.Timeline; using osu.Game.Skinning; namespace osu.Game.Screens.Edit.Compose { public class ComposeScreen : EditorScreenWithTimeline { private HitObjectComposer composer; protected override Drawable CreateMainContent() { var ruleset = Beatmap.Value.BeatmapInfo.Ruleset?.CreateInstance(); composer = ruleset?.CreateHitObjectComposer(); if (ruleset == null || composer == null) return new ScreenWhiteBox.UnderConstructionMessage(ruleset == null ? "This beatmap" : $"{ruleset.Description}'s composer"); var beatmapSkinProvider = new BeatmapSkinProvidingContainer(Beatmap.Value.Skin); // the beatmapSkinProvider is used as the fallback source here to allow the ruleset-specific skin implementation // full access to all skin sources. var rulesetSkinProvider = new SkinProvidingContainer(ruleset.CreateLegacySkinProvider(beatmapSkinProvider)); // load the skinning hierarchy first. // this is intentionally done in two stages to ensure things are in a loaded state before exposing the ruleset to skin sources. return beatmapSkinProvider.WithChild(rulesetSkinProvider.WithChild(composer)); } protected override Drawable CreateTimelineContent() => composer == null ? base.CreateTimelineContent() : new TimelineHitObjectDisplay(composer.EditorBeatmap); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Edit; using osu.Game.Screens.Edit.Compose.Components.Timeline; using osu.Game.Skinning; namespace osu.Game.Screens.Edit.Compose { public class ComposeScreen : EditorScreenWithTimeline { private HitObjectComposer composer; protected override Drawable CreateMainContent() { var ruleset = Beatmap.Value.BeatmapInfo.Ruleset?.CreateInstance(); composer = ruleset?.CreateHitObjectComposer(); if (ruleset == null || composer == null) return new ScreenWhiteBox.UnderConstructionMessage(ruleset == null ? "This beatmap" : $"{ruleset.Description}'s composer"); var beatmapSkinProvider = new BeatmapSkinProvidingContainer(Beatmap.Value.Skin); // the beatmapSkinProvider is used as the fallback source here to allow the ruleset-specific skin implementation // full access to all skin sources. var rulesetSkinProvider = new SkinProvidingContainer(ruleset.CreateLegacySkinProvider(beatmapSkinProvider)); // load the skinning hierarchy first. // this is intentionally done in two stages to ensure things are in a loaded state before exposing the ruleset to skin sources. return beatmapSkinProvider.WithChild(rulesetSkinProvider.WithChild(composer)); } protected override Drawable CreateTimelineContent() => new TimelineHitObjectDisplay(composer.EditorBeatmap); } }
mit
C#
cd62ec9a691716882f1542bb207d0bb79059a08f
Change Windows small icon from 24px to 16px
smoogipooo/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework
osu.Framework/Platform/Windows/WindowsDesktopWindow.cs
osu.Framework/Platform/Windows/WindowsDesktopWindow.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 System.Runtime.InteropServices; using osu.Framework.Platform.Windows.Native; namespace osu.Framework.Platform.Windows { public class WindowsDesktopWindow : DesktopWindow { private const int seticon_message = 0x0080; private const int icon_big = 1; private const int icon_small = 0; private const int large_icon_size = 256; private const int small_icon_size = 16; private Icon smallIcon; private Icon largeIcon; /// <summary> /// On Windows, SDL will use the same image for both large and small icons (scaled as necessary). /// This can look bad if scaling down a large image, so we use the Windows API directly so as /// to get a cleaner icon set than SDL can provide. /// If called before the window has been created, or we do not find two separate icon sizes, we fall back to the base method. /// </summary> internal override void SetIconFromGroup(IconGroup iconGroup) { smallIcon = iconGroup.CreateIcon(small_icon_size, small_icon_size); largeIcon = iconGroup.CreateIcon(large_icon_size, large_icon_size); var windowHandle = WindowBackend.WindowHandle; if (windowHandle == IntPtr.Zero || largeIcon == null || smallIcon == null) base.SetIconFromGroup(iconGroup); else { SendMessage(windowHandle, seticon_message, (IntPtr)icon_small, smallIcon.Handle); SendMessage(windowHandle, seticon_message, (IntPtr)icon_big, largeIcon.Handle); } } [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); } }
// 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 System.Runtime.InteropServices; using osu.Framework.Platform.Windows.Native; namespace osu.Framework.Platform.Windows { public class WindowsDesktopWindow : DesktopWindow { private const int seticon_message = 0x0080; private const int icon_big = 1; private const int icon_small = 0; private const int large_icon_size = 256; private const int small_icon_size = 24; private Icon smallIcon; private Icon largeIcon; /// <summary> /// On Windows, SDL will use the same image for both large and small icons (scaled as necessary). /// This can look bad if scaling down a large image, so we use the Windows API directly so as /// to get a cleaner icon set than SDL can provide. /// If called before the window has been created, or we do not find two separate icon sizes, we fall back to the base method. /// </summary> internal override void SetIconFromGroup(IconGroup iconGroup) { smallIcon = iconGroup.CreateIcon(small_icon_size, small_icon_size); largeIcon = iconGroup.CreateIcon(large_icon_size, large_icon_size); var windowHandle = WindowBackend.WindowHandle; if (windowHandle == IntPtr.Zero || largeIcon == null || smallIcon == null) base.SetIconFromGroup(iconGroup); else { SendMessage(windowHandle, seticon_message, (IntPtr)icon_small, smallIcon.Handle); SendMessage(windowHandle, seticon_message, (IntPtr)icon_big, largeIcon.Handle); } } [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); } }
mit
C#
af09ed1b7fe648930f4bc084e2dd00b7307cf1e1
Make cursor test scene more automated
NeoAdonis/osu,EVAST9919/osu,peppy/osu-new,smoogipoo/osu,UselessToucan/osu,EVAST9919/osu,johnneijzen/osu,smoogipoo/osu,ppy/osu,peppy/osu,ZLima12/osu,ZLima12/osu,ppy/osu,peppy/osu,peppy/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,2yangk23/osu,johnneijzen/osu,UselessToucan/osu,NeoAdonis/osu,2yangk23/osu
osu.Game.Rulesets.Osu.Tests/TestSceneGameplayCursor.cs
osu.Game.Rulesets.Osu.Tests/TestSceneGameplayCursor.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 System.Collections.Generic; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Testing.Input; using osu.Game.Rulesets.Osu.UI.Cursor; using osuTK; namespace osu.Game.Rulesets.Osu.Tests { [TestFixture] public class TestSceneGameplayCursor : SkinnableTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(CursorTrail) }; [BackgroundDependencyLoader] private void load() { SetContents(() => new MovingCursorInputManager { Child = new OsuCursorContainer { RelativeSizeAxes = Axes.Both, Masking = true, } }); } private class MovingCursorInputManager : ManualInputManager { public MovingCursorInputManager() { UseParentInput = false; } protected override void Update() { base.Update(); const double spin_duration = 5000; double currentTime = Time.Current; double angle = (currentTime % spin_duration) / spin_duration * 2 * Math.PI; Vector2 rPos = new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle)); MoveMouseTo(ToScreenSpace(DrawSize / 2 + DrawSize / 3 * rPos)); } } } }
// 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 System.Collections.Generic; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Rulesets.Osu.UI.Cursor; namespace osu.Game.Rulesets.Osu.Tests { [TestFixture] public class TestSceneGameplayCursor : SkinnableTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(CursorTrail) }; [BackgroundDependencyLoader] private void load() { SetContents(() => new OsuCursorContainer { RelativeSizeAxes = Axes.Both, Masking = true, }); } } }
mit
C#
bc69ec77678f0a8c718ab7c5d44cd6334275b6ac
Change VSO to VSTS
devlead/website,cake-build-bot/website,SharpeRAD/Cake.Website,cake-build/website,cake-build/website,devlead/website,SharpeRAD/Cake.Website,cake-build-bot/website,devlead/website,cake-build/website
src/Cake.Web/Views/Home/Index.cshtml
src/Cake.Web/Views/Home/Index.cshtml
@model dynamic @{ ViewBag.Title = "Start"; ViewBag.Menu = "Home"; Layout = "~/Views/Shared/_Layout.cshtml"; } <div class="jumbotron"> <div class="container"> <h1>What is Cake?</h1> <p>Cake (C# Make) is a cross platform build automation system with a C# DSL to do things like compiling code, copy files/folders, running unit tests, compress files and build NuGet packages.</p> <p> <a class="btn btn-primary btn-lg" href="@Url.Action("Index", "Docs", new { path = "tutorials/getting-started" })" role="button">Get Started &raquo;</a> </p> </div> </div> <div class="container"> <div class="row"> <div class="col-xs-12 col-sm-6"> <h3 class="align-top">Familiar</h3> <p> Cake is built on top of the Roslyn and Mono compiler which enables you to write your build scripts in C#. </p> <h3>Cross platform</h3> <p> Cake is available on Windows, Linux and OS X. </p> <h3>Reliable</h3> <p> Regardless if you're building on your own machine, or building on a CI system such as AppVeyor, TeamCity, TFS, VSTS or Jenkins, Cake is built to behave in the same way. </p> <h3>Batteries included</h3> <p> Cake supports the most common tools used during builds such as MSBuild, MSTest, xUnit, NUnit, NuGet, ILMerge, WiX and SignTool out of the box. </p> <h3>Open source</h3> <p> We believe in open source and so should you. The source code for Cake is <a href="https://github.com/cake-build/cake">hosted on GitHub</a> and includes everything needed to build it yourself. </p> </div> <div class="col-sm-6 hidden-xs"> <img style="width: 100%;" src="~/Content/img/screenshot.png" alt=""/> </div> </div> </div>
@model dynamic @{ ViewBag.Title = "Start"; ViewBag.Menu = "Home"; Layout = "~/Views/Shared/_Layout.cshtml"; } <div class="jumbotron"> <div class="container"> <h1>What is Cake?</h1> <p>Cake (C# Make) is a cross platform build automation system with a C# DSL to do things like compiling code, copy files/folders, running unit tests, compress files and build NuGet packages.</p> <p> <a class="btn btn-primary btn-lg" href="@Url.Action("Index", "Docs", new { path = "tutorials/getting-started" })" role="button">Get Started &raquo;</a> </p> </div> </div> <div class="container"> <div class="row"> <div class="col-xs-12 col-sm-6"> <h3 class="align-top">Familiar</h3> <p> Cake is built on top of the Roslyn and Mono compiler which enables you to write your build scripts in C#. </p> <h3>Cross platform</h3> <p> Cake is available on Windows, Linux and OS X. </p> <h3>Reliable</h3> <p> Regardless if you're building on your own machine, or building on a CI system such as AppVeyor, TeamCity, TFS, VSO or Jenkins, Cake is built to behave in the same way. </p> <h3>Batteries included</h3> <p> Cake supports the most common tools used during builds such as MSBuild, MSTest, xUnit, NUnit, NuGet, ILMerge, WiX and SignTool out of the box. </p> <h3>Open source</h3> <p> We believe in open source and so should you. The source code for Cake is <a href="https://github.com/cake-build/cake">hosted on GitHub</a> and includes everything needed to build it yourself. </p> </div> <div class="col-sm-6 hidden-xs"> <img style="width: 100%;" src="~/Content/img/screenshot.png" alt=""/> </div> </div> </div>
mit
C#
fb6e06c5e4aac12f4ec85200cc327f3e3d00a26a
Fix bug
BERef/BibTeXLibrary
BibTeXLibrary/UnexpectedCharacterException.cs
BibTeXLibrary/UnexpectedCharacterException.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BibTeXLibrary { public class UnexpectedCharacterException : ParserErrorException { #region Private Field /// <summary> /// Customed error message. /// </summary> private readonly string _message; #endregion #region Public Property /// <summary> /// Error message. /// </summary> public override string Message { get { return _message; } } #endregion #region Constructor public UnexpectedCharacterException(int lineNo, int colNo, char unexpected) : base(lineNo, colNo) { _message = $"Line {lineNo}, Col {colNo}. Unexpected character: {unexpected.ToString()}."; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BibTeXLibrary { class UnexpectedCharacterException : ParserErrorException { #region Private Field /// <summary> /// Customed error message. /// </summary> private readonly string _message; #endregion #region Public Property /// <summary> /// Error message. /// </summary> public override string Message { get { return _message; } } #endregion #region Constructor public UnexpectedCharacterException(int lineNo, int colNo, char unexpected) : base(lineNo, colNo) { _message = $"Line {lineNo}, Col {colNo}. Unexpected character: {unexpected.ToString()}."; } #endregion } }
mit
C#
8fcb3cd667a857a08dff2486f4e4598aacddd19c
Use DefaultContractResolver in default JSON response negotiator (#70)
jchannon/Botwin
src/DefaultJsonResponseNegotiator.cs
src/DefaultJsonResponseNegotiator.cs
namespace Botwin { using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Net.Http.Headers; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; public class DefaultJsonResponseNegotiator : IResponseNegotiator { private readonly JsonSerializerSettings jsonSettings; public DefaultJsonResponseNegotiator() { var contractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy() }; this.jsonSettings = new JsonSerializerSettings { ContractResolver = contractResolver }; } public bool CanHandle(IList<MediaTypeHeaderValue> accept) { return accept.Any(x => x.MediaType.ToString().IndexOf("json", StringComparison.OrdinalIgnoreCase) >= 0); } public async Task Handle(HttpRequest req, HttpResponse res, object model, CancellationToken cancellationToken) { res.ContentType = "application/json; charset=utf-8"; await res.WriteAsync(JsonConvert.SerializeObject(model, this.jsonSettings), cancellationToken); } } }
namespace Botwin { using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Net.Http.Headers; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; public class DefaultJsonResponseNegotiator : IResponseNegotiator { private readonly JsonSerializerSettings jsonSettings; public DefaultJsonResponseNegotiator() { this.jsonSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; } public bool CanHandle(IList<MediaTypeHeaderValue> accept) { return accept.Any(x => x.MediaType.ToString().IndexOf("json", StringComparison.OrdinalIgnoreCase) >= 0); } public async Task Handle(HttpRequest req, HttpResponse res, object model, CancellationToken cancellationToken) { res.ContentType = "application/json; charset=utf-8"; await res.WriteAsync(JsonConvert.SerializeObject(model, this.jsonSettings), cancellationToken); } } }
mit
C#
c7407e2b358551ce3448fd6af2c420a81cd8f123
Add Version string to package for support for yaml script
AlexEyler/VSCopyAsPathCommand
CopyAsPathCommand/CopyAsPathCommandPackage.cs
CopyAsPathCommand/CopyAsPathCommandPackage.cs
using System; using System.Runtime.InteropServices; using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace CopyAsPathCommand { [PackageRegistration(UseManagedResourcesOnly = true)] [ProvideMenuResource("Menus.ctmenu", 1)] [InstalledProductRegistration(CopyAsPathCommandPackage.ProductName, CopyAsPathCommandPackage.ProductDescription, CopyAsPathCommandPackage.Version)] [Guid(CopyAsPathCommandPackage.PackageGuidString)] [ProvideAutoLoad(UIContextGuids.SolutionExists)] [ProvideOptionPage(typeof(OptionsPage), "Environment", "Copy as Path Command", 0, 0, true)] public sealed class CopyAsPathCommandPackage : Package { public const string Version = "1.0.6"; public const string ProductName = "Copy as path command"; public const string ProductDescription = "Right click on a solution explorer item and get its absolute path."; public const string PackageGuidString = "d40a488d-23d0-44cc-99fb-f6dd0717ab7d"; #region Package Members protected override void Initialize() { DTE2 envDte = this.GetService(typeof(DTE)) as DTE2; UIHierarchy solutionWindow = envDte.ToolWindows.SolutionExplorer; CopyAsPathCommand.Initialize(this, solutionWindow); base.Initialize(); } #endregion } }
using System; using System.Runtime.InteropServices; using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace CopyAsPathCommand { [PackageRegistration(UseManagedResourcesOnly = true)] [ProvideMenuResource("Menus.ctmenu", 1)] [InstalledProductRegistration(CopyAsPathCommandPackage.ProductName, CopyAsPathCommandPackage.ProductDescription, "1.0")] [Guid(CopyAsPathCommandPackage.PackageGuidString)] [ProvideAutoLoad(UIContextGuids.SolutionExists)] [ProvideOptionPage(typeof(OptionsPage), "Environment", "Copy as Path Command", 0, 0, true)] public sealed class CopyAsPathCommandPackage : Package { public const string ProductName = "Copy as path command"; public const string ProductDescription = "Right click on a solution explorer item and get its absolute path."; public const string PackageGuidString = "d40a488d-23d0-44cc-99fb-f6dd0717ab7d"; #region Package Members protected override void Initialize() { DTE2 envDte = this.GetService(typeof(DTE)) as DTE2; UIHierarchy solutionWindow = envDte.ToolWindows.SolutionExplorer; CopyAsPathCommand.Initialize(this, solutionWindow); base.Initialize(); } #endregion } }
mit
C#
973093653618fc015d75f0b46cc0fc706d84d32a
Add GetAttributeValue et SetAttribute to IBaseEntity
xaviermonin/EntityCore
EntityCore.Proxy/IBaseEntity.cs
EntityCore.Proxy/IBaseEntity.cs
 namespace EntityCore.Proxy { public interface IBaseEntity { int Id { get; set; } T GetAttributeValue<T>(string propertyName); void SetAttributeValue<T>(string propertyName, T value); } }
 namespace EntityCore.Proxy { public interface IBaseEntity { int Id { get; set; } } }
mit
C#
e15a00dec4bc9d0f412bb4fa362162549744be1a
Change PropertyAsObservable to return a BehaviorSubject
MHeasell/Mappy,MHeasell/Mappy
Mappy/ExtensionMethods.cs
Mappy/ExtensionMethods.cs
namespace Mappy { using System; using System.ComponentModel; using System.Reactive.Linq; using System.Reactive.Subjects; public static class ExtensionMethods { public static BehaviorSubject<TField> PropertyAsObservable<TSource, TField>(this TSource source, Func<TSource, TField> accessor, string name) where TSource : INotifyPropertyChanged { var subject = new BehaviorSubject<TField>(accessor(source)); // FIXME: This is leaky. // We create a subscription here but don't hold on to the reference. // We can never unregister our event handler without this. Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>( x => source.PropertyChanged += x, x => source.PropertyChanged -= x) .Where(x => x.EventArgs.PropertyName == name) .Select(_ => accessor(source)) .Subscribe(subject); return subject; } } }
namespace Mappy { using System; using System.ComponentModel; using System.Reactive.Linq; using System.Reactive.Subjects; public static class ExtensionMethods { public static IObservable<TField> PropertyAsObservable<TSource, TField>(this TSource source, Func<TSource, TField> accessor, string name) where TSource : INotifyPropertyChanged { var obs = Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>( x => source.PropertyChanged += x, x => source.PropertyChanged -= x) .Where(x => x.EventArgs.PropertyName == name) .Select(_ => accessor(source)) .Multicast(new BehaviorSubject<TField>(accessor(source))); // FIXME: This is leaky. // We create a connection here but don't hold on to the reference. // We can never unregister our event handler without this. obs.Connect(); return obs; } } }
mit
C#
254673e69e7a8ae7be63cd4470cd756fb12d401c
Use flag instead of `StreamWriter` changes
ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework
osu.Framework/Platform/FlushingStream.cs
osu.Framework/Platform/FlushingStream.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.IO; namespace osu.Framework.Platform { /// <summary> /// A <see cref="FileStream"/> which always flushes to disk on disposal. /// </summary> /// <remarks> /// This adds a considerable overhead, but is required to avoid files being potentially written to disk in a corrupt state. /// See https://stackoverflow.com/questions/49260358/what-could-cause-an-xml-file-to-be-filled-with-null-characters/52751216#52751216. /// </remarks> public class FlushingStream : FileStream { public FlushingStream(string path, FileMode mode, FileAccess access) : base(path, mode, access) { } private bool finalFlushRun; protected override void Dispose(bool disposing) { // dispose may be called more than once. without this check Flush will throw on an already-closed stream. if (!finalFlushRun) { finalFlushRun = true; try { Flush(true); } catch { // on some platforms, may fail due to a lower level file access issue. // we don't want to throw in disposal though. } } base.Dispose(disposing); } } }
// 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.IO; namespace osu.Framework.Platform { /// <summary> /// A <see cref="FileStream"/> which always flushes to disk on disposal. /// </summary> /// <remarks> /// This adds a considerable overhead, but is required to avoid files being potentially written to disk in a corrupt state. /// See https://stackoverflow.com/questions/49260358/what-could-cause-an-xml-file-to-be-filled-with-null-characters/52751216#52751216. /// </remarks> public class FlushingStream : FileStream { public FlushingStream(string path, FileMode mode, FileAccess access) : base(path, mode, access) { } protected override void Dispose(bool disposing) { try { Flush(true); } catch { // on some platforms, may fail due to the stream already being closed, or never being opened. // we don't really care about such failures. } base.Dispose(disposing); } } }
mit
C#
0fb33a3feaa9e33a8c1051b11b031badbccfe693
Rephrase for loop as Select within GenericArgumentResolver.ResolveTypeArguments.
fixie/fixie,JakeGinnivan/fixie,EliotJones/fixie,bardoloi/fixie,bardoloi/fixie,Duohong/fixie,KevM/fixie
src/Fixie/GenericArgumentResolver.cs
src/Fixie/GenericArgumentResolver.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Fixie { public class GenericArgumentResolver { public static Type[] ResolveTypeArguments(MethodInfo method, object[] parameters) { var genericArguments = method.GetGenericArguments(); var parameterTypes = method.GetParameters().Select(p => p.ParameterType).ToArray(); return genericArguments.Select(genericArgument => GetArgumentType(genericArgument, parameterTypes, parameters)).ToArray(); } static Type GetArgumentType(Type genericArgumentType, IList<Type> parameterTypes, object[] parameterValues) { var matchingArguments = new List<int>(); for (int i = 0; i < parameterTypes.Count; i++) if (parameterTypes[i] == genericArgumentType) matchingArguments.Add(i); if (matchingArguments.Count == 0) return typeof(object); if (matchingArguments.Count == 1) return parameterValues[matchingArguments[0]] == null ? typeof(object) : parameterValues[matchingArguments[0]].GetType(); object result = Combine(parameterValues[matchingArguments[0]], parameterValues[matchingArguments[1]]); result = matchingArguments.Skip(2).Select(a => parameterValues[a]).Aggregate(result, Combine); return result == null ? typeof(object) : result.GetType(); } static object Combine(object a, object b) { if (a == null) return b == null ? null : b.GetType().IsValueType ? null : b; if (b == null) return a.GetType().IsValueType ? null : a; if (a.GetType() == b.GetType()) return a; return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Fixie { public class GenericArgumentResolver { public static Type[] ResolveTypeArguments(MethodInfo method, object[] parameters) { var genericArguments = method.GetGenericArguments(); var parameterTypes = method.GetParameters().Select(p => p.ParameterType).ToList(); var typeParameters = new Type[genericArguments.Length]; for (int i = 0; i < typeParameters.Length; i++) typeParameters[i] = GetArgumentType(genericArguments[i], parameterTypes, parameters); return typeParameters; } static Type GetArgumentType(Type genericArgumentType, IList<Type> parameterTypes, object[] parameterValues) { var matchingArguments = new List<int>(); for (int i = 0; i < parameterTypes.Count; i++) if (parameterTypes[i] == genericArgumentType) matchingArguments.Add(i); if (matchingArguments.Count == 0) return typeof(object); if (matchingArguments.Count == 1) return parameterValues[matchingArguments[0]] == null ? typeof(object) : parameterValues[matchingArguments[0]].GetType(); object result = Combine(parameterValues[matchingArguments[0]], parameterValues[matchingArguments[1]]); result = matchingArguments.Skip(2).Select(a => parameterValues[a]).Aggregate(result, Combine); return result == null ? typeof(object) : result.GetType(); } static object Combine(object a, object b) { if (a == null) return b == null ? null : b.GetType().IsValueType ? null : b; if (b == null) return a.GetType().IsValueType ? null : a; if (a.GetType() == b.GetType()) return a; return null; } } }
mit
C#
0f121aa9ee9d6cf4c43b83f4cb9a2285ff45bc36
Update ExtractPhase.cs
Desolath/ConfuserEx3
Confuser.Protections/Compress/ExtractPhase.cs
Confuser.Protections/Compress/ExtractPhase.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Confuser.Core; using dnlib.DotNet; using dnlib.DotNet.MD; using dnlib.DotNet.Writer; namespace Confuser.Protections.Compress { internal class ExtractPhase : ProtectionPhase { public ExtractPhase(Compressor parent) : base(parent) { } public override ProtectionTargets Targets { get { return ProtectionTargets.Modules; } } public override string Name { get { return "Packer info extraction"; } } protected override void Execute(ConfuserContext context, ProtectionParameters parameters) { if (context.Packer == null) return; bool isExe = context.CurrentModule.Kind == ModuleKind.Windows || context.CurrentModule.Kind == ModuleKind.Console; if (context.Annotations.Get<CompressorContext>(context, Compressor.ContextKey) != null) { if (isExe) { context.Logger.Error("Too many executable modules!"); throw new ConfuserException(null); } return; } if (isExe) { var ctx = new CompressorContext { ModuleIndex = context.CurrentModuleIndex, Assembly = context.CurrentModule.Assembly, CompatMode = parameters.GetParameter(context, null, "compat", false) }; context.Annotations.Set(context, Compressor.ContextKey, ctx); ctx.ModuleName = context.CurrentModule.Name; ctx.EntryPoint = context.CurrentModule.EntryPoint; ctx.Kind = context.CurrentModule.Kind; if (!ctx.CompatMode) { context.CurrentModule.Name = "a"; context.CurrentModule.EntryPoint = null; context.CurrentModule.Kind = ModuleKind.NetModule; } context.CurrentModuleWriterListener.OnWriterEvent += new ResourceRecorder(ctx, context.CurrentModule).OnWriterEvent; } } class ResourceRecorder { readonly CompressorContext ctx; ModuleDef targetModule; public ResourceRecorder(CompressorContext ctx, ModuleDef module) { this.ctx = ctx; targetModule = module; } public void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { if (e.WriterEvent == ModuleWriterEvent.MDEndAddResources) { var writer = (ModuleWriterBase)sender; ctx.ManifestResources = new List<Tuple<uint, uint, string>>(); Dictionary<uint, byte[]> stringDict = writer.MetaData.StringsHeap.GetAllRawData().ToDictionary(pair => pair.Key, pair => pair.Value); foreach (RawManifestResourceRow resource in writer.MetaData.TablesHeap.ManifestResourceTable) ctx.ManifestResources.Add(Tuple.Create(resource.Offset, resource.Flags, Encoding.UTF8.GetString(stringDict[resource.Name]))); ctx.EntryPointToken = writer.MetaData.GetToken(ctx.EntryPoint).Raw; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Confuser.Core; using dnlib.DotNet; using dnlib.DotNet.MD; using dnlib.DotNet.Writer; namespace Confuser.Protections.Compress { internal class ExtractPhase : ProtectionPhase { public ExtractPhase(Compressor parent) : base(parent) { } public override ProtectionTargets Targets { get { return ProtectionTargets.Modules; } } public override string Name { get { return "Packer info extraction"; } } protected override void Execute(ConfuserContext context, ProtectionParameters parameters) { if (context.Packer == null) return; bool isExe = context.CurrentModule.Kind == ModuleKind.Windows || context.CurrentModule.Kind == ModuleKind.Console; if (context.Annotations.Get<CompressorContext>(context, Compressor.ContextKey) != null) { if (isExe) { context.Logger.Error("Too many executable modules!"); throw new ConfuserException(null); } return; } if (isExe) { var ctx = new CompressorContext { ModuleIndex = context.CurrentModuleIndex, Assembly = context.CurrentModule.Assembly, CompatMode = parameters.GetParameter(context, null, "compat", false) }; context.Annotations.Set(context, Compressor.ContextKey, ctx); ctx.ModuleName = context.CurrentModule.Name; ctx.EntryPoint = context.CurrentModule.EntryPoint; ctx.Kind = context.CurrentModule.Kind; if (!ctx.CompatMode) { context.CurrentModule.Name = "koi"; context.CurrentModule.EntryPoint = null; context.CurrentModule.Kind = ModuleKind.NetModule; } context.CurrentModuleWriterListener.OnWriterEvent += new ResourceRecorder(ctx, context.CurrentModule).OnWriterEvent; } } class ResourceRecorder { readonly CompressorContext ctx; ModuleDef targetModule; public ResourceRecorder(CompressorContext ctx, ModuleDef module) { this.ctx = ctx; targetModule = module; } public void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { if (e.WriterEvent == ModuleWriterEvent.MDEndAddResources) { var writer = (ModuleWriterBase)sender; ctx.ManifestResources = new List<Tuple<uint, uint, string>>(); Dictionary<uint, byte[]> stringDict = writer.MetaData.StringsHeap.GetAllRawData().ToDictionary(pair => pair.Key, pair => pair.Value); foreach (RawManifestResourceRow resource in writer.MetaData.TablesHeap.ManifestResourceTable) ctx.ManifestResources.Add(Tuple.Create(resource.Offset, resource.Flags, Encoding.UTF8.GetString(stringDict[resource.Name]))); ctx.EntryPointToken = writer.MetaData.GetToken(ctx.EntryPoint).Raw; } } } } }
mit
C#
19ae7a737ff8e9018267502c7f77ce065723ef7d
Rename to reflect which position is meant
Xeeynamo/KingdomHearts
OpenKh.Kh2/Jiminy/Char.cs
OpenKh.Kh2/Jiminy/Char.cs
using System.Collections.Generic; using System.IO; using System.Linq; using Xe.BinaryMapper; namespace OpenKh.Kh2.Jiminy { public class Char { public const int MagicCode = 0x48434D4A; [Data] public byte World { get; set; } [Data] public byte Picture { get; set; } //index jmface [Data] public byte PictureBgColor { get; set; } [Data] public byte Padding { get; set; } [Data] public ushort Id { get; set; } [Data] public ushort Title { get; set; } [Data] public ushort Description { get; set; } [Data] public ushort SecondTitle { get; set; } //used for disney and ff characters, describes where they come from [Data] public ushort ObjectId { get; set; } //00objentry [Data] public ushort Unk0E { get; set; } [Data] public ushort Unk10 { get; set; } [Data] public short ObjectPositionX { get; set; } //z_un_0029e4c8 [Data] public short ObjectPositionY { get; set; } [Data] public short ObjectRotationX { get; set; } [Data] public short Unk18 { get; set; } [Data] public short Unk1A { get; set; } [Data] public float Unk1C { get; set; } //this is read like a float, but the it behaves different?! third byte controls the size [Data] public float Unk20 { get; set; } public static List<Char> Read(Stream stream) => BaseJiminy<Char>.Read(stream).Items; public static void Write(Stream stream, IEnumerable<Char> items) => BaseJiminy<Char>.Write(stream, MagicCode, items.ToList()); } }
using System.Collections.Generic; using System.IO; using System.Linq; using Xe.BinaryMapper; namespace OpenKh.Kh2.Jiminy { public class Char { public const int MagicCode = 0x48434D4A; [Data] public byte World { get; set; } [Data] public byte Picture { get; set; } //index jmface [Data] public byte PictureBgColor { get; set; } [Data] public byte Padding { get; set; } [Data] public ushort Id { get; set; } [Data] public ushort Title { get; set; } [Data] public ushort Description { get; set; } [Data] public ushort SecondTitle { get; set; } //used for disney and ff characters, describes where they come from [Data] public ushort ObjectId { get; set; } //00objentry [Data] public ushort Unk0E { get; set; } [Data] public ushort Unk10 { get; set; } [Data] public short PositionX { get; set; } //z_un_0029e4c8 [Data] public short PositionY { get; set; } [Data] public short RotationX { get; set; } [Data] public short Unk18 { get; set; } [Data] public short Unk1A { get; set; } [Data] public float Unk1C { get; set; } //this is read like a float, but the it behaves different?! third byte controls the size [Data] public float Unk20 { get; set; } public static List<Char> Read(Stream stream) => BaseJiminy<Char>.Read(stream).Items; public static void Write(Stream stream, IEnumerable<Char> items) => BaseJiminy<Char>.Write(stream, MagicCode, items.ToList()); } }
mit
C#
ba865af04b8eed34e6da3d282bce27f3ff38bd5a
Update Program.cs
ffMathy/testability-kata
src/TestabilityKata/Program.cs
src/TestabilityKata/Program.cs
using System; using System.IO; namespace TestabilityKata { public class Program { public static void Main(string[] args) { try { Logger.Log(LogLevel.Warning, "Some warning - program is starting up or whatever"); MailSender.SendMail("some-invalid-email-address.com", "Program has started."); } catch(Exception ex) { Logger.Log(LogLevel.Error, "An error occured: " + ex); } } } enum LogLevel { Warning, Error } static class Logger { public static void Log(LogLevel logLevel, string logText) { Console.WriteLine(logLevel + ": " + logText); if (logLevel == LogLevel.Error) { //also log to file var writer = new CustomFileWriter(@"C:\" + logLevel + "-annoying-log-file.txt"); writer.AppendLine(logText); //send e-mail about error MailSender.SendMail("mathias.lorenzen@mailinator.com", logText); } } } static class MailSender { public static void SendMail(string recipient, string content) { if (!recipient.Contains("@")) throw new ArgumentException("The recipient must be a valid e-mail.", nameof(recipient)); //for the sake of simplicity, this actually doesn't send an e-mail right now - but let's pretend it does. Console.WriteLine("Sent e-mail to " + recipient + " with content \"" + content + "\""); } } class CustomFileWriter { public string FilePath { get; } public CustomFileWriter(string filePath) { FilePath = filePath; } public void AppendLine(string line) { if (!File.Exists(FilePath)) File.WriteAllText(FilePath, ""); File.SetAttributes(FilePath, FileAttributes.Normal); File.AppendAllLines(FilePath, new[] { line }); File.SetAttributes(FilePath, FileAttributes.ReadOnly); } } }
using System; using System.IO; namespace TestabilityKata { public class Program { public static void Main(string[] args) { try { Logger.Log(LogLevel.Warning, "Some warning - program is starting up or whatever"); MailSender.SendMail("some-invalid-email-address.com", "Program has started."); } catch(Exception ex) { Logger.Log(LogLevel.Error, "An error occured: " + ex); } } } enum LogLevel { Warning, Error } static class Logger { public static void Log(LogLevel logLevel, string logText) { Console.WriteLine(logLevel + ": " + logText); if (logLevel == LogLevel.Error) { //also log to file var writer = new CustomFileWriter(@"C:\annoying-log-file.txt"); writer.AppendLine(logText); //send e-mail about error MailSender.SendMail("mathias.lorenzen@mailinator.com", logText); } } } static class MailSender { public static void SendMail(string recipient, string content) { if (!recipient.Contains("@")) throw new ArgumentException("The recipient must be a valid e-mail.", nameof(recipient)); //for the sake of simplicity, this actually doesn't send an e-mail right now - but let's pretend it does. Console.WriteLine("Sent e-mail to " + recipient + " with content \"" + content + "\""); } } class CustomFileWriter { public string FilePath { get; } public CustomFileWriter(string filePath) { FilePath = filePath; } public void AppendLine(string line) { if (!File.Exists(FilePath)) File.WriteAllText(FilePath, ""); File.SetAttributes(FilePath, FileAttributes.Normal); File.AppendAllLines(FilePath, new[] { line }); File.SetAttributes(FilePath, FileAttributes.ReadOnly); } } }
mit
C#
822ee5f981b9f44f5743fe45ea8f80fa807fb4c2
Add MatchTo2
bartsokol/Monacs
Monacs.Core/Tuples/Result.Tuple.Extensions.cs
Monacs.Core/Tuples/Result.Tuple.Extensions.cs
using System; using static Monacs.Core.Result; namespace Monacs.Core.Tuples { public static class Result { /* Bind2 */ public static Result<TResult> Bind2<TResult, T1, T2>(this Result<(T1, T2)> result, Func<T1, T2, Result<TResult>> func) => result.IsOk ? func(result.Value.Item1, result.Value.Item2) : Error<TResult>(result.Error); /* Bind3 */ public static Result<TResult> Bind3<TResult, T1, T2, T3>(this Result<(T1, T2, T3)> result, Func<T1, T2, T3, Result<TResult>> func) => result.IsOk ? func(result.Value.Item1, result.Value.Item2, result.Value.Item3) : Error<TResult>(result.Error); /* Map2 */ public static Result<TResult> Map2<TResult, T1, T2>(this Result<(T1, T2)> result, Func<T1, T2, TResult> func) => result.IsOk ? Ok(func(result.Value.Item1, result.Value.Item2)) : Error<TResult>(result.Error); /* Map3 */ public static Result<TResult> Map3<TResult, T1, T2, T3>(this Result<(T1, T2, T3)> result, Func<T1, T2, T3, TResult> func) => result.IsOk ? Ok(func(result.Value.Item1, result.Value.Item2, result.Value.Item3)) : Error<TResult>(result.Error); /* Match2 */ public static TVal Match2<TFst, TSnd, TVal>( this Result<(TFst fst, TSnd snd)> result, Func<TFst, TSnd, TVal> ok, Func<ErrorDetails, TVal> error) => result.IsOk ? ok(result.Value.fst, result.Value.snd) : error(result.Error); public static TVal MatchTo2<TFst, TSnd, TVal>(this Result<(TFst fst, TSnd snd)> result, TVal some, TVal none) => result.IsOk ? some : none; /* Match3 */ public static TVal Match3<TFst, TSnd, TTrd, TVal>(this Result<(TFst fst, TSnd snd, TTrd trd)> result, Func<TFst, TSnd, TTrd, TVal> ok, Func<ErrorDetails, TVal> error) => result.IsOk ? ok(result.Value.fst, result.Value.snd, result.Value.trd) : error(result.Error); } }
using System; using static Monacs.Core.Result; namespace Monacs.Core.Tuples { public static class Result { /* Bind2 */ public static Result<TResult> Bind2<TResult, T1, T2>(this Result<(T1, T2)> result, Func<T1, T2, Result<TResult>> func) => result.IsOk ? func(result.Value.Item1, result.Value.Item2) : Error<TResult>(result.Error); /* Bind3 */ public static Result<TResult> Bind3<TResult, T1, T2, T3>(this Result<(T1, T2, T3)> result, Func<T1, T2, T3, Result<TResult>> func) => result.IsOk ? func(result.Value.Item1, result.Value.Item2, result.Value.Item3) : Error<TResult>(result.Error); /* Map2 */ public static Result<TResult> Map2<TResult, T1, T2>(this Result<(T1, T2)> result, Func<T1, T2, TResult> func) => result.IsOk ? Ok(func(result.Value.Item1, result.Value.Item2)) : Error<TResult>(result.Error); /* Map3 */ public static Result<TResult> Map3<TResult, T1, T2, T3>(this Result<(T1, T2, T3)> result, Func<T1, T2, T3, TResult> func) => result.IsOk ? Ok(func(result.Value.Item1, result.Value.Item2, result.Value.Item3)) : Error<TResult>(result.Error); /* Match2 */ public static TVal Match2<TFst, TSnd, TVal>( this Result<(TFst fst, TSnd snd)> result, Func<TFst, TSnd, TVal> ok, Func<ErrorDetails, TVal> error) => result.IsOk ? ok(result.Value.fst, result.Value.snd) : error(result.Error); /* Match3 */ public static TVal Match3<TFst, TSnd, TTrd, TVal>(this Result<(TFst fst, TSnd snd, TTrd trd)> result, Func<TFst, TSnd, TTrd, TVal> ok, Func<ErrorDetails, TVal> error) => result.IsOk ? ok(result.Value.fst, result.Value.snd, result.Value.trd) : error(result.Error); } }
mit
C#
ddf623a784929303a345af326032cbab0eb66aff
Make user not-required for DirectEmailHistory
MCLD/greatreadingadventure,MCLD/greatreadingadventure,MCLD/greatreadingadventure,MCLD/greatreadingadventure,MCLD/greatreadingadventure
src/GRA.Data/Model/DirectEmailHistory.cs
src/GRA.Data/Model/DirectEmailHistory.cs
using System.ComponentModel.DataAnnotations; namespace GRA.Data.Model { public class DirectEmailHistory : Abstract.BaseDbEntity { public string BodyHtml { get; set; } public string BodyText { get; set; } [Required] [MaxLength(255)] public string FromEmailAddress { get; set; } [Required] [MaxLength(255)] public string FromName { get; set; } public bool IsBulk { get; set; } [Required] public int LanguageId { get; set; } [MaxLength(255)] public string OverrideToEmailAddress { get; set; } [Required] public string SentResponse { get; set; } [Required] [MaxLength(255)] public string Subject { get; set; } public bool Successful { get; set; } [Required] [MaxLength(255)] public string ToEmailAddress { get; set; } [MaxLength(255)] public string ToName { get; set; } public User User { get; set; } public int? UserId { get; set; } } }
using System.ComponentModel.DataAnnotations; namespace GRA.Data.Model { public class DirectEmailHistory : Abstract.BaseDbEntity { public string BodyHtml { get; set; } public string BodyText { get; set; } [Required] [MaxLength(255)] public string FromEmailAddress { get; set; } [Required] [MaxLength(255)] public string FromName { get; set; } public bool IsBulk { get; set; } [Required] public int LanguageId { get; set; } [MaxLength(255)] public string OverrideToEmailAddress { get; set; } [Required] public string SentResponse { get; set; } [Required] [MaxLength(255)] public string Subject { get; set; } public bool Successful { get; set; } [Required] [MaxLength(255)] public string ToEmailAddress { get; set; } [MaxLength(255)] public string ToName { get; set; } public User User { get; set; } [Required] public int UserId { get; set; } } }
mit
C#
cc5723faaab81a3cac22fec817916ec08515bea8
update version number
ekonbenefits/impromptu-interface,LancelotMak/lancelotmakumbila9-description,cgourlay/impromptu-interface,LancelotMak/lancelotmakumbila9-description,ekonbenefits/impromptu-interface
ImpromptuInterface/Properties/AssemblyInfo.cs
ImpromptuInterface/Properties/AssemblyInfo.cs
// // Copyright 2010 Ekon Benefits // // 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.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("ImpromptuInterface")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ekon Benefits")] [assembly: AssemblyProduct("ImpromptuInterface")] [assembly: AssemblyCopyright("Copyright © Ekon Benefits 2010")] [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("fe08c33f-ea0d-429f-82c2-846f6e4c4f13")] // 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.0.0.*")]
// // Copyright 2010 Ekon Benefits // // 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.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("ImpromptuInterface")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ekon Benefits")] [assembly: AssemblyProduct("ImpromptuInterface")] [assembly: AssemblyCopyright("Copyright © Ekon Benefits 2010")] [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("fe08c33f-ea0d-429f-82c2-846f6e4c4f13")] // 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.*")]
apache-2.0
C#
206806915a8382cbeae81fba737064be6ad038d3
Add Read/Write methods
ektrah/nsec
src/Cryptography/Utilities.cs
src/Cryptography/Utilities.cs
using System; using System.Runtime.CompilerServices; namespace NSec.Cryptography { internal static class Utilities { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T Read<T>( this ReadOnlySpan<byte> span) where T : struct { if (span.Length < Unsafe.SizeOf<T>()) throw new ArgumentException(); return Unsafe.ReadUnaligned<T>(ref span.DangerousGetPinnableReference()); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint ReadBigEndian( this ReadOnlySpan<byte> span) { return BitConverter.IsLittleEndian ? Reverse(span.Read<uint>()) : span.Read<uint>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint ReadLittleEndian( this ReadOnlySpan<byte> span) { return BitConverter.IsLittleEndian ? span.Read<uint>() : Reverse(span.Read<uint>()); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint ToBigEndian( uint value) { return BitConverter.IsLittleEndian ? Reverse(value) : value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Write<T>( this Span<byte> span, T value) where T : struct { if (span.Length < Unsafe.SizeOf<T>()) throw new ArgumentException(); Unsafe.WriteUnaligned(ref span.DangerousGetPinnableReference(), value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteBigEndian( this Span<byte> span, uint value) { span.Write(BitConverter.IsLittleEndian ? Reverse(value) : value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteLittleEndian( this Span<byte> span, uint value) { span.Write(BitConverter.IsLittleEndian ? value : Reverse(value)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint Reverse( uint value) { return unchecked( (value << 24) | ((value & 0xFF00) << 8) | ((value & 0xFF0000) >> 8) | (value >> 24)); } } }
using System; using System.Runtime.CompilerServices; namespace NSec.Cryptography { internal static class Utilities { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint ToBigEndian( uint value) { if (BitConverter.IsLittleEndian) { return unchecked( (value << 24) | ((value & 0xFF00) << 8) | ((value & 0xFF0000) >> 8) | (value >> 24)); } else { return value; } } } }
mit
C#
70d6f52a7f36c66418f6d8d3e541e63715f98ed4
fix #6
bengreenier/Unity-MenuStack
Assets/Scripts/Navigation/NextMenuNavigator.cs
Assets/Scripts/Navigation/NextMenuNavigator.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace MenuStack.Navigation { /// <summary> /// Represents a menu navigator that navigates the next <see cref="Menu"/> in the <see cref="MenuRoot"/> /// </summary> public class NextMenuNavigator : BaseMenuNavigator { /// <summary> /// Provides a location to navigate to, when navigation occurs /// </summary> /// <returns><see cref="Menu"/> to navigate to</returns> protected override Menu GetNavigationLocation() { return FindFirstRecursively(this.GetComponentInParent<MenuRoot>().transform, this.GetComponentInParent<Menu>()); } /// <summary> /// Internal recursive matcher /// </summary> /// <param name="root">the root level transform to start matching</param> /// <param name="current">the current menu, we want the one after this</param> /// <param name="hasSeenCurrent">indicates if we've yet passed <c>current</c> in the tree</param> /// <returns>a matched <see cref="Menu"/>, or <c>null</c></returns> public Menu FindFirstRecursively(Transform root, Menu current, bool hasSeenCurrent = false) { for (var i = 0; i < root.childCount; i++) { var child = root.GetChild(i); var menu = child.GetDerivedMenuComponent(); if (menu != null) { if (menu == current) { hasSeenCurrent = true; } else if (menu != current && hasSeenCurrent) { return menu; } } if (child.childCount > 0) { var res = FindFirstRecursively(child, current, hasSeenCurrent); if (res != null) { return res; } } } return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace MenuStack.Navigation { /// <summary> /// Represents a menu navigator that navigates the next <see cref="Menu"/> in the <see cref="MenuRoot"/> /// </summary> public class NextMenuNavigator : BaseMenuNavigator { /// <summary> /// Provides a location to navigate to, when navigation occurs /// </summary> /// <returns><see cref="Menu"/> to navigate to</returns> protected override Menu GetNavigationLocation() { return FindFirstRecursively(this.GetComponentInParent<MenuRoot>().transform, this.GetComponentInParent<Menu>()); } /// <summary> /// Internal recursive matcher /// </summary> /// <param name="root">the root level transform to start matching</param> /// <param name="current">the current menu, we want the one after this</param> /// <returns>a matched <see cref="Menu"/>, or <c>null</c></returns> public Menu FindFirstRecursively(Transform root, Menu current) { for (var i = 0; i < root.childCount; i++) { var child = root.GetChild(i); var menu = child.GetDerivedMenuComponent(); if (menu != null && menu != current) { return menu; } if (child.childCount > 0) { var res = FindFirstRecursively(child, current); if (res != null) { return res; } } } return null; } } }
mit
C#
7cf4248ca443d8ad05a8ffcd5d5cf47ff54fc43d
Fix next page button on listinvoices
btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver
BTCPayServer/Views/Invoice/ListInvoices.cshtml
BTCPayServer/Views/Invoice/ListInvoices.cshtml
@model InvoicesModel @{ ViewData["Title"] = "Invoices"; } <section> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> @Html.Partial("_StatusMessage", Model.StatusMessage) </div> </div> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">@ViewData["Title"]</h2> <hr class="primary"> <p>Create, search or pay an invoice.</p> <div class="form-group"> <form asp-action="SearchInvoice" method="post"> <input asp-for="SearchTerm" class="form-control" /> <input type="hidden" asp-for="Count" /> <span asp-validation-for="SearchTerm" class="text-danger"></span> <button type="button" class="btn btn-default" title="Search invoice"> <span class="glyphicon glyphicon-search"></span> Search </button> </form> </div> </div> </div> <div class="row"> <a asp-action="CreateInvoice" class="btn btn-success" role="button"><span class="glyphicon glyphicon-plus"></span> Create a new invoice</a> <table class="table"> <thead class="thead-inverse"> <tr> <th>Date</th> <th>InvoiceId</th> <th>Status</th> <th>Amount</th> <th>Actions</th> </tr> </thead> <tbody> @foreach(var invoice in Model.Invoices) { <tr> <td>@invoice.Date</td> <td>@invoice.InvoiceId</td> <td>@invoice.Status</td> <td>@invoice.AmountCurrency</td> <td><a asp-action="Checkout" asp-route-invoiceId="@invoice.InvoiceId">Checkout</a></td> </tr> } </tbody> </table> <span> @if(Model.Skip != 0) { <a href="@Url.Action("ListInvoices", new { searchTerm = Model.SearchTerm, skip = Math.Max(0, Model.Skip - Model.Count), count = Model.Count, })"><<</a><span> - </span> } <a href="@Url.Action("ListInvoices", new { searchTerm = Model.SearchTerm, skip = Model.Skip + Model.Count, count = Model.Count, })">>></a> </span> </div> </div> </section>
@model InvoicesModel @{ ViewData["Title"] = "Invoices"; } <section> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> @Html.Partial("_StatusMessage", Model.StatusMessage) </div> </div> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">@ViewData["Title"]</h2> <hr class="primary"> <p>Create, search or pay an invoice.</p> <div class="form-group"> <form asp-action="SearchInvoice" method="post"> <input asp-for="SearchTerm" class="form-control" /> <input type="hidden" asp-for="Count" /> <span asp-validation-for="SearchTerm" class="text-danger"></span> <button type="button" class="btn btn-default" title="Search invoice"> <span class="glyphicon glyphicon-search"></span> Search </button> </form> </div> </div> </div> <div class="row"> <a asp-action="CreateInvoice" class="btn btn-success" role="button"><span class="glyphicon glyphicon-plus"></span> Create a new invoice</a> <table class="table"> <thead class="thead-inverse"> <tr> <th>Date</th> <th>InvoiceId</th> <th>Status</th> <th>Amount</th> <th>Actions</th> </tr> </thead> <tbody> @foreach(var invoice in Model.Invoices) { <tr> <td>@invoice.Date</td> <td>@invoice.InvoiceId</td> <td>@invoice.Status</td> <td>@invoice.AmountCurrency</td> <td><a asp-action="Checkout" asp-route-invoiceId="@invoice.InvoiceId">Checkout</a></td> </tr> } </tbody> </table> <span> @if(Model.Skip != 0) { <a href="@Url.Action("Index", new { searchTerm = Model.SearchTerm, skip = Math.Max(0, Model.Skip - Model.Count), count = Model.Count, })"><<</a><span> - </span> } <a href="@Url.Action("Index", new { searchTerm = Model.SearchTerm, skip = Model.Skip + Model.Count, count = Model.Count, })">>></a> </span> </div> </div> </section>
mit
C#
5f2f8d17596639f29be78315c668e90295be315a
Complete unit tests
aloisdg/RandomUtils
RandomUtils.Test/Tests.cs
RandomUtils.Test/Tests.cs
using System; using System.Diagnostics; using NUnit.Framework; namespace RandomUtils.Test { [TestFixture] public class Tests { private const int Seed = 4; [Test] public void TestNextBoolean() { Assert.IsTrue(RandomUtils.NextBoolean(new Random(Seed)) && !RandomUtils.NextBoolean(new Random(Seed - 1))); } [Test] public void TestNextInt() { Assert.AreEqual(1752227528, (RandomUtils.NextInt(new Random(Seed)))); } [Test] public void TestNextLong() { Assert.AreEqual(496238097881962952, RandomUtils.NextLong(new Random(Seed))); } [Test] public void TestNextFloat() { Assert.AreEqual(-0.0120300725f, RandomUtils.NextFloat(new Random(Seed))); } [Test] public void TestNextDouble() { Assert.AreEqual(0.81594452672449147d, RandomUtils.NextDouble(new Random(Seed))); } } }
using NUnit.Framework; namespace RandomUtils.Test { [TestFixture] public class Tests { [Test] public void TestNextBoolean() { Assert.IsTrue(RandomUtils.NextBoolean() is bool); } } }
apache-2.0
C#
7ec9ba69c836de6e5ca3fb2198c92a29c8d58885
Update the assembly information to add the right owners to the package.
AlexGhiondea/OAuth.net,AlexGhiondea/OAuth.net
src/OAuth.net/Properties/AssemblyInfo.cs
src/OAuth.net/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("OAuth.net")] [assembly: AssemblyDescription("OAuth authenticator implementation")] [assembly: AssemblyProduct("OAuth.net")] [assembly: AssemblyCopyright("Copyright © Alex Ghiondea 2015")] // 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("53713a6f-04fb-46ff-954b-366a7ce12eb0")] // 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")]
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("OAuth.net")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("OAuth.net")] [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("53713a6f-04fb-46ff-954b-366a7ce12eb0")] // 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#
0438aa69f336b47ddd5121b1ee684dc6cdd5fcd2
Use range and theory to test a larger range
mattgwagner/CertiPay.Payroll.Common
CertiPay.Payroll.Common.Tests/PayrollFrequencyTests.cs
CertiPay.Payroll.Common.Tests/PayrollFrequencyTests.cs
using NUnit.Framework; using System; namespace CertiPay.Payroll.Common.Tests { public class PayrollFrequencyTests { [Test] [TestCase(PayrollFrequency.Monthly, 12)] [TestCase(PayrollFrequency.SemiMonthly, 24)] [TestCase(PayrollFrequency.Weekly, 52)] [TestCase(PayrollFrequency.Daily, 260)] [TestCase(PayrollFrequency.BiWeekly, 26)] public void Should_Return_Correct_Annualized_PayPeriods(PayrollFrequency freq, int expectedPeriods) { Assert.AreEqual(expectedPeriods, freq.AnnualizedPayPeriods()); } [Theory] public void Should_Calculate_Annualized_Pay(PayrollFrequency freq, [Random(0, 10000.00, 50)]Decimal payPeriod) { Assert.That(freq.CalculateAnnualized(payPeriod), Is.EqualTo(freq.AnnualizedPayPeriods() * payPeriod)); } [Theory] public void Should_Calculate_DeAnnualized_Pay(PayrollFrequency freq, [Random(0, 300000.00, 50)]Decimal perYear) { Assert.That(freq.CalculateDeannualized(perYear), Is.EqualTo(perYear / freq.AnnualizedPayPeriods()).Within(0.01)); } } }
using NUnit.Framework; using System; namespace CertiPay.Payroll.Common.Tests { public class PayrollFrequencyTests { [Test] [TestCase(PayrollFrequency.Monthly, 12)] [TestCase(PayrollFrequency.SemiMonthly, 24)] [TestCase(PayrollFrequency.Weekly, 52)] [TestCase(PayrollFrequency.Daily, 260)] [TestCase(PayrollFrequency.BiWeekly, 26)] public void Should_Return_Correct_Annualized_PayPeriods(PayrollFrequency freq, int expectedPeriods) { Assert.AreEqual(expectedPeriods, freq.AnnualizedPayPeriods()); } [Test] [TestCase(PayrollFrequency.Monthly, 1000, 12000)] [TestCase(PayrollFrequency.BiWeekly, 1000, 26000)] [TestCase(PayrollFrequency.Weekly, 1000, 52000)] [TestCase(PayrollFrequency.SemiMonthly, 1000, 24000)] [TestCase(PayrollFrequency.Daily, 1000, 260000)] [TestCase(PayrollFrequency.BiWeekly, 1234.56, 32098.56)] public void Should_Calculate_Annualized_Pay(PayrollFrequency freq, Decimal payPeriod, Decimal expected) { Assert.AreEqual(expected, freq.CalculateAnnualized(payPeriod)); } [Test] [TestCase(PayrollFrequency.Monthly, 1000, 12000)] [TestCase(PayrollFrequency.BiWeekly, 1000, 26000)] [TestCase(PayrollFrequency.Weekly, 1000, 52000)] [TestCase(PayrollFrequency.SemiMonthly, 1000, 24000)] [TestCase(PayrollFrequency.Daily, 1000, 260000)] [TestCase(PayrollFrequency.BiWeekly, 1234.56, 32098.56)] public void Should_Calculate_DeAnnualized_Pay(PayrollFrequency freq, Decimal expected, Decimal perYear) { Assert.AreEqual(expected, freq.CalculateDeannualized(perYear)); } } }
mit
C#
9389376fe76963d86dcbdfb4ff610eff0605a96b
Update tests for loose mode
adamreeve/semver.net
SemVer.Tests/LooseMode.cs
SemVer.Tests/LooseMode.cs
using System; using Xunit; using Xunit.Extensions; namespace SemVer.Tests { public class LooseMode { [Theory] [InlineData("=1.2.3", "1.2.3")] [InlineData("v 1.2.3", "1.2.3")] [InlineData("1.2.3alpha", "1.2.3-alpha")] // SemVer spec is ambiguous about whether 01 in a prerelease identifier // means the identifier is invalid or must be treated as alphanumeric, // but consensus seems to be that it is invalid (this is the behaviour of node-semver). [InlineData("1.2.3-01", "1.2.3-1")] public void Versions(string looseVersionString, string strictVersionString) { var looseVersion = new Version(looseVersionString, true); // Loose version is equivalent to strict version var strictVersion = new Version(strictVersionString); Assert.Equal(strictVersion.Clean(), looseVersion.Clean()); Assert.Equal(strictVersion, looseVersion); // Loose version should be invalid in strict mode Assert.Throws<ArgumentException>(() => new Version(looseVersionString)); } [Theory] [InlineData(">=1.2.3", "=1.2.3")] public void Ranges(string rangeString, string versionString) { var range = new Range(rangeString); // Version doesn't satisfy range in strict mode Assert.False(range.IsSatisfied(versionString, false)); // Version satisfies range in loose mode Assert.True(range.IsSatisfied(versionString, true)); } } }
using System; using Xunit; using Xunit.Extensions; namespace SemVer.Tests { public class LooseMode { [Theory] [InlineData("=1.2.3", "1.2.3")] [InlineData("v 1.2.3", "1.2.3")] [InlineData("1.2.3alpha", "1.2.3-alpha")] // SemVer spec is ambiguous about whether 01 in a prerelease identifier // means the identifier is invalid or must be treated as alphanumeric, // but consensus seems to be that it is invalid (this is the behaviour of node-semver). [InlineData("1.2.3-01", "1.2.3-1")] public void Versions(string looseVersionString, string strictVersionString) { var looseVersion = new Version(looseVersionString); // Loose version is equivalent to strict version var strictVersion = new Version(strictVersionString); Assert.Equal(strictVersion, looseVersion); // Loose version should be invalid in strict mode Assert.Throws<ArgumentException>(() => new Version(looseVersionString)); } [Theory] [InlineData(">=1.2.3", "=1.2.3")] public void Ranges(string rangeString, string versionString) { var range = new Range(rangeString); // Version doesn't satisfy range in strict mode Assert.False(range.IsSatisfied(versionString)); // Version satisfies range in loose mode Assert.True(range.IsSatisfied(versionString, true)); } } }
mit
C#
a6a05d09e4562ca809700bd59d4e756013a65ee5
Return trampoline from lazy function
sharper-library/Sharper.C.Enumerable
Sharper.C.Enumerable/Data/EnumerableModule.cs
Sharper.C.Enumerable/Data/EnumerableModule.cs
using System; using System.Collections.Generic; using System.Linq; using Sharper.C.Control; namespace Sharper.C.Data { using static TrampolineModule; public static class EnumerableModule { public static B FoldLeft<A, B>(this IEnumerable<A> e, B x, Func<B, A, B> f) => e.Aggregate(x, f); public static B FoldRight<A, B>(this IEnumerable<A> e, B x, Func<A, B, B> f) => e.Reverse().Aggregate(x, (b, a) => f(a, b)); public static Trampoline<B> LazyFoldRight<A, B> ( this IEnumerable<A> e , B x , Func<A, Trampoline<B>, Trampoline<B>> f ) => LazyFoldRight(e.GetEnumerator(), x, f); private static Trampoline<B> LazyFoldRight<A, B> ( IEnumerator<A> e , B x , Func<A, Trampoline<B>, Trampoline<B>> f ) => e.MoveNext() ? f(e.Current, Suspend(() => LazyFoldRight(e, x, f))) : Done(x); } }
using System; using System.Collections.Generic; using System.Linq; using Sharper.C.Control; namespace Sharper.C.Data { using static TrampolineModule; public static class EnumerableModule { public static B FoldLeft<A, B>(this IEnumerable<A> e, B x, Func<B, A, B> f) => e.Aggregate(x, f); public static B FoldRight<A, B>(this IEnumerable<A> e, B x, Func<A, B, B> f) => e.Reverse().Aggregate(x, (b, a) => f(a, b)); public static B LazyFoldRight<A, B> ( this IEnumerable<A> e , B x , Func<A, Trampoline<B>, Trampoline<B>> f ) => LazyFoldRight(e.GetEnumerator(), x, f).Eval(); private static Trampoline<B> LazyFoldRight<A, B> ( IEnumerator<A> e , B x , Func<A, Trampoline<B>, Trampoline<B>> f ) => e.MoveNext() ? f(e.Current, Suspend(() => LazyFoldRight(e, x, f))) : Done(x); } }
mit
C#
722a194463e3a1de79ef3cd983b448521590fda2
Implement IHtmlString in LocalizedString
mios-fi/mios.localization
Localization/LocalizedString.cs
Localization/LocalizedString.cs
using System.Web; namespace Mios.Localization { public struct LocalizedString : IHtmlString { public string Localization { get; private set; } public string String { get; private set; } public LocalizedString(string @string, string localization) : this() { Localization = localization; String = @string; } public override string ToString() { return Localization??String; } public string ToHtmlString() { return ToString(); } public static implicit operator string(LocalizedString d) { return d.ToString(); } } }
namespace Mios.Localization { public struct LocalizedString { public string Localization { get; private set; } public string String { get; private set; } public LocalizedString(string @string, string localization) : this() { Localization = localization; String = @string; } public override string ToString() { return Localization??String; } public static implicit operator string(LocalizedString d) { return d.ToString(); } } }
bsd-2-clause
C#
ea752807f142d1ada00672ee1dc0513ee867cc89
support null metrics filter in WIthFilter extension method
Liwoj/Metrics.NET,Liwoj/Metrics.NET,Recognos/Metrics.NET,Recognos/Metrics.NET
Src/Metrics/MetricData/MetricsDataProvider.cs
Src/Metrics/MetricData/MetricsDataProvider.cs
 namespace Metrics.MetricData { /// <summary> /// A provider capable of returning the current values for a set of metrics /// </summary> public interface MetricsDataProvider : Utils.IHideObjectMembers { /// <summary> /// Returns the current metrics data for the context for which this provider has been created. /// </summary> MetricsData CurrentMetricsData { get; } } public sealed class FilteredMetrics : MetricsDataProvider { private readonly MetricsDataProvider provider; private readonly MetricsFilter filter; public FilteredMetrics(MetricsDataProvider provider, MetricsFilter filter) { this.provider = provider; this.filter = filter; } public MetricsData CurrentMetricsData { get { return this.provider.CurrentMetricsData.Filter(this.filter); } } } public static class FilteredMetricsExtensions { public static MetricsDataProvider WithFilter(this MetricsDataProvider provider, MetricsFilter filter) { if(filter == null) { return provider; } return new FilteredMetrics(provider, filter); } } }
 namespace Metrics.MetricData { /// <summary> /// A provider capable of returning the current values for a set of metrics /// </summary> public interface MetricsDataProvider : Utils.IHideObjectMembers { /// <summary> /// Returns the current metrics data for the context for which this provider has been created. /// </summary> MetricsData CurrentMetricsData { get; } } public sealed class FilteredMetrics : MetricsDataProvider { private readonly MetricsDataProvider provider; private readonly MetricsFilter filter; public FilteredMetrics(MetricsDataProvider provider, MetricsFilter filter) { this.provider = provider; this.filter = filter; } public MetricsData CurrentMetricsData { get { return this.provider.CurrentMetricsData.Filter(this.filter); } } } public static class FilteredMetricsExtensions { public static MetricsDataProvider WithFilter(this MetricsDataProvider provider, MetricsFilter filter) { return new FilteredMetrics(provider, filter); } } }
apache-2.0
C#
1290698f24d9d936af00332e947ab90f9c78ee4b
Add GetValue<T>() and SetValue<T>()
whampson/bft-spec,whampson/cascara
Src/WHampson.Cascara/Types/ICascaraPointer.cs
Src/WHampson.Cascara/Types/ICascaraPointer.cs
#region License /* Copyright (c) 2017 Wes Hampson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #endregion using System; namespace WHampson.Cascara.Types { /// <summary> /// Provides a framework for creating a pointer to an <see cref="ICascaraType"/>. /// </summary> public interface ICascaraPointer : IConvertible { /// <summary> /// Gets the absolute memory address pointed to. /// </summary> IntPtr Address { get; } /// <summary> /// Gets a value indicating whether this pointer is zero. /// </summary> /// <remarks> /// A pointer that is not <code>null</code> does not necessarily /// mean that is usable. /// </remarks> /// <returns> /// <code>True</code> if the pointer points to zero, /// <code>False</code> othwewise. /// </returns> bool IsNull(); T GetValue<T>() where T : struct; void SetValue<T>(T value) where T : struct; } }
#region License /* Copyright (c) 2017 Wes Hampson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #endregion using System; namespace WHampson.Cascara.Types { /// <summary> /// Provides a framework for creating a pointer to an <see cref="ICascaraType"/>. /// </summary> public interface ICascaraPointer : IConvertible { /// <summary> /// Gets the absolute memory address pointed to. /// </summary> IntPtr Address { get; } /// <summary> /// Gets a value indicating whether this pointer is zero. /// </summary> /// <remarks> /// A pointer that is not <code>null</code> does not necessarily /// mean that is usable. /// </remarks> /// <returns> /// <code>True</code> if the pointer points to zero, /// <code>False</code> othwewise. /// </returns> bool IsNull(); } }
mit
C#
4202704e110d11e1d675684d4ff32b10165527de
Add documentaton for SparkMessage
RichLogan/CiscoSpark-UnityProject,RichLogan/CiscoSpark-UnityProject
SparkUnity/Assets/Cisco/Spark/SparkMessage.cs
SparkUnity/Assets/Cisco/Spark/SparkMessage.cs
using System.Collections.Generic; using UnityEngine.Networking; namespace Cisco.Spark { /// <summary> /// A message Spark returns in response to an operation. /// This is usually a wrapping of a SparkError. /// </summary> public class SparkMessage { /// <summary> /// The specific message from Spark. /// </summary> public string Message { get; private set; } /// <summary> /// A collection of one or more <see cref="SparkError"/>s. /// </summary> public IEnumerable<SparkError> Errors { get; private set; } /// <summary> /// Spark's internal tracking ID for this message. /// </summary> public string TrackingId { get; private set; } /// <summary> /// The associated web request. /// </summary> public UnityWebRequest WebRequest {get; private set; } /// <summary> /// Creates a SparkMessage from a JSON Spark response. /// </summary> /// <param name="data">Dictionary of data about the SparkMessage.</param> /// <param name="request">The associated UnityWebRequest.</param> public SparkMessage(Dictionary<string, object> data, UnityWebRequest request) { WebRequest = request; Message = (string)data["message"]; Errors = new List<SparkError>(); object errors; if (data.TryGetValue("errors", out errors)) { var listOfErrors = errors as List<object>; var errorList = new List<SparkError>(); foreach (var error in listOfErrors) { errorList.Add(new SparkError(error as Dictionary<string, object>)); } Errors = errorList; } TrackingId = (string)data["trackingId"]; } /// <summary> /// Creates a SparkMessage object from a UnityWebRequest. /// </summary> /// <param name="request">The associated UnityWebRequest.</param> public SparkMessage(UnityWebRequest request) { WebRequest = request; } } }
using System.Collections.Generic; using UnityEngine.Networking; namespace Cisco.Spark { /// <summary> /// A message Spark returns in response to an operation. /// This is usually a wrapping of a SparkError. /// </summary> public class SparkMessage { /// <summary> /// The specific message from Spark. /// </summary> public string Message { get; private set; } /// <summary> /// A collection of one or more <see cref="SparkError"/>s. /// </summary> public IEnumerable<SparkError> Errors { get; private set; } /// <summary> /// Spark's internal tracking ID for this message. /// </summary> public string TrackingId { get; private set; } /// <summary> /// The associated web request. /// </summary> public UnityWebRequest WebRequest {get; private set; } /// <summary> /// Creates a SparkMessage from a JSON Spark response. /// </summary> /// <param name="data">Dictionary of data about the SparkMessage.</param> public SparkMessage(Dictionary<string, object> data, UnityWebRequest request) { WebRequest = request; Message = (string)data["message"]; Errors = new List<SparkError>(); object errors; if (data.TryGetValue("errors", out errors)) { var listOfErrors = errors as List<object>; var errorList = new List<SparkError>(); foreach (var error in listOfErrors) { errorList.Add(new SparkError(error as Dictionary<string, object>)); } Errors = errorList; } TrackingId = (string)data["trackingId"]; } /// <summary> /// Creates a SparkMessage object from a UnityWebRequest. /// </summary> /// <param name="statusCode">UnityWebRequest.</param> public SparkMessage(UnityWebRequest request) { WebRequest = request; } } }
apache-2.0
C#
92d9071574013bce0a16b70b9431b6c6710c5d5b
Fix type name prettyfying for generics
lazlo-bonin/unity-reflection,lazlo-bonin/ludiq-reflection
Reflection/Editor/Extensions.cs
Reflection/Editor/Extensions.cs
using System; using System.CodeDom; using System.Linq; using System.Text.RegularExpressions; using Microsoft.CSharp; namespace Ludiq.Reflection.Editor { public static class Extensions { // Used to print pretty type names for primitives private static CSharpCodeProvider csharp = new CSharpCodeProvider(); /// <summary> /// Returns the name for the given type where primitives are in their shortcut form. /// </summary> public static string PrettyName(this Type type) { string cSharpOutput = csharp.GetTypeOutput(new CodeTypeReference(type)); var matches = Regex.Matches(cSharpOutput, @"([a-zA-Z0-9_\.]+)"); var prettyName = RemoveNamespace(matches[0].Value); if (matches.Count > 1) { prettyName += "<"; prettyName += string.Join(", ", matches.Cast<Match>().Skip(1).Select(m => RemoveNamespace(m.Value)).ToArray()); prettyName += ">"; } return prettyName; } private static string RemoveNamespace(string typeFullName) { if (!typeFullName.Contains('.')) { return typeFullName; } return typeFullName.Substring(typeFullName.LastIndexOf('.') + 1); } } }
using System; using System.CodeDom; using System.Linq; using Microsoft.CSharp; namespace Ludiq.Reflection.Editor { public static class Extensions { // Used to print pretty type names for primitives private static CSharpCodeProvider csharp = new CSharpCodeProvider(); /// <summary> /// Returns the name for the given type where primitives are in their shortcut form. /// </summary> public static string PrettyName(this Type type) { string cSharpOutput = csharp.GetTypeOutput(new CodeTypeReference(type)); if (cSharpOutput.Contains('.')) { return cSharpOutput.Substring(cSharpOutput.LastIndexOf('.') + 1); } else { return cSharpOutput; } } } }
mit
C#
9bdf913e40c03ad91d7efffefb7ff6d18ccc9187
change amount -> ratio1 in Blend()
TakeAsh/cs-3DGraphics
3DGraphics/ColorExtensionMethods.cs
3DGraphics/ColorExtensionMethods.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Media; namespace _3DGraphics { public static class ColorExtensionMethods { /// <summary> /// Blends the specified colors together. /// </summary> /// <param name="color0">Base color.</param> /// <param name="color1">Color onto <paramref name="color0" />.</param> /// <param name="ratio1">How much of <paramref name="color1" /> on top of <paramref name="color0" />.</param> /// <returns>The blended color.</returns> /// <remarks> /// [c# - Is there an easy way to blend two System.Drawing.Color values? - Stack Overflow](http://stackoverflow.com/questions/3722307/) /// </remarks> public static Color Blend(this Color color0, Color color1, double ratio1) { var ratio0 = 1 - ratio1; return Color.FromArgb( (byte)(color0.A * ratio0 + color1.A * ratio1), (byte)(color0.R * ratio0 + color1.R * ratio1), (byte)(color0.G * ratio0 + color1.G * ratio1), (byte)(color0.B * ratio0 + color1.B * ratio1) ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Media; namespace _3DGraphics { public static class ColorExtensionMethods { /// <summary> /// Blends the specified colors together. /// </summary> /// <param name="color">Color to blend onto the background color.</param> /// <param name="backColor">Color to blend the other color onto.</param> /// <param name="amount">How much of <paramref name="color"/> to keep, "on top of" <paramref name="backColor"/>.</param> /// <returns>The blended color.</returns> /// <remarks> /// [c# - Is there an easy way to blend two System.Drawing.Color values? - Stack Overflow](http://stackoverflow.com/questions/3722307/) /// </remarks> public static Color Blend(this Color color, Color backColor, double amount) { var r = (byte)((color.R * amount) + backColor.R * (1 - amount)); var g = (byte)((color.G * amount) + backColor.G * (1 - amount)); var b = (byte)((color.B * amount) + backColor.B * (1 - amount)); var a = (byte)((color.A * amount) + backColor.A * (1 - amount)); return Color.FromArgb(a, r, g, b); } } }
mit
C#
c42550a0b7b433ce75fde304e860b7acf3ac54e2
set keychain access as less restrictive
HTBox/MobileKidsIdApp,HTBox/MobileKidsIdApp,HTBox/MobileKidsIdApp,HTBox/MobileKidsIdApp
src/MobileKidsIdApp/MobileKidsIdApp.iOS/AppDelegate.cs
src/MobileKidsIdApp/MobileKidsIdApp.iOS/AppDelegate.cs
using Foundation; using MobileKidsIdApp.iOS.Platform; using MobileKidsIdApp.Platform; using Security; using UIKit; using Unity; using Xamarin.Essentials; namespace MobileKidsIdApp.iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { SecureStorage.DefaultAccessible = SecAccessible.AlwaysThisDeviceOnly; global::Xamarin.Forms.Forms.Init(); var formsApp = new App(); formsApp.Init(PlatformInitializeContainer); LoadApplication(formsApp); return base.FinishedLaunching(app, options); } private void PlatformInitializeContainer(UnityContainer container) { container.RegisterType<IContactPicker, ContactPicker>(); container.RegisterType<IWebViewContentHelper, WebViewContentHelper>(); container.RegisterType<IPhotoPicker, PhotoPicker>(); } } }
using Foundation; using MobileKidsIdApp.iOS.Platform; using MobileKidsIdApp.Platform; using Security; using UIKit; using Unity; using Xamarin.Essentials; namespace MobileKidsIdApp.iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { SecureStorage.DefaultAccessible = SecAccessible.WhenUnlockedThisDeviceOnly; global::Xamarin.Forms.Forms.Init(); var formsApp = new App(); formsApp.Init(PlatformInitializeContainer); LoadApplication(formsApp); return base.FinishedLaunching(app, options); } private void PlatformInitializeContainer(UnityContainer container) { container.RegisterType<IContactPicker, ContactPicker>(); container.RegisterType<IWebViewContentHelper, WebViewContentHelper>(); container.RegisterType<IPhotoPicker, PhotoPicker>(); } } }
apache-2.0
C#
d43b31be1918120659a2170210872731fb6d0687
Remove V1 code to send notifcations to employer and providers
SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments
src/SFA.DAS.Commitments.Notification.WebJob/Program.cs
src/SFA.DAS.Commitments.Notification.WebJob/Program.cs
using System; using System.Threading.Tasks; using NLog; using SFA.DAS.Commitments.Notification.WebJob.Configuration; using SFA.DAS.Commitments.Notification.WebJob.DependencyResolution; using SFA.DAS.NLog.Logger; namespace SFA.DAS.Commitments.Notification.WebJob { // To learn more about Microsoft Azure WebJobs SDK, please see http://go.microsoft.com/fwlink/?LinkID=320976 class Program { // Please set the following connection strings in app.config for this WebJob to run: // AzureWebJobsDashboard and AzureWebJobsStorage static void Main() { var container = IoC.Initialize(); var logger = container.GetInstance<ILog>(); var config = container.GetInstance<CommitmentNotificationConfiguration>(); var notificationJob = container.GetInstance<INotificationJob>(); var notificationJobId = $"Notification.WJ.{DateTime.UtcNow.Ticks}"; MappedDiagnosticsLogicalContext.Set(Constants.HeaderNameSessionCorrelationId, notificationJobId); if (!config.EnableJob) { logger.Info($"CommitmentNotification.WebJob job is turned off, JobId: {notificationJobId}"); return; } logger.Trace($"Starting CommitmentNotification.WebJob, JobId: {notificationJobId}"); // NOTE: both the T1 an T2 tasks need to be disabled when testing is complete on CON-4584 - the code // may be removed afterwards or swept up in a general cleanup of V1 code /*var t1 = notificationJob.RunEmployerAlertSummaryNotification($"{notificationJobId}.Employer") .ContinueWith(t => WhenDone(t, logger, "Employer")); var t2 = notificationJob.RunProviderAlertSummaryNotification($"{notificationJobId}.Provider") .ContinueWith(t => WhenDone(t, logger, "Provider"));*/ var t3 = notificationJob.RunSendingEmployerTransferRequestNotification($"{notificationJobId}.SendingEmployer") .ContinueWith(t => WhenDone(t, logger, "SendingEmployer")); Task.WaitAll(/*t1, t2,*/ t3); } private static void WhenDone(Task task, ILog logger, string identifier) { if(task.IsFaulted) logger.Error(task.Exception, $"Error running {identifier} CommitmentNotification.WebJob"); else logger.Info($"Successfully ran CommitmentNotification.WebJob for {identifier}"); } } }
using System; using System.Threading.Tasks; using NLog; using SFA.DAS.Commitments.Notification.WebJob.Configuration; using SFA.DAS.Commitments.Notification.WebJob.DependencyResolution; using SFA.DAS.NLog.Logger; namespace SFA.DAS.Commitments.Notification.WebJob { // To learn more about Microsoft Azure WebJobs SDK, please see http://go.microsoft.com/fwlink/?LinkID=320976 class Program { // Please set the following connection strings in app.config for this WebJob to run: // AzureWebJobsDashboard and AzureWebJobsStorage static void Main() { var container = IoC.Initialize(); var logger = container.GetInstance<ILog>(); var config = container.GetInstance<CommitmentNotificationConfiguration>(); var notificationJob = container.GetInstance<INotificationJob>(); var notificationJobId = $"Notification.WJ.{DateTime.UtcNow.Ticks}"; MappedDiagnosticsLogicalContext.Set(Constants.HeaderNameSessionCorrelationId, notificationJobId); if (!config.EnableJob) { logger.Info($"CommitmentNotification.WebJob job is turned off, JobId: {notificationJobId}"); return; } logger.Trace($"Starting CommitmentNotification.WebJob, JobId: {notificationJobId}"); // NOTE: both the T1 an T2 tasks need to be disabled when testing is complete on CON-4584 - the code // may be removed afterwards or swept up in a general cleanup of V1 code var t1 = notificationJob.RunEmployerAlertSummaryNotification($"{notificationJobId}.Employer") .ContinueWith(t => WhenDone(t, logger, "Employer")); var t2 = notificationJob.RunProviderAlertSummaryNotification($"{notificationJobId}.Provider") .ContinueWith(t => WhenDone(t, logger, "Provider")); var t3 = notificationJob.RunSendingEmployerTransferRequestNotification($"{notificationJobId}.SendingEmployer") .ContinueWith(t => WhenDone(t, logger, "SendingEmployer")); Task.WaitAll(t1, t2, t3); } private static void WhenDone(Task task, ILog logger, string identifier) { if(task.IsFaulted) logger.Error(task.Exception, $"Error running {identifier} CommitmentNotification.WebJob"); else logger.Info($"Successfully ran CommitmentNotification.WebJob for {identifier}"); } } }
mit
C#
abcbc45761e168c0ddbbae2da191319c05c5caa7
Raise authentication server prerelease version.
affecto/dotnet-AuthenticationServer
Source/AuthenticationServer/Properties/AssemblyInfo.cs
Source/AuthenticationServer/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle("Affecto Authentication Server")] [assembly: AssemblyProduct("Affecto Authentication Server")] [assembly: AssemblyCompany("Affecto")] [assembly: AssemblyVersion("2.1.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")] [assembly: AssemblyInformationalVersion("2.1.0-prerelease03")] [assembly: InternalsVisibleTo("Affecto.AuthenticationServer.Tests")] [assembly: InternalsVisibleTo("Affecto.AuthenticationServer.Configuration.Tests")]
using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle("Affecto Authentication Server")] [assembly: AssemblyProduct("Affecto Authentication Server")] [assembly: AssemblyCompany("Affecto")] [assembly: AssemblyVersion("2.1.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")] [assembly: AssemblyInformationalVersion("2.1.0-prerelease02")] [assembly: InternalsVisibleTo("Affecto.AuthenticationServer.Tests")] [assembly: InternalsVisibleTo("Affecto.AuthenticationServer.Configuration.Tests")]
mit
C#
c7783e70fc76fb2a7972ca2ac0a99eb5a67cf2fb
Make SyslogNet.Client CLS-compliant
YallaDotNet/syslog
SyslogNet.Client/Transport/SyslogEncryptedTcpSender.cs
SyslogNet.Client/Transport/SyslogEncryptedTcpSender.cs
using System; using System.Net.Security; using System.Security; using System.Security.Cryptography.X509Certificates; using System.Threading; namespace SyslogNet.Client.Transport { public class SyslogEncryptedTcpSender : SyslogTcpSender { protected int IOTimeout; public Boolean IgnoreTLSChainErrors { get; private set; } protected MessageTransfer m_messageTransfer; public override MessageTransfer messageTransfer { get { return m_messageTransfer; } set { if (!value.Equals(MessageTransfer.OctetCounting) && transportStream is SslStream) { throw new SyslogTransportException("Non-Transparent-Framing can not be used with TLS transport"); } m_messageTransfer = value; } } public SyslogEncryptedTcpSender(string hostname, int port, int timeout = Timeout.Infinite, bool ignoreChainErrors = false) : base(hostname, port) { IOTimeout = timeout; IgnoreTLSChainErrors = ignoreChainErrors; startTLS(); } public override void Reconnect() { base.Reconnect(); startTLS(); } private void startTLS() { transportStream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate)) { ReadTimeout = IOTimeout, WriteTimeout = IOTimeout }; // According to RFC 5425 we MUST support TLS 1.2, but this protocol version only implemented in framework 4.5 and Windows Vista+... ((SslStream)transportStream).AuthenticateAsClient( hostname, null, System.Security.Authentication.SslProtocols.Tls, false ); if (!((SslStream)transportStream).IsEncrypted) throw new SecurityException("Could not establish an encrypted connection"); m_messageTransfer = MessageTransfer.OctetCounting; } private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None || (IgnoreTLSChainErrors && sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors)) return true; CertificateErrorHandler(String.Format("Certificate error: {0}", sslPolicyErrors)); return false; } // Quick and nasty way to avoid logging framework dependency public static Action<string> CertificateErrorHandler = err => { }; } }
using System; using System.Net.Security; using System.Security; using System.Security.Cryptography.X509Certificates; using System.Threading; namespace SyslogNet.Client.Transport { public class SyslogEncryptedTcpSender : SyslogTcpSender { protected int IOTimeout; public Boolean IgnoreTLSChainErrors { get; private set; } protected MessageTransfer _messageTransfer; public override MessageTransfer messageTransfer { get { return _messageTransfer; } set { if (!value.Equals(MessageTransfer.OctetCounting) && transportStream is SslStream) { throw new SyslogTransportException("Non-Transparent-Framing can not be used with TLS transport"); } _messageTransfer = value; } } public SyslogEncryptedTcpSender(string hostname, int port, int timeout = Timeout.Infinite, bool ignoreChainErrors = false) : base(hostname, port) { IOTimeout = timeout; IgnoreTLSChainErrors = ignoreChainErrors; startTLS(); } public override void Reconnect() { base.Reconnect(); startTLS(); } private void startTLS() { transportStream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate)) { ReadTimeout = IOTimeout, WriteTimeout = IOTimeout }; // According to RFC 5425 we MUST support TLS 1.2, but this protocol version only implemented in framework 4.5 and Windows Vista+... ((SslStream)transportStream).AuthenticateAsClient( hostname, null, System.Security.Authentication.SslProtocols.Tls, false ); if (!((SslStream)transportStream).IsEncrypted) throw new SecurityException("Could not establish an encrypted connection"); messageTransfer = MessageTransfer.OctetCounting; } private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None || (IgnoreTLSChainErrors && sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors)) return true; CertificateErrorHandler(String.Format("Certificate error: {0}", sslPolicyErrors)); return false; } // Quick and nasty way to avoid logging framework dependency public static Action<string> CertificateErrorHandler = err => { }; } }
mit
C#
88e0c53dffcafdac214b1eaf466de9586417c81b
Fix constructor visibility for plugin
pleonex/NitroDebugger,pleonex/NitroDebugger,pleonex/NitroDebugger
NitroDebugger/Plugin.cs
NitroDebugger/Plugin.cs
// // Plugin.cs // // Author: // Benito Palacios Sánchez <benito356@gmail.com> // // Copyright (c) 2015 Benito Palacios Sánchez // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Mono.Addins; namespace NitroDebugger { [TypeExtensionPoint] public abstract class Plugin : IDisposable { static List<Plugin> instances = new List<Plugin>(); protected Plugin() { instances.Add(this); } ~Plugin() { this.Dispose(false); } public static ReadOnlyCollection<Plugin> Instances { get { return new ReadOnlyCollection<Plugin>(instances); } } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool freeManagedResourcesAlso) { instances.Remove(this); } } }
// // Plugin.cs // // Author: // Benito Palacios Sánchez <benito356@gmail.com> // // Copyright (c) 2015 Benito Palacios Sánchez // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Mono.Addins; namespace NitroDebugger { [TypeExtensionPoint] public abstract class Plugin : IDisposable { static List<Plugin> instances = new List<Plugin>(); public Plugin() { instances.Add(this); } ~Plugin() { this.Dispose(false); } public static ReadOnlyCollection<Plugin> Instances { get { return new ReadOnlyCollection<Plugin>(instances); } } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool freeManagedResourcesAlso) { instances.Remove(this); } } }
mit
C#
b142440f83ba0c11ea14cd266cfb657fbd119395
Revert access modifier change and update its comment
botaberg/coreclr,poizan42/coreclr,parjong/coreclr,yizhang82/coreclr,kyulee1/coreclr,yizhang82/coreclr,kyulee1/coreclr,kyulee1/coreclr,JosephTremoulet/coreclr,rartemev/coreclr,dpodder/coreclr,wateret/coreclr,hseok-oh/coreclr,botaberg/coreclr,poizan42/coreclr,kyulee1/coreclr,JosephTremoulet/coreclr,krk/coreclr,yizhang82/coreclr,mmitche/coreclr,JosephTremoulet/coreclr,ruben-ayrapetyan/coreclr,dpodder/coreclr,cshung/coreclr,wateret/coreclr,parjong/coreclr,botaberg/coreclr,parjong/coreclr,dpodder/coreclr,AlexGhiondea/coreclr,cshung/coreclr,wtgodbe/coreclr,cshung/coreclr,cshung/coreclr,kyulee1/coreclr,parjong/coreclr,mmitche/coreclr,krk/coreclr,rartemev/coreclr,rartemev/coreclr,AlexGhiondea/coreclr,rartemev/coreclr,dpodder/coreclr,cshung/coreclr,wateret/coreclr,AlexGhiondea/coreclr,wtgodbe/coreclr,ruben-ayrapetyan/coreclr,mmitche/coreclr,JosephTremoulet/coreclr,cshung/coreclr,ruben-ayrapetyan/coreclr,rartemev/coreclr,JosephTremoulet/coreclr,kyulee1/coreclr,ruben-ayrapetyan/coreclr,poizan42/coreclr,krk/coreclr,wtgodbe/coreclr,dpodder/coreclr,parjong/coreclr,mmitche/coreclr,botaberg/coreclr,yizhang82/coreclr,dpodder/coreclr,yizhang82/coreclr,wtgodbe/coreclr,mmitche/coreclr,AlexGhiondea/coreclr,botaberg/coreclr,wtgodbe/coreclr,JosephTremoulet/coreclr,wateret/coreclr,wateret/coreclr,wtgodbe/coreclr,poizan42/coreclr,yizhang82/coreclr,krk/coreclr,AlexGhiondea/coreclr,botaberg/coreclr,hseok-oh/coreclr,poizan42/coreclr,krk/coreclr,parjong/coreclr,ruben-ayrapetyan/coreclr,hseok-oh/coreclr,hseok-oh/coreclr,hseok-oh/coreclr,hseok-oh/coreclr,wateret/coreclr,poizan42/coreclr,ruben-ayrapetyan/coreclr,mmitche/coreclr,rartemev/coreclr,AlexGhiondea/coreclr,krk/coreclr
src/mscorlib/shared/System/UnitySerializationHolder.cs
src/mscorlib/shared/System/UnitySerializationHolder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.Serialization; using System.Reflection; namespace System { /// <summary> /// Holds Null class for which we guarantee that there is only ever one instance of. /// This only exists for backwarts compatibility with /// </summary> #if CORECLR internal #else public // On CoreRT this must be public. #endif sealed class UnitySerializationHolder : ISerializable, IObjectReference { internal const int NullUnity = 0x0002; public static void GetUnitySerializationInfo(SerializationInfo info, int unityType, string data, Assembly assembly) { // A helper method that returns the SerializationInfo that a class utilizing // UnitySerializationHelper should return from a call to GetObjectData. It contains // the unityType (defined above) and any optional data (used only for the reflection // types.) info.SetType(typeof(UnitySerializationHolder)); info.AddValue("Data", data, typeof(string)); info.AddValue("UnityType", unityType); info.AddValue("AssemblyName", assembly?.FullName ?? string.Empty); } public UnitySerializationHolder(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } // We are ignoring any serialization input as we are only concerned about DBNull. } public void GetObjectData(SerializationInfo info, StreamingContext context) => throw new NotSupportedException(SR.NotSupported_UnitySerHolder); public object GetRealObject(StreamingContext context) { // We are always returning the same DBNull instance and ignoring serialization input. return DBNull.Value; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.Serialization; using System.Reflection; namespace System { /// <summary> /// Holds Null class for which we guarantee that there is only ever one instance of. /// This only exists for backwarts compatibility with /// </summary> internal sealed class UnitySerializationHolder : ISerializable, IObjectReference { internal const int NullUnity = 0x0002; public static void GetUnitySerializationInfo(SerializationInfo info, int unityType, string data, Assembly assembly) { // A helper method that returns the SerializationInfo that a class utilizing // UnitySerializationHelper should return from a call to GetObjectData. It contains // the unityType (defined above) and any optional data (used only for the reflection // types.) info.SetType(typeof(UnitySerializationHolder)); info.AddValue("Data", data, typeof(string)); info.AddValue("UnityType", unityType); info.AddValue("AssemblyName", assembly?.FullName ?? string.Empty); } public UnitySerializationHolder(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } // We are ignoring any serialization input as we are only concerned about DBNull. } public void GetObjectData(SerializationInfo info, StreamingContext context) => throw new NotSupportedException(SR.NotSupported_UnitySerHolder); public object GetRealObject(StreamingContext context) { // We are always returning the same DBNull instance and ignoring serialization input. return DBNull.Value; } } }
mit
C#
71914b2aa1ead163c400f38fc7340344c1bd8a5e
Update JunianTriajianto.cs short bio (#277)
planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
src/Firehose.Web/Authors/JunianTriajianto.cs
src/Firehose.Web/Authors/JunianTriajianto.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class JunianTriajianto : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "Junian"; public string LastName => "Triajianto"; public string ShortBioOrTagLine => "Software Engineer, who enjoys problem solving and technology related to C#, Xamarin, ASP.NET Core, and Unity 3D."; public string StateOrRegion => "Surabaya, Indonesia"; public string EmailAddress => ""; public string TwitterHandle => "JunianNet"; public string GravatarHash => "b67cdce8e2da7ffdadb5ff32bb66c132"; public string GitHubHandle => "junian"; public GeoPosition Position => new GeoPosition(-7.2574719, 112.75208829999997); public Uri WebSite => new Uri("https://www.junian.net"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.junian.net/feeds/posts/default?alt=rss"); } } public bool Filter(SyndicationItem item) => item.Title.Text.ToLowerInvariant().Contains("xamarin") || item.Categories.Any(category => category.Name.ToLowerInvariant().Contains("xamarin")); } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class JunianTriajianto : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "Junian"; public string LastName => "Triajianto"; public string ShortBioOrTagLine => "software engineer"; public string StateOrRegion => "Surabaya, Indonesia"; public string EmailAddress => ""; public string TwitterHandle => "JunianNet"; public string GravatarHash => "b67cdce8e2da7ffdadb5ff32bb66c132"; public string GitHubHandle => "junian"; public GeoPosition Position => new GeoPosition(-7.2574719, 112.75208829999997); public Uri WebSite => new Uri("https://www.junian.net"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.junian.net/feeds/posts/default?alt=rss"); } } public bool Filter(SyndicationItem item) => item.Title.Text.ToLowerInvariant().Contains("xamarin") || item.Categories.Any(category => category.Name.ToLowerInvariant().Contains("xamarin")); } }
mit
C#
e5f09a1420d350530478fac447664f4b4e444a77
Fix SqlTemplates concurrency
NikRimington/Umbraco-CMS,robertjf/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,hfloyd/Umbraco-CMS,rasmuseeg/Umbraco-CMS,rasmuseeg/Umbraco-CMS,tcmorris/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,mattbrailsford/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,lars-erik/Umbraco-CMS,tcmorris/Umbraco-CMS,lars-erik/Umbraco-CMS,marcemarc/Umbraco-CMS,bjarnef/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,rasmuseeg/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,NikRimington/Umbraco-CMS,lars-erik/Umbraco-CMS,lars-erik/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,lars-erik/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,madsoulswe/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,bjarnef/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,abryukhov/Umbraco-CMS,mattbrailsford/Umbraco-CMS,dawoe/Umbraco-CMS,madsoulswe/Umbraco-CMS,hfloyd/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,mattbrailsford/Umbraco-CMS,tcmorris/Umbraco-CMS,bjarnef/Umbraco-CMS,hfloyd/Umbraco-CMS,bjarnef/Umbraco-CMS,madsoulswe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,hfloyd/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,leekelleher/Umbraco-CMS,umbraco/Umbraco-CMS,leekelleher/Umbraco-CMS,NikRimington/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,leekelleher/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS
src/Umbraco.Core/Persistence/SqlTemplates.cs
src/Umbraco.Core/Persistence/SqlTemplates.cs
using System; using System.Collections.Concurrent; using NPoco; namespace Umbraco.Core.Persistence { public class SqlTemplates { private readonly ConcurrentDictionary<string, SqlTemplate> _templates = new ConcurrentDictionary<string, SqlTemplate>(); private readonly ISqlContext _sqlContext; public SqlTemplates(ISqlContext sqlContext) { _sqlContext = sqlContext; } // for tests internal void Clear() { _templates.Clear(); } public SqlTemplate Get(string key, Func<Sql<ISqlContext>, Sql<ISqlContext>> sqlBuilder) { SqlTemplate CreateTemplate(string _) { var sql = sqlBuilder(new Sql<ISqlContext>(_sqlContext)); return new SqlTemplate(_sqlContext, sql.SQL, sql.Arguments); } return _templates.GetOrAdd(key, CreateTemplate); } } }
using System; using System.Collections.Generic; using NPoco; namespace Umbraco.Core.Persistence { public class SqlTemplates { private readonly Dictionary<string, SqlTemplate> _templates = new Dictionary<string, SqlTemplate>(); private readonly ISqlContext _sqlContext; public SqlTemplates(ISqlContext sqlContext) { _sqlContext = sqlContext; } // for tests internal void Clear() { _templates.Clear(); } public SqlTemplate Get(string key, Func<Sql<ISqlContext>, Sql<ISqlContext>> sqlBuilder) { if (_templates.TryGetValue(key, out var template)) return template; var sql = sqlBuilder(new Sql<ISqlContext>(_sqlContext)); return _templates[key] = new SqlTemplate(_sqlContext, sql.SQL, sql.Arguments); } } }
mit
C#
eb7e4389c05340530cc336ddef3dd935a015ac68
bump to 1.3.1
ronin1/urbanairsharp
src/UrbanAirSharp/Properties/AssemblyInfo.cs
src/UrbanAirSharp/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // 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("UrbanAirSharp")] [assembly: AssemblyDescription("C# .Net library to simplify server-side calls to the Urban Airship API Version 3")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("UrbanAirSharp")] [assembly: AssemblyProduct("UrbanAirSharp")] [assembly: AssemblyCopyright("Copyright © Jeff Gosling (jeffery.gosling@gmail.com) 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)] [assembly: InternalsVisibleTo("UrbanAirSharp.Tests")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e99d3143-1d57-40dd-8ff7-5cd8570e17f0")] // 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.1.0")] [assembly: AssemblyFileVersion("1.3.1.0")]
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // 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("UrbanAirSharp")] [assembly: AssemblyDescription("C# .Net library to simplify server-side calls to the Urban Airship API Version 3")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("UrbanAirSharp")] [assembly: AssemblyProduct("UrbanAirSharp")] [assembly: AssemblyCopyright("Copyright © Jeff Gosling (jeffery.gosling@gmail.com) 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)] [assembly: InternalsVisibleTo("UrbanAirSharp.Tests")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e99d3143-1d57-40dd-8ff7-5cd8570e17f0")] // 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.0.0")] [assembly: AssemblyFileVersion("1.3.0.0")]
mit
C#
10c3edd6f35158beef14edd76c54660a8d97e4a8
Mark connectionstrings.json as optional
JamieMagee/GovUK-Pulse,JamieMagee/GovUK-Pulse,JamieMagee/GovUK-Pulse
GovUk/Startup.cs
GovUk/Startup.cs
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace GovUk { public class Startup { public Startup(IHostingEnvironment env) { // Set up configuration sources. var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile("connectionstring.json", true) .AddEnvironmentVariables(); if (env.IsDevelopment()) { // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. builder.AddApplicationInsightsSettings(true); } Configuration = builder.Build(); } public static IConfigurationRoot Configuration { get; set; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseApplicationInsightsRequestTelemetry(); if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStatusCodePagesWithReExecute("/Home/Error"); app.UseIISPlatformHandler(); app.UseApplicationInsightsExceptionTelemetry(); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute("default", "{controller=Home}/{action=Index}"); }); } // Entry point for the application. public static void Main(string[] args) => WebApplication.Run<Startup>(args); } }
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace GovUk { public class Startup { public Startup(IHostingEnvironment env) { // Set up configuration sources. var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile("connectionstring.json") .AddEnvironmentVariables(); if (env.IsDevelopment()) { // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. builder.AddApplicationInsightsSettings(true); } Configuration = builder.Build(); } public static IConfigurationRoot Configuration { get; set; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseApplicationInsightsRequestTelemetry(); if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStatusCodePagesWithReExecute("/Home/Error"); app.UseIISPlatformHandler(); app.UseApplicationInsightsExceptionTelemetry(); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute("default", "{controller=Home}/{action=Index}"); }); } // Entry point for the application. public static void Main(string[] args) => WebApplication.Run<Startup>(args); } }
mit
C#
dc2d20f0e6ae1e5ef8ed050fb1e6f0c6b338eb77
Add Catch to IAsyncSpec to be able to use it in async tests
robfe/SpecLight
SpecLight/IAsyncSpec.cs
SpecLight/IAsyncSpec.cs
using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace SpecLight { /// <summary> /// When you call any Async method on a Spec, you get back an IAsyncSpec instead of a Spec. The only difference is that the <see cref="Execute"/> method is marked as Obsolete in favour of <see cref="ExecuteAsync"/> /// </summary> public partial interface IAsyncSpec { string Description { get; } MethodBase CallingMethod { get; set; } string TestMethodNameOverride { get; set; } List<Step> Steps { get; } /// <summary> /// A bag to attach random stuff to a step. Most likely used by an <see cref="ISpecFixture"/>. Refers to the same datastore as the <see cref="DataDictionary"/>. Any contents of type string will be printed to output. /// </summary> dynamic DataBag { get; } /// <summary> /// A dictionary to attach random stuff to a step. Most likely used by an <see cref="ISpecFixture"/>. Refers to the same datastore as the <see cref="DataBag"/>. Any contents of type string will be printed to output. /// </summary> IDictionary<string, object> DataDictionary { get; } Spec Tag(params string[] tags); Spec Finally(IDisposable disposable); Spec Finally(Action finalAction); Spec WithFixture<T>() where T : ISpecFixture, new(); /// <summary> /// Run the spec async, printing its results to the output windows, and re-throwing the first exception that it encountered /// (such as an Assert failure) /// Be sure to call Execute from your unit test method directly so that it can detect its calling method correctly /// </summary> Task ExecuteAsync([CallerMemberName] string testMethodNameOverride = null); /// <inheritdoc cref="Spec.Catch"/> Spec Catch(out Lazy<Exception> caughtExceptionReference); /// <summary> /// Because you have used one of the async step methods, you should be awaiting/returning ExecuteAsync instead /// </summary> [Obsolete("Because you have used one of the Async step methods, you should be calling ExecuteAsync instead, and returning that task to your test runner")] void Execute([CallerMemberName] string testMethodNameOverride = null); } }
using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace SpecLight { /// <summary> /// When you call any Async method on a Spec, you get back an IAsyncSpec instead of a Spec. The only difference is that the <see cref="Execute"/> method is marked as Obsolete in favour of <see cref="ExecuteAsync"/> /// </summary> public partial interface IAsyncSpec { string Description { get; } MethodBase CallingMethod { get; set; } string TestMethodNameOverride { get; set; } List<Step> Steps { get; } /// <summary> /// A bag to attach random stuff to a step. Most likely used by an <see cref="ISpecFixture"/>. Refers to the same datastore as the <see cref="DataDictionary"/>. Any contents of type string will be printed to output. /// </summary> dynamic DataBag { get; } /// <summary> /// A dictionary to attach random stuff to a step. Most likely used by an <see cref="ISpecFixture"/>. Refers to the same datastore as the <see cref="DataBag"/>. Any contents of type string will be printed to output. /// </summary> IDictionary<string, object> DataDictionary { get; } Spec Tag(params string[] tags); Spec Finally(IDisposable disposable); Spec Finally(Action finalAction); Spec WithFixture<T>() where T : ISpecFixture, new(); /// <summary> /// Run the spec async, printing its results to the output windows, and re-throwing the first exception that it encountered /// (such as an Assert failure) /// Be sure to call Execute from your unit test method directly so that it can detect its calling method correctly /// </summary> Task ExecuteAsync([CallerMemberName] string testMethodNameOverride = null); /// <summary> /// Because you have used one of the async step methods, you should be awaiting/returning ExecuteAsync instead /// </summary> [Obsolete("Because you have used one of the Async step methods, you should be calling ExecuteAsync instead, and returning that task to your test runner")] void Execute([CallerMemberName] string testMethodNameOverride = null); } }
mit
C#
e59490779bc36a637b1663e03e282cb4e39bffd3
バージョン番号更新。
YKSoftware/YKToolkit.Controls
YKToolkit.Controls/Properties/AssemblyInfo.cs
YKToolkit.Controls/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; [assembly: AssemblyTitle("YKToolkit.Controls")] #if NET4 [assembly: AssemblyDescription(".NET Framework 4.0 用 の WPF カスタムコントロールライブラリです。")] #else [assembly: AssemblyDescription("WPF カスタムコントロールライブラリです。")] #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("YKSoftware")] [assembly: AssemblyProduct("YKToolkit.Controls")] [assembly: AssemblyCopyright("Copyright © 2015 YKSoftware")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly:ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)] [assembly: AssemblyVersion("2.4.3.0")]
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; [assembly: AssemblyTitle("YKToolkit.Controls")] #if NET4 [assembly: AssemblyDescription(".NET Framework 4.0 用 の WPF カスタムコントロールライブラリです。")] #else [assembly: AssemblyDescription("WPF カスタムコントロールライブラリです。")] #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("YKSoftware")] [assembly: AssemblyProduct("YKToolkit.Controls")] [assembly: AssemblyCopyright("Copyright © 2015 YKSoftware")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly:ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)] [assembly: AssemblyVersion("2.4.2.2")]
mit
C#
1e88db6d86471ca25810ab589ac1a41aeafac9e6
Update JSON.cs
Ryanb58/JSONTool
JSONTool/JSON.cs
JSONTool/JSON.cs
namespace JSONTool { public class JSON { public string minify(string json) { //Return the json string. return System.Text.RegularExpressions.Regex.Replace(json, "(\"(?:[^\"\\\\]|\\\\.)*\")|\\s+", "$1"); } } }
namespace JSONTool { public class JSON { public static string minify(string json) { //Return the json string. return System.Text.RegularExpressions.Regex.Replace(json, "(\"(?:[^\"\\\\]|\\\\.)*\")|\\s+", "$1"); } } }
mit
C#
ffccaf60c297fc4fddbdd907268c74c5cafa05b3
comment clean up
smeehan82/Hermes,smeehan82/Hermes,smeehan82/Hermes
src/Hermes.Web/Controllers/BlogsController.cs
src/Hermes.Web/Controllers/BlogsController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Mvc; using Microsoft.Extensions.Logging; using Hermes.Content.Blogs; namespace Hermes.Web.Controllers { [Route("api/blogs")] public class BlogsController : Controller { #region Contructor private BlogsManager _blogsManager; private ILogger _logger; public BlogsController(BlogsManager blogsManager, ILoggerFactory loggerFactory) { _blogsManager = blogsManager; _logger = loggerFactory.CreateLogger<BlogsController>(); } #endregion //GET #region list [HttpGet] [Route("list")] public async Task<IActionResult> Get() { var blogs = _blogsManager.Blogs; return new ObjectResult(blogs); } #endregion //GET #region single by id [HttpGet] [Route("single")] public async Task<IActionResult> Get(Guid id) { var blog = await _blogsManager.FindByIdAsync(id); return new ObjectResult(blog); } #endregion //GET #region single by slug [HttpGet] [Route("single")] public async Task<IActionResult> Get(string slug) { var blog = await _blogsManager.FindBySlugAsync(slug); return new ObjectResult(blog); } #endregion //POST #region add [HttpPost] [Route("add")] public async Task<IActionResult> Put(string title, string slug) { var blog = new Blog(); blog.Id = new Guid(); blog.Title = title; blog.Slug = slug; blog.DateCreated = DateTimeOffset.Now; blog.DateModified = DateTimeOffset.Now; blog.DatePublished = DateTimeOffset.Now; await _blogsManager.AddAsync(blog); return new ObjectResult(true); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Mvc; using Microsoft.Extensions.Logging; using Hermes.Content.Blogs; namespace Hermes.Web.Controllers { [Route("api/blogs")] public class BlogsController : Controller { #region Contructor private BlogsManager _blogsManager; private ILogger _logger; public BlogsController(BlogsManager blogsManager, ILoggerFactory loggerFactory) { _blogsManager = blogsManager; _logger = loggerFactory.CreateLogger<BlogsController>(); } #endregion //GET #region list [HttpGet] [Route("list")] public async Task<IActionResult> Get() { var blogs = _blogsManager.Blogs; return new ObjectResult(blogs); } #endregion //GET #region single by id [HttpGet] [Route("single")] public async Task<IActionResult> Get(Guid id) { var blog = await _blogsManager.FindByIdAsync(id); return new ObjectResult(blog); } #endregion //GET #region single by id [HttpGet] [Route("single")] public async Task<IActionResult> Get(string slug) { var blog = await _blogsManager.FindBySlugAsync(slug); return new ObjectResult(blog); } #endregion //POST #region add [HttpPost] [Route("add")] public async Task<IActionResult> Put(string title, string slug) { var blog = new Blog(); blog.Id = new Guid(); blog.Title = title; blog.Slug = slug; blog.DateCreated = DateTimeOffset.Now; blog.DateModified = DateTimeOffset.Now; blog.DatePublished = DateTimeOffset.Now; await _blogsManager.AddAsync(blog); return new ObjectResult(true); } #endregion } }
mit
C#
93caa2db629e97e6c11f78e152e8ddc28de87d34
Add FNV1a-32 description to example usage
bhannan/csharp-bloom-filter
BloomFilter/ExampleUsage.cs
BloomFilter/ExampleUsage.cs
using System.Collections.Generic; using System.Security.Cryptography; namespace BloomFilter { class ExampleUsage { static void Main(string[] args) { //standard usage using SHA1 hashing using (var bf = new BloomFilter<string>(MaxItems: 1000, FalsePositiveProbability: .001)) { //add an item to the filter bf.Add("My Text"); //checking for existence in the filter bool b; b = bf.Contains("My Text"); //true b = bf.Contains("Never been seen before"); //false (usually ;)) } //using a different hash algorithm (such as the provided FNV1a-32 implementation) using (var bf = new BloomFilter<string, FNV1a32>(MaxItems: 1000, FalsePositiveProbability: .001)) { //add, check for existence, etc. } } } }
using System.Collections.Generic; using System.Security.Cryptography; namespace BloomFilter { class ExampleUsage { static void Main(string[] args) { //standard usage using SHA1 hashing using (var bf = new BloomFilter<string>(MaxItems: 1000, FalsePositiveProbability: .001)) { //add an item to the filter bf.Add("My Text"); //checking for existence in the filter bool b; b = bf.Contains("My Text"); //true b = bf.Contains("Never been seen before"); //false (usually ;)) } //using a different algorithm using (var bf = new BloomFilter<string, FNV1a32>(MaxItems: 1000, FalsePositiveProbability: .001)) { //add, check for existence, etc. } } } }
mit
C#
b7edc59442bb82dda4ed1295f38a9e2cc8e451cf
Remove redundant configuration-checking tests from ACallToTests
FakeItEasy/FakeItEasy,thomaslevesque/FakeItEasy,adamralph/FakeItEasy,FakeItEasy/FakeItEasy,thomaslevesque/FakeItEasy,blairconrad/FakeItEasy,adamralph/FakeItEasy,blairconrad/FakeItEasy
tests/FakeItEasy.Tests/ACallToTests.cs
tests/FakeItEasy.Tests/ACallToTests.cs
namespace FakeItEasy.Tests { using System; using System.Collections.Generic; using System.Linq; using FluentAssertions; using Xunit; public class ACallToTests { public static IEnumerable<object[]> CallSpecificationActions => TestCases.FromObject<Action<IFoo>>( foo => A.CallTo(() => foo.Bar()), foo => A.CallTo(() => foo.Baz()), foo => A.CallToSet(() => foo.SomeProperty), foo => A.CallTo(foo)); [Theory] [MemberData(nameof(CallSpecificationActions))] public void CallTo_should_not_add_rule_to_manager(Action<IFoo> action) { // Arrange var foo = A.Fake<IFoo>(); var manager = Fake.GetFakeManager(foo); var initialRules = manager.Rules.ToList(); // Act action(foo); // Assert manager.Rules.Should().Equal(initialRules); } } }
namespace FakeItEasy.Tests { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using FakeItEasy.Configuration; using FluentAssertions; using Xunit; public class ACallToTests : ConfigurableServiceLocatorTestBase { private readonly IFakeConfigurationManager configurationManager; public ACallToTests() { this.configurationManager = A.Fake<IFakeConfigurationManager>(x => x.Wrapping(ServiceLocator.Current.Resolve<IFakeConfigurationManager>())); this.StubResolve(this.configurationManager); } public static IEnumerable<object[]> CallSpecificationActions => TestCases.FromObject<Action<IFoo>>( foo => A.CallTo(() => foo.Bar()), foo => A.CallTo(() => foo.Baz()), foo => A.CallToSet(() => foo.SomeProperty), foo => A.CallTo(foo)); [Fact] public void CallTo_with_void_call_should_return_configuration_from_configuration_manager() { // Arrange var foo = A.Fake<IFoo>(); Expression<Action> callSpecification = () => foo.Bar(); var configuration = A.Fake<IVoidArgumentValidationConfiguration>(); A.CallTo(() => this.configurationManager.CallTo(callSpecification)).Returns(configuration); // Act var result = A.CallTo(callSpecification); // Assert result.Should().BeSameAs(configuration); } [Fact] public void CallTo_with_function_call_should_return_configuration_from_configuration_manager() { // Arrange var foo = A.Fake<IFoo>(); Expression<Func<int>> callSpecification = () => foo.Baz(); var configuration = A.Fake<IReturnValueArgumentValidationConfiguration<int>>(); A.CallTo(() => this.configurationManager.CallTo(callSpecification)).Returns(configuration); // Act var result = A.CallTo(callSpecification); // Assert result.Should().BeSameAs(configuration); } [Theory] [MemberData(nameof(CallSpecificationActions))] public void CallTo_should_not_add_rule_to_manager(Action<IFoo> action) { // Arrange var foo = A.Fake<IFoo>(); var manager = Fake.GetFakeManager(foo); var initialRules = manager.Rules.ToList(); // Act action(foo); // Assert manager.Rules.Should().Equal(initialRules); } } }
mit
C#
b551cb6d5decfdea8ab820042e2e46daf8220964
build 1.5.8
agileharbor/Netco
src/GlobalAssemblyInfo.cs
src/GlobalAssemblyInfo.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 : AssemblyProduct( "Netco" ) ] [ assembly : AssemblyCompany( "Agile Harbor LLC" ) ] [ assembly : AssemblyCopyright( "Copyright Agile Harbor LLC." ) ] [ 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 ) ] // 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.5.8.0" ) ]
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 : AssemblyProduct( "Netco" ) ] [ assembly : AssemblyCompany( "Agile Harbor LLC" ) ] [ assembly : AssemblyCopyright( "Copyright Agile Harbor LLC." ) ] [ 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 ) ] // 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.5.7.0" ) ]
bsd-3-clause
C#
529cd84a9f8aeae49db8317780e83a8d157da6f0
add DataPtr so the mapped Data can be accessed without copying
gstreamer-sharp/gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,gstreamer-sharp/gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,GStreamer/gstreamer-sharp,GStreamer/gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,GStreamer/gstreamer-sharp,gstreamer-sharp/gstreamer-sharp
sources/custom/MapInfo.cs
sources/custom/MapInfo.cs
// // MapInfo.cs // // Authors: // Stephan Sundermann <stephansundermann@gmail.com> // // Copyright (C) 2014 Stephan Sundermann // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA // 02110-1301 USA namespace Gst { using System; using System.Runtime.InteropServices; partial struct MapInfo { public byte[] Data { get { byte[] data = new byte[Size]; Marshal.Copy (_data, data, 0, (int)Size); return data; } set { Marshal.Copy (value, 0, _data, Data.Length); } } public IntPtr DataPtr { get { return _data; } } } }
// // MapInfo.cs // // Authors: // Stephan Sundermann <stephansundermann@gmail.com> // // Copyright (C) 2014 Stephan Sundermann // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA // 02110-1301 USA namespace Gst { using System; using System.Runtime.InteropServices; partial struct MapInfo { public byte[] Data { get { byte[] data = new byte[Size]; Marshal.Copy (_data, data, 0, (int)Size); return data; } set { Marshal.Copy (value, 0, _data, Data.Length); } } } }
lgpl-2.1
C#
2dfd37779c53e00743cf15b66b0ff30d285b1f82
increment minor to 2.2.0
adamralph/xbehave.net,xbehave/xbehave.net
src/VersionInfo.2.cs
src/VersionInfo.2.cs
// <copyright file="VersionInfo.2.cs" company="xBehave.net contributors"> // Copyright (c) xBehave.net contributors. All rights reserved. // </copyright> using System.Reflection; [assembly: AssemblyVersion("2.2.0.0")] [assembly: AssemblyFileVersion("2.2.0.0")] [assembly: AssemblyInformationalVersion("2.2.0")]
// <copyright file="VersionInfo.2.cs" company="xBehave.net contributors"> // Copyright (c) xBehave.net contributors. All rights reserved. // </copyright> using System.Reflection; [assembly: AssemblyVersion("2.1.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")] [assembly: AssemblyInformationalVersion("2.1.0")]
mit
C#
f44b7d152dcbf1eb96d5cee2312d774d3e09c3ff
order by descending comments
fullstack101/SuggestionSystem,fullstack101/SuggestionSystem,fullstack101/SuggestionSystem,fullstack101/SuggestionSystem
Source/SuggestionSystem/Services/SuggestionSystem.Services.Data/CommentService.cs
Source/SuggestionSystem/Services/SuggestionSystem.Services.Data/CommentService.cs
namespace SuggestionSystem.Services.Data { using System; using SuggestionSystem.Data.Models; using SuggestionSystem.Services.Data.Contracts; using SuggestionSystem.Data.Repositories; using System.Linq; using Web.DataTransferModels.Comment; public class CommentService : ICommentService { private readonly IRepository<Comment> comments; public CommentService(IRepository<Comment> comments) { this.comments = comments; } public Comment AddComment(int suggestionId, string userId, Comment comment) { comment.DateCreated = DateTime.UtcNow; comment.SuggestionId = suggestionId; comment.UserId = userId; this.comments.Add(comment); this.comments.SaveChanges(); return comment; } public IQueryable<Comment> GetCommentsForSuggestion(int id, int from, int count) { return this.comments.All() .Where(c => c.SuggestionId == id) .OrderByDescending(c => c.DateCreated) .Skip(from) .Take(count); } public IQueryable<Comment> GetCommentById(int id) { return this.comments.All().Where(s => s.Id == id); } public bool UserIsEligibleToModifyComment(Comment comment, string userId, bool isAdmin) { return (isAdmin) || !(comment.UserId == null || comment.UserId != userId); } public void Delete(Comment comment) { this.comments.Delete(comment); this.comments.SaveChanges(); } public Comment UpdateComment(Comment commentToUpdate, CommentRequestModel model) { commentToUpdate.Content = model.Content; this.comments.SaveChanges(); return commentToUpdate; } } }
namespace SuggestionSystem.Services.Data { using System; using SuggestionSystem.Data.Models; using SuggestionSystem.Services.Data.Contracts; using SuggestionSystem.Data.Repositories; using System.Linq; using Web.DataTransferModels.Comment; public class CommentService : ICommentService { private readonly IRepository<Comment> comments; public CommentService(IRepository<Comment> comments) { this.comments = comments; } public Comment AddComment(int suggestionId, string userId, Comment comment) { comment.DateCreated = DateTime.UtcNow; comment.SuggestionId = suggestionId; comment.UserId = userId; this.comments.Add(comment); this.comments.SaveChanges(); return comment; } public IQueryable<Comment> GetCommentsForSuggestion(int id, int from, int count) { return this.comments.All() .Where(c => c.SuggestionId == id) .OrderBy(c => c.DateCreated) .Skip(from) .Take(count); } public IQueryable<Comment> GetCommentById(int id) { return this.comments.All().Where(s => s.Id == id); } public bool UserIsEligibleToModifyComment(Comment comment, string userId, bool isAdmin) { return (isAdmin) || !(comment.UserId == null || comment.UserId != userId); } public void Delete(Comment comment) { this.comments.Delete(comment); this.comments.SaveChanges(); } public Comment UpdateComment(Comment commentToUpdate, CommentRequestModel model) { commentToUpdate.Content = model.Content; this.comments.SaveChanges(); return commentToUpdate; } } }
mit
C#
1823358b0e530f642dacc27466c7d4f2f6862dc0
Bump to v0.23.0
danielwertheim/mycouch,danielwertheim/mycouch
src/SharedAssemblyInfo.cs
src/SharedAssemblyInfo.cs
using System.Runtime.InteropServices; using System.Reflection; #if DEBUG [assembly: AssemblyProduct("MyCouch (Debug)")] [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyProduct("MyCouch (Release)")] [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyDescription("MyCouch - the async .Net client for CouchDb and Cloudant.")] [assembly: AssemblyCompany("Daniel Wertheim")] [assembly: AssemblyCopyright("Copyright © 2014 Daniel Wertheim")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("0.23.0.*")] [assembly: AssemblyFileVersion("0.23.0")]
using System.Runtime.InteropServices; using System.Reflection; #if DEBUG [assembly: AssemblyProduct("MyCouch (Debug)")] [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyProduct("MyCouch (Release)")] [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyDescription("MyCouch - the async .Net client for CouchDb and Cloudant.")] [assembly: AssemblyCompany("Daniel Wertheim")] [assembly: AssemblyCopyright("Copyright © 2014 Daniel Wertheim")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("0.22.0.*")] [assembly: AssemblyFileVersion("0.22.0")]
mit
C#
d5edcc7febde78beb6da3cb1e73a59454d08fa39
remove existing fix
GHPReporter/Ghpr.Core,GHPReporter/Ghpr.Core,GHPReporter/Ghpr.Core
Ghpr.Core/Helpers/ItemInfoHelper.cs
Ghpr.Core/Helpers/ItemInfoHelper.cs
using System.Collections.Generic; using System.IO; using System.Linq; using Ghpr.Core.Common; using Newtonsoft.Json; namespace Ghpr.Core.Helpers { public static class ItemInfoHelper { public static void SaveItemInfo(string path, string filename, ItemInfo itemInfo, bool removeExisting = true) { var serializer = new JsonSerializer(); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } var fullRunsPath = Path.Combine(path, filename); if (!File.Exists(fullRunsPath)) { var items = new List<ItemInfo> { itemInfo }; using (var file = File.CreateText(fullRunsPath)) { serializer.Serialize(file, items); } } else { List<ItemInfo> items; using (var file = File.OpenText(fullRunsPath)) { items = (List<ItemInfo>)serializer.Deserialize(file, typeof(List<ItemInfo>)); if (removeExisting && items.Any(i => i.Guid.Equals(itemInfo.Guid))) { var existingItems = items.Where(i => i.Guid.Equals(itemInfo.Guid)); foreach (var item in existingItems) { items.Remove(item); } } items.Add(itemInfo); } using (var file = File.CreateText(fullRunsPath)) { items = items.OrderByDescending(x => x.Start).ToList(); serializer.Serialize(file, items); } } } } }
using System.Collections.Generic; using System.IO; using System.Linq; using Ghpr.Core.Common; using Newtonsoft.Json; namespace Ghpr.Core.Helpers { public static class ItemInfoHelper { public static void SaveItemInfo(string path, string filename, ItemInfo itemInfo, bool removeExisting = true) { var serializer = new JsonSerializer(); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } var fullRunsPath = Path.Combine(path, filename); if (!File.Exists(fullRunsPath)) { var items = new List<ItemInfo> { itemInfo }; using (var file = File.CreateText(fullRunsPath)) { serializer.Serialize(file, items); } } else { List<ItemInfo> items; using (var file = File.OpenText(fullRunsPath)) { items = (List<ItemInfo>)serializer.Deserialize(file, typeof(List<ItemInfo>)); if (removeExisting && items.Any(i => i.Guid.Equals(itemInfo.Guid))) { items.Remove(items.First(i => i.Guid.Equals(itemInfo.Guid))); } items.Add(itemInfo); } using (var file = File.CreateText(fullRunsPath)) { items = items.OrderByDescending(x => x.Start).ToList(); serializer.Serialize(file, items); } } } } }
mit
C#
0922d11f13b179660b80f989eaf16763fa45f9d2
Remove the debugging log
Unity-Technologies/editorconfig-visualstudio,Unity-Technologies/editorconfig-visualstudio,jedmao/editorconfig-visualstudio,jedmao/editorconfig-visualstudio
Plugin/Plugin.cs
Plugin/Plugin.cs
using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace EditorConfig.VisualStudio { /// <summary> /// This plugin attaches to an editor instance and updates its settings at /// the appropriate times /// </summary> internal class Plugin { public Plugin(IWpfTextView view, ITextDocument document) { document.FileActionOccurred += FileActionOccurred; LoadSettings(document.FilePath); } /// <summary> /// Reloads the settings when the filename changes /// </summary> void FileActionOccurred(object sender, TextDocumentFileActionEventArgs e) { if ((e.FileActionType & FileActionTypes.DocumentRenamed) != 0) LoadSettings(e.FilePath); } /// <summary> /// Loads the settings for the given file path /// </summary> private void LoadSettings(string path) { } } }
using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace EditorConfig.VisualStudio { /// <summary> /// This plugin attaches to an editor instance and updates its settings at /// the appropriate times /// </summary> internal class Plugin { public Plugin(IWpfTextView view, ITextDocument document) { document.FileActionOccurred += FileActionOccurred; LoadSettings(document.FilePath); } /// <summary> /// Reloads the settings when the filename changes /// </summary> void FileActionOccurred(object sender, TextDocumentFileActionEventArgs e) { if ((e.FileActionType & FileActionTypes.DocumentRenamed) != 0) LoadSettings(e.FilePath); } /// <summary> /// Loads the settings for the given file path /// </summary> private void LoadSettings(string path) { using (var log = new System.IO.StreamWriter(System.IO.Path.GetTempPath() + "editorconfig.log")) log.Write("Load settings for file " + path); } } }
bsd-2-clause
C#
10c81586239d8e336409e3bb96e495c1ebbe7376
tidy up
edyoung/prequel
Prequel/Checker.cs
Prequel/Checker.cs
using Microsoft.SqlServer.TransactSql.ScriptDom; using System; using System.Collections.Generic; using System.IO; namespace Prequel { public class Checker { private Arguments arguments; public Checker(Arguments arguments) { this.arguments = arguments; } public CheckResults Run() { var parser = (TSqlParser)Activator.CreateInstance(arguments.SqlParserType,new object[] { true }); Input input = arguments.Inputs[0]; try { TextReader reader = new StreamReader(input.Stream); IList<ParseError> errors; TSqlFragment sqlFragment = parser.Parse(reader, out errors); CheckVisitor checkVisitor = new CheckVisitor(); sqlFragment.Accept(checkVisitor); return new CheckResults(input, errors, checkVisitor.Warnings); } catch (IOException ex) { throw new ProgramTerminatingException( String.Format("Error reading file {0}: {1}", input.Path, ex.Message), ex) { ExitCode = 2 }; } } } }
using Microsoft.SqlServer.TransactSql.ScriptDom; using System; using System.Collections.Generic; using System.IO; namespace Prequel { public class Checker { private Arguments arguments; public Checker(Arguments arguments) { this.arguments = arguments; } public CheckResults Run() { var parser = (TSqlParser)Activator.CreateInstance(arguments.SqlParserType,new object[] { true }); Input input = arguments.Inputs[0]; TextReader reader; try { reader = new StreamReader(input.Stream); } catch(IOException ex) { throw new ProgramTerminatingException( String.Format("Error reading file {0}: {1}", input.Path, ex.Message), ex) { ExitCode = 2 }; } IList<ParseError> errors; TSqlFragment sqlFragment = parser.Parse(reader, out errors); CheckVisitor checkVisitor = new CheckVisitor(); sqlFragment.Accept(checkVisitor); return new CheckResults(input, errors, checkVisitor.Warnings); } } }
mit
C#
fbec18c94bb79c9aae9c2c074a5484e13627d083
Set internals visible to DynamicProxyGenAssembly2 for Moq
mattherman/MbDotNet,mattherman/MbDotNet,SuperDrew/MbDotNet
MbDotNet/Properties/AssemblyInfo.cs
MbDotNet/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("MbDotNet")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MbDotNet")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8a9a51ae-32ad-412d-a8f3-683af705ce80")] // 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.0.0")] [assembly: AssemblyFileVersion("1.3.0.0")] [assembly: InternalsVisibleTo("MbDotNet.Tests")] [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("MbDotNet")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MbDotNet")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8a9a51ae-32ad-412d-a8f3-683af705ce80")] // 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.0.0")] [assembly: AssemblyFileVersion("1.3.0.0")] [assembly: InternalsVisibleTo("MbDotNet.Tests")]
mit
C#
e12235885ac0ce0505b2023fb95dc7c7ac7f8f46
Implement the operators in MPoint2
charlenni/Mapsui,charlenni/Mapsui
Mapsui/MPoint2.cs
Mapsui/MPoint2.cs
using Mapsui.Utilities; namespace Mapsui; public class MPoint2 { public MPoint2(double x, double y) { X = x; Y = y; } public MPoint2(MPoint2 point) { X = point.X; Y = point.Y; } public double X { get; set; } public double Y { get; set; } public MRect MRect => new MRect(X, Y, X, Y); public MPoint2 Copy() { return new MPoint2(X, Y); } public double Distance(MPoint2 point) { return Algorithms.Distance(X, Y, point.X, point.Y); } public bool Equals(MPoint2? point) { if (point == null) return false; return X == point.X && Y == point.Y; } public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); } public MPoint2 Offset(double offsetX, double offsetY) { return new MPoint2(X + offsetX, Y + offsetY); } /// <summary> /// Calculates a new point by rotating this point clockwise about the specified center point /// </summary> /// <param name="degrees">Angle to rotate clockwise (degrees)</param> /// <param name="centerX">X coordinate of point about which to rotate</param> /// <param name="centerY">Y coordinate of point about which to rotate</param> /// <returns>Returns the rotated point</returns> public MPoint2 Rotate(double degrees, double centerX, double centerY) { // translate this point back to the center var newX = X - centerX; var newY = Y - centerY; // rotate the values var p = Algorithms.RotateClockwiseDegrees(newX, newY, degrees); // translate back to original reference frame newX = p.X + centerX; newY = p.Y + centerY; return new MPoint2(newX, newY); } /// <summary> /// Calculates a new point by rotating this point clockwise about the specified center point /// </summary> /// <param name="degrees">Angle to rotate clockwise (degrees)</param> /// <param name="center">MPoint about which to rotate</param> /// <returns>Returns the rotated point</returns> public MPoint2 Rotate(double degrees, MPoint2 center) { return Rotate(degrees, center.X, center.Y); } public static MPoint2 operator +(MPoint2 point1, MPoint2 point2) { return new MPoint2(point1.X + point2.X, point1 .Y + point2.Y); } public static MPoint2 operator -(MPoint2 point1, MPoint2 point2) { return new MPoint2(point1.X - point2.X, point1.Y - point2.Y); } public static MPoint2 operator *(MPoint2 point1, double multiplier) { return new MPoint2(point1.X * multiplier, point1.Y * multiplier); } }
using Mapsui.Utilities; namespace Mapsui; public class MPoint2 { public double X { get; set; } public double Y { get; set; } public MRect MRect => new MRect(X, Y, X, Y); public MPoint Copy() { return new MPoint(X, Y); } public double Distance(MPoint point) { return Algorithms.Distance(X, Y, point.X, point.Y); } public bool Equals(MPoint? point) { if (point == null) return false; return X == point.X && Y == point.Y; } public int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); } public MPoint Offset(double offsetX, double offsetY) { return new MPoint(X + offsetX, Y + offsetY); } /// <summary> /// Calculates a new point by rotating this point clockwise about the specified center point /// </summary> /// <param name="degrees">Angle to rotate clockwise (degrees)</param> /// <param name="centerX">X coordinate of point about which to rotate</param> /// <param name="centerY">Y coordinate of point about which to rotate</param> /// <returns>Returns the rotated point</returns> public MPoint Rotate(double degrees, double centerX, double centerY) { // translate this point back to the center var newX = X - centerX; var newY = Y - centerY; // rotate the values var p = Algorithms.RotateClockwiseDegrees(newX, newY, degrees); // translate back to original reference frame newX = p.X + centerX; newY = p.Y + centerY; return new MPoint(newX, newY); } /// <summary> /// Calculates a new point by rotating this point clockwise about the specified center point /// </summary> /// <param name="degrees">Angle to rotate clockwise (degrees)</param> /// <param name="center">MPoint about which to rotate</param> /// <returns>Returns the rotated point</returns> public MPoint Rotate(double degrees, MPoint center) { return Rotate(degrees, center.X, center.Y); } }
mit
C#
dad1d2aecf8c988f7e013a631c7d2f8c49f06ff8
Update Applied.cs
datanets/kask-kiosk,datanets/kask-kiosk
Models/Applied.cs
Models/Applied.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Empty.Models { public class Applied { public int Applicant_ID { get; set; } public int Application_ID { get; set; } public int JobID { get; set; } public DateTime dateApplied { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Empty.Models { public class Applied { public int applicant_ID { get; set; } public int application_ID { get; set; } public int jobID { get; set; } //date type?? public string dateApplied { get; set; } } }
mit
C#
a4fddf77df0cae50013e06630323e6281925b116
Add GroupTestAsync
ats124/backlog4net
src/Backlog4net.Test/GroupMethodsTest.cs
src/Backlog4net.Test/GroupMethodsTest.cs
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Runtime.Remoting; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Backlog4net.Test { using Api; using Api.Option; using Backlog4net.Internal.Json; using Backlog4net.Internal.Json.Activities; using Conf; using Newtonsoft.Json; using TestConfig; [TestClass] public class GroupMethodsTest { private static BacklogClient client; private static GeneralConfig generalConfig; private static string projectKey; private static long projectId; private static User ownUser; private static User anotherUser; [ClassInitialize] public static async Task SetupClient(TestContext context) { generalConfig = GeneralConfig.Instance.Value; var conf = new BacklogJpConfigure(generalConfig.SpaceKey); conf.ApiKey = generalConfig.ApiKey; client = new BacklogClientFactory(conf).NewClient(); var users = await client.GetUsersAsync(); projectKey = generalConfig.ProjectKey; var project = await client.GetProjectAsync(projectKey); projectId = project.Id; ownUser = await client.GetMyselfAsync(); var conf2 = new BacklogJpConfigure(generalConfig.SpaceKey); conf2.ApiKey = generalConfig.ApiKey2; var client2 = new BacklogClientFactory(conf).NewClient(); anotherUser = await client2.GetMyselfAsync(); } [TestMethod] public async Task GroupTestAsync() { var group = await client.CreateGroupAsync(new CreateGroupParams("TestGroup") { Members = new[] { ownUser.Id } }); Assert.AreNotEqual(group.Id, 0L); Assert.AreEqual(group.Name, "TestGroup"); Assert.IsTrue(group.Members.Any(x => x.Id == ownUser.Id)); var groupGet = await client.GetGroupAsync(group.Id); Assert.AreEqual(groupGet.Id, group.Id); Assert.AreEqual(groupGet.Name, group.Name); Assert.IsTrue(groupGet.Members.Any(x => x.Id == ownUser.Id)); var groupUpdated = await client.UpdateGroupAsync(new UpdateGroupParams(group.Id) { Name = "TestGroupUpdated", Members = new[] { anotherUser.Id } }); Assert.AreEqual(groupUpdated.Id, group.Id); Assert.AreEqual(groupUpdated.Name, "TestGroupUpdated"); Assert.IsTrue(groupGet.Members.Any(x => x.Id == anotherUser.Id)); await client.GetGroupsAsync(new OffsetParams() { Count = 100, Offset = 1, Order = Order.Desc }); var groupDeleted = await client.DeleteGroupAsync(groupUpdated.Id); Assert.AreEqual(groupDeleted.Id, groupDeleted.Id); Assert.AreEqual(groupDeleted.Name, groupDeleted.Name); Assert.IsTrue(groupDeleted.Members.Any(x => x.Id == anotherUser.Id)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Runtime.Remoting; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Backlog4net.Test { using Api; using Api.Option; using Backlog4net.Internal.Json; using Backlog4net.Internal.Json.Activities; using Conf; using Newtonsoft.Json; using TestConfig; [TestClass] public class GroupMethodsTest { private static BacklogClient client; private static GeneralConfig generalConfig; private static string projectKey; private static long projectId; private static User ownUser; [ClassInitialize] public static async Task SetupClient(TestContext context) { generalConfig = GeneralConfig.Instance.Value; var conf = new BacklogJpConfigure(generalConfig.SpaceKey); conf.ApiKey = generalConfig.ApiKey; client = new BacklogClientFactory(conf).NewClient(); var users = await client.GetUsersAsync(); projectKey = generalConfig.ProjectKey; var project = await client.GetProjectAsync(projectKey); projectId = project.Id; ownUser = await client.GetMyselfAsync(); } } }
mit
C#
df7ee53fa0d6d7cc6f0266ab77b994fdd9c01535
load the parser assembly with Assembly.LoadWithPartialName to support the GAC
boo/boo-lang,boo/boo-lang,boo/boo-lang,boo/boo-lang,boo/boo-lang,boo/boo-lang,boo/boo-lang
src/Boo.Lang.Compiler/Pipelines/Parse.cs
src/Boo.Lang.Compiler/Pipelines/Parse.cs
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion namespace Boo.Lang.Compiler.Pipelines { using System; using System.Reflection; using Boo.Lang.Compiler.Steps; public class Parse : CompilerPipeline { static Type _defaultParserStepType; public static ICompilerStep NewParserStep() { if (null == _defaultParserStepType) { Assembly assembly = Assembly.LoadWithPartialName("Boo.Lang.Parser"); _defaultParserStepType = assembly.GetType("Boo.Lang.Parser.BooParsingStep", true); } return (ICompilerStep)Activator.CreateInstance(_defaultParserStepType); } public Parse() { Add(NewParserStep()); } } }
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion namespace Boo.Lang.Compiler.Pipelines { using System; using Boo.Lang.Compiler.Steps; public class Parse : CompilerPipeline { static Type _defaultParserStepType; public static ICompilerStep NewParserStep() { if (null == _defaultParserStepType) { _defaultParserStepType = Type.GetType("Boo.Lang.Parser.BooParsingStep, Boo.Lang.Parser", true); } return (ICompilerStep)Activator.CreateInstance(_defaultParserStepType); } public Parse() { Add(NewParserStep()); } } }
bsd-3-clause
C#
c1bd154eb60b3e1877e6e480d30f0a8ab7de99a6
return AsyncTask when you invoke Async.Run
mdavid/SuperSocket,mdavid/SuperSocket,mdavid/SuperSocket
mainline/Common/Async.cs
mainline/Common/Async.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SuperSocket.Common { public static class Async { public static Task Run(Action task) { return Run(task, TaskCreationOptions.None); } public static Task Run(Action task, TaskCreationOptions taskOption) { return Run(task, taskOption, null); } public static Task Run(Action task, Action<Exception> exceptionHandler) { return Run(task, TaskCreationOptions.None, exceptionHandler); } public static Task Run(Action task, TaskCreationOptions taskOption, Action<Exception> exceptionHandler) { return Task.Factory.StartNew(task, taskOption).ContinueWith(t => { if (exceptionHandler != null) exceptionHandler(t.Exception); else LogUtil.LogError(t.Exception); }, TaskContinuationOptions.OnlyOnFaulted); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SuperSocket.Common { public static class Async { public static void Run(Action task) { Run(task, TaskCreationOptions.None); } public static void Run(Action task, TaskCreationOptions taskOption) { Run(task, taskOption, null); } public static void Run(Action task, Action<Exception> exceptionHandler) { Run(task, TaskCreationOptions.None, exceptionHandler); } public static void Run(Action task, TaskCreationOptions taskOption, Action<Exception> exceptionHandler) { Task.Factory.StartNew(task, taskOption).ContinueWith(t => { if (exceptionHandler != null) exceptionHandler(t.Exception); else LogUtil.LogError(t.Exception); }, TaskContinuationOptions.OnlyOnFaulted); } } }
apache-2.0
C#
e963d21ecff6311e9a27199a94ec0ce4d2f71df2
Clean up code
mike-rowley/XamarinMediaManager,mike-rowley/XamarinMediaManager
MediaManager/Platforms/Uap/Media/MediaItemExtensions.cs
MediaManager/Platforms/Uap/Media/MediaItemExtensions.cs
using System; using System.IO; using System.Threading.Tasks; using MediaManager.Library; using MediaManager.Media; using Windows.Media.Core; using Windows.Media.Playback; using Windows.Storage; namespace MediaManager.Platforms.Uap.Media { public static class MediaItemExtensions { public static async Task<MediaSource> ToMediaSource(this IMediaItem mediaItem) { //TODO: Get Metadata from MediaSource if (mediaItem.MediaLocation.IsLocal()) { var storageFile = await StorageFile.GetFileFromPathAsync(mediaItem.MediaUri); return MediaSource.CreateFromStorageFile(storageFile); } else if (mediaItem.MediaLocation == MediaLocation.InMemory) return MediaSource.CreateFromStream(mediaItem.Data.AsRandomAccessStream(), mediaItem.MimeType.ToMimeTypeString()); else return MediaSource.CreateFromUri(new Uri(mediaItem.MediaUri)); } public static MediaPlaybackItem ToMediaPlaybackItem(this MediaSource mediaSource) { return new MediaPlaybackItem(mediaSource); } public static MediaPlaybackItem ToMediaPlaybackItem(this MediaSource mediaSource, TimeSpan startAt, TimeSpan? stopAt = null) { if (stopAt is TimeSpan endTime) return new MediaPlaybackItem(mediaSource, startAt, endTime); return new MediaPlaybackItem(mediaSource, startAt); } } }
using System; using System.IO; using System.Threading.Tasks; using MediaManager.Library; using MediaManager.Media; using Windows.Media.Core; using Windows.Media.Playback; using Windows.Storage; namespace MediaManager.Platforms.Uap.Media { public static class MediaItemExtensions { public static async Task<MediaSource> ToMediaSource(this IMediaItem mediaItem) { //TODO: Get Metadata from MediaSource if (mediaItem.MediaLocation.IsLocal()) { var storageFile = await StorageFile.GetFileFromPathAsync(mediaItem.MediaUri); return MediaSource.CreateFromStorageFile(storageFile); } else if (mediaItem.MediaLocation == MediaLocation.InMemory) { return MediaSource.CreateFromStream(mediaItem.Data.AsRandomAccessStream(), mediaItem.MimeType.ToMimeTypeString()); } else return MediaSource.CreateFromUri(new Uri(mediaItem.MediaUri)); } public static MediaPlaybackItem ToMediaPlaybackItem(this MediaSource mediaSource) { return new MediaPlaybackItem(mediaSource); } public static MediaPlaybackItem ToMediaPlaybackItem(this MediaSource mediaSource, TimeSpan startAt, TimeSpan? stopAt = null) { if (stopAt is TimeSpan endTime) return new MediaPlaybackItem(mediaSource, startAt, endTime); return new MediaPlaybackItem(mediaSource, startAt); } } }
mit
C#
0a57c043acc336641cf0c013ca6dc5cf0014b94b
Fix whitespace in tests file
SharpeRAD/Cake.Services
src/Services.Tests/Tests/ServiceTests.cs
src/Services.Tests/Tests/ServiceTests.cs
#region Using Statements using System; using System.IO; using System.Collections.ObjectModel; using System.ServiceProcess; using Xunit; using System.Management.Automation; using System.Management.Automation.Runspaces; using Cake.Core.Diagnostics; using Cake.Core.IO; using Cake.Powershell; #endregion namespace Cake.Services.Tests { public class ServiceTests { [Fact] public void Should_Service_IsInstalled() { IServiceManager manager = CakeHelper.CreateServiceManager(); bool result1 = manager.IsInstalled("MpsSvc"); bool result2 = manager.IsInstalled("TestSer"); Assert.True(result1); Assert.False(result2); } [Fact] public void Should_Get_Service() { IServiceManager manager = CakeHelper.CreateServiceManager(); ServiceController controller = manager.GetService("MpsSvc"); Assert.True(controller != null, "Check Rights"); } [Fact] public void Should_Change_Service_State() { IServiceManager manager = CakeHelper.CreateServiceManager(); bool result = false; if (manager.IsRunning("MpsSvc")) { result = manager.Stop("MpsSvc"); } else { result = manager.Start("MpsSvc"); } Assert.True(result, "Check Rights"); } [Fact] public void Should_Construct_Arg_String() { ServiceManager manager = (ServiceManager) CakeHelper.CreateServiceManager(); var argumentBuilder = manager.CreateInstallArguments("", new InstallSettings() { ServiceName = "TestService", ExecutablePath = @"C:\my\path\to\bin.exe", DisplayName = "Test Service Display Name", Dependencies = "TestDependencies", Username = "TestUsername", Password = "TestPasswordPassword", StartMode = "TestStartMode" }); var actual = argumentBuilder.Render(); var expected = @"""TestService"" binPath= ""C:/my/path/to/bin.exe"" DisplayName= ""Test Service Display Name"" depend= ""TestDependencies"" start= ""TestStartMode"" obj= ""TestUsername"" password= ""TestPasswordPassword"""; Assert.Equal(expected, actual); } } }
#region Using Statements using System; using System.IO; using System.Collections.ObjectModel; using System.ServiceProcess; using Xunit; using System.Management.Automation; using System.Management.Automation.Runspaces; using Cake.Core.Diagnostics; using Cake.Core.IO; using Cake.Powershell; #endregion namespace Cake.Services.Tests { public class ServiceTests { [Fact] public void Should_Service_IsInstalled() { IServiceManager manager = CakeHelper.CreateServiceManager(); bool result1 = manager.IsInstalled("MpsSvc"); bool result2 = manager.IsInstalled("TestSer"); Assert.True(result1); Assert.False(result2); } [Fact] public void Should_Get_Service() { IServiceManager manager = CakeHelper.CreateServiceManager(); ServiceController controller = manager.GetService("MpsSvc"); Assert.True(controller != null, "Check Rights"); } [Fact] public void Should_Change_Service_State() { IServiceManager manager = CakeHelper.CreateServiceManager(); bool result = false; if (manager.IsRunning("MpsSvc")) { result = manager.Stop("MpsSvc"); } else { result = manager.Start("MpsSvc"); } Assert.True(result, "Check Rights"); } [Fact] public void Should_Construct_Arg_String() { ServiceManager manager = (ServiceManager) CakeHelper.CreateServiceManager(); var argumentBuilder = manager.CreateInstallArguments("", new InstallSettings() { ServiceName = "TestService", ExecutablePath = @"C:\my\path\to\bin.exe", DisplayName = "Test Service Display Name", Dependencies = "TestDependencies", Username = "TestUsername", Password = "TestPasswordPassword", StartMode = "TestStartMode" }); var actual = argumentBuilder.Render(); var expected = @"""TestService"" binPath= ""C:/my/path/to/bin.exe"" DisplayName= ""Test Service Display Name"" depend= ""TestDependencies"" start= ""TestStartMode"" obj= ""TestUsername"" password= ""TestPasswordPassword"""; Assert.Equal(expected, actual); } } }
mit
C#
18ec9068e86b3dc60ad29eaeaad496bcf4694dd4
Bump the patch version.
SparkPost/csharp-sparkpost,kirilsi/csharp-sparkpost,darrencauthon/csharp-sparkpost,kirilsi/csharp-sparkpost,ZA1/csharp-sparkpost,darrencauthon/csharp-sparkpost
src/SparkPost/Properties/AssemblyInfo.cs
src/SparkPost/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("SparkPost")] [assembly: AssemblyDescription("SparkPost API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SparkPost")] [assembly: AssemblyProduct("SparkPost")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a5dda3e3-7b3d-46c3-b4bb-c627fba37812")] // 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.1.*")] [assembly: AssemblyFileVersion("1.0.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("SparkPost")] [assembly: AssemblyDescription("SparkPost API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SparkPost")] [assembly: AssemblyProduct("SparkPost")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a5dda3e3-7b3d-46c3-b4bb-c627fba37812")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
12809cdff162fd6ca0e522f544ac2b46216d9c91
add s6
Mooophy/158212
sudoku/Library/Sudoku6.cs
sudoku/Library/Sudoku6.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Library { public class Sudoku6 : Library.Matrix { public Sudoku6() : base(6, new RRangeSet(), new CRangeSet()) { } public Sudoku6(int[,] data) : base(6, new RRangeSet(), new CRangeSet(), data) { } public class RRangeSet : HashSet<Library.Matrix.Range> { public RRangeSet() { this.Add(new Matrix.Range(0, 2)); this.Add(new Matrix.Range(2, 2)); this.Add(new Matrix.Range(4, 2)); } } public class CRangeSet : HashSet<Library.Matrix.Range> { public CRangeSet() { this.Add(new Matrix.Range(0, 3)); this.Add(new Matrix.Range(3, 3)); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Library { public class Sudoku6 { public class RowRangeSet : HashSet<Matrix.Range> { public RowRangeSet() { this.Add(new Matrix.Range(0, 2)); this.Add(new Matrix.Range(2, 2)); this.Add(new Matrix.Range(4, 2)); } } public class ColRangeSet : HashSet<Matrix.Range> { public ColRangeSet() { this.Add(new Matrix.Range(0, 3)); this.Add(new Matrix.Range(3, 3)); } } } }
mit
C#
a7e2362fbeeb6c4d16f64ea66f3b805c4bb0674e
Make Range a more wholesome implementation (#65)
sebastienros/esprima-dotnet,sebastienros/esprima-dotnet
src/Esprima/Ast/Range.cs
src/Esprima/Ast/Range.cs
using System; using System.Globalization; namespace Esprima.Ast { public readonly struct Range : IEquatable<Range> { public readonly int Start; public readonly int End; public Range(int start, int end) { Start = start >= 0 ? start : throw new ArgumentOutOfRangeException(nameof(start)); End = end > start ? end : throw new ArgumentOutOfRangeException(nameof(end)); } public bool Equals(Range other) => Start == other.Start && End == other.End; public override bool Equals(object obj) => obj is Range other && Equals(other); public override int GetHashCode() => unchecked((Start * 397) ^ End); public override string ToString() => string.Format(CultureInfo.InvariantCulture, "[{0}..{1})", Start, End); public static bool operator ==(Range left, Range right) => left.Equals(right); public static bool operator !=(Range left, Range right) => !left.Equals(right); } }
namespace Esprima.Ast { public struct Range { public readonly int Start; public readonly int End; public Range(int start, int end) { Start = start; End = end; } } }
bsd-3-clause
C#
9bfcd0db7d9c3a00dd677289ba23e16df451541a
Fix integration test build error due to overprotective warning. (#1540)
PomeloFoundation/Pomelo.EntityFrameworkCore.MySql,PomeloFoundation/Pomelo.EntityFrameworkCore.MySql
test/EFCore.MySql.IntegrationTests/Program.cs
test/EFCore.MySql.IntegrationTests/Program.cs
using System; using Pomelo.EntityFrameworkCore.MySql.IntegrationTests.Commands; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Pomelo.EntityFrameworkCore.MySql.Tests; namespace Pomelo.EntityFrameworkCore.MySql.IntegrationTests { public class Program { public static void Main(string[] args) { if (args.Length == 0) { BuildWebHost(args).Run(); } else { var serviceCollection = new ServiceCollection(); serviceCollection .AddLogging(builder => builder .AddConfiguration(AppConfig.Config.GetSection("Logging")) .AddConsole() ) .AddSingleton<ICommandRunner, CommandRunner>() .AddSingleton<IConnectionStringCommand, ConnectionStringCommand>() .AddSingleton<ITestMigrateCommand, TestMigrateCommand>() .AddSingleton<ITestPerformanceCommand, TestPerformanceCommand>(); Startup.ConfigureEntityFramework(serviceCollection); #pragma warning disable ASP0000 var serviceProvider = serviceCollection.BuildServiceProvider(); #pragma warning restore ASP0000 var commandRunner = serviceProvider.GetService<ICommandRunner>(); Environment.Exit(commandRunner.Run(args)); } } public static IWebHost BuildWebHost(string[] args) { return WebHost.CreateDefaultBuilder(args) .UseUrls("http://*:5000") .UseStartup<Startup>() .Build(); } } }
using System; using Pomelo.EntityFrameworkCore.MySql.IntegrationTests.Commands; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Pomelo.EntityFrameworkCore.MySql.Tests; namespace Pomelo.EntityFrameworkCore.MySql.IntegrationTests { public class Program { public static void Main(string[] args) { if (args.Length == 0) { BuildWebHost(args).Run(); } else { var serviceCollection = new ServiceCollection(); serviceCollection .AddLogging(builder => builder .AddConfiguration(AppConfig.Config.GetSection("Logging")) .AddConsole() ) .AddSingleton<ICommandRunner, CommandRunner>() .AddSingleton<IConnectionStringCommand, ConnectionStringCommand>() .AddSingleton<ITestMigrateCommand, TestMigrateCommand>() .AddSingleton<ITestPerformanceCommand, TestPerformanceCommand>(); Startup.ConfigureEntityFramework(serviceCollection); var serviceProvider = serviceCollection.BuildServiceProvider(); var commandRunner = serviceProvider.GetService<ICommandRunner>(); Environment.Exit(commandRunner.Run(args)); } } public static IWebHost BuildWebHost(string[] args) { return WebHost.CreateDefaultBuilder(args) .UseUrls("http://*:5000") .UseStartup<Startup>() .Build(); } } }
mit
C#
04dc2f8dd3d4c6a630559c7af3f8cfa26ab28091
Add ability to match nearest DisplayMode
smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework
osu.Framework/Platform/Display.cs
osu.Framework/Platform/Display.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 System.Drawing; using System.Linq; namespace osu.Framework.Platform { /// <summary> /// Represents a physical display device on the current system. /// </summary> public sealed class Display : IEquatable<Display> { /// <summary> /// The name of the display, if available. Usually the manufacturer. /// </summary> public string Name { get; } /// <summary> /// The current rectangle of the display in screen space. /// Non-zero X and Y values represent a non-primary monitor, and indicate its position /// relative to the primary monitor. /// </summary> public Rectangle Bounds { get; } /// <summary> /// The available <see cref="DisplayMode"/>s on this display. /// </summary> public DisplayMode[] DisplayModes { get; } /// <summary> /// The zero-based index of the <see cref="Display"/>. /// </summary> public int Index { get; } public Display(int index, string name, Rectangle bounds, DisplayMode[] displayModes) { Index = index; Name = name; Bounds = bounds; DisplayModes = displayModes; } public override string ToString() => $"Name: {Name ?? "Unknown"}, Bounds: {Bounds}, DisplayModes: {DisplayModes.Length}"; public bool Equals(Display other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Index == other.Index; } /// <summary> /// Attempts to find a <see cref="DisplayMode"/> for the given <see cref="Display"/> that /// closely matches the requested parameters. /// </summary> /// <param name="size">The <see cref="Size"/> to match.</param> /// <param name="bitsPerPixel">The bits per pixel to match. If null, the highest available bits per pixel will be used.</param> /// <param name="refreshRate">The refresh rate in hertz. If null, the highest available refresh rate will be used.</param> /// <returns></returns> public DisplayMode FindDisplayMode(Size size, int? bitsPerPixel = null, int? refreshRate = null) => DisplayModes.Where(mode => mode.Size.Width <= size.Width && mode.Size.Height <= size.Height && (bitsPerPixel == null || mode.BitsPerPixel == bitsPerPixel) && (refreshRate == null || mode.RefreshRate == refreshRate)) .OrderByDescending(mode => mode.Size.Width) .ThenByDescending(mode => mode.Size.Height) .ThenByDescending(mode => mode.RefreshRate) .ThenByDescending(mode => mode.BitsPerPixel) .FirstOrDefault(); } }
// 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 System.Drawing; namespace osu.Framework.Platform { /// <summary> /// Represents a physical display device on the current system. /// </summary> public sealed class Display : IEquatable<Display> { /// <summary> /// The name of the display, if available. Usually the manufacturer. /// </summary> public string Name { get; } /// <summary> /// The current rectangle of the display in screen space. /// Non-zero X and Y values represent a non-primary monitor, and indicate its position /// relative to the primary monitor. /// </summary> public Rectangle Bounds { get; } /// <summary> /// The available <see cref="DisplayMode"/>s on this display. /// </summary> public DisplayMode[] DisplayModes { get; } /// <summary> /// The zero-based index of the <see cref="Display"/>. /// </summary> public int Index { get; } public Display(int index, string name, Rectangle bounds, DisplayMode[] displayModes) { Index = index; Name = name; Bounds = bounds; DisplayModes = displayModes; } public override string ToString() => $"Name: {Name ?? "Unknown"}, Bounds: {Bounds}, DisplayModes: {DisplayModes.Length}"; public bool Equals(Display other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Index == other.Index; } } }
mit
C#
a04e6d22bae679f75debd648516a5ccf4fe918f7
add equals to intstr
kubernetes-client/csharp,kubernetes-client/csharp
src/IntstrIntOrString.cs
src/IntstrIntOrString.cs
using System; using Newtonsoft.Json; namespace k8s.Models { internal class IntOrStringConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var s = (value as IntstrIntOrString)?.Value; if (int.TryParse(s, out var intv)) { serializer.Serialize(writer, intv); return; } serializer.Serialize(writer, s); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return (IntstrIntOrString) serializer.Deserialize<string>(reader); } public override bool CanConvert(Type objectType) { return objectType == typeof(int) || objectType == typeof(string); } } [JsonConverter(typeof(IntOrStringConverter))] public partial class IntstrIntOrString { public static implicit operator int(IntstrIntOrString v) { return int.Parse(v.Value); } public static implicit operator IntstrIntOrString(int v) { return new IntstrIntOrString(Convert.ToString(v)); } public static implicit operator string(IntstrIntOrString v) { return v.Value; } public static implicit operator IntstrIntOrString(string v) { return new IntstrIntOrString(v); } protected bool Equals(IntstrIntOrString other) { return string.Equals(Value, other.Value); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((IntstrIntOrString) obj); } public override int GetHashCode() { return (Value != null ? Value.GetHashCode() : 0); } } }
using System; using Newtonsoft.Json; namespace k8s.Models { internal class IntOrStringConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var s = (value as IntstrIntOrString)?.Value; if (int.TryParse(s, out var intv)) { serializer.Serialize(writer, intv); return; } serializer.Serialize(writer, s); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return (IntstrIntOrString) serializer.Deserialize<string>(reader); } public override bool CanConvert(Type objectType) { return objectType == typeof(int) || objectType == typeof(string); } } [JsonConverter(typeof(IntOrStringConverter))] public partial class IntstrIntOrString { public static implicit operator int(IntstrIntOrString v) { return int.Parse(v.Value); } public static implicit operator IntstrIntOrString(int v) { return new IntstrIntOrString(Convert.ToString(v)); } public static implicit operator string(IntstrIntOrString v) { return v.Value; } public static implicit operator IntstrIntOrString(string v) { return new IntstrIntOrString(v); } } }
apache-2.0
C#
b74402f734f834e3b1752f57eda1269f484ec37d
Bump version v1.1.5
karronoli/tiny-sato
TinySato/Properties/AssemblyInfo.cs
TinySato/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("TinySato")] [assembly: AssemblyDescription("You can construct and send SBPL packet to Sato printer. Sato printer is needed to be recognized by windows driver.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TinySato")] [assembly: AssemblyCopyright("Copyright 2016 karronoli")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("f56213db-fa1f-42da-b930-b642a56ee840")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: [assembly: AssemblyVersion("1.1.5.*")] [assembly: AssemblyFileVersion("1.1.5")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("TinySato")] [assembly: AssemblyDescription("You can construct and send SBPL packet to Sato printer. Sato printer is needed to be recognized by windows driver.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TinySato")] [assembly: AssemblyCopyright("Copyright 2016 karronoli")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("f56213db-fa1f-42da-b930-b642a56ee840")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: [assembly: AssemblyVersion("1.1.4.*")] [assembly: AssemblyFileVersion("1.1.4")]
apache-2.0
C#
b7b54d1c9a840773c3cccdbac167892cec10914a
Switch to version 1.4.6
Abc-Arbitrage/Zebus,biarne-a/Zebus
src/SharedVersionInfo.cs
src/SharedVersionInfo.cs
using System.Reflection; [assembly: AssemblyVersion("1.4.6")] [assembly: AssemblyFileVersion("1.4.6")] [assembly: AssemblyInformationalVersion("1.4.6")]
using System.Reflection; [assembly: AssemblyVersion("1.4.6")] [assembly: AssemblyFileVersion("1.4.6")] [assembly: AssemblyInformationalVersion("1.4.6-subsfix01")]
mit
C#
3a61099829886b48d8f0ca130794fab7dba4320c
Adjust the namespace for the test program
mathnet/mathnet-numerics,mathnet/mathnet-numerics,shaia/mathnet-numerics,shaia/mathnet-numerics,mathnet/mathnet-numerics,mathnet/mathnet-numerics,mathnet/mathnet-numerics,shaia/mathnet-numerics,shaia/mathnet-numerics,shaia/mathnet-numerics
src/UnitTests/Program.cs
src/UnitTests/Program.cs
// <copyright file="Program.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2017 Math.NET // // 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. // </copyright> using NUnitLite; using System.Reflection; namespace MathNet.Numerics.UnitTests { class Program { public static int Main(string[] args) { return new AutoRun(typeof(Program).GetTypeInfo().Assembly).Execute(args); } } }
// <copyright file="Program.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2017 Math.NET // // 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. // </copyright> using NUnitLite; using System.Reflection; namespace NodaTime.Test { class Program { public static int Main(string[] args) { return new AutoRun(typeof(Program).GetTypeInfo().Assembly).Execute(args); } } }
mit
C#
5fba9e1aa85aa7ef2e1e7125975073641b0e5c15
Fix generic constraint for ValueType (from ValueType to EquatableByValue).
tpierrain/Value
Value/ValueType.cs
Value/ValueType.cs
// // -------------------------------------------------------------------------------------------------------------------- // // <copyright file="ValueType.cs"> // // Copyright 2016 // // Thomas PIERRAIN (@tpierrain) // // 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.b // // </copyright> // // -------------------------------------------------------------------------------------------------------------------- namespace Value { /// <summary> /// Base class for any Value Type (i.e. the 'Value Object' oxymoron of DDD). /// All you have to do is to implement the abstract methods: <see cref="EquatableByValue{T}.GetAllAttributesToBeUsedForEquality"/> /// </summary> /// <typeparam name="T">Domain type to be 'turned' into a Value Type.</typeparam> public abstract class ValueType<T> : EquatableByValue<T> where T : EquatableByValue<T> { } }
// // -------------------------------------------------------------------------------------------------------------------- // // <copyright file="ValueType.cs"> // // Copyright 2016 // // Thomas PIERRAIN (@tpierrain) // // 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.b // // </copyright> // // -------------------------------------------------------------------------------------------------------------------- namespace Value { /// <summary> /// Base class for any Value Type (i.e. the 'Value Object' oxymoron of DDD). /// All you have to do is to implement the abstract methods: <see cref="EquatableByValue{T}.GetAllAttributesToBeUsedForEquality"/> /// </summary> /// <typeparam name="T">Domain type to be 'turned' into a Value Type.</typeparam> public abstract class ValueType<T> : EquatableByValue<T> where T : ValueType<T> { } }
apache-2.0
C#
fd14b1d992a0a87837d079366806859d693e4747
Add test
sakapon/Tools-2016
FileReplacer/UnitTest/FileHelperTest.cs
FileReplacer/UnitTest/FileHelperTest.cs
using System; using System.IO; using System.Text; using FileReplacer; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTest { [TestClass] public class FileHelperTest { [TestMethod] public void ReplaceContent_UTF8() { ReplaceContent("ReplaceContent_UTF8.txt", Encoding.UTF8); } [TestMethod] public void ReplaceContent_UTF8N() { ReplaceContent("ReplaceContent_UTF8N.txt", FileHelper.UTF8N); } static void ReplaceContent(string filePath, Encoding encoding) { File.WriteAllText(filePath, "A Old Name.\r\n123\r\n", encoding); var file = new FileInfo(filePath); FileHelper.ReplaceContent(file, "Old Name", "New Name"); var actual = File.ReadAllBytes(filePath); var expected = ToBytes("A New Name.\r\n123\r\n", encoding); CollectionAssert.AreEqual(expected, actual); } static byte[] ToBytes(string content, Encoding encoding) { using (var stream = new MemoryStream()) using (var writer = new StreamWriter(stream, encoding)) { writer.Write(content); writer.Flush(); return stream.ToArray(); } } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTest { [TestClass] public class FileHelperTest { [TestMethod] public void TestMethod1() { } } }
mit
C#
b6b5c84f9151e801b3c7c8f6e306dc0d0a7e1211
Set TCP keepalive for all OSes. Fixes #746
mysql-net/MySqlConnector,mysql-net/MySqlConnector
src/MySqlConnector/Utilities/SocketExtensions.cs
src/MySqlConnector/Utilities/SocketExtensions.cs
using System; using System.Net.Sockets; using System.Runtime.InteropServices; namespace MySqlConnector.Utilities { internal static class SocketExtensions { #if !NETSTANDARD2_1 && !NETCOREAPP3_0 public static SocketAwaitable ReceiveAsync(this Socket socket, SocketAwaitable awaitable) { awaitable.Reset(); if (!socket.ReceiveAsync(awaitable.EventArgs)) awaitable.WasCompleted = true; return awaitable; } public static SocketAwaitable SendAsync(this Socket socket, SocketAwaitable awaitable) { awaitable.Reset(); if (!socket.SendAsync(awaitable.EventArgs)) awaitable.WasCompleted = true; return awaitable; } #endif #if !NETSTANDARD2_1 && !NETCOREAPP2_1 && !NETCOREAPP3_0 public static void SetBuffer(this SocketAsyncEventArgs args, Memory<byte> buffer) { MemoryMarshal.TryGetArray<byte>(buffer, out var arraySegment); args.SetBuffer(arraySegment.Array, arraySegment.Offset, arraySegment.Count); } public static int Send(this Socket socket, ReadOnlyMemory<byte> data, SocketFlags flags) { MemoryMarshal.TryGetArray(data, out var arraySegment); return socket.Send(arraySegment.Array, arraySegment.Offset, arraySegment.Count, flags); } #else public static int Send(this Socket socket, ReadOnlyMemory<byte> data, SocketFlags flags) => socket.Send(data.Span, flags); #endif public static void SetKeepAlive(this Socket socket, uint keepAliveTimeSeconds) { // Always use the OS Default Keepalive settings socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); if (keepAliveTimeSeconds == 0) return; // If keepAliveTimeSeconds > 0, override keepalive options on the socket const int keepAliveIntervalMillis = 1000; #if !NETCOREAPP3_0 if (Utility.IsWindows()) { // http://stackoverflow.com/a/11834055/1419658 // Windows takes time in milliseconds var keepAliveTimeMillis = keepAliveTimeSeconds > uint.MaxValue / 1000 ? uint.MaxValue : keepAliveTimeSeconds * 1000; var inOptionValues = new byte[sizeof(uint) * 3]; BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0); BitConverter.GetBytes(keepAliveTimeMillis).CopyTo(inOptionValues, sizeof(uint)); BitConverter.GetBytes(keepAliveIntervalMillis).CopyTo(inOptionValues, sizeof(uint) * 2); socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null); } // Unix not supported: The appropriate socket options to set Keepalive options are not exposd in .NET // https://github.com/dotnet/corefx/issues/14237 // Unix will still respect the OS Default Keepalive settings #else socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, keepAliveIntervalMillis / 1000); socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, (int) keepAliveTimeSeconds); #endif } } }
using System; using System.Net.Sockets; using System.Runtime.InteropServices; namespace MySqlConnector.Utilities { internal static class SocketExtensions { #if !NETSTANDARD2_1 && !NETCOREAPP3_0 public static SocketAwaitable ReceiveAsync(this Socket socket, SocketAwaitable awaitable) { awaitable.Reset(); if (!socket.ReceiveAsync(awaitable.EventArgs)) awaitable.WasCompleted = true; return awaitable; } public static SocketAwaitable SendAsync(this Socket socket, SocketAwaitable awaitable) { awaitable.Reset(); if (!socket.SendAsync(awaitable.EventArgs)) awaitable.WasCompleted = true; return awaitable; } #endif #if !NETSTANDARD2_1 && !NETCOREAPP2_1 && !NETCOREAPP3_0 public static void SetBuffer(this SocketAsyncEventArgs args, Memory<byte> buffer) { MemoryMarshal.TryGetArray<byte>(buffer, out var arraySegment); args.SetBuffer(arraySegment.Array, arraySegment.Offset, arraySegment.Count); } public static int Send(this Socket socket, ReadOnlyMemory<byte> data, SocketFlags flags) { MemoryMarshal.TryGetArray(data, out var arraySegment); return socket.Send(arraySegment.Array, arraySegment.Offset, arraySegment.Count, flags); } #else public static int Send(this Socket socket, ReadOnlyMemory<byte> data, SocketFlags flags) => socket.Send(data.Span, flags); #endif public static void SetKeepAlive(this Socket socket, uint keepAliveTimeSeconds) { // Always use the OS Default Keepalive settings socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); if (keepAliveTimeSeconds == 0) return; // If keepAliveTimeSeconds > 0, override keepalive options on the socket const uint keepAliveIntervalMillis = 1000; if (Utility.IsWindows()) { // http://stackoverflow.com/a/11834055/1419658 // Windows takes time in milliseconds var keepAliveTimeMillis = keepAliveTimeSeconds > uint.MaxValue / 1000 ? uint.MaxValue : keepAliveTimeSeconds * 1000; var inOptionValues = new byte[sizeof(uint) * 3]; BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0); BitConverter.GetBytes(keepAliveTimeMillis).CopyTo(inOptionValues, sizeof(uint)); BitConverter.GetBytes(keepAliveIntervalMillis).CopyTo(inOptionValues, sizeof(uint) * 2); socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null); } // Unix not supported: The appropriate socket options to set Keepalive options are not exposd in .NET // https://github.com/dotnet/corefx/issues/14237 // Unix will still respect the OS Default Keepalive settings } } }
mit
C#
d40117ec93eaaf2ce13cf4ccf0c8290f898a2977
fix up
jefking/King.Azure.Imaging,jefking/King.Azure.Imaging,jefking/King.Azure.Imaging
King.Azure.Imaging/ImagePreProcessor.cs
King.Azure.Imaging/ImagePreProcessor.cs
namespace King.Azure.Imaging { using King.Azure.Data; using King.Azure.Imaging.Entities; using King.Azure.Imaging.Models; using Newtonsoft.Json; using System; using King.Mapper; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage.Queue; public class ImagePreProcessor : IImagePreProcessor { #region Members /// <summary> /// File Name Header /// </summary> public const string FileNameHeader = "X-File-Name"; /// <summary> /// Content Type Header /// </summary> public const string ContentTypeHeader = "X-File-Type"; /// <summary> /// Blob Container /// </summary> private readonly IContainer container = null; /// <summary> /// Table /// </summary> private readonly ITableStorage table = null; /// <summary> /// Storage Queue /// </summary> private readonly IStorageQueue queue = null; #endregion #region Methods public ImagePreProcessor(string connectionString) { this.container = new Container("", connectionString); this.table = new TableStorage("", connectionString); this.queue = new StorageQueue("", connectionString); } #endregion #region Methods public async Task Process(byte[] content, string contentType, string fileName) { var data = new RawData() { Contents = content, Identifier = Guid.NewGuid(), ContentType = contentType, FileName = fileName, }; data.FileSize = data.Contents.Length; var entity = data.Map<ImageEntity>(); entity.PartitionKey = "original"; entity.RowKey = data.Identifier.ToString(); await table.InsertOrReplace(entity); var toQueue = data.Map<ImageQueued>(); await this.queue.Save(new CloudQueueMessage(JsonConvert.SerializeObject(toQueue))); await container.Save(data.Identifier.ToString(), data.Contents, data.ContentType); } #endregion } }
namespace King.Azure.Imaging { using King.Azure.Data; using King.Azure.Imaging.Entities; using King.Azure.Imaging.Models; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class ImagePreProcessor : IImagePreProcessor { #region Members /// <summary> /// File Name Header /// </summary> public const string FileNameHeader = "X-File-Name"; /// <summary> /// Content Type Header /// </summary> public const string ContentTypeHeader = "X-File-Type"; /// <summary> /// Blob Container /// </summary> private readonly IContainer container = null; /// <summary> /// Table /// </summary> private readonly ITableStorage table = null; /// <summary> /// Storage Queue /// </summary> private readonly IStorageQueue queue = null; #endregion #region Methods public ImagePreProcessor(string connectionString) { this.container = new Container("", connectionString); this.table = new TableStorage("", connectionString); this.queue = new StorageQueue("", connectionString); } #endregion #region Methods public async Task Process(byte[] content, string contentType, string fileName) { var data = new RawData() { Contents = content, Identifier = Guid.NewGuid(), ContentType = contentType, FileName = fileName, }; data.FileSize = data.Contents.Length; var entity = data.Map<ImageEntity>(); entity.PartitionKey = "original"; entity.RowKey = data.Identifier.ToString(); await table.InsertOrReplace(entity); var toQueue = data.Map<ImageQueued>(); await this.queue.Save(new CloudQueueMessage(JsonConvert.SerializeObject(toQueue))); await container.Save(data.Identifier.ToString(), data.Contents, data.ContentType); } #endregion } }
mit
C#
960a4a07bb4c6d3899a18200d85f8a08df3dd076
Edit it
sta/websocket-sharp,2Toad/websocket-sharp,2Toad/websocket-sharp,2Toad/websocket-sharp,jogibear9988/websocket-sharp,sta/websocket-sharp,jogibear9988/websocket-sharp,jogibear9988/websocket-sharp,jogibear9988/websocket-sharp,2Toad/websocket-sharp,sta/websocket-sharp,sta/websocket-sharp
websocket-sharp/Net/HttpBasicIdentity.cs
websocket-sharp/Net/HttpBasicIdentity.cs
#region License /* * HttpBasicIdentity.cs * * This code is derived from HttpListenerBasicIdentity.cs (System.Net) of * Mono (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2014 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Authors /* * Authors: * - Gonzalo Paniagua Javier <gonzalo@novell.com> */ #endregion using System; using System.Security.Principal; namespace WebSocketSharp.Net { /// <summary> /// Holds the username and password from an HTTP Basic authentication attempt. /// </summary> public class HttpBasicIdentity : GenericIdentity { #region Private Fields private string _password; #endregion #region Internal Constructors internal HttpBasicIdentity (string username, string password) : base (username, "Basic") { _password = password; } #endregion #region Public Properties /// <summary> /// Gets the password from an HTTP Basic authentication attempt. /// </summary> /// <value> /// A <see cref="string"/> that represents the password. /// </value> public virtual string Password { get { return _password; } } #endregion } }
#region License /* * HttpBasicIdentity.cs * * This code is derived from System.Net.HttpListenerBasicIdentity.cs of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2014 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Authors /* * Authors: * - Gonzalo Paniagua Javier <gonzalo@novell.com> */ #endregion using System; using System.Security.Principal; namespace WebSocketSharp.Net { /// <summary> /// Holds the username and password from an HTTP Basic authentication attempt. /// </summary> public class HttpBasicIdentity : GenericIdentity { #region Private Fields private string _password; #endregion #region Internal Constructors internal HttpBasicIdentity (string username, string password) : base (username, "Basic") { _password = password; } #endregion #region Public Properties /// <summary> /// Gets the password from an HTTP Basic authentication attempt. /// </summary> /// <value> /// A <see cref="string"/> that represents the password. /// </value> public virtual string Password { get { return _password; } } #endregion } }
mit
C#
c7cd8de6f21be80237740849c52d14511ca97bef
Fix XAML path parsing
Desolath/ConfuserEx3,timnboys/ConfuserEx,Desolath/Confuserex,yeaicc/ConfuserEx,engdata/ConfuserEx
Confuser.Renamer/BAML/BAMLPropertyReference.cs
Confuser.Renamer/BAML/BAMLPropertyReference.cs
using System; using System.Diagnostics; using Confuser.Core; namespace Confuser.Renamer.BAML { internal class BAMLPropertyReference : IBAMLReference { PropertyRecord rec; public BAMLPropertyReference(PropertyRecord rec) { this.rec = rec; } public bool CanRename(string oldName, string newName) { return true; } public void Rename(string oldName, string newName) { var value = rec.Value; if (value.IndexOf(oldName, StringComparison.OrdinalIgnoreCase) != -1) value = newName; else if (oldName.EndsWith(".baml")) { Debug.Assert(newName.EndsWith(".baml")); value = newName.Substring(0, newName.Length - 5) + ".xaml"; } else throw new UnreachableException(); rec.Value = "pack://application:,,,/" + value; } } }
using System; using System.Diagnostics; using Confuser.Core; namespace Confuser.Renamer.BAML { internal class BAMLPropertyReference : IBAMLReference { PropertyRecord rec; public BAMLPropertyReference(PropertyRecord rec) { this.rec = rec; } public bool CanRename(string oldName, string newName) { return true; } public void Rename(string oldName, string newName) { var value = rec.Value; if (value.IndexOf(oldName, StringComparison.OrdinalIgnoreCase) != -1) value = newName; else if (oldName.EndsWith(".baml")) { Debug.Assert(newName.EndsWith(".baml")); value = newName.Substring(0, newName.Length - 5) + ".xaml"; } else throw new UnreachableException(); rec.Value = value; } } }
mit
C#
7160a48bab4fc69166e30c19954d0585528097f2
Adjust hold to confirm animation curve to better show intention
peppy/osu,ppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,peppy/osu
osu.Game/Graphics/Containers/HoldToConfirmContainer.cs
osu.Game/Graphics/Containers/HoldToConfirmContainer.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Configuration; namespace osu.Game.Graphics.Containers { public abstract class HoldToConfirmContainer : Container { public Action Action; private const int fadeout_delay = 200; /// <summary> /// Whether currently in a fired state (and the confirm <see cref="Action"/> has been sent). /// </summary> public bool Fired { get; private set; } private bool confirming; /// <summary> /// Whether the overlay should be allowed to return from a fired state. /// </summary> protected virtual bool AllowMultipleFires => false; /// <summary> /// Specify a custom activation delay, overriding the game-wide user setting. /// </summary> /// <remarks> /// This should be used in special cases where we want to be extra sure the user knows what they are doing. An example is when changes would be lost. /// </remarks> protected virtual double? HoldActivationDelay => null; public Bindable<double> Progress = new BindableDouble(); private Bindable<double> holdActivationDelay; [BackgroundDependencyLoader] private void load(OsuConfigManager config) { holdActivationDelay = HoldActivationDelay != null ? new Bindable<double>(HoldActivationDelay.Value) : config.GetBindable<double>(OsuSetting.UIHoldActivationDelay); } protected void BeginConfirm() { if (confirming || (!AllowMultipleFires && Fired)) return; confirming = true; this.TransformBindableTo(Progress, 1, holdActivationDelay.Value * (1 - Progress.Value), Easing.Out).OnComplete(_ => Confirm()); } protected virtual void Confirm() { Action?.Invoke(); Fired = true; } protected void AbortConfirm() { if (!AllowMultipleFires && Fired) return; confirming = false; Fired = false; this .TransformBindableTo(Progress, Progress.Value) .Delay(200) .TransformBindableTo(Progress, 0, fadeout_delay, Easing.InSine); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Configuration; namespace osu.Game.Graphics.Containers { public abstract class HoldToConfirmContainer : Container { public Action Action; private const int fadeout_delay = 200; /// <summary> /// Whether currently in a fired state (and the confirm <see cref="Action"/> has been sent). /// </summary> public bool Fired { get; private set; } private bool confirming; /// <summary> /// Whether the overlay should be allowed to return from a fired state. /// </summary> protected virtual bool AllowMultipleFires => false; /// <summary> /// Specify a custom activation delay, overriding the game-wide user setting. /// </summary> /// <remarks> /// This should be used in special cases where we want to be extra sure the user knows what they are doing. An example is when changes would be lost. /// </remarks> protected virtual double? HoldActivationDelay => null; public Bindable<double> Progress = new BindableDouble(); private Bindable<double> holdActivationDelay; [BackgroundDependencyLoader] private void load(OsuConfigManager config) { holdActivationDelay = HoldActivationDelay != null ? new Bindable<double>(HoldActivationDelay.Value) : config.GetBindable<double>(OsuSetting.UIHoldActivationDelay); } protected void BeginConfirm() { if (confirming || (!AllowMultipleFires && Fired)) return; confirming = true; this.TransformBindableTo(Progress, 1, holdActivationDelay.Value * (1 - Progress.Value), Easing.Out).OnComplete(_ => Confirm()); } protected virtual void Confirm() { Action?.Invoke(); Fired = true; } protected void AbortConfirm() { if (!AllowMultipleFires && Fired) return; confirming = false; Fired = false; this.TransformBindableTo(Progress, 0, fadeout_delay, Easing.Out); } } }
mit
C#