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
31d9fb7793922827758b0520fc6f662708e0bd61
add ProductImageService
vinhch/BizwebSharp
src/BizwebSharp/Services/ProductImage/ProductImageService.cs
src/BizwebSharp/Services/ProductImage/ProductImageService.cs
using System.Collections.Generic; using System.Threading.Tasks; using BizwebSharp.Entities; using BizwebSharp.Infrastructure; using BizwebSharp.Options; namespace BizwebSharp.Services { public class ProductImageService : BaseService { public ProductImageService(BizwebAuthorizationState authState) : base(authState) { } public virtual async Task<int> CountAsync(long productId, PublishableListOption option = null) { return await MakeRequest<int>($"products/{productId}/images/count.json", HttpMethod.GET, "count", option); } public virtual async Task<IEnumerable<ProductImage>> ListAsync(long productId, PublishableListOption option = null) { return await MakeRequest<List<ProductImage>>($"products/{productId}/images.json", HttpMethod.GET, "images", option); } public virtual async Task<ProductImage> GetAsync(long productId, long imageId, string fields = null) { dynamic options = null; if (!string.IsNullOrEmpty(fields)) { options = new { fields }; } return await MakeRequest<ProductImage>($"products/{productId}/images/{imageId}.json", HttpMethod.GET, "image", options); } public virtual async Task<ProductImage> CreateAsync(long productId, ProductImage inputObject) { var root = new Dictionary<string, object> { {"image", inputObject} }; return await MakeRequest<ProductImage>($"products/{productId}/images.json", HttpMethod.POST, "image", root); } public virtual async Task<ProductImage> UpdateAsync(long productId, long productImageId, ProductImage inputObject) { var root = new Dictionary<string, object> { {"image", inputObject} }; return await MakeRequest<ProductImage>($"products/{productId}/images/{productImageId}.json", HttpMethod.PUT, "image", root); } public virtual async Task DeleteAsync(long productId, long imageId) { await MakeRequest($"products/{productId}/images/{imageId}.json", HttpMethod.DELETE); } } }
mit
C#
a4acf26f171e54ed3d37b333d186114bc802cc4c
Create ImageRender.cs
fatmagazaile/Projet
ImageRender.cs
ImageRender.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; using MvcMeublatexApp.Models; namespace MvcMeublatexApp { public class ImageRender { image img = new image(); public void UploadImageToDB(HttpPostedFileBase file,int id) { img.img_id= id; img.img_name = file.FileName; img.img = ConvertToBytes(file); using (MeublatexDataEntities a = new MeublatexDataEntities()) { a.image.AddObject(img); a.SaveChanges(); } } public byte[] ConvertToBytes(HttpPostedFileBase Image) { byte[] imageBytes = null; BinaryReader reader = new BinaryReader(Image.InputStream); imageBytes = reader.ReadBytes((int)Image.ContentLength); return imageBytes; } } }
apache-2.0
C#
8e756cd2603cfef7f91fbaaad5f2014a6bcd4c4e
update the version number to 3.0.0
RachelTucker/ds3_net_sdk,shabtaisharon/ds3_net_sdk,rpmoore/ds3_net_sdk,SpectraLogic/ds3_net_sdk,RachelTucker/ds3_net_sdk,shabtaisharon/ds3_net_sdk,shabtaisharon/ds3_net_sdk,rpmoore/ds3_net_sdk,SpectraLogic/ds3_net_sdk,rpmoore/ds3_net_sdk,RachelTucker/ds3_net_sdk,SpectraLogic/ds3_net_sdk
VersionInfo.cs
VersionInfo.cs
/* * ****************************************************************************** * Copyright 2014 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file 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; // 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("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")]
/* * ****************************************************************************** * Copyright 2014 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file 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; // 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.2.5.0")] [assembly: AssemblyFileVersion("1.2.5.0")]
apache-2.0
C#
206334cae01d8bc0f1aa13205b385c1369b4e255
Add tests for IsGitHubApiException
github/VisualStudio,github/VisualStudio,github/VisualStudio
test/GitHub.Exports.UnitTests/ApiExceptionExtensionsTests.cs
test/GitHub.Exports.UnitTests/ApiExceptionExtensionsTests.cs
using System.Collections.Generic; using System.Collections.Immutable; using Octokit; using NSubstitute; using NUnit.Framework; using GitHub.Extensions; public class ApiExceptionExtensionsTests { public class TheIsGitHubApiExceptionMethod { [TestCase("Not-GitHub-Request-Id", false)] [TestCase("X-GitHub-Request-Id", true)] public void NoGitHubRequestId(string key, bool expect) { var ex = CreateApiException(new Dictionary<string, string> { { key, "ANYTHING" } }); var result = ApiExceptionExtensions.IsGitHubApiException(ex); Assert.That(result, Is.EqualTo(expect)); } static ApiException CreateApiException(Dictionary<string, string> headers) { var response = Substitute.For<IResponse>(); response.Headers.Returns(headers.ToImmutableDictionary()); var ex = new ApiException(response); return ex; } } }
mit
C#
3171fea0e65694f7a82cadb110ba32fbb3be710a
Create AssemblyInfo.cs
SMihand/Cache-GlobalsProxy-Framework
CacheExtremeProxy/Properties/AssemblyInfo.cs
CacheExtremeProxy/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Resources; // Управление общими сведениями о сборке осуществляется с помощью // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, // связанные со сборкой. [assembly: AssemblyTitle("Cache GlobalsProxy Framework")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Cache GlobalsProxy Framework")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Параметр ComVisible со значением FALSE делает типы в сборке невидимыми // для COM-компонентов. Если требуется обратиться к типу в этой сборке через // COM, задайте атрибуту ComVisible значение TRUE для этого типа. [assembly: ComVisible(false)] // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM [assembly: Guid("4810cd9d-82c8-454a-814a-c1be599e1f48")] // Сведения о версии сборки состоят из следующих четырех значений: // // Основной номер версии // Дополнительный номер версии // Номер построения // Редакция // // Можно задать все значения или принять номер построения и номер редакции по умолчанию, // используя "*", как показано ниже: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: NeutralResourcesLanguageAttribute("en")]
mit
C#
fa6d55956dcf959eaa976c77eca8ca5c2b424743
Create task_1.3.5.2.cs
AndrewTurlanov/ANdrew
task_1.3.5.2.cs
task_1.3.5.2.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Lesson1 { class Program { static void Main(string[] args) { string message = "Результат: " + (8 * 2 + 5); Console.WriteLine(message); } } }
apache-2.0
C#
cd1e89924a849ffba04438e219bd4f6d8f44d6c1
Create Delete.cshtml
CarmelSoftware/Generic-Data-Repository-With-Caching
Views/Blogs/Delete.cshtml
Views/Blogs/Delete.cshtml
@model GenericRepositoryWithCatching.Models.Blog @{ ViewBag.Title = "Delete"; } <div class="jumbotron"> <h2>Generic Repository With Memory Caching - @ViewBag.Title</h2> <h4>By Carmel</h4> </div> <div class="jumbotron"> <h3>Are you sure you want to delete this?</h3> <fieldset> <legend>Blog</legend> <div class="display-label"> @Html.DisplayNameFor(model => model.Title) </div> <div class="display-field"> @Html.DisplayFor(model => model.Title) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.Text) </div> <div class="display-field"> @Html.DisplayFor(model => model.Text) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.DatePosted) </div> <div class="display-field"> @String.Format("{0:yyyy-MM-dd}", @Model.DatePosted) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.MainPicture) </div> <div class="display-field"> <img src="~/Content/Images/@Model.MainPicture" /> </div> <div class="display-label"> @Html.DisplayNameFor(model => model.Blogger.Name) </div> <div class="display-field"> @Html.DisplayFor(model => model.Blogger.Name) </div> </fieldset> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <p> <input type="submit" value="Delete" class="btn btn-success" /> | @Html.ActionLink("Back to List", "Index", null, new { @class="btn btn-success" }) </p> } </div>
mit
C#
b930eed23fa81b4219fe19c2c37e40ebc6a6d5a6
Create ServiceCollectionExtensions.cs
tiksn/TIKSN-Framework
TIKSN.Core/DependencyInjection/ServiceCollectionExtensions.cs
TIKSN.Core/DependencyInjection/ServiceCollectionExtensions.cs
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Localization; using ReactiveUI; using System; using TIKSN.FileSystem; using TIKSN.Globalization; using TIKSN.Serialization; using TIKSN.Serialization.Bond; using TIKSN.Serialization.MessagePack; using TIKSN.Shell; using TIKSN.Time; using TIKSN.Web.Rest; namespace TIKSN.DependencyInjection { public static class ServiceCollectionExtensions { public static IServiceCollection AddFrameworkCore(this IServiceCollection services) { services.AddLocalization(); services.AddMemoryCache(); services.AddOptions(); services.TryAddSingleton<IConsoleService, ConsoleService>(); services.TryAddSingleton<ICultureFactory, CultureFactory>(); services.TryAddSingleton<ICurrencyFactory, CurrencyFactory>(); services.TryAddSingleton<IRegionFactory, RegionFactory>(); services.TryAddSingleton<IResourceNamesCache, ResourceNamesCache>(); services.TryAddSingleton<IShellCommandEngine, ShellCommandEngine>(); services.TryAddSingleton<ITimeProvider, TimeProvider>(); services.TryAddSingleton<Random>(); services.TryAddSingleton(MsgPack.Serialization.SerializationContext.Default); services.TryAddSingleton<IKnownFolders, KnownFolders>(); services.TryAddSingleton<CompactBinaryBondDeserializer>(); services.TryAddSingleton<CompactBinaryBondSerializer>(); services.TryAddSingleton<DotNetXmlDeserializer>(); services.TryAddSingleton<DotNetXmlSerializer>(); services.TryAddSingleton<FastBinaryBondDeserializer>(); services.TryAddSingleton<FastBinaryBondSerializer>(); services.TryAddSingleton<IRestRequester, RestRequester>(); services.TryAddSingleton<JsonDeserializer>(); services.TryAddSingleton<JsonSerializer>(); services.TryAddSingleton<MessagePackDeserializer>(); services.TryAddSingleton<MessagePackSerializer>(); services.TryAddSingleton<SimpleBinaryBondDeserializer>(); services.TryAddSingleton<SimpleBinaryBondSerializer>(); services.TryAddSingleton<SimpleJsonBondDeserializer>(); services.TryAddSingleton<SimpleJsonBondSerializer>(); services.TryAddSingleton<SimpleXmlBondDeserializer>(); services.TryAddSingleton<SimpleXmlBondSerializer>(); services.TryAddScoped<IShellCommandContext, ShellCommandContext>(); services.AddSingleton(MessageBus.Current); return services; } } }
mit
C#
74a1abbe9a3ebadc7ba4f7b424f2c81bfb35589f
add sharedmemorybuffer
JohnMasen/ChakraCore.NET,JohnMasen/ChakraCore.NET,JohnMasen/ChakraCore.NET
source/ChakraCore.NET/SharedMemory/SharedMemoryBuffer.cs
source/ChakraCore.NET/SharedMemory/SharedMemoryBuffer.cs
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace ChakraCore.NET.SharedMemory { public class SharedMemoryBuffer : SafeBuffer { public IntPtr DataAddress => handle; public SharedMemoryBuffer(int size):base(true) { var h=Marshal.AllocHGlobal(size); SetHandle(h); Initialize((ulong)size); } public SharedMemoryBuffer(IntPtr data,int size) : base(false) { SetHandle(data); Initialize((ulong)size); } protected override bool ReleaseHandle() { Marshal.FreeHGlobal(handle); return true; } } }
mit
C#
2b35197612742801ce127c37b642fc21d7e3d657
Create OpenDoorSteps.cs
AdrianSchneble/nap
usecases/OpenDoorSteps.cs
usecases/OpenDoorSteps.cs
using System; using TechTalk.SpecFlow; namespace NAP { [Binding] public class OpenDoorSteps { [Given(@"I am standing on a GroundTile adjacent to the door")] public void GivenIAmStandingOnAGroundTileAdjacentToTheDoor() { ScenarioContext.Current.Pending(); } [Given(@"the door is closed")] public void GivenTheDoorIsClosed() { ScenarioContext.Current.Pending(); } [Given(@"the door is unlocked")] public void GivenTheDoorIsUnlocked() { ScenarioContext.Current.Pending(); } [Given(@"the door is locked")] public void GivenTheDoorIsLocked() { ScenarioContext.Current.Pending(); } [Given(@"I have a key")] public void GivenIHaveAKey() { ScenarioContext.Current.Pending(); } [Given(@"I do not have a key")] public void GivenIDoNotHaveAKey() { ScenarioContext.Current.Pending(); } [Given(@"the door is open")] public void GivenTheDoorIsOpen() { ScenarioContext.Current.Pending(); } [Given(@"no Entity is in the door")] public void GivenNoEntityIsInTheDoor() { ScenarioContext.Current.Pending(); } [When(@"I press E")] public void WhenIPressE() { ScenarioContext.Current.Pending(); } [Then(@"the door should open")] public void ThenTheDoorShouldOpen() { ScenarioContext.Current.Pending(); } [Then(@"the key should be removed from my Inventory")] public void ThenTheKeyShouldBeRemovedFromMyInventory() { ScenarioContext.Current.Pending(); } [Then(@"the door should not open")] public void ThenTheDoorShouldNotOpen() { ScenarioContext.Current.Pending(); } [Then(@"the door should close")] public void ThenTheDoorShouldClose() { ScenarioContext.Current.Pending(); } } }
mit
C#
0e6d96ff2487d4fa4e51934f626bde161e407609
Add BassRelativeFrequencyHandler helper class with zero frequency special handling
peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework
osu.Framework/Audio/BassRelativeFrequencyHandler.cs
osu.Framework/Audio/BassRelativeFrequencyHandler.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 ManagedBass; namespace osu.Framework.Audio { /// <summary> /// A helper class for translating relative frequency values to absolute hertz values based on the initial channel frequency. /// Also handles zero frequency value by requesting the component to pause the channel and maintain that until it's set back from zero. /// </summary> internal class BassRelativeFrequencyHandler { private int channel; private float initialFrequency; public Action RequestZeroFrequencyPause; public Action RequestZeroFrequencyResume; public bool ZeroFrequencyPauseRequested { get; private set; } public void SetChannel(int c) { channel = c; ZeroFrequencyPauseRequested = false; Bass.ChannelGetAttribute(channel, ChannelAttribute.Frequency, out initialFrequency); } public void UpdateChannelFrequency(double relativeFrequency) { // http://bass.radio42.com/help/html/ff7623f0-6e9f-6be8-c8a7-17d3a6dc6d51.htm (BASS_ATTRIB_FREQ's description) const int min_bass_freq = 100; const int max_bass_freq = 100000; int channelFrequency = (int)Math.Clamp(Math.Abs(initialFrequency * relativeFrequency), min_bass_freq, max_bass_freq); Bass.ChannelSetAttribute(channel, ChannelAttribute.Frequency, channelFrequency); // Maintain internal pause on zero frequency due to BASS not supporting them (0 is took for original rate in BASS API) // Above documentation shows the frequency limits which the constants (min_bass_freq, max_bass_freq) came from. if (!ZeroFrequencyPauseRequested && relativeFrequency == 0) { RequestZeroFrequencyPause?.Invoke(); ZeroFrequencyPauseRequested = true; } else if (ZeroFrequencyPauseRequested && relativeFrequency > 0) { ZeroFrequencyPauseRequested = false; RequestZeroFrequencyResume?.Invoke(); } } } }
mit
C#
ef63ff32f43e7e5f6d49cefe83b137e0ffddb3cc
move http verbs enum into a single file
coolya/logv.http
Server/HttpVerb.cs
Server/HttpVerb.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleHttpServer { public enum HttpVerb { Get, Post, Put, Delete, Head, Patch } }
apache-2.0
C#
c5c74c07fe7be1ac56971abce484f30cdac1516b
Implement EndPointCommand Annotation
MagedAlNaamani/DynThings,MagedAlNaamani/DynThings,MagedAlNaamani/DynThings,cmoussalli/DynThings,cmoussalli/DynThings,cmoussalli/DynThings,MagedAlNaamani/DynThings,cmoussalli/DynThings
DynThings.Data.Models/ModelsExtensions/EndPointCommand.cs
DynThings.Data.Models/ModelsExtensions/EndPointCommand.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DynThings.Data.Models { public partial class EndPointCommand { private DynThingsEntities db = new DynThingsEntities(); } }
mit
C#
884def16a0deb30bea4fb849140ea3a8dccecf05
add missing file
IvanZheng/IFramework,IvanZheng/IFramework,IvanZheng/IFramework
Src/iFramework.Plugins/ServiceBusTest/Properties/AssemblyInfo.cs
Src/iFramework.Plugins/ServiceBusTest/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("ServiceBusTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ServiceBusTest")] [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("a17ca38b-2790-4dc5-8af9-c7f63bfbbb1f")] // 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#
4d0736fc2da6328430b2e403a9af1dc78f361bec
Add unit test for compute max stack override.
Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver
test/AsmResolver.DotNet.Tests/Builder/CilMethodBodySerializerTest.cs
test/AsmResolver.DotNet.Tests/Builder/CilMethodBodySerializerTest.cs
using AsmResolver.DotNet.Builder; using AsmResolver.DotNet.Code.Cil; using AsmResolver.DotNet.Signatures; using AsmResolver.PE.DotNet.Cil; using AsmResolver.PE.DotNet.Metadata.Tables.Rows; using Xunit; namespace AsmResolver.DotNet.Tests.Builder { public class CilMethodBodySerializerTest { [Theory] [InlineData(false, true, 0)] [InlineData(false, false, 100)] [InlineData(false, null, 100)] [InlineData(true, true, 0)] [InlineData(true, false, 100)] [InlineData(true, null, 0)] public void ComputeMaxStackOnBuildOverride(bool computeMaxStack, bool? computeMaxStackOverride, int expectedMaxStack) { const int maxStack = 100; var module = new ModuleDefinition("SomeModule", KnownCorLibs.SystemPrivateCoreLib_v4_0_0_0); var main = new MethodDefinition( "Main", MethodAttributes.Public | MethodAttributes.Static, MethodSignature.CreateStatic(module.CorLibTypeFactory.Void)); main.CilMethodBody = new CilMethodBody(main) { ComputeMaxStackOnBuild = computeMaxStack, MaxStack = maxStack, Instructions = {new CilInstruction(CilOpCodes.Ret)}, LocalVariables = {new CilLocalVariable(module.CorLibTypeFactory.Int32)} // Force fat method body. }; module.GetOrCreateModuleType().Methods.Add(main); module.ManagedEntrypoint = main; var builder = new ManagedPEImageBuilder(new DotNetDirectoryFactory { MethodBodySerializer = new CilMethodBodySerializer { ComputeMaxStackOnBuildOverride = computeMaxStackOverride } }); var newImage = builder.CreateImage(module); var newModule = ModuleDefinition.FromImage(newImage); Assert.Equal(expectedMaxStack, newModule.ManagedEntrypointMethod.CilMethodBody.MaxStack); } } }
mit
C#
75e59b98756dce7ad363941da9f7f832d05db91f
Prepare an initial model.
lehmamic/EnterpriseApplicationConfigurationManager,lehmamic/EnterpriseApplicationConfigurationManager,lehmamic/EnterpriseApplicationConfigurationManager,lehmamic/EnterpriseApplicationConfigurationManager
src/Zuehlke.Eacm.Web.Backend/DomainModel/Project.cs
src/Zuehlke.Eacm.Web.Backend/DomainModel/Project.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Zuehlke.Eacm.Web.Backend.DomainModel { public class Project { public ModelDefinition Definition { get; } = new ModelDefinition(); } public class ModelDefinition { private readonly List<EntityDefinition> entities = new List<EntityDefinition>(); } public class EntityDefinition { private readonly List<PropertyDefinition> entities = new List<PropertyDefinition>(); private string name; } public class PropertyDefinition { public Guid Id { get; set; } public string Name { get; set; } public string PropertyType { get; set; } public EntityDefinition Reference { get; set; } } public class ConfigurationEntity { } public class ConfigurationEntry { } public class ConfigurationValue { public Guid Id { get; set; } public PropertyDefinition Property { get; set; } public string Value { get; set; } } }
mit
C#
29e8f7030ee6b4b3d28739425f0e4e1d5ac966fe
Add test cases for CsvProfile in SaveSuiteAction.
Seddryck/NBi,Seddryck/NBi
NBi.Testing.GenbiL/Action/Suite/SaveSuiteActionTest.cs
NBi.Testing.GenbiL/Action/Suite/SaveSuiteActionTest.cs
using NBi.GenbiL.Action.Suite; using NBi.GenbiL.Stateful; using NBi.Xml; using NUnit.Framework; using System; using System.IO; namespace NBi.Testing.GenbiL.Action.Suite { [TestFixture] public class SaveSuiteActionTest { protected TestSuiteXml DeserializeFile(string filename) { // Declare an object variable of the type to be deserialized. var manager = new XmlManager(); // A Stream is needed to read the XML document. using (Stream stream = new FileStream(filename, FileMode.Open)) using (StreamReader reader = new StreamReader(stream)) { manager.Read(reader); } manager.ApplyDefaultSettings(); return manager.TestSuite; } [Test] [TestCase("(empty)", "(null)", ';', "\r\n", '"', false)] // All defaults [TestCase("(empty)", "(null)", ';', "\r\n", '"', true)] // All defaults except FirstRowHeader [TestCase("#", "(null)", ';', "\r\n", '"', true)] // All defaults except EmptyCell and FirstRowHeader [TestCase("(empty)", "#", ';', "\r\n", '"', true)] // All defaults except MissingCell and FirstRowHeader [TestCase("(empty)", "(null)", '#', "\r\n", '"', true)] // All defaults except FieldSeparator and FirstRowHeader [TestCase("(empty)", "(null)", ';', "#", '"', true)] // All defaults except RecordSeparator and FirstRowHeader [TestCase("(empty)", "(null)", ';', "\r\n", '#', true)] // All defaults except TextQualifier and FirstRowHeader [TestCase("#", "(null)", ';', "\r\n", '"', false)] // All defaults except EmptyCell [TestCase("#", "(null)", '|', "\r\n", '"', false)] // All defaults except EmptyCell and FieldSeparator [TestCase("(empty)", "#", ';', "\r\n", '"', false)] // All defaults except MissingCell [TestCase("(empty)", "#", '|', "\r\n", '"', false)] // All defaults except MissingCell and FieldSeparator public void Execute_CsvProfile_PropertiesSerialized(string emptyCell, string missingCell, char fieldSeparator, string recordSeparator, char textQualifier, bool firstRowHeader) { string filepath = Path.Combine(Path.GetTempPath(), $"Execute_CsvProfile_Saved_{ Guid.NewGuid() }.nbits"); if (File.Exists(filepath)) { File.Delete(filepath); } var state = new GenerationState(); state.Settings.CsvProfile.EmptyCell = emptyCell; state.Settings.CsvProfile.MissingCell = missingCell; state.Settings.CsvProfile.FieldSeparator = fieldSeparator; state.Settings.CsvProfile.RecordSeparator = recordSeparator; state.Settings.CsvProfile.TextQualifier = textQualifier; state.Settings.CsvProfile.FirstRowHeader = firstRowHeader; var saveAction = new SaveSuiteAction(filepath); saveAction.Execute(state); var fileContent = DeserializeFile(filepath); Assert.That(fileContent.Settings.CsvProfile.EmptyCell, Is.EqualTo(emptyCell)); Assert.That(fileContent.Settings.CsvProfile.MissingCell, Is.EqualTo(missingCell)); Assert.That(fileContent.Settings.CsvProfile.FieldSeparator, Is.EqualTo(fieldSeparator)); Assert.That(fileContent.Settings.CsvProfile.RecordSeparator, Is.EqualTo(recordSeparator)); Assert.That(fileContent.Settings.CsvProfile.TextQualifier, Is.EqualTo(textQualifier)); Assert.That(fileContent.Settings.CsvProfile.FirstRowHeader, Is.EqualTo(firstRowHeader)); if (File.Exists(filepath)) { File.Delete(filepath); } } } }
apache-2.0
C#
bd40784eaca0f17c68f86022c3449abe2f600a1d
create static BitHelper class for providing general operations with bit sequences
mstya/DES-Algorithm
DES/BitHelper.cs
DES/BitHelper.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace DES { static class BitHelper { public static void PrintBitArray(BitArray array) { foreach (bool item in array) { Console.Write(item ? "1" : "0"); } Console.WriteLine(); } public static void PrintBitArray(List<bool> bits) { foreach (var item in bits) { Console.Write(item ? "1" : "0"); } Console.WriteLine(); } public static BitArray ShiftLeft(BitArray aSource, int shiftOn) { bool[] new_arr = new bool[aSource.Count]; for (int i = 0; i < aSource.Count - shiftOn; i++) { new_arr[i] = aSource[i + shiftOn]; } return new BitArray(new_arr); } public static List<bool> ShiftLeft(List<bool> aSource, int shiftOn) { bool[] new_arr = new bool[aSource.Count]; for (int i = 0; i < aSource.Count - shiftOn; i++) { new_arr[i] = aSource[i + shiftOn]; } return new_arr.ToList(); } } }
mit
C#
b28ad085574c4ea046fb6c9ab457823e8ad29932
Create Customer.cs
thuru/CustomIHttpActionResult
Customer.cs
Customer.cs
public class Customer { public int CustomerId { get; set; } public string Name { get; set; } }
mit
C#
28ab1149ea8cecd5f292e80dd57ba90b315fd41b
Add a convenience method to store CommonData.
ZhangLeiCharles/mobile,masterrr/mobile,eatskolnikov/mobile,eatskolnikov/mobile,masterrr/mobile,peeedge/mobile,eatskolnikov/mobile,peeedge/mobile,ZhangLeiCharles/mobile
Phoebe/Data/DataExtensions.cs
Phoebe/Data/DataExtensions.cs
using System; using System.Collections.Generic; using System.Threading.Tasks; using Toggl.Phoebe.Data.DataObjects; namespace Toggl.Phoebe.Data { public static class DataExtensions { /// <summary> /// Checks if the two objects share the same type and primary key. /// </summary> /// <param name="data">Data object.</param> /// <param name="other">Other data object.</param> public static bool Matches (this CommonData data, object other) { if (data == other) return true; if (data == null || other == null) return false; if (data.GetType () != other.GetType ()) return false; return data.Id == ((CommonData)other).Id; } public static bool UpdateData<T> (this IList<T> list, T data) where T : CommonData { var updateCount = 0; for (var idx = 0; idx < list.Count; idx++) { if (data.Matches (list [idx])) { list [idx] = data; updateCount++; } } return updateCount > 0; } public static async Task<CommonData> PutDataAsync (this IDataStore ds, CommonData data) { var type = data.GetType (); if (type == typeof(ClientData)) { return await ds.PutAsync ((ClientData)data).ConfigureAwait (false); } else if (type == typeof(ProjectData)) { return await ds.PutAsync ((ProjectData)data).ConfigureAwait (false); } else if (type == typeof(ProjectUserData)) { return await ds.PutAsync ((ProjectUserData)data).ConfigureAwait (false); } else if (type == typeof(TagData)) { return await ds.PutAsync ((TagData)data).ConfigureAwait (false); } else if (type == typeof(TaskData)) { return await ds.PutAsync ((TaskData)data).ConfigureAwait (false); } else if (type == typeof(TimeEntryData)) { return await ds.PutAsync ((TimeEntryData)data).ConfigureAwait (false); } else if (type == typeof(UserData)) { return await ds.PutAsync ((UserData)data).ConfigureAwait (false); } else if (type == typeof(WorkspaceData)) { return await ds.PutAsync ((WorkspaceData)data).ConfigureAwait (false); } else if (type == typeof(WorkspaceUserData)) { return await ds.PutAsync ((WorkspaceUserData)data).ConfigureAwait (false); } throw new InvalidOperationException (String.Format ("Unknown type of {0}", type)); } } }
using System; using System.Collections.Generic; using Toggl.Phoebe.Data.DataObjects; namespace Toggl.Phoebe.Data { public static class DataExtensions { /// <summary> /// Checks if the two objects share the same type and primary key. /// </summary> /// <param name="data">Data object.</param> /// <param name="other">Other data object.</param> public static bool Matches (this CommonData data, object other) { if (data == other) return true; if (data == null || other == null) return false; if (data.GetType () != other.GetType ()) return false; return data.Id == ((CommonData)other).Id; } public static bool UpdateData<T> (this IList<T> list, T data) where T : CommonData { var updateCount = 0; for (var idx = 0; idx < list.Count; idx++) { if (data.Matches (list [idx])) { list [idx] = data; updateCount++; } } return updateCount > 0; } } }
bsd-3-clause
C#
2f3794165708bfcfc706e60287fc5035e24acf32
Add EditorCommandAttribute class
PowerShell/PowerShellEditorServices
src/PowerShellEditorServices/Extensions/EditorCommandAttribute.cs
src/PowerShellEditorServices/Extensions/EditorCommandAttribute.cs
using System; namespace Microsoft.PowerShell.EditorServices.Extensions { /// <summary> /// Provides an attribute that can be used to target PowerShell /// commands for import as editor commands. /// </summary> [AttributeUsage(AttributeTargets.Class)] public class EditorCommandAttribute : Attribute { #region Properties /// <summary> /// Gets or sets the name which uniquely identifies the command. /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets the display name for the command. /// </summary> public string DisplayName { get; set; } /// <summary> /// Gets or sets a value indicating whether this command's output /// should be suppressed. /// </summary> public bool SuppressOutput { get; set; } #endregion } }
mit
C#
e62c63f17b9edadce360bf104d50d5823854c0e8
Add Excercise2.cs
tlaothong/lab-swp-ws-kiatnakin,tlaothong/lab-swp-ws-kiatnakin,tlaothong/lab-swp-ws-kiatnakin
Excercise2.cs
Excercise2.cs
public static string NumberToWords(int number) { if (number == 0) return "zero"; if (number < 0) return "minus " + NumberToWords(Math.Abs(number)); string words = ""; if ((number / 1000000) > 0) { words += NumberToWords(number / 1000000) + " million "; number %= 1000000; } if ((number / 1000) > 0) { words += NumberToWords(number / 1000) + " thousand "; number %= 1000; } if ((number / 100) > 0) { words += NumberToWords(number / 100) + " hundred "; number %= 100; } if (number > 0) { if (words != "") words += "and "; var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; if (number < 20) words += unitsMap[number]; else { words += tensMap[number / 10]; if ((number % 10) > 0) words += "-" + unitsMap[number % 10]; } } return words; }
mit
C#
3349cddf8a46da0e3ad30a0c0dcdc310ec5fc66e
Add publication interface
Vtek/Bartender
src/Bartender/IPublish.cs
src/Bartender/IPublish.cs
namespace Bartender { /// <summary> /// Define a publication /// </summary> public interface IPublish { } }
mit
C#
e6f183e39edcfe699de25370a91ca2c42bfbe508
Add RenderTreeBuilder extension methods for "prevent default" and "stop bubbling"
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Components/Web/src/Web/RenderTreeBuilderExtensions.cs
src/Components/Web/src/Web/RenderTreeBuilderExtensions.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.Components.RenderTree; namespace Microsoft.AspNetCore.Components.Web { /// <summary> /// Provides methods for building a collection of <see cref="RenderTreeFrame"/> entries. /// </summary> public static class RenderTreeBuilderExtensions { // The "prevent default" and "stop bubbling" flags behave like attributes, in that: // - you can have multiple of them on a given element (for separate events) // - you can add and remove them dynamically // - they are independent of other attributes (e.g., you can "stop bubbling" of a given // event type on an element that doesn't itself have a handler for that event) // As such, they are represented as attributes to give the right diffing behavior. // // As a private implementation detail, their internal representation is magic-named // attributes. This may change in the future. If we add support for multiple-same // -named-attributes-per-element (#14365), then we will probably also declare a new // AttributeType concept, and have specific attribute types for these flags, and // the "name" can simply be the name of the event being modified. /// <summary> /// Appends a frame representing an instruction to prevent the default action /// for a specified event. /// </summary> /// <param name="builder">The <see cref="RenderTreeBuilder"/>.</param> /// <param name="sequence">An integer that represents the position of the instruction in the source code.</param> /// <param name="eventName">The name of the event to be affected.</param> /// <param name="value">True if the default action is to be prevented, otherwise false.</param> public static void AddEventPreventDefaultAttribute(this RenderTreeBuilder builder, int sequence, string eventName, bool value) { builder.AddAttribute(sequence, $"__internal_preventDefault_{eventName}", value); } /// <summary> /// Appends a frame representing an instruction to stop the specified event from /// bubbling up beyond the current element. /// </summary> /// <param name="builder">The <see cref="RenderTreeBuilder"/>.</param> /// <param name="sequence">An integer that represents the position of the instruction in the source code.</param> /// <param name="eventName">The name of the event to be affected.</param> /// <param name="value">True if bubbling should stop bubbling here, otherwise false.</param> public static void AddEventStopBubblingAttribute(this RenderTreeBuilder builder, int sequence, string eventName, bool value) { builder.AddAttribute(sequence, $"__internal_stopBubbling_{eventName}", value); } } }
apache-2.0
C#
e207f3bd2c6c8a6cc017ba969e8364641b0f4ee4
Add an AnnounceTask - Used to advertise to the DHT that you are downloading a specific torrent.
dipeshc/BTDeploy
src/MonoTorrent.Dht/MonoTorrent.Dht/Tasks/AnnounceTask.cs
src/MonoTorrent.Dht/MonoTorrent.Dht/Tasks/AnnounceTask.cs
using System; using System.Collections.Generic; using System.Text; using MonoTorrent.Dht.Messages; namespace MonoTorrent.Dht.Tasks { class AnnounceTask : Task { private int activeAnnounces; private NodeId infoHash; private DhtEngine engine; private int port; public AnnounceTask(DhtEngine engine, NodeId infoHash, int port) { this.engine = engine; this.infoHash = infoHash; this.port = port; } public override void Execute() { GetPeersTask task = new GetPeersTask(engine, infoHash); task.Completed += GotPeers; task.Execute(); } private void GotPeers(object o, TaskCompleteEventArgs e) { e.Task.Completed -= GotPeers; GetPeersTask getpeers = (GetPeersTask)e.Task; foreach (Node n in getpeers.ClosestActiveNodes.Values) { AnnouncePeer query = new AnnouncePeer(engine.LocalId, infoHash, port, n.Token); SendQueryTask task = new SendQueryTask(engine, query, n); task.Completed += SentAnnounce; task.Execute(); activeAnnounces++; } if (activeAnnounces == 0) RaiseComplete(new TaskCompleteEventArgs(this)); } private void SentAnnounce(object o, TaskCompleteEventArgs e) { e.Task.Completed -= SentAnnounce; activeAnnounces--; if (activeAnnounces == 0) RaiseComplete(new TaskCompleteEventArgs(this)); } } }
mit
C#
47cf4bcf2595c672c0f70a85da4c55a36beea182
Add `CheckBackground` tests
ppy/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,peppy/osu-new,UselessToucan/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu
osu.Game.Tests/Editing/Checks/CheckBackgroundTest.cs
osu.Game.Tests/Editing/Checks/CheckBackgroundTest.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Edit.Checks; using osu.Game.Rulesets.Objects; namespace osu.Game.Tests.Editing.Checks { [TestFixture] public class CheckBackgroundTest { private CheckBackground check; private IBeatmap beatmap; [SetUp] public void Setup() { check = new CheckBackground(); beatmap = new Beatmap<HitObject> { BeatmapInfo = new BeatmapInfo { Metadata = new BeatmapMetadata { BackgroundFile = "abc123.jpg" }, BeatmapSet = new BeatmapSetInfo { Files = new List<BeatmapSetFileInfo>(new [] { new BeatmapSetFileInfo { Filename = "abc123.jpg" } }) } } }; } [Test] public void TestBackgroundSetAndInFiles() { var issues = check.Run(beatmap); Assert.That(!issues.Any()); } [Test] public void TestBackgroundSetAndNotInFiles() { beatmap.BeatmapInfo.BeatmapSet.Files.Clear(); var issues = check.Run(beatmap).ToList(); var issue = issues.FirstOrDefault(); Assert.That(issues.Count == 1); Assert.That(issue != null); Assert.That(issue.Template.Equals(check.PossibleTemplates.ElementAt(1))); } [Test] public void TestBackgroundNotSet() { beatmap.Metadata.BackgroundFile = null; var issues = check.Run(beatmap).ToList(); var issue = issues.FirstOrDefault(); Assert.That(issues.Count == 1); Assert.That(issue != null); Assert.That(issue.Template.Equals(check.PossibleTemplates.ElementAt(0))); } } }
mit
C#
ff5b1066b0da1c640bb93c8f8fb67992988e601d
add missing file
SabotageAndi/ELMAR
net.the-engineers.elmar/elmar.droid/MediaButtonService.cs
net.the-engineers.elmar/elmar.droid/MediaButtonService.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Media.Session; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using MediaController = Android.Media.Session.MediaController; namespace elmar.droid { [Service] class MediaButtonService : Service { private MediaSession _mediaSession; private VoiceRecognizer _voiceRecognizer; class MediaButtonPressedCallback : MediaSession.Callback { private readonly Func<bool> _action; public MediaButtonPressedCallback(Func<bool> action) { _action = action; } public override bool OnMediaButtonEvent(Intent mediaButtonIntent) { return _action(); } } public override void OnCreate() { _mediaSession = new MediaSession(this, "Elmar"); _mediaSession.SetFlags(MediaSessionFlags.HandlesMediaButtons | MediaSessionFlags.HandlesTransportControls); _mediaSession.SetCallback(new MediaButtonPressedCallback(OnMediaButtonPressed)); _mediaSession.Active = true; _voiceRecognizer = new VoiceRecognizer(this); } private bool OnMediaButtonPressed() { //Toast.MakeText(this, "Key pressed", ToastLength.Short).Show(); _voiceRecognizer.StartVoiceRecognition(); return true; } public MediaController MediaController { get; set; } public override IBinder OnBind(Intent intent) { return null; } } }
agpl-3.0
C#
1c8212d510e6bb218570a2ad2fa1afb5a3abc383
Add a TestCase for looong combos
ppy/osu,2yangk23/osu,naoey/osu,smoogipooo/osu,peppy/osu,naoey/osu,naoey/osu,UselessToucan/osu,ZLima12/osu,ppy/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,ZLima12/osu,peppy/osu,NeoAdonis/osu,2yangk23/osu,smoogipoo/osu,johnneijzen/osu,DrabWeb/osu,UselessToucan/osu,DrabWeb/osu,EVAST9919/osu,NeoAdonis/osu,ppy/osu,DrabWeb/osu,EVAST9919/osu,johnneijzen/osu,UselessToucan/osu,peppy/osu-new,NeoAdonis/osu
osu.Game.Rulesets.Osu.Tests/TestCaseHitCircleLongCombo.cs
osu.Game.Rulesets.Osu.Tests/TestCaseHitCircleLongCombo.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Osu.Objects; using osuTK; namespace osu.Game.Rulesets.Osu.Tests { [TestFixture] public class TestCaseHitCircleLongCombo : Game.Tests.Visual.TestCasePlayer { public TestCaseHitCircleLongCombo() : base(new OsuRuleset()) { } protected override IBeatmap CreateBeatmap(Ruleset ruleset) { var beatmap = new Beatmap { BeatmapInfo = new BeatmapInfo { BaseDifficulty = new BeatmapDifficulty { CircleSize = 6 }, Ruleset = ruleset.RulesetInfo } }; for (int i = 0; i < 512; i++) beatmap.HitObjects.Add(new HitCircle { Position = new Vector2(256, 192), StartTime = i * 100 }); return beatmap; } } }
mit
C#
f4db2c1ff421588f3896f8e26bcb43da082179a7
Add test
peppy/osu,peppy/osu,ppy/osu,ppy/osu,ppy/osu,peppy/osu
osu.Game.Rulesets.Taiko.Tests/TestSceneControlPointConversion.cs
osu.Game.Rulesets.Taiko.Tests/TestSceneControlPointConversion.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Rulesets.Objects; using osu.Game.Tests.Visual; namespace osu.Game.Rulesets.Taiko.Tests { public class TestSceneControlPointConversion : OsuTestScene { [Test] public void TestSceneScrollSpeedConversion() { const double start_time = 1000; const double slider_velocity = 10; var beatmap = new Beatmap<HitObject> { HitObjects = { new HitObject { StartTime = start_time, DifficultyControlPoint = new DifficultyControlPoint { SliderVelocity = slider_velocity } } }, BeatmapInfo = { Ruleset = { OnlineID = 0 } }, }; var convertedBeatmap = new TaikoRuleset().CreateBeatmapConverter(beatmap).Convert(); AddAssert("effect point generated", () => convertedBeatmap.ControlPointInfo.EffectPointAt(start_time).ScrollSpeed == slider_velocity); } } }
mit
C#
a60387ef3aaa73993def0bd8ffb047fb664de2f0
Add initial code file from xamarin-bluetooth-status-widget project
wislon/xamarin-bluetooth-toggle-widget
src/BluetoothWidget/BTWidget.cs
src/BluetoothWidget/BTWidget.cs
/* The MIT License (MIT) Copyright (c) 2014 John Wilson 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. */ using Android.App; using Android.Appwidget; using Android.Content; using Android.Bluetooth; using Android.Util; using Android.Widget; namespace BluetoothWidget { // see https://developer.android.com/guide/topics/appwidgets/index.html // and http://stackoverflow.com/questions/4073907/update-android-widget-from-activity?rq=1 [BroadcastReceiver(Label = "Bluetooth Widget")] [IntentFilter(new string[] { "android.appwidget.action.APPWIDGET_UPDATE", BluetoothAdapter.ActionStateChanged })] [MetaData("android.appwidget.provider", Resource = "@xml/bt_widget")] public class BTWidget : AppWidgetProvider { private const string APP_NAME = "BTWidget"; /// <summary> /// This event fires for every intent you're filtering for. There can be lots of them, /// and they can arrive very quickly, so spend as little time as possible processing them /// on the UI thread. /// </summary> /// <param name="context">The Context in which the receiver is running.</param> /// <param name="intent">The Intent being received.</param> public override void OnReceive(Context context, Intent intent) { Log.Info(APP_NAME, "OnReceive received intent: {0}", intent.Action); if(intent.Action == "android.appwidget.action.APPWIDGET_UPDATE") { Log.Info(APP_NAME, "Received AppWidget Update"); var currentState = Android.Bluetooth.BluetoothAdapter.DefaultAdapter.State; Log.Info(APP_NAME, "BT adapter state currently {0}", currentState); UpdateWidgetDisplay(context, (int)currentState); return; } if(intent.Action == Android.Bluetooth.BluetoothAdapter.ActionStateChanged) { Log.Info(APP_NAME, "Received BT Action State change message"); ProcessBTStateChangeMessage(context, intent); return; } } private void ProcessBTStateChangeMessage(Context context, Intent intent) { int prevState = intent.GetIntExtra(BluetoothAdapter.ExtraPreviousState, -1); int newState = intent.GetIntExtra(BluetoothAdapter.ExtraState, -1); string message = string.Format("Bluetooth State Change from {0} to {1}", prevState, newState); Log.Info(APP_NAME, message); UpdateWidgetDisplay(context, newState); } /// <summary> /// Updates the widget display image based on the new state /// </summary> /// <param name="context">Context.</param> /// <param name="newState">New state.</param> private void UpdateWidgetDisplay(Context context, int newState) { var appWidgetManager = AppWidgetManager.GetInstance(context); var remoteViews = new RemoteViews(context.PackageName, Resource.Layout.initial_layout); Log.Debug(APP_NAME, "this.GetType().ToString(): {0}", this.GetType().ToString()); var thisWidget = new ComponentName(context, this.Class); Log.Debug(APP_NAME, thisWidget.FlattenToString()); Log.Debug(APP_NAME, "remoteViews: {0}", remoteViews.ToString()); int imgResource = Resource.Drawable.bluetooth_off; switch((Android.Bluetooth.State)newState) { case Android.Bluetooth.State.Off: case Android.Bluetooth.State.TurningOn: { imgResource = Resource.Drawable.bluetooth_off; break; } case Android.Bluetooth.State.On: case Android.Bluetooth.State.TurningOff: { imgResource = Resource.Drawable.bluetooth_on; break; } default: { imgResource = Resource.Drawable.bluetooth_off; break; } } remoteViews.SetImageViewResource(Resource.Id.imgBluetooth, imgResource); appWidgetManager.UpdateAppWidget(thisWidget, remoteViews); } } }
mit
C#
4c0456a8d5c19020d2b50d387b573384efbec08c
add mapper for scope entity
levid-gc/IdentityServer3.Dapper
source/IdentityServer3.Dapper/Mappers/ScopeMapper.cs
source/IdentityServer3.Dapper/Mappers/ScopeMapper.cs
using DapperExtensions.Mapper; using IdentityServer3.Dapper.Entities; namespace IdentityServer3.Dapper.Mappers { public class ScopeMapper : ClassMapper<Scope> { public ScopeMapper() { // use a custom schema Schema("dbo"); // use different table name Table("Scopes"); // Ignore this property entirely Map(x => x.ScopeClaims).Ignore(); // optional, map all other columns AutoMap(); } } }
apache-2.0
C#
3940f0b99ccfc2e2da96e746add1beb768d40749
Test CI Template Message
wojtpl2/ExtendedXmlSerializer,wojtpl2/ExtendedXmlSerializer
test/ExtendedXmlSerializer.Tests.ReportedIssues/Issue479Tests.cs
test/ExtendedXmlSerializer.Tests.ReportedIssues/Issue479Tests.cs
using FluentAssertions; using Xunit; namespace ExtendedXmlSerializer.Tests.ReportedIssues { public sealed class Issue479Tests { [Fact] public void Verify() { true.Should().BeTrue(); } } }
mit
C#
08842fccc13e432b35d80a4c565b4a855e63a863
Fix comment on attribute ctor. bugid: 862
rockfordlhotka/csla,BrettJaner/csla,rockfordlhotka/csla,ronnymgm/csla-light,JasonBock/csla,ronnymgm/csla-light,ronnymgm/csla-light,MarimerLLC/csla,jonnybee/csla,MarimerLLC/csla,jonnybee/csla,JasonBock/csla,rockfordlhotka/csla,jonnybee/csla,JasonBock/csla,BrettJaner/csla,MarimerLLC/csla,BrettJaner/csla
Source/Csla.Wp/DataAnnotations/StringLengthAttribute.cs
Source/Csla.Wp/DataAnnotations/StringLengthAttribute.cs
using System; namespace System.ComponentModel.DataAnnotations { /// <summary> /// Specifies that a data field value must /// fall within the specified range. /// </summary> [AttributeUsage(AttributeTargets.Property)] public class StringLengthAttribute : ValidationAttribute { private int _max; /// <summary> /// Creates an instance of the attribute. /// </summary> /// <param name="stringMaxLength">Maximum string length allowed.</param> public StringLengthAttribute(int stringMaxLength) { _max = stringMaxLength; ErrorMessage = "Field length must not exceed maximum length."; } /// <summary> /// Validates the specified value with respect to /// the current validation attribute. /// </summary> /// <param name="value">Value of the object to validate.</param> /// <param name="validationContext">The context information about the validation operation.</param> protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null && value.ToString().Length > _max) return new ValidationResult(this.ErrorMessage); else return null; } } }
using System; namespace System.ComponentModel.DataAnnotations { /// <summary> /// Specifies that a data field value must /// fall within the specified range. /// </summary> [AttributeUsage(AttributeTargets.Property)] public class StringLengthAttribute : ValidationAttribute { private int _max; public StringLengthAttribute(int stringMaxLength) { _max = stringMaxLength; ErrorMessage = "Field length must not exceed maximum length."; } /// <summary> /// Validates the specified value with respect to /// the current validation attribute. /// </summary> /// <param name="value">Value of the object to validate.</param> /// <param name="validationContext">The context information about the validation operation.</param> protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null && value.ToString().Length > _max) return new ValidationResult(this.ErrorMessage); else return null; } } }
mit
C#
8bea93a59b2668a1a13763c02e93e9857c89028c
add CityMapController
tkaretsos/ProceduralBuildings,AlexanderMazaletskiy/ProceduralBuildings
Scripts/CityMapController.cs
Scripts/CityMapController.cs
using UnityEngine; using Thesis; public class CityMapController : MonoBehaviour { Block block; void Awake () { block = new Block(new Vector3(1f, 0f, 0f), new Vector3(0f, 0f, 300f), new Vector3(700f, 0f, 300f), new Vector3(700f, 0f, 0f)); block.Bisect(); } void Update () { foreach (Block b in CityMapManager.Instance.blocks) foreach (Edge e in b.lot.edges) Debug.DrawLine(e.start, e.end, Color.green); } }
mit
C#
8cb20f4c8efbe1f73f9ac515702706b2e10f0f8e
test created
tiksn/TIKSN-Framework
UnitTests/Finance/ForeignExchange/MyCurrencyDotNetTests.cs
UnitTests/Finance/ForeignExchange/MyCurrencyDotNetTests.cs
using FluentAssertions; using Microsoft.Extensions.DependencyInjection; using System; using System.Linq; using System.Threading.Tasks; using TIKSN.DependencyInjection.Tests; using TIKSN.Globalization; using Xunit; using Xunit.Abstractions; namespace TIKSN.Finance.ForeignExchange.Tests { public class MyCurrencyDotNetTests { private readonly IServiceProvider _serviceProvider; public MyCurrencyDotNetTests(ITestOutputHelper testOutputHelper) { _serviceProvider = new TestCompositionRootSetup(testOutputHelper, services => { services.AddSingleton<ICurrencyFactory, CurrencyFactory>(); services.AddSingleton<IRegionFactory, RegionFactory>(); }).CreateServiceProvider(); } [Fact] public async Task GetCurrencyPairsAsync() { var myCurrencyDotNet = new MyCurrencyDotNet(_serviceProvider.GetRequiredService<ICurrencyFactory>(), _serviceProvider.GetRequiredService<IRegionFactory>()); var pairs = await myCurrencyDotNet.GetCurrencyPairsAsync(DateTimeOffset.Now); pairs.Count().Should().BeGreaterThan(0); } } }
mit
C#
e7f7e5588d0d57919518e50fcfd76656aa47b6e7
Add typeDefinition file to slnWithCsproj test project
OmniSharp/omnisharp-vscode,OmniSharp/omnisharp-vscode,OmniSharp/omnisharp-vscode,OmniSharp/omnisharp-vscode,OmniSharp/omnisharp-vscode
test/integrationTests/testAssets/slnWithCsproj/src/app/typeDefinition.cs
test/integrationTests/testAssets/slnWithCsproj/src/app/typeDefinition.cs
using System; namespace Test { public class LinkedList { public void MyMethod() { var linked = new LinkedList(); var str = "test string"; var part = new PartialClass(); Console.WriteLine(str); } } public partial class PartialClass { public string Foo {get; set;}; } public partial class PartialClass { public int Bar {get; set;} } }
mit
C#
b7b5eaa7026bf6a1f2863d2c828296e3fe738f6d
Add a failing test
AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Perspex,jkoritzinsky/Avalonia,grokys/Perspex,Perspex/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex
tests/Avalonia.Markup.Xaml.UnitTests/Xaml/IgnoredDirectivesTests.cs
tests/Avalonia.Markup.Xaml.UnitTests/Xaml/IgnoredDirectivesTests.cs
using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.UnitTests; using Xunit; namespace Avalonia.Markup.Xaml.UnitTests.Xaml { public class IgnoredDirectivesTests : XamlTestBase { [Fact] public void Ignored_Directives_Should_Compile() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { const string xaml = @" <Window xmlns='https://github.com/avaloniaui' xmlns:sys='clr-namespace:System;assembly=netstandard' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'> <TextBlock x:Name='target' x:FieldModifier='Public' Text='Foo'/> </Window>"; var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml); var target = window.FindControl<TextBlock>("target"); window.ApplyTemplate(); target.ApplyTemplate(); Assert.Equal("Foo", target.Text); } } } }
mit
C#
0805396a4e12e1e0cbda48921b579a51cde9540d
Revert "Delete SlackUserExtensions.cs"
Sankra/DIPSbot,Sankra/DIPSbot
src/Hjerpbakk.DIPSbot/Extensions/SlackUserExtensions.cs
src/Hjerpbakk.DIPSbot/Extensions/SlackUserExtensions.cs
using System; using SlackConnector.Models; namespace Hjerpbakk.DIPSbot.Extensions { public static class SlackUserExtensions { public static void Guard(this SlackUser slackUser) { if (slackUser == null) { throw new ArgumentNullException(nameof(slackUser)); } if (string.IsNullOrEmpty(slackUser.Id)) { throw new ArgumentException(nameof(slackUser)); } } } }
mit
C#
defa118b95bdd1f2b7ee736fbbae3e9aeb8ef39f
Select everything outside of pcb profile
sts-CAD-Software/PCB-Investigator-Scripts
Select.outside.of.Profile.cs
Select.outside.of.Profile.cs
//Synchronous template //----------------------------------------------------------------------------------- // PCB-Investigator Automation Script // Created on 14.10.2015 // Autor Fabio Gruber // // Select all elements outside the board contour, e.g. to delete them. //----------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using PCBI.Plugin; using PCBI.Plugin.Interfaces; using System.Windows.Forms; using System.Drawing; using PCBI.Automation; using System.IO; using System.Drawing.Drawing2D; using PCBI.MathUtils; namespace PCBIScript { public class PScript : IPCBIScript { public PScript() { } public void Execute(IPCBIWindow Parent) { IStep step = Parent.GetCurrentStep(); IMatrix matrix = Parent.GetMatrix(); if (step == null) return; IODBObject profile = step.GetPCBOutlineAsODBObject(); foreach (string layerName in step.GetAllLayerNames()) { if (matrix.GetMatrixLayerType(layerName) == MatrixLayerType.Component) continue; //no component layer ILayer Layer = step.GetLayer(layerName); if (Layer is IODBLayer) { bool foundOne = false; IODBLayer layer = (IODBLayer)Layer; foreach (IODBObject obj in layer.GetAllLayerObjects()) { if (profile.IsPointOfSecondObjectIncluded(obj)) { //inside not relevant } else { obj.Select(true); foundOne = true; } } if (foundOne) Layer.EnableLayer(true); } } Parent.UpdateSelection(); Parent.UpdateView(); } } }
bsd-3-clause
C#
b60af897315c6164c7675e7b3dc1b677f5ddc655
Add stub for notification svc
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Services/NotificationService.cs
Battery-Commander.Web/Services/NotificationService.cs
namespace BatteryCommander.Web.Services { public class NotificationService { // Send Email // Send SMS } }
mit
C#
80560afd91db160c0a2721a64c0411788e562d9c
Update the nuget
AuxMon/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,DeepakRajendranMsft/azure-sdk-for-net,hyonholee/azure-sdk-for-net,vivsriaus/azure-sdk-for-net,namratab/azure-sdk-for-net,gubookgu/azure-sdk-for-net,pomortaz/azure-sdk-for-net,AzCiS/azure-sdk-for-net,oburlacu/azure-sdk-for-net,djyou/azure-sdk-for-net,hallihan/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,dasha91/azure-sdk-for-net,avijitgupta/azure-sdk-for-net,scottrille/azure-sdk-for-net,AzCiS/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,oburlacu/azure-sdk-for-net,tonytang-microsoft-com/azure-sdk-for-net,akromm/azure-sdk-for-net,marcoippel/azure-sdk-for-net,relmer/azure-sdk-for-net,hovsepm/azure-sdk-for-net,btasdoven/azure-sdk-for-net,amarzavery/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,avijitgupta/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,alextolp/azure-sdk-for-net,dominiqa/azure-sdk-for-net,Nilambari/azure-sdk-for-net,peshen/azure-sdk-for-net,MabOneSdk/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,pattipaka/azure-sdk-for-net,kagamsft/azure-sdk-for-net,pilor/azure-sdk-for-net,yitao-zhang/azure-sdk-for-net,abhing/azure-sdk-for-net,namratab/azure-sdk-for-net,juvchan/azure-sdk-for-net,Matt-Westphal/azure-sdk-for-net,yoreddy/azure-sdk-for-net,naveedaz/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,ogail/azure-sdk-for-net,divyakgupta/azure-sdk-for-net,arijitt/azure-sdk-for-net,tonytang-microsoft-com/azure-sdk-for-net,juvchan/azure-sdk-for-net,pinwang81/azure-sdk-for-net,nemanja88/azure-sdk-for-net,avijitgupta/azure-sdk-for-net,olydis/azure-sdk-for-net,pattipaka/azure-sdk-for-net,shipram/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,DeepakRajendranMsft/azure-sdk-for-net,yadavbdev/azure-sdk-for-net,zaevans/azure-sdk-for-net,peshen/azure-sdk-for-net,rohmano/azure-sdk-for-net,peshen/azure-sdk-for-net,jamestao/azure-sdk-for-net,vladca/azure-sdk-for-net,jtlibing/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,shipram/azure-sdk-for-net,msfcolombo/azure-sdk-for-net,markcowl/azure-sdk-for-net,yitao-zhang/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,herveyw/azure-sdk-for-net,hyonholee/azure-sdk-for-net,nacaspi/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,pankajsn/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,begoldsm/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,pattipaka/azure-sdk-for-net,gubookgu/azure-sdk-for-net,lygasch/azure-sdk-for-net,r22016/azure-sdk-for-net,shuagarw/azure-sdk-for-net,kagamsft/azure-sdk-for-net,zaevans/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,shuainie/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,pankajsn/azure-sdk-for-net,mihymel/azure-sdk-for-net,SpotLabsNET/azure-sdk-for-net,shuagarw/azure-sdk-for-net,atpham256/azure-sdk-for-net,tpeplow/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,felixcho-msft/azure-sdk-for-net,herveyw/azure-sdk-for-net,pomortaz/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,MabOneSdk/azure-sdk-for-net,xindzhan/azure-sdk-for-net,jasper-schneider/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,makhdumi/azure-sdk-for-net,vhamine/azure-sdk-for-net,stankovski/azure-sdk-for-net,enavro/azure-sdk-for-net,xindzhan/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,nathannfan/azure-sdk-for-net,enavro/azure-sdk-for-net,makhdumi/azure-sdk-for-net,juvchan/azure-sdk-for-net,abhing/azure-sdk-for-net,pinwang81/azure-sdk-for-net,robertla/azure-sdk-for-net,MabOneSdk/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,scottrille/azure-sdk-for-net,vladca/azure-sdk-for-net,shixiaoyu/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,msfcolombo/azure-sdk-for-net,amarzavery/azure-sdk-for-net,djyou/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,xindzhan/azure-sdk-for-net,relmer/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,divyakgupta/azure-sdk-for-net,djoelz/azure-sdk-for-net,hovsepm/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,Matt-Westphal/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,dominiqa/azure-sdk-for-net,tonytang-microsoft-com/azure-sdk-for-net,relmer/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,jamestao/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,ailn/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,AuxMon/azure-sdk-for-net,djoelz/azure-sdk-for-net,bgold09/azure-sdk-for-net,cwickham3/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,yadavbdev/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,nathannfan/azure-sdk-for-net,akromm/azure-sdk-for-net,samtoubia/azure-sdk-for-net,btasdoven/azure-sdk-for-net,felixcho-msft/azure-sdk-for-net,Nilambari/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,divyakgupta/azure-sdk-for-net,scottrille/azure-sdk-for-net,bgold09/azure-sdk-for-net,shuainie/azure-sdk-for-net,gubookgu/azure-sdk-for-net,pilor/azure-sdk-for-net,pinwang81/azure-sdk-for-net,lygasch/azure-sdk-for-net,jamestao/azure-sdk-for-net,jasper-schneider/azure-sdk-for-net,shixiaoyu/azure-sdk-for-net,makhdumi/azure-sdk-for-net,marcoippel/azure-sdk-for-net,hyonholee/azure-sdk-for-net,guiling/azure-sdk-for-net,oaastest/azure-sdk-for-net,jtlibing/azure-sdk-for-net,Nilambari/azure-sdk-for-net,felixcho-msft/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,jtlibing/azure-sdk-for-net,mabsimms/azure-sdk-for-net,vivsriaus/azure-sdk-for-net,robertla/azure-sdk-for-net,begoldsm/azure-sdk-for-net,nathannfan/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,r22016/azure-sdk-for-net,shipram/azure-sdk-for-net,arijitt/azure-sdk-for-net,naveedaz/azure-sdk-for-net,rohmano/azure-sdk-for-net,smithab/azure-sdk-for-net,r22016/azure-sdk-for-net,vhamine/azure-sdk-for-net,ailn/azure-sdk-for-net,smithab/azure-sdk-for-net,guiling/azure-sdk-for-net,travismc1/azure-sdk-for-net,abhing/azure-sdk-for-net,smithab/azure-sdk-for-net,dasha91/azure-sdk-for-net,nemanja88/azure-sdk-for-net,oburlacu/azure-sdk-for-net,shuagarw/azure-sdk-for-net,hovsepm/azure-sdk-for-net,zaevans/azure-sdk-for-net,ailn/azure-sdk-for-net,msfcolombo/azure-sdk-for-net,hyonholee/azure-sdk-for-net,yitao-zhang/azure-sdk-for-net,shutchings/azure-sdk-for-net,stankovski/azure-sdk-for-net,jasper-schneider/azure-sdk-for-net,alextolp/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,shutchings/azure-sdk-for-net,btasdoven/azure-sdk-for-net,enavro/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,marcoippel/azure-sdk-for-net,olydis/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,akromm/azure-sdk-for-net,tpeplow/azure-sdk-for-net,AzCiS/azure-sdk-for-net,Matt-Westphal/azure-sdk-for-net,naveedaz/azure-sdk-for-net,pilor/azure-sdk-for-net,nemanja88/azure-sdk-for-net,mihymel/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,tpeplow/azure-sdk-for-net,ogail/azure-sdk-for-net,cwickham3/azure-sdk-for-net,guiling/azure-sdk-for-net,vivsriaus/azure-sdk-for-net,mihymel/azure-sdk-for-net,oaastest/azure-sdk-for-net,vladca/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,namratab/azure-sdk-for-net,mabsimms/azure-sdk-for-net,ogail/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,cwickham3/azure-sdk-for-net,atpham256/azure-sdk-for-net,olydis/azure-sdk-for-net,samtoubia/azure-sdk-for-net,hyonholee/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,mumou/azure-sdk-for-net,djyou/azure-sdk-for-net,alextolp/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,mumou/azure-sdk-for-net,SpotLabsNET/azure-sdk-for-net,dominiqa/azure-sdk-for-net,nacaspi/azure-sdk-for-net,atpham256/azure-sdk-for-net,hallihan/azure-sdk-for-net,yadavbdev/azure-sdk-for-net,mabsimms/azure-sdk-for-net,SpotLabsNET/azure-sdk-for-net,begoldsm/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,samtoubia/azure-sdk-for-net,samtoubia/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,yoreddy/azure-sdk-for-net,robertla/azure-sdk-for-net,herveyw/azure-sdk-for-net,dasha91/azure-sdk-for-net,kagamsft/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,yoreddy/azure-sdk-for-net,bgold09/azure-sdk-for-net,lygasch/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,jamestao/azure-sdk-for-net,DeepakRajendranMsft/azure-sdk-for-net,AuxMon/azure-sdk-for-net,amarzavery/azure-sdk-for-net,shutchings/azure-sdk-for-net,rohmano/azure-sdk-for-net,pankajsn/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,pomortaz/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,oaastest/azure-sdk-for-net
src/StreamAnalyticsManagement/Generated/Models/CommonOperationResponse.cs
src/StreamAnalyticsManagement/Generated/Models/CommonOperationResponse.cs
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // 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. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using Microsoft.WindowsAzure; namespace Microsoft.Azure.Management.StreamAnalytics.Models { /// <summary> /// The common operation response. /// </summary> public partial class CommonOperationResponse : OperationResponse { private DateTime _date; /// <summary> /// Optional. Gets a UTC date/time value generated by the service that /// indicates the time at which the response was initiated. /// </summary> public DateTime Date { get { return this._date; } set { this._date = value; } } /// <summary> /// Initializes a new instance of the CommonOperationResponse class. /// </summary> public CommonOperationResponse() { } } }
apache-2.0
C#
3bc5aa7ec43b8ff47383991a7e9d6106c885626d
Create AssemblyInfo.cs
etirelli/tck,etirelli/tck
runners/dmn-tck-runner-csharp/Properties/AssemblyInfo.cs
runners/dmn-tck-runner-csharp/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("DMN.TCK.Runner")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DMN.TCK.Runner")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("51c64351-4875-4170-a264-d189ed318cb6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
88e98c73cbd65d4d28a339158ecb26ef7c9b37f7
Create Filip.cs
SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming
Kattis-Solutions/Filip.cs
Kattis-Solutions/Filip.cs
using System; namespace Filip { class Program { static void Main(string[] args) { String s = Console.ReadLine(); String[] arr = s.Split(" "); String a = Reverse(arr[0]); String b = Reverse(arr[1]); for(int i = 0; i < 3; i++) { int ta = int.Parse(a.Substring(i, 1)); int tb = int.Parse(b.Substring(i, 1)); if (ta > tb) { Console.WriteLine(a); break; }else if(tb > ta) { Console.WriteLine(b); break; } } } static string Reverse(string s) { String r = ""; for(int i = s.Length - 1; i >= 0; i--) { r += s.Substring(i, 1); } return r; } } }
mit
C#
555b089a1eb789599618b2fee52e5dc1ebe63be3
Add a static class with all stone platforms
faint32/snowflake-1,faint32/snowflake-1,faint32/snowflake-1,RonnChyran/snowflake,SnowflakePowered/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake
Snowflake.API/Platform/StonePlatforms.cs
Snowflake.API/Platform/StonePlatforms.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Snowflake.Platform { public static class StonePlatforms { public static string ATARI_2600 = "ATARI_2600"; public static string ATARI_5200 = "ATARI_5200"; public static string ATARI_7200 = "ATARI_7200"; public static string ATARI_LYNX = "ATARI_LYNX"; public static string ATARI_JAGUAR = "ATARI_JAGUAR"; public static string NINTENDO_NES = "NINTENDO_NES"; public static string NINTENDO_SNES = "NINTENDO_SNES"; public static string NINTENDO_N64 = "NINTENDO_N64"; public static string NINTENDO_GCN = "NINTENDO_GCN"; public static string NINTENDO_WII = "NINTENDO_WII"; public static string NINTENDO_GB = "NINTENDO_GB"; public static string NINTENDO_GBC = "NINTENDO_GBC"; public static string NINTENDO_GBA = "NINTENDO_GBA"; public static string NINTEND_VB = "NINTEND_VB"; public static string NINTENDO_NDS = "NINTENDO_NDS"; public static string NINTENDO_3DS = "NINTENDO_3DS"; public static string SONY_PSX = "SONY_PSX"; public static string SONY_PS2 = "SONY_PS2"; public static string SONY_PS3 = "SONY_PS3"; public static string SONY_PS4 = "SONY_PS4"; public static string SONY_PKS = "SONY_PKS"; public static string SONY_PSP = "SONY_PSP"; public static string SONY_PSV = "SONY_PSV"; public static string SEGA_SMS = "SEGA_SMS"; public static string SEGA_GEN = "SEGA_GEN"; public static string SEGA_CD = "SEGA_CD"; public static string SEGA_32X = "SEGA_32X"; public static string SEGA_SAT = "SEGA_SAT"; public static string SEGA_DC = "SEGA_DC"; public static string SEGA_GG = "SEGA_GG"; public static string NEC_PC98 = "NEC_PC98"; public static string NEC_PCE = "NEC_PCE"; public static string NEC_PCFX = "NEC_PCFX"; public static string MS_XBOX = "MS_XBOX"; public static string MS_360 = "MS_360"; public static string MS_ONE = "MS_ONE"; public static string MS_DOS = "MS_DOS"; public static string ZX_SPECTRUM = "ZX_SPECTRUM"; public static string AMSTRAD_CPC = "AMSTRAD_CPC"; public static string COMMODORE_C64 = "COMMODORE_C64"; public static string MS_MSX = "MS_MSX"; public static string COMMODORE_AMIGA = "COMMODORE_AMIGA"; public static string SNK_NG = "SNK_NG"; public static string SNK_NGP = "SNK_NGP"; public static string ARCADE_MAS = "ARCADE_MAS"; public static string DICE = "DICE"; public static string BANDAI_WS = "BANDAI_WS"; public static string AFP_MP1000 = "AFP_MP1000"; public static string ARCADIA_2001 = "ARCADIA_2001"; public static string BALLY_ASTROCADE = "BALLY_ASTROCADE"; public static string BANDAI_SV = "BANDAI_SV"; public static string ENTEX_AV = "ENTEX_AV"; public static string EPOCH_CV = "EPOCH_CV"; public static string EPOCH_SCV = "EPOCH_SCV"; public static string FAIRCHILD_CHF = "FAIRCHILD_CHF"; public static string MB_INTELLIVISION = "MB_INTELLIVISION"; public static string MAGNAVOX_ODDESSEY = "MAGNAVOX_ODDESSEY"; public static string MAGNAVOX_ODDESSEY2 = "MAGNAVOX_ODDESSEY2"; public static string RCA_STUDIOII = "RCA_STUDIOII"; public static string VC_4000 = "VC_4000"; } }
mpl-2.0
C#
04a5ea24190754802527bd1c31b129982a529e2d
Add Drive
KerbaeAdAstra/KerbalFuture
KerbalFuture/SpaceFolderFlightDrive.cs
KerbalFuture/SpaceFolderFlightDrive.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using KSP; namespace KerbalFuture { class FlightDrive : VesselModule { Vector3 vslObtVel; public void FixedUpdate() { if((HighLogic.LoadedSceneIsFlight) && (SpaceFolderWarpCheck())) { vslObtVel = Vessel.GetObtVelocity(); if (SpacefolderWarpCheck()) { } } } } }
mit
C#
eb8a9d9de69838b8c3c4c32813e0475523d9eee2
Add basic proxy tests.
harrison314/MassiveDynamicProxyGenerator,harrison314/MassiveDynamicProxyGenerator,harrison314/MassiveDynamicProxyGenerator
src/MassiveDynamicProxyGenerator.DependencyInjection.Test/AddProxyTests.cs
src/MassiveDynamicProxyGenerator.DependencyInjection.Test/AddProxyTests.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Text; using MassiveDynamicProxyGenerator.Microsoft.DependencyInjection; using Microsoft.Extensions.DependencyInjection; using MassiveDynamicProxyGenerator.DependencyInjection.Test.Services; using Moq; using Shouldly; namespace MassiveDynamicProxyGenerator.DependencyInjection.Test { [TestClass] public class AddProxyTests { [TestMethod] public void AddProxy_GenericInstance_Register() { ServiceCollection serviceCollection = new ServiceCollection(); bool isCall = false; InterceptorAdapter interceptor = new InterceptorAdapter(intercept => { isCall = true; intercept.MethodName.ShouldBe("Send"); }); serviceCollection.AddProxy<IMessageService>(interceptor); IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider(); IMessageService typeA = serviceProvider.GetRequiredService<IMessageService>(); typeA.ShouldNotBeNull(); typeA.Send("some@email.com", "body"); isCall.ShouldBeTrue("Interceptor can not call."); } [TestMethod] public void AddProxy_GenericAction_Register() { ServiceCollection serviceCollection = new ServiceCollection(); bool isCall = false; serviceCollection.AddProxy<IMessageService>(intercept => { isCall = true; intercept.MethodName.ShouldBe("Send"); }); IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider(); IMessageService typeA = serviceProvider.GetRequiredService<IMessageService>(); typeA.ShouldNotBeNull(); typeA.Send("some@email.com", "body"); isCall.ShouldBeTrue("Interceptor can not call."); } [TestMethod] public void AddProxy_GenericWithNullInterceptor_Register() { ServiceCollection serviceCollection = new ServiceCollection(); serviceCollection.AddProxy<IMessageService>(); IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider(); IMessageService typeA = serviceProvider.GetRequiredService<IMessageService>(); typeA.ShouldNotBeNull(); } } }
mit
C#
e5720ae475b90710586b734f149df2ded318cf73
Add RemovableFeatureAttribute
shimingsg/corefx,wtgodbe/corefx,mmitche/corefx,Jiayili1/corefx,wtgodbe/corefx,Jiayili1/corefx,wtgodbe/corefx,ViktorHofer/corefx,ViktorHofer/corefx,shimingsg/corefx,ericstj/corefx,mmitche/corefx,ViktorHofer/corefx,BrennanConroy/corefx,mmitche/corefx,shimingsg/corefx,shimingsg/corefx,ptoonen/corefx,ViktorHofer/corefx,ptoonen/corefx,ericstj/corefx,ViktorHofer/corefx,ptoonen/corefx,ptoonen/corefx,mmitche/corefx,wtgodbe/corefx,BrennanConroy/corefx,ViktorHofer/corefx,mmitche/corefx,mmitche/corefx,mmitche/corefx,wtgodbe/corefx,ericstj/corefx,shimingsg/corefx,ptoonen/corefx,Jiayili1/corefx,wtgodbe/corefx,ericstj/corefx,ericstj/corefx,shimingsg/corefx,wtgodbe/corefx,ViktorHofer/corefx,Jiayili1/corefx,ericstj/corefx,ericstj/corefx,shimingsg/corefx,Jiayili1/corefx,Jiayili1/corefx,BrennanConroy/corefx,ptoonen/corefx,ptoonen/corefx,Jiayili1/corefx
src/Common/src/System/Runtime/CompilerServices/RemovableFeatureAttribute.cs
src/Common/src/System/Runtime/CompilerServices/RemovableFeatureAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace System.Runtime.CompilerServices { // Instructs IL linkers that the method body decorated with this attribute can be removed // during publishing. // // By default, the body gets replaced by throwing code. // // UseNopBody can be set to suppress the throwing behavior, replacing the throw with // a no-operation body. [AttributeUsage(AttributeTargets.Method)] internal class RemovableFeatureAttribute : Attribute { public bool UseNopBody; public string FeatureSwitchName; public RemovableFeatureAttribute(string featureSwitchName) { FeatureSwitchName = featureSwitchName; } } }
mit
C#
ce78f3af70f35cf6ffb4b70275ec2c1c9937d398
Transform repeat rules into a tree
jagrem/slang,jagrem/slang,jagrem/slang
slang/Lexing/Trees/Transformers/RepeatRuleExtensions.cs
slang/Lexing/Trees/Transformers/RepeatRuleExtensions.cs
using System.Linq; using slang.Lexing.Rules.Core; using slang.Lexing.Trees.Nodes; namespace slang.Lexing.Trees.Transformers { public static class RepeatRuleExtensions { public static Tree Transform (this Repeat rule) { var tree = rule.Value.Transform (); var transitions = tree.Root.Transitions; tree.Leaves .ToList () .ForEach (leaf => { transitions.ToList ().ForEach (transition => leaf.Transitions.Add (transition.Key, transition.Value)); leaf.Transitions [Character.Any] = new Transition (null, rule.TokenCreator); }); return tree; } } }
mit
C#
c4281fb36b320d0093627f1f7240d0039686652a
Add Q213
txchen/localleet
csharp/Q213_HouseRobberII.cs
csharp/Q213_HouseRobberII.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; // Note: This is an extension of House Robber. // // After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street. // // Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. // https://leetcode.com/problems/house-robber-ii/ namespace LocalLeet { public class Q213 { public int Rob(int[] nums) { if (nums.Length == 0) { return 0; } if (nums.Length <= 1) { return nums[0]; } if (nums.Length == 2) { return Math.Max(nums[0], nums[1]); } // similar to house-robber-i, just the max of (rob(nums[0, -2]), rob(nums[1, -1])) int[] shrinkedNums = new int[nums.Length - 1]; Array.Copy(nums, 0, shrinkedNums, 0, shrinkedNums.Length); int answer1 = RobInternal(shrinkedNums); Array.Copy(nums, 1, shrinkedNums, 0, shrinkedNums.Length); int answer2 = RobInternal(shrinkedNums); return Math.Max(answer1, answer2); } private int RobInternal(int[] nums) { nums[1] = Math.Max(nums[0], nums[1]); for (int i = 2; i < nums.Length; i++) { nums[i] = Math.Max(nums[i-2] + nums[i], nums[i-1]); // rob current or not } return nums[nums.Length - 1]; } [Fact] public void Q213_HouseRobberII() { TestHelper.Run(input => Rob(input.EntireInput.ToIntArray()).ToString()); } } }
mit
C#
88e85bec683c9a69369e7e19bfc3655a0d280a07
Add back AssemblyInfo.cs
mganss/HtmlSanitizer
src/HtmlSanitizer/Properties/AssemblyInfo.cs
src/HtmlSanitizer/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; #if !NETSTANDARD // 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("16af04e9-e712-417e-b749-c8d10148dda9")] #endif [assembly: AssemblyVersion("3.0.0.0")]
mit
C#
9687ffc5c6fb47386e6703f8d6043d60cf13e988
Remove duplicates from sorted list II
Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews
LeetCode/remote/remove_duplicates_from_sorted_list_II.cs
LeetCode/remote/remove_duplicates_from_sorted_list_II.cs
// https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ // Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. // // For example, // Given 1->2->3->3->4->4->5, return 1->2->5. // Given 1->1->1->2->3, return 2->3. // // https://leetcode.com/submissions/detail/67082686/ // // Submission Details // 166 / 166 test cases passed. // Status: Accepted // Runtime: 171 ms // // Submitted: 9 hours, 19 minutes ago public class Solution { public ListNode DeleteDuplicates(ListNode head) { if (head == null || head.next == null) { return head; } if (head.val == head.next.val) { while (head.next != null && head.val == head.next.val) { head = head.next; } return DeleteDuplicates(head.next); } head.next = DeleteDuplicates(head.next); return head; } }
mit
C#
e6b2e3b0ed1f4059a9fef74053b7ed5d6ec39d9d
Add osu!catch skin configurations
peppy/osu,NeoAdonis/osu,peppy/osu-new,ppy/osu,peppy/osu,ppy/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,UselessToucan/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu
osu.Game.Rulesets.Catch/Skinning/CatchSkinConfiguration.cs
osu.Game.Rulesets.Catch/Skinning/CatchSkinConfiguration.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. namespace osu.Game.Rulesets.Catch.Skinning { public enum CatchSkinConfiguration { /// <summary> /// The colour to be used for the catcher while on hyper-dashing state. /// </summary> HyperDash, /// <summary> /// The colour to be used for hyper-dash fruits. /// </summary> HyperDashFruit, /// <summary> /// The colour to be used for the "exploding" catcher sprite on beginning of hyper-dashing. /// </summary> HyperDashAfterImage, } }
mit
C#
3602a2671ce2d1920b966866902aff2b9b066cae
Create Index.cshtml
CarmelSoftware/Generic-Data-Repository-for-ASP.NET-MVC
Views/Blogs/Index.cshtml
Views/Blogs/Index.cshtml
@model IEnumerable<GenericRepository.Models.Blog> @{ ViewBag.Title = "Index"; } <div class="jumbotron"> <h2>Generic Data Repository - Index</h2><br /><h4>By Carmel Schvartzman</h4> </div> <div class="jumbotron"> <p> @Html.ActionLink("Create New", "Create") </p> <table class="table"> <tr> <th> Post Title </th> <th> Post Text </th> <th> @Html.DisplayNameFor(model => model.DatePosted) </th> <th> Orchid Picture </th> <th> Blogger Name </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Title) </td> <td> @Html.DisplayFor(modelItem => item.Text) </td> <td> @String.Format("{0:yyyy-MM-dd}",item.DatePosted.HasValue ? item.DatePosted.Value : DateTime.Today ) </td> <td> <img src="/Content/Images/@Html.DisplayFor(modelItem => item.MainPicture)"/> </td> <td> @Html.DisplayFor(modelItem => item.Blogger.Name) </td> <td> @Html.ActionLink("Edit", "Edit", new { id = item.BlogID }) @Html.ActionLink("Details", "Details", new { id = item.BlogID }) @Html.ActionLink("Delete", "Delete", new { id = item.BlogID }) </td> </tr> } </table> </div> </div>
mit
C#
3f6b153320412377dd96eb3d4526d5e213e1e8ab
Create main.cs
alsuka/CSharp-Lazy-Loading
main.cs
main.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Objects; using System.Diagnostics; using SeleniumTests; namespace EntityTest { class Program { static void Main(string[] args) { string sql = ""; Stopwatch sw = new Stopwatch(); TimeSpan e1; long ms; using (var context = new TUMISDBEntities()) { sw.Reset(); sw = Stopwatch.StartNew(); // Lazy Loading foreach (var parent in context.DemoBook) { Console.Write("Book :{0}, author:", parent.title); foreach (var item in parent.DemoBookAuth) { Console.Write("{0}, ",item.psn_nam ); } Console.WriteLine(); } sw.Stop(); e1 = sw.Elapsed; ms = sw.ElapsedMilliseconds; Console.WriteLine("Lazy Loading: " + e1 + "秒 " + ms + "毫秒"); Console.WriteLine("----------"); var booklist = from tmp in context.DemoBook select new { tmp.title, tmp.DemoBookAuth }; sql = (booklist as ObjectQuery).ToTraceString(); // check sql //Console.WriteLine(sql); sw.Reset(); sw = Stopwatch.StartNew(); //Eager Loading 機制: Include Method foreach (var parent in context.DemoBook.Include("DemoBookAuth")) { Console.Write("Book :{0}, author:", parent.title); foreach (var item in parent.DemoBookAuth) { Console.Write("{0}, ", item.psn_nam); } Console.WriteLine(); } sw.Stop(); e1 = sw.Elapsed; ms = sw.ElapsedMilliseconds; Console.WriteLine("Eager Loading: " + e1 + "秒 " + ms + "毫秒"); } } } }
mit
C#
7f67e7c3248ac1e7ce34dc46893b988b6bf03fed
Fix unit test issues in storage account cmdlets.
enavro/azure-powershell,chef-partners/azure-powershell,AzureRT/azure-powershell,rohmano/azure-powershell,krkhan/azure-powershell,dulems/azure-powershell,seanbamsft/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,ankurchoubeymsft/azure-powershell,pankajsn/azure-powershell,rohmano/azure-powershell,yantang-msft/azure-powershell,juvchan/azure-powershell,zaevans/azure-powershell,alfantp/azure-powershell,TaraMeyer/azure-powershell,naveedaz/azure-powershell,arcadiahlyy/azure-powershell,DeepakRajendranMsft/azure-powershell,AzureRT/azure-powershell,dulems/azure-powershell,yantang-msft/azure-powershell,yoavrubin/azure-powershell,CamSoper/azure-powershell,chef-partners/azure-powershell,pomortaz/azure-powershell,hungmai-msft/azure-powershell,yadavbdev/azure-powershell,CamSoper/azure-powershell,arcadiahlyy/azure-powershell,pankajsn/azure-powershell,hallihan/azure-powershell,chef-partners/azure-powershell,AzureAutomationTeam/azure-powershell,shuagarw/azure-powershell,juvchan/azure-powershell,hallihan/azure-powershell,krkhan/azure-powershell,naveedaz/azure-powershell,dominiqa/azure-powershell,stankovski/azure-powershell,SarahRogers/azure-powershell,AzureAutomationTeam/azure-powershell,SarahRogers/azure-powershell,AzureRT/azure-powershell,devigned/azure-powershell,haocs/azure-powershell,hungmai-msft/azure-powershell,ClogenyTechnologies/azure-powershell,jtlibing/azure-powershell,pomortaz/azure-powershell,rhencke/azure-powershell,akurmi/azure-powershell,bgold09/azure-powershell,pomortaz/azure-powershell,DeepakRajendranMsft/azure-powershell,nickheppleston/azure-powershell,atpham256/azure-powershell,zhencui/azure-powershell,pelagos/azure-powershell,dominiqa/azure-powershell,PashaPash/azure-powershell,yoavrubin/azure-powershell,hungmai-msft/azure-powershell,tonytang-microsoft-com/azure-powershell,dominiqa/azure-powershell,pelagos/azure-powershell,arcadiahlyy/azure-powershell,dulems/azure-powershell,naveedaz/azure-powershell,Matt-Westphal/azure-powershell,naveedaz/azure-powershell,alfantp/azure-powershell,pelagos/azure-powershell,DeepakRajendranMsft/azure-powershell,yantang-msft/azure-powershell,DeepakRajendranMsft/azure-powershell,jtlibing/azure-powershell,ailn/azure-powershell,ankurchoubeymsft/azure-powershell,hungmai-msft/azure-powershell,nemanja88/azure-powershell,akurmi/azure-powershell,seanbamsft/azure-powershell,oaastest/azure-powershell,enavro/azure-powershell,SarahRogers/azure-powershell,TaraMeyer/azure-powershell,shuagarw/azure-powershell,alfantp/azure-powershell,SarahRogers/azure-powershell,krkhan/azure-powershell,mayurid/azure-powershell,zaevans/azure-powershell,yoavrubin/azure-powershell,haocs/azure-powershell,yoavrubin/azure-powershell,oaastest/azure-powershell,pankajsn/azure-powershell,ClogenyTechnologies/azure-powershell,hallihan/azure-powershell,ailn/azure-powershell,PashaPash/azure-powershell,Matt-Westphal/azure-powershell,zaevans/azure-powershell,akurmi/azure-powershell,hallihan/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,yoavrubin/azure-powershell,ailn/azure-powershell,praveennet/azure-powershell,tonytang-microsoft-com/azure-powershell,dulems/azure-powershell,haocs/azure-powershell,haocs/azure-powershell,yantang-msft/azure-powershell,naveedaz/azure-powershell,tonytang-microsoft-com/azure-powershell,oaastest/azure-powershell,atpham256/azure-powershell,CamSoper/azure-powershell,stankovski/azure-powershell,Matt-Westphal/azure-powershell,rhencke/azure-powershell,dominiqa/azure-powershell,arcadiahlyy/azure-powershell,zhencui/azure-powershell,rohmano/azure-powershell,PashaPash/azure-powershell,alfantp/azure-powershell,atpham256/azure-powershell,nemanja88/azure-powershell,AzureRT/azure-powershell,oaastest/azure-powershell,jasper-schneider/azure-powershell,AzureAutomationTeam/azure-powershell,jtlibing/azure-powershell,jianghaolu/azure-powershell,seanbamsft/azure-powershell,tonytang-microsoft-com/azure-powershell,ailn/azure-powershell,hovsepm/azure-powershell,nemanja88/azure-powershell,kagamsft/azure-powershell,zhencui/azure-powershell,TaraMeyer/azure-powershell,kagamsft/azure-powershell,TaraMeyer/azure-powershell,rohmano/azure-powershell,zhencui/azure-powershell,nickheppleston/azure-powershell,kagamsft/azure-powershell,devigned/azure-powershell,praveennet/azure-powershell,Matt-Westphal/azure-powershell,AzureAutomationTeam/azure-powershell,bgold09/azure-powershell,arcadiahlyy/azure-powershell,AzureRT/azure-powershell,tonytang-microsoft-com/azure-powershell,jasper-schneider/azure-powershell,hovsepm/azure-powershell,hallihan/azure-powershell,hungmai-msft/azure-powershell,CamSoper/azure-powershell,ankurchoubeymsft/azure-powershell,praveennet/azure-powershell,yadavbdev/azure-powershell,shuagarw/azure-powershell,jtlibing/azure-powershell,rhencke/azure-powershell,ankurchoubeymsft/azure-powershell,atpham256/azure-powershell,atpham256/azure-powershell,kagamsft/azure-powershell,juvchan/azure-powershell,krkhan/azure-powershell,PashaPash/azure-powershell,pomortaz/azure-powershell,yadavbdev/azure-powershell,pelagos/azure-powershell,shuagarw/azure-powershell,yantang-msft/azure-powershell,stankovski/azure-powershell,nickheppleston/azure-powershell,zaevans/azure-powershell,yadavbdev/azure-powershell,enavro/azure-powershell,seanbamsft/azure-powershell,oaastest/azure-powershell,devigned/azure-powershell,mayurid/azure-powershell,zaevans/azure-powershell,naveedaz/azure-powershell,pankajsn/azure-powershell,zhencui/azure-powershell,stankovski/azure-powershell,pelagos/azure-powershell,mayurid/azure-powershell,dulems/azure-powershell,praveennet/azure-powershell,AzureRT/azure-powershell,bgold09/azure-powershell,hungmai-msft/azure-powershell,ClogenyTechnologies/azure-powershell,enavro/azure-powershell,praveennet/azure-powershell,Matt-Westphal/azure-powershell,mayurid/azure-powershell,yadavbdev/azure-powershell,bgold09/azure-powershell,alfantp/azure-powershell,juvchan/azure-powershell,devigned/azure-powershell,PashaPash/azure-powershell,SarahRogers/azure-powershell,krkhan/azure-powershell,DeepakRajendranMsft/azure-powershell,shuagarw/azure-powershell,devigned/azure-powershell,rohmano/azure-powershell,nemanja88/azure-powershell,krkhan/azure-powershell,ailn/azure-powershell,jtlibing/azure-powershell,dominiqa/azure-powershell,akurmi/azure-powershell,jasper-schneider/azure-powershell,rohmano/azure-powershell,jianghaolu/azure-powershell,jianghaolu/azure-powershell,ankurchoubeymsft/azure-powershell,jianghaolu/azure-powershell,akurmi/azure-powershell,seanbamsft/azure-powershell,juvchan/azure-powershell,haocs/azure-powershell,nickheppleston/azure-powershell,rhencke/azure-powershell,seanbamsft/azure-powershell,mayurid/azure-powershell,hovsepm/azure-powershell,bgold09/azure-powershell,pankajsn/azure-powershell,atpham256/azure-powershell,pomortaz/azure-powershell,nickheppleston/azure-powershell,TaraMeyer/azure-powershell,hovsepm/azure-powershell,rhencke/azure-powershell,jianghaolu/azure-powershell,chef-partners/azure-powershell,nemanja88/azure-powershell,chef-partners/azure-powershell,kagamsft/azure-powershell,yantang-msft/azure-powershell,pankajsn/azure-powershell,jasper-schneider/azure-powershell,enavro/azure-powershell,zhencui/azure-powershell,ClogenyTechnologies/azure-powershell,CamSoper/azure-powershell,stankovski/azure-powershell,hovsepm/azure-powershell,jasper-schneider/azure-powershell
src/ResourceManager/Compute/Commands.Compute/Models/PSStorageAccount.cs
src/ResourceManager/Compute/Commands.Compute/Models/PSStorageAccount.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Management.Storage.Models; namespace Microsoft.Azure.Commands.Compute.Models { class PSStorageAccount { public PSStorageAccount(StorageAccount storageAccount) { this.ResourceGroupName = ParseResourceGroupFromId(storageAccount.Id); this.Name = storageAccount.Name; this.Id = storageAccount.Id; this.Location = storageAccount.Location; this.AccountType = storageAccount.AccountType; this.CreationTime = storageAccount.CreationTime; this.CustomDomain = storageAccount.CustomDomain; this.LastGeoFailoverTime = storageAccount.LastGeoFailoverTime; this.PrimaryEndpoints = storageAccount.PrimaryEndpoints; this.PrimaryLocation = storageAccount.PrimaryLocation; this.ProvisioningState = storageAccount.ProvisioningState; this.SecondaryEndpoints = storageAccount.SecondaryEndpoints; this.SecondaryLocation = storageAccount.SecondaryLocation; this.StatusOfPrimary = storageAccount.StatusOfPrimary; this.StatusOfSecondary = storageAccount.StatusOfSecondary; this.Tags = storageAccount.Tags; } public string ResourceGroupName { get; set; } public string Name { get; set; } public string Id { get; set; } public string Location { get; set; } public AccountType? AccountType { get; set; } public DateTime? CreationTime { get; set; } public CustomDomain CustomDomain { get; set; } public DateTime? LastGeoFailoverTime { get; set; } public Endpoints PrimaryEndpoints { get; set; } public string PrimaryLocation { get; set; } public ProvisioningState? ProvisioningState { get; set; } public Endpoints SecondaryEndpoints { get; set; } public string SecondaryLocation { get; set; } public AccountStatus? StatusOfPrimary { get; set; } public AccountStatus? StatusOfSecondary { get; set; } public IDictionary<string, string> Tags { get; set; } private static string ParseResourceGroupFromId(string idFromServer) { if (!string.IsNullOrEmpty(idFromServer)) { string[] tokens = idFromServer.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); return tokens[3]; } return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Management.Storage.Models; namespace Microsoft.Azure.Commands.Compute.Models { class PSStorageAccount { public PSStorageAccount(StorageAccount storageAccount) { this.ResourceGroupName = ParseResourceGroupFromId(storageAccount.Id); this.Name = storageAccount.Name; this.Id = storageAccount.Id; this.AccountType = storageAccount.AccountType; this.CreationTime = storageAccount.CreationTime; this.CustomDomain = storageAccount.CustomDomain; this.LastGeoFailoverTime = storageAccount.LastGeoFailoverTime; this.PrimaryEndpoints = storageAccount.PrimaryEndpoints; this.PrimaryLocation = storageAccount.PrimaryLocation; this.ProvisioningState = storageAccount.ProvisioningState; this.SecondaryEndpoints = storageAccount.SecondaryEndpoints; this.SecondaryLocation = storageAccount.SecondaryLocation; this.StatusOfPrimary = storageAccount.StatusOfPrimary; this.StatusOfSecondary = storageAccount.StatusOfSecondary; } public string ResourceGroupName { get; set; } public string Name { get; set; } public string Id { get; set; } public AccountType? AccountType { get; set; } public DateTime? CreationTime { get; set; } public CustomDomain CustomDomain { get; set; } public DateTime? LastGeoFailoverTime { get; set; } public Endpoints PrimaryEndpoints { get; set; } public string PrimaryLocation { get; set; } public ProvisioningState? ProvisioningState { get; set; } public Endpoints SecondaryEndpoints { get; set; } public string SecondaryLocation { get; set; } public AccountStatus? StatusOfPrimary { get; set; } public AccountStatus? StatusOfSecondary { get; set; } private static string ParseResourceGroupFromId(string idFromServer) { if (!string.IsNullOrEmpty(idFromServer)) { string[] tokens = idFromServer.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); return tokens[3]; } return null; } } }
apache-2.0
C#
434eb747d2d6c5a57d4d7d66bb22377a3dab0cb6
move http status code descriptions to own class
hibri/HttpMock,zhdusurfin/HttpMock,oschwald/HttpMock,mattolenik/HttpMock
src/HttpMock/ResponseBuilder.cs
src/HttpMock/ResponseBuilder.cs
using System.Collections.Generic; using System.Net; using Kayak; using Kayak.Http; namespace HttpMock { public class ResponseBuilder { private string _body; private static HttpStatusCode _httpStatusCode = HttpStatusCode.OK; public ResponseBuilder WithBody(string body) { _body = body; return this; } public IDataProducer BuildBody() { return new BufferedBody(GetBody()); } public HttpResponseHead BuildHeaders() { return new HttpResponseHead { Status = string.Format("{0} {1}", (int)_httpStatusCode, HttpStatusCodeDescriptions.GetStatusDescription(_httpStatusCode)), Headers = new Dictionary<string, string> { {HttpHeaderNames.ContentType, "text/plain"}, {HttpHeaderNames.ContentLength, GetBody().Length.ToString()}, } }; } private string GetBody() { return _body; } public void WithStatus(HttpStatusCode httpStatusCode) { _httpStatusCode = httpStatusCode; } } public class HttpStatusCodeDescriptions { private static readonly Dictionary<HttpStatusCode, string> _httpStatusCodeDescriptions = new Dictionary<HttpStatusCode, string> {{HttpStatusCode.OK, "OK"}, {HttpStatusCode.NotFound, "NotFound"}}; public static string GetStatusDescription(HttpStatusCode httpStatusCode) { return _httpStatusCodeDescriptions[httpStatusCode]; } } }
using System.Collections.Generic; using System.Net; using Kayak; using Kayak.Http; namespace HttpMock { public class ResponseBuilder { private string _body; private static HttpStatusCode _httpStatusCode = HttpStatusCode.OK; public ResponseBuilder WithBody(string body) { _body = body; return this; } public IDataProducer BuildBody() { return new BufferedBody(GetBody()); } public HttpResponseHead BuildHeaders() { return new HttpResponseHead { Status = string.Format("{0} OK", (int)_httpStatusCode), Headers = new Dictionary<string, string> { {HttpHeaderNames.ContentType, "text/plain"}, {HttpHeaderNames.ContentLength, GetBody().Length.ToString()}, } }; } private string GetBody() { return _body; } public void WithStatus(HttpStatusCode httpStatusCode) { _httpStatusCode = httpStatusCode; } } }
mit
C#
2ef2781575ec8ecaa13fef8720942cfb7a9eb2a9
add initial file
KerbaeAdAstra/KerbalFuture
KerbalFuture/FrameShift/FrameShiftEngine.cs
KerbalFuture/FrameShift/FrameShiftEngine.cs
namespace FrameShift { }
mit
C#
f9064cb2ccbc6be4e39a1ca4d3a4a9f24e9597d5
Add PlatformIdentifier
Cyberboss/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server
src/Tgstation.Server.Host/Core/PlatformIdentifier.cs
src/Tgstation.Server.Host/Core/PlatformIdentifier.cs
using System.Runtime.InteropServices; namespace Tgstation.Server.Host.Core { /// <inheritdoc /> sealed class PlatformIdentifier : IPlatformIdentifier { /// <inheritdoc /> public bool IsWindows { get; } /// <summary> /// Construct a <see cref="PlatformIdentifier"/> /// </summary> public PlatformIdentifier() { IsWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); } } }
agpl-3.0
C#
59cb0b20f8b4caa959d72c1614c0e4d33f8184a7
Add ArrayExtensions
Weingartner/SolidworksAddinFramework
SolidworksAddinFramework/ArrayExtensions.cs
SolidworksAddinFramework/ArrayExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using Accord; namespace SolidworksAddinFramework { public static class ArrayExtensions { /// <summary> /// Enumerate a 2D matrix defined as T[row,column] by traversing /// each column completey before the next column /// </summary> /// <typeparam name="T"></typeparam> /// <param name="array"></param> /// <returns></returns> public static IEnumerable<T> EnumerateColumnWise<T>(this T[,] array) { for (int v = 0; v < array.GetLength(1); v++) { for (int u = 0; u < array.GetLength(0); u++) { yield return array[u, v]; } } } /// <summary> /// Enumerate a 2D matrix defined as T[row,column] by traversing /// each row completely before the next row. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="array"></param> /// <returns></returns> public static IEnumerable<T> EnumerateRowWise<T>(this T[,] array) { for (int u = 0; u < array.GetLength(0); u++) { for (int v = 0; v < array.GetLength(1); v++) { yield return array[u, v]; } } } public static U[,] Select<T, U>(this T[,] ts, Func<T, U> sel) { var t0 = ts.GetLength(0); var t1 = ts.GetLength(1); var us = new U[t0, t1]; for (int t0i = 0; t0i < t0; t0i++) { for (int t1i = 0; t1i < t1; t1i++) { us[t0i, t1i] = sel(ts[t0i, t1i]); } } return us; } public static U[,] Zip<T0,T1, U>(this T0[,] t0s, T1[,] t1s, Func<T0,T1, U> sel) { var t00 = t0s.GetLength(0); var t01 = t0s.GetLength(1); var t10 = t1s.GetLength(0); var t11 = t1s.GetLength(1); if(t00!=t10) throw new DimensionMismatchException(nameof(t0s) ); if(t01!=t11) throw new DimensionMismatchException(nameof(t0s) ); var t0 = t00; var t1 = t01; var us = new U[t0, t1]; for (var t0i = 0; t0i < t0; t0i++) { for (var t1i = 0; t1i < t1; t1i++) { us[t0i, t1i] = sel(t0s[t0i, t1i], t1s[t0i, t1i]); } } return us; } public static void Foreach<T>(this T[,] ts, Action<T> action) { ts.Cast<T>().ForEach(action); } } }
mit
C#
892d68512f1fb6835bed2ed386e36d8603c00a0b
Add mock builder for CarsContextQuery
senioroman4uk/PathFinder
CarsControllersTests/CarContextMockBuilder.cs
CarsControllersTests/CarContextMockBuilder.cs
using System.Collections.Generic; using System.Linq; using PathFinder.Cars.DAL.Model; using PathFinder.Cars.WebApi.Queries; namespace CarsControllersTests { public class CarContextQueryMockBuilder { private readonly CarContextMock _fakeQuery; public CarContextQueryMockBuilder() { _fakeQuery = new CarContextMock(); } public ICarsContextQuery CarsContextQuery { get { return _fakeQuery; } } public CarContextQueryMockBuilder SetCars(IEnumerable<Car> cars) { _fakeQuery.Cars = new EnumerableQuery<Car>(cars); return this; } public CarContextQueryMockBuilder SetUsers(IEnumerable<User> users) { _fakeQuery.Users = new EnumerableQuery<User>(users); return this; } public CarContextQueryMockBuilder SetCarBrands(IEnumerable<CarBrand> carBrands) { _fakeQuery.CarBrands = new EnumerableQuery<CarBrand>(carBrands); return this; } public CarContextQueryMockBuilder SetCarColors(IEnumerable<CarColor> carColors) { _fakeQuery.CarColors = new EnumerableQuery<CarColor>(carColors); return this; } public CarContextQueryMockBuilder SetCarModels(IEnumerable<CarModel> carModels) { _fakeQuery.CarModels = new EnumerableQuery<CarModel>(carModels); return this; } } public class CarContextMock : ICarsContextQuery { public CarContextMock() { Users = new EnumerableQuery<User>(Enumerable.Empty<User>()); CarColors = new EnumerableQuery<CarColor>(Enumerable.Empty<CarColor>()); CarBrands = new EnumerableQuery<CarBrand>(Enumerable.Empty<CarBrand>()); CarModels = new EnumerableQuery<CarModel>(Enumerable.Empty<CarModel>()); Cars = new EnumerableQuery<Car>(Enumerable.Empty<Car>()); } public IOrderedQueryable<User> Users { get; set; } public IOrderedQueryable<CarBrand> CarBrands { get; set; } public IOrderedQueryable<CarColor> CarColors { get; set; } public IOrderedQueryable<CarModel> CarModels { get; set; } public IOrderedQueryable<Car> Cars { get; set; } } }
mit
C#
b99fd1397660dc99d2ed15b14d5114a7b0fccab4
Create Defender.cs
InfernumDeus/Csharp-PokemonGO-battle-simulation
source/Defender.cs
source/Defender.cs
using System; namespace battle_simulation { public class Defender { public string pokemonName; public int attack, defense, hp; public Single cpm; public string q_move, c_move; public int q_power, c_power; public Single q_cd, c_cd; public Single q_mult, c_mult; public int q_damage, c_damage; public int enrg_gain, enrg_cost; public int current_hp, current_en, incoming_damage; public Single waiting; //parameters for dodge public bool next_attack_is_charged; public Single start_dodge_q, end_dodge_q; public Single start_dodge_c, end_dodge_c; //to handle first defender's attacks with special cool down public bool attacked; public int overkill_hp_point; public bool take_damage() { current_hp -= incoming_damage; current_en += incoming_damage / 2; incoming_damage = 0; if (current_en > 200) current_en = 200; if (current_hp < 1) return true; //fainted return false; //survived } public void reset() { current_hp = hp * 2; current_en = 0; waiting = 0.9F; next_attack_is_charged = false; incoming_damage = 0; } } }
mit
C#
5519c644b6c868f82ec93acc6848792be3cf9c7e
Create EcodingConvertor.cs
Forward2015/Download,Forward2015/Download,Forward2015/Download,Forward2015/Download
Dotnet/EcodingConvertor.cs
Dotnet/EcodingConvertor.cs
/// // Convert a string from one encoding to another /// public static string EncodingConvert(Encoding srcEncoding,Encoding desEncoding,string str){ byte[] srcBytes = srcEncoding.GetBytes(Message); byte[] desBytes = Encoding.Convert(desEncoding, desEncoding, utfBytes); string result = desEncoding.GetString(desBytes); return result; }
mit
C#
b89311bdc421692b0cbc25efb0ebe4c57c0daa9f
Add Q190
txchen/localleet
csharp/Q190_ReverseBits.cs
csharp/Q190_ReverseBits.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; // Reverse bits of a given 32 bits unsigned integer. // // For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). // https://leetcode.com/problems/reverse-bits/ namespace LocalLeet { public class Q190 { public uint ReverseBits(uint n) { uint high = (uint)1 << 31; uint low = 1; while (high > low) { bool highHasOne = (n & high) > 0; bool lowHasOne = (n & low) > 0; if (highHasOne && !lowHasOne) { n &= ~high; n |= low; } if (lowHasOne && !highHasOne) { n &= ~low; n |= high; } high = high >> 1; low = low << 1; } return n; } [Fact] public void Q190_ReverseBits() { TestHelper.Run(input => { int idx = input.EntireInput.IndexOf('('); uint inputUInt = uint.Parse(input.EntireInput.Substring(0, idx).Trim()); uint result = ReverseBits(inputUInt); return String.Format(" {0, 11} ({1})", result, Convert.ToString(result, 2).PadLeft(32, '0')); }); } } }
mit
C#
d856356c45d88d9c65079229298d36d541267b8f
Create GameState.cs
efruchter/UnityUtilities
GameState.cs
GameState.cs
using UnityEngine; using System.Collections.Generic; namespace GameState { public delegate void GameStateFunction(); public delegate bool IsGameStateOver(); public interface State { void OnGameStateStart(); void OnGameStateUpdate(); void OnGameStateEnd(); bool IsGameStateOver(); } public class GameStatePipe { LinkedList<DelegateState> _pipe; bool _currentStateActivated; public GameStatePipe() { this._pipe = new LinkedList<DelegateState>(); this._currentStateActivated = false; } private void AddState(DelegateState state) { this._pipe.AddLast(state); } public void AddState(GameStateFunction onStart, GameStateFunction onUpdate, GameStateFunction onEnd, IsGameStateOver isStateOver) { this.AddState( new DelegateState(){ onStart = onStart, onUpdate = onUpdate, onEnd = onEnd, isStateOver = isStateOver}); } public void AddState(State state) { this.AddState( () => {state.OnGameStateStart();}, () => {state.OnGameStateUpdate();}, () => {state.OnGameStateEnd();}, () => {return state.IsGameStateOver();}); } public void Update() { if (this._pipe.Count == 0) { return; } DelegateState currentState = this._pipe.First.Value; if (!this._currentStateActivated) { currentState.onStart(); this._currentStateActivated = true; } currentState.onUpdate(); if (currentState.isStateOver()) { currentState.onEnd(); this._currentStateActivated = false; this._pipe.RemoveFirst(); } } private class DelegateState { static void EmptyStateFunction(){} static bool EmptyIsOverFunction(){return true;} public GameStateFunction onStart = EmptyStateFunction; public GameStateFunction onUpdate = EmptyStateFunction; public GameStateFunction onEnd = EmptyStateFunction; public IsGameStateOver isStateOver = EmptyIsOverFunction; } } }
mit
C#
ae19a38a805ef4a4a758115497da32f9d31e9030
Make metadata accessible without reflection
twcclegg/log4net,freedomvoice/log4net,twcclegg/log4net,freedomvoice/log4net,freedomvoice/log4net,freedomvoice/log4net,twcclegg/log4net,twcclegg/log4net
src/Log4netAssemblyInfo.cs
src/Log4netAssemblyInfo.cs
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you 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. // #endregion namespace log4net { /// <summary> /// Provides information about the environment the assembly has /// been built for. /// </summary> public sealed class AssemblyInfo { /// <summary>Version of the assembly</summary> public const string Version = "1.2.11"; /// <summary>Version of the framework targeted</summary> #if NET_1_1 public const decimal TargetFrameworkVersion = 1.1M; #elif NET_4_0 public const decimal TargetFrameworkVersion = 4.0M; #elif NET_2_0 || NETCF_2_0 || MONO_2_0 #if !CLIENT_PROFILE public const decimal TargetFrameworkVersion = 2.0M; #else public const decimal TargetFrameworkVersion = 3.5M; #endif // Client Profile #else public const decimal TargetFrameworkVersion = 1.0M; #endif /// <summary>Type of framework targeted</summary> #if CLI public const string TargetFramework = "CLI Compatible Frameworks"; #elif NET public const string TargetFramework = ".NET Framework"; #elif NETCF public const string TargetFramework = ".NET Compact Framework"; #elif MONO public const string TargetFramework = "Mono"; #elif SSCLI public const string TargetFramework = "Shared Source CLI"; #else public const string TargetFramework = "Unknown"; #endif /// <summary>Does it target a client profile?</summary> #if !CLIENT_PROFILE public const bool ClientProfile = false; #else public const bool ClientProfile = true; #endif /// <summary> /// Identifies the version and target for this assembly. /// </summary> public static string Info { get { return string.Format("Apache log4net version {0} compiled for {1}{2} {3}", Version, TargetFramework, /* Can't use ClientProfile && true ? " Client Profile" : or the compiler whines about unreachable expressions */ #if !CLIENT_PROFILE string.Empty, #else " Client Profile", #endif TargetFrameworkVersion); } } } }
apache-2.0
C#
83c6d82f9f866c995fa9f41d533ab885683444bc
Set Profil to fix Rectangle
sts-CAD-Software/PCB-Investigator-Scripts
SetProfil.cs
SetProfil.cs
//----------------------------------------------------------------------------------- // PCB-Investigator Automation Script // Created on 2014-04-24 // Autor support@easylogix.de // www.pcb-investigator.com // SDK online reference http://www.pcb-investigator.com/sites/default/files/documents/InterfaceDocumentation/Index.html // SDK http://www.pcb-investigator.com/en/sdk-participate // // Set Profil to fix Rectangle. // The example rectangle is fixed size with 15 Inch x 10 Inch, just change the newBounds rectangle to get the size your company needs. //----------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using PCBI.Plugin; using PCBI.Plugin.Interfaces; using System.Windows.Forms; using System.Drawing; using PCBI.Automation; using System.IO; using System.Drawing.Drawing2D; using PCBI.MathUtils; namespace PCBIScript { public class PScript : IPCBIScript { public PScript() { } public void Execute(IPCBIWindow parent) { IFilter filter = new IFilter(parent); IODBObject outlinePolygon = filter.CreateOutlinePolygon(); IStep parentStep = parent.GetCurrentStep(); ISurfaceSpecifics spec = (ISurfaceSpecifics)outlinePolygon.GetSpecifics(); spec.StartPolygon(false, new PointF()); RectangleF newBounds = new RectangleF(0, 0, 15000, 10000); //create 4 lines and add them to an contour polygon PointF leftUp = new PointF(newBounds.Left, newBounds.Top); PointF leftDown = new PointF(newBounds.Left, newBounds.Bottom); PointF rightUp = new PointF(newBounds.Right, newBounds.Top); PointF rightDown = new PointF(newBounds.Right, newBounds.Bottom); spec.AddLine(leftUp, rightUp); spec.AddLine(rightUp, rightDown); spec.AddLine(rightDown, leftDown); spec.AddLine(leftDown, leftUp); spec.EndPolygon(); //close the new contour parentStep.SetPCBOutline(spec); parent.UpdateView(); } public StartMethode GetStartMethode() { return StartMethode.Synchronous; } } }
bsd-3-clause
C#
ec9cdd8bbc24b270e4890ccdf524319942a6e5cd
Add test class 'NotificationEntitiesInfoCarrierTest'
azabluda/InfoCarrier.Core
test/InfoCarrier.Core.EFCore.FunctionalTests/NotificationEntitiesInfoCarrierTest.cs
test/InfoCarrier.Core.EFCore.FunctionalTests/NotificationEntitiesInfoCarrierTest.cs
namespace InfoCarrier.Core.EFCore.FunctionalTests { using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Specification.Tests; public class NotificationEntitiesInfoCarrierTest : NotificationEntitiesTestBase<TestStore, NotificationEntitiesInfoCarrierTest.NotificationEntitiesInfoCarrierFixture> { public NotificationEntitiesInfoCarrierTest(NotificationEntitiesInfoCarrierFixture fixture) : base(fixture) { } public class NotificationEntitiesInfoCarrierFixture : NotificationEntitiesFixtureBase { private readonly InfoCarrierInMemoryTestHelper<DbContext> helper; public NotificationEntitiesInfoCarrierFixture() { this.helper = InfoCarrierInMemoryTestHelper.Create( this.OnModelCreating, (opt, _) => new DbContext(opt)); } public override DbContext CreateContext() => this.helper.CreateInfoCarrierContext(); public override TestStore CreateTestStore() => this.helper.CreateTestStore(_ => this.EnsureCreated()); } } }
mit
C#
4cfdb51ddde2eaaaeaeab375b2e586c45c1e884e
Create WriteLine.cs
jakubcze/prywatnejm
WriteLine.cs
WriteLine.cs
Console.WriteLine("aklsjdlakjsdlkajslkdasd");
mit
C#
332bf7ec400dead93f8971f2fd0d0e15344c2029
Move DMScienceData to separate class
DMagic1/Orbital-Science,Kerbas-ad-astra/Orbital-Science
Source/Scenario/DMScienceData.cs
Source/Scenario/DMScienceData.cs
#region license /* DMagic Orbital Science - DM Science Data * Object to store custom science data information * * Copyright (c) 2014, David Grandy <david.grandy@gmail.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder 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 HOLDER 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 using System; namespace DMagic.Scenario { public class DMScienceData { private string title; private float scival, science, cap, basevalue; internal DMScienceData(string T, float BV, float Scv, float Sci, float C) { title = T; basevalue = BV; scival = Scv; science = Sci; cap = C; } public DMScienceData() { } public string Title { get { return title; } } public float SciVal { get { return scival; } internal set { if (value >= 0 && value <= 1) scival = value; } } public float Science { get { return science; } internal set { if (value >= 0) science = value; } } public float BaseValue { get { return basevalue; } } public float Cap { get { return cap; } } } }
bsd-3-clause
C#
8cad007a278800176f1152428e1762fbd2bc982a
Fix culture conditional fact attribute
abock/roslyn,vslsnap/roslyn,mattscheffer/roslyn,physhi/roslyn,cston/roslyn,rgani/roslyn,TyOverby/roslyn,khellang/roslyn,MattWindsor91/roslyn,mattwar/roslyn,VSadov/roslyn,TyOverby/roslyn,orthoxerox/roslyn,mmitche/roslyn,xoofx/roslyn,akrisiun/roslyn,bkoelman/roslyn,tvand7093/roslyn,xasx/roslyn,jkotas/roslyn,gafter/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,CyrusNajmabadi/roslyn,jmarolf/roslyn,mattwar/roslyn,aelij/roslyn,AnthonyDGreen/roslyn,nguerrera/roslyn,stephentoub/roslyn,heejaechang/roslyn,AArnott/roslyn,sharwell/roslyn,KevinRansom/roslyn,zooba/roslyn,wvdd007/roslyn,VSadov/roslyn,AArnott/roslyn,eriawan/roslyn,KevinH-MS/roslyn,davkean/roslyn,jasonmalinowski/roslyn,mattwar/roslyn,bbarry/roslyn,natidea/roslyn,akrisiun/roslyn,orthoxerox/roslyn,zooba/roslyn,KiloBravoLima/roslyn,KiloBravoLima/roslyn,brettfo/roslyn,tvand7093/roslyn,jmarolf/roslyn,ErikSchierboom/roslyn,natgla/roslyn,drognanar/roslyn,basoundr/roslyn,budcribar/roslyn,natgla/roslyn,heejaechang/roslyn,heejaechang/roslyn,Pvlerick/roslyn,MatthieuMEZIL/roslyn,swaroop-sridhar/roslyn,cston/roslyn,KiloBravoLima/roslyn,OmarTawfik/roslyn,balajikris/roslyn,mgoertz-msft/roslyn,SeriaWei/roslyn,jcouv/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,aelij/roslyn,diryboy/roslyn,ljw1004/roslyn,amcasey/roslyn,ericfe-ms/roslyn,gafter/roslyn,swaroop-sridhar/roslyn,Shiney/roslyn,tmat/roslyn,AmadeusW/roslyn,robinsedlaczek/roslyn,davkean/roslyn,eriawan/roslyn,sharadagrawal/Roslyn,AArnott/roslyn,basoundr/roslyn,reaction1989/roslyn,stephentoub/roslyn,a-ctor/roslyn,eriawan/roslyn,xasx/roslyn,lorcanmooney/roslyn,amcasey/roslyn,tmeschter/roslyn,pdelvo/roslyn,paulvanbrenk/roslyn,dotnet/roslyn,srivatsn/roslyn,drognanar/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,weltkante/roslyn,kelltrick/roslyn,amcasey/roslyn,ErikSchierboom/roslyn,sharwell/roslyn,jkotas/roslyn,agocke/roslyn,mmitche/roslyn,jhendrixMSFT/roslyn,xoofx/roslyn,bbarry/roslyn,jhendrixMSFT/roslyn,shyamnamboodiripad/roslyn,mattscheffer/roslyn,mmitche/roslyn,panopticoncentral/roslyn,jcouv/roslyn,sharadagrawal/Roslyn,tvand7093/roslyn,tmeschter/roslyn,agocke/roslyn,mavasani/roslyn,tmeschter/roslyn,SeriaWei/roslyn,dpoeschl/roslyn,jkotas/roslyn,bkoelman/roslyn,ErikSchierboom/roslyn,vslsnap/roslyn,genlu/roslyn,yeaicc/roslyn,jcouv/roslyn,michalhosala/roslyn,bkoelman/roslyn,natgla/roslyn,AlekseyTs/roslyn,rgani/roslyn,shyamnamboodiripad/roslyn,panopticoncentral/roslyn,jaredpar/roslyn,CaptainHayashi/roslyn,tannergooding/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,jeffanders/roslyn,weltkante/roslyn,mgoertz-msft/roslyn,DustinCampbell/roslyn,MatthieuMEZIL/roslyn,agocke/roslyn,dpoeschl/roslyn,lorcanmooney/roslyn,Giftednewt/roslyn,kelltrick/roslyn,budcribar/roslyn,jeffanders/roslyn,leppie/roslyn,Pvlerick/roslyn,paulvanbrenk/roslyn,michalhosala/roslyn,jeffanders/roslyn,pdelvo/roslyn,ericfe-ms/roslyn,AnthonyDGreen/roslyn,robinsedlaczek/roslyn,MichalStrehovsky/roslyn,gafter/roslyn,khyperia/roslyn,a-ctor/roslyn,brettfo/roslyn,DustinCampbell/roslyn,KevinH-MS/roslyn,mavasani/roslyn,rgani/roslyn,cston/roslyn,zooba/roslyn,xasx/roslyn,CaptainHayashi/roslyn,balajikris/roslyn,panopticoncentral/roslyn,leppie/roslyn,CyrusNajmabadi/roslyn,abock/roslyn,aelij/roslyn,ljw1004/roslyn,diryboy/roslyn,srivatsn/roslyn,AnthonyDGreen/roslyn,khellang/roslyn,tmat/roslyn,khyperia/roslyn,xoofx/roslyn,weltkante/roslyn,AlekseyTs/roslyn,natidea/roslyn,DustinCampbell/roslyn,Pvlerick/roslyn,shyamnamboodiripad/roslyn,mattscheffer/roslyn,MattWindsor91/roslyn,abock/roslyn,jmarolf/roslyn,KevinRansom/roslyn,OmarTawfik/roslyn,jamesqo/roslyn,drognanar/roslyn,natidea/roslyn,kelltrick/roslyn,davkean/roslyn,genlu/roslyn,nguerrera/roslyn,Hosch250/roslyn,physhi/roslyn,physhi/roslyn,basoundr/roslyn,dpoeschl/roslyn,sharadagrawal/Roslyn,jhendrixMSFT/roslyn,lorcanmooney/roslyn,reaction1989/roslyn,srivatsn/roslyn,orthoxerox/roslyn,VSadov/roslyn,MatthieuMEZIL/roslyn,mgoertz-msft/roslyn,diryboy/roslyn,dotnet/roslyn,MichalStrehovsky/roslyn,michalhosala/roslyn,TyOverby/roslyn,KirillOsenkov/roslyn,KirillOsenkov/roslyn,tmat/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,CyrusNajmabadi/roslyn,KirillOsenkov/roslyn,ericfe-ms/roslyn,sharwell/roslyn,mavasani/roslyn,Hosch250/roslyn,akrisiun/roslyn,balajikris/roslyn,dotnet/roslyn,Hosch250/roslyn,AmadeusW/roslyn,yeaicc/roslyn,AmadeusW/roslyn,jamesqo/roslyn,AlekseyTs/roslyn,wvdd007/roslyn,ljw1004/roslyn,bartdesmet/roslyn,jaredpar/roslyn,MichalStrehovsky/roslyn,Shiney/roslyn,stephentoub/roslyn,SeriaWei/roslyn,KevinH-MS/roslyn,Giftednewt/roslyn,robinsedlaczek/roslyn,leppie/roslyn,MattWindsor91/roslyn,genlu/roslyn,khellang/roslyn,Giftednewt/roslyn,yeaicc/roslyn,paulvanbrenk/roslyn,budcribar/roslyn,vslsnap/roslyn,KevinRansom/roslyn,tannergooding/roslyn,tannergooding/roslyn,pdelvo/roslyn,MattWindsor91/roslyn,jaredpar/roslyn,nguerrera/roslyn,a-ctor/roslyn,Shiney/roslyn,reaction1989/roslyn,CaptainHayashi/roslyn,khyperia/roslyn,jasonmalinowski/roslyn,swaroop-sridhar/roslyn,brettfo/roslyn,bbarry/roslyn,jamesqo/roslyn,OmarTawfik/roslyn
src/Test/Utilities/Shared/Assert/ConditionalFactAttribute.cs
src/Test/Utilities/Shared/Assert/ConditionalFactAttribute.cs
// Copyright (c) Microsoft. 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.Text; using Xunit; namespace Roslyn.Test.Utilities { public class ConditionalFactAttribute : FactAttribute { public ConditionalFactAttribute(params Type[] skipConditions) { foreach (var skipCondition in skipConditions) { ExecutionCondition condition = (ExecutionCondition)Activator.CreateInstance(skipCondition); if (condition.ShouldSkip) { Skip = condition.SkipReason; break; } } } } public abstract class ExecutionCondition { public abstract bool ShouldSkip { get; } public abstract string SkipReason { get; } } public class x86 : ExecutionCondition { public override bool ShouldSkip => IntPtr.Size != 4; public override string SkipReason => "Target platform is not x86"; } public class HasShiftJisDefaultEncoding : ExecutionCondition { public override bool ShouldSkip => Encoding.GetEncoding(0)?.CodePage != 932; public override string SkipReason => "OS default codepage is not Shift-JIS (932)."; } public class IsEnglishLocal : ExecutionCondition { public override bool ShouldSkip => System.Globalization.CultureInfo.CurrentCulture.ToString() != "en-US"; public override string SkipReason => "Current culture is not en-US"; } public class IsRelease : ExecutionCondition { #if DEBUG public override bool ShouldSkip => true; #else public override bool ShouldSkip => false; #endif public override string SkipReason => "Not in release mode."; } }
// Copyright (c) Microsoft. 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.Text; using Xunit; namespace Roslyn.Test.Utilities { public class ConditionalFactAttribute : FactAttribute { public ConditionalFactAttribute(params Type[] skipConditions) { foreach (var skipCondition in skipConditions) { ExecutionCondition condition = (ExecutionCondition)Activator.CreateInstance(skipCondition); if (condition.ShouldSkip) { Skip = condition.SkipReason; break; } } } } public abstract class ExecutionCondition { public abstract bool ShouldSkip { get; } public abstract string SkipReason { get; } } public class x86 : ExecutionCondition { public override bool ShouldSkip => IntPtr.Size != 4; public override string SkipReason => "Target platform is not x86"; } public class HasShiftJisDefaultEncoding : ExecutionCondition { public override bool ShouldSkip => Encoding.GetEncoding(0)?.CodePage != 932; public override string SkipReason => "OS default codepage is not Shift-JIS (932)."; } public class IsEnglishLocal : ExecutionCondition { public override bool ShouldSkip => System.Globalization.CultureInfo.CurrentCulture != new System.Globalization.CultureInfo("en-US"); public override string SkipReason => "Current culture is not en-US"; } public class IsRelease : ExecutionCondition { #if DEBUG public override bool ShouldSkip => true; #else public override bool ShouldSkip => false; #endif public override string SkipReason => "Not in release mode."; } }
apache-2.0
C#
4bfdfd3360bd29826acd24d494bdf43a95532e87
Create DatabaseConnection.cs
ilgazdotcom/Arches
ArchesFramework/Arches.DataAccess/DatabaseConnection.cs
ArchesFramework/Arches.DataAccess/DatabaseConnection.cs
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; namespace Arches.DataAccess { /// <summary> /// Database Class /// </summary> public class DatabaseConnection { DataTable _dt; SqlDataAdapter _da; SqlCommand _cmd; SqlConnection _conn; /// <summary> /// Creating a new connection with the name of ConnectionString in ConnectionStrings in which web.config file. /// </summary> /// <param name="ConnectionString"></param> public DatabaseConnection(String ConnectionString) { _conn = new SqlConnection(ConfigurationManager.ConnectionStrings[ConnectionString].ConnectionString); } /// <summary> /// Creating a new connection with serverName, dbName, username, password using SqlConnection class. /// </summary> /// <param name="serverName"></param> /// <param name="dbName"></param> /// <param name="username"></param> /// <param name="password"></param> public DatabaseConnection(String serverName, String dbName, String username, String password) { _conn = new SqlConnection("server =" + serverName + "; Initial Catalog =" + dbName + "; Persist Security Info = True; User ID =" + username + "; password =" + password + ";MultipleActiveResultSets=true;"); } /// <summary> /// It executes Select queries and Views and retrieves data as DataTable. /// </summary> /// <param name="SQL"></param> /// <returns></returns> public DataTable Select(String SQL) { _da = new SqlDataAdapter(SQL, _conn); _dt = new DataTable("EntTable"); _da.Fill(_dt); return _dt; } /// <summary> /// It executes Insert, Update and Delete queries. /// </summary> /// <param name="SQL"></param> /// <returns></returns> public int ExecQuery(String SQL) { int result = 0; try { _cmd = new SqlCommand(SQL, _conn); _conn.Open(); result = _cmd.ExecuteNonQuery(); } catch { result = -1; } _conn.Close(); return result; } /// <summary> /// It executes {SPName} with {parameters} and returns int (1 successful, 0 no row affected, -1 failed, -2 process failed). /// </summary> /// <param name="SPName"></param> /// <param name="parameters"></param> /// <returns></returns> public int Execute(String SPName, SqlParameter[] parameters) { int val = 0; _cmd = new SqlCommand(SPName, _conn); _cmd.CommandType = CommandType.StoredProcedure; _conn.Open(); foreach (var param in parameters) { _cmd.Parameters.Add(param); } try { val = _cmd.ExecuteNonQuery(); } catch (Exception e) { val = -2; throw e; } _conn.Close(); return val; } /// <summary> /// It executes {SPName} with {parameters} and retrieves data as DataTable. /// </summary> /// <param name="SPName"></param> /// <param name="parameters"></param> /// <returns></returns> public DataTable ExecuteWithReturn(String SPName, SqlParameter[] parameters) { _dt = new DataTable("EntTable"); _cmd = new SqlCommand(SPName, _conn); _da = new SqlDataAdapter(); _cmd.CommandType = CommandType.StoredProcedure; //conn.Open(); foreach (var param in parameters) { _cmd.Parameters.Add(param); } _da.SelectCommand = _cmd; _da.Fill(_dt); //conn.Close(); return _dt; } } }
mpl-2.0
C#
8d7bf5d21f22da296aa347438957e424296f1178
Create BaseResponseMessage.cs
daniela1991/hack4europecontest
BaseResponseMessage.cs
BaseResponseMessage.cs
namespace Cdiscount.OpenApi.ProxyClient.Contract.Common { /// <summary> /// Base response message for open api results /// </summary> public class BaseResponseMessage { /// <summary> /// True if the operation ended successfully /// </summary> public bool OperationSuccess { get; set; } /// <summary> /// Error message /// </summary> public string ErrorMessage { get; set; } } }
mit
C#
41874841cfe53148fd4fde7c10637daaf709567c
Update ImageResizer sample, remove System.Drawing
mattchenderson/azure-webjobs-sdk-templates,Azure/azure-webjobs-sdk-templates,soninaren/azure-webjobs-sdk-templates,mattchenderson/azure-webjobs-sdk-templates,mattchenderson/azure-webjobs-sdk-templates,Azure/azure-webjobs-sdk-templates,soninaren/azure-webjobs-sdk-templates,Azure/azure-webjobs-sdk-templates,mattchenderson/azure-webjobs-sdk-templates,mattchenderson/azure-webjobs-sdk-templates,davidlai-msft/azure-webjobs-sdk-templates,davidlai-msft/azure-webjobs-sdk-templates,davidlai-msft/azure-webjobs-sdk-templates,davidlai-msft/azure-webjobs-sdk-templates,Azure/azure-webjobs-sdk-templates,mattchenderson/azure-webjobs-sdk-templates,Azure/azure-webjobs-sdk-templates,Azure/azure-webjobs-sdk-templates,davidlai-msft/azure-webjobs-sdk-templates,soninaren/azure-webjobs-sdk-templates
Templates/ImageResizer-CSharp/run.csx
Templates/ImageResizer-CSharp/run.csx
using ImageResizer; public static void Run( Stream image, // input blob, large size Stream imageSmall, Stream imageMedium) // output blobs { var imageBuilder = ImageResizer.ImageBuilder.Current; var size = imageDimensionsTable[ImageSize.Small]; imageBuilder.Build( image, imageSmall, new ResizeSettings(size.Item1, size.Item2, FitMode.Max, null), false); image.Position = 0; size = imageDimensionsTable[ImageSize.Medium]; imageBuilder.Build( image, imageMedium, new ResizeSettings(size.Item1, size.Item2, FitMode.Max, null), false); } public enum ImageSize { ExtraSmall, Small, Medium } private static Dictionary<ImageSize, Tuple<int, int>> imageDimensionsTable = new Dictionary<ImageSize, Tuple<int, int>>() { { ImageSize.ExtraSmall, Tuple.Create(320, 200) }, { ImageSize.Small, Tuple.Create(640, 400) }, { ImageSize.Medium, Tuple.Create(800, 600) } };
#r "Microsoft.WindowsAzure.Storage" #r "System.Drawing" using System; using System.Linq; using System.Threading.Tasks; using Microsoft.Azure.WebJobs.Host; using Microsoft.WindowsAzure.Storage.Blob; using System.IO; using System.Drawing; using System.Drawing.Imaging; // Use the ImageResizer NuGet to resize images based a blob trigger. // Currently, NuGet restore doesn't work for templates. To trigger a restore manually, click "View Files" // in the bottom left of the code editor. Make an edit to project.json. Once you save, you'll see "Starting NuGet restore" in the Log window. // Or, use the version based on System.Drawing by commenting out this method and using statement and uncommenting the one below. using ImageResizer; public static void Run( Stream image, // input blob, large size Stream imageSmall, Stream imageMedium) // output blobs { var imageBuilder = ImageResizer.ImageBuilder.Current; var size = imageDimensionsTable[ImageSize.Small]; imageBuilder.Build( image, imageSmall, new ResizeSettings(size.Width, size.Height, FitMode.Max, null), false); image.Position = 0; size = imageDimensionsTable[ImageSize.Medium]; imageBuilder.Build( image, imageMedium, new ResizeSettings(size.Width, size.Height, FitMode.Max, null), false); } // Image resize based on System.Drawing. Do NOT use in production! // See http://www.asprangers.com/post/2012/03/23/Why-you-should-not-use-SystemDrawing-from-ASPNET-applications.aspx // public static void Run( // Stream image, // input blob, large size // Stream imageSmall, Stream imageMedium) // output blobs // { // ScaleImage(image, imageSmall, ImageSize.Small); // ScaleImage(image, imageMedium, ImageSize.Medium); // } #region Helpers public enum ImageSize { ExtraSmall, Small, Medium } private static Dictionary<ImageSize, Size> imageDimensionsTable = new Dictionary<ImageSize, Size>() { { ImageSize.ExtraSmall, new Size(320, 200) }, { ImageSize.Small, new Size(640, 400) }, { ImageSize.Medium, new Size(800, 600) } }; private static ImageFormat ScaleImage(Stream blobInput, Stream output, ImageSize imageSize) { ImageFormat imageFormat; var size = imageDimensionsTable[imageSize]; blobInput.Position = 0; using (var img = System.Drawing.Image.FromStream(blobInput)) { var widthRatio = (double)size.Width / (double)img.Width; var heightRatio = (double)size.Height / (double)img.Height; var minAspectRatio = Math.Min(widthRatio, heightRatio); if (minAspectRatio > 1) { size.Width = img.Width; size.Width = img.Height; } else { size.Width = (int)(img.Width * minAspectRatio); size.Height = (int)(img.Height * minAspectRatio); } using (Bitmap bitmap = new Bitmap(img, size)) { bitmap.Save(output, img.RawFormat); imageFormat = img.RawFormat; } } return imageFormat; } #endregion
mit
C#
60afaf8668671c69676b4a9d702ad93ba9a158b6
Create HeadlessModeChecker.cs
felladrin/unity-scripts,felladrin/unity3d-scripts
HeadlessModeChecker.cs
HeadlessModeChecker.cs
public static class HeadlessModeChecker { public static bool IsInHeadlessMode() { var condition1 = System.Environment.CommandLine.Contains("-batchmode"); var condition2 = System.Environment.CommandLine.Contains("-nographics"); var condition3 = (UnityEngine.SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Null); return (condition1 || condition2 || condition3); } }
mit
C#
45a57f99f87492b10a209555fba07e7c1f8efac4
Create DisablePSLogging.cs
leechristensen/Random
CSharp/DisablePSLogging.cs
CSharp/DisablePSLogging.cs
/* One of the many ways one could disabled PS logging if there's prior code execution Author: Lee Christensen (@tifkin_) License: BSD 3-Clause Required Dependencies: None Optional Dependencies: None Instructions: C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe DisablePSLogging.cs /reference:c:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll DisablePSLogging.exe If you have a PS window open, you can run the following as well: $EtwProvider = [Ref].Assembly.GetType('System.Management.Automation.Tracing.PSEtwLogProvider').GetField('etwProvider','NonPublic,Static'); $EventProvider = New-Object System.Diagnostics.Eventing.EventProvider -ArgumentList @([Guid]::NewGuid()); $EtwProvider.SetValue($null, $EventProvider); */ using System; using System.Management.Automation; using System.Reflection; namespace Program { class Program { public static void Main(string[] args) { string Command = @"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Hello from PowerShell!');"; using (PowerShell PowerShellInstance = PowerShell.Create()) { var PSEtwLogProvider = PowerShellInstance.GetType().Assembly.GetType("System.Management.Automation.Tracing.PSEtwLogProvider"); if(PSEtwLogProvider != null) { var EtwProvider = PSEtwLogProvider.GetField("etwProvider", BindingFlags.NonPublic | BindingFlags.Static); var EventProvider = new System.Diagnostics.Eventing.EventProvider(Guid.NewGuid()); EtwProvider.SetValue(null, EventProvider); } PowerShellInstance.AddScript(Command); PowerShellInstance.Invoke(); } } } }
bsd-3-clause
C#
8542a5f3fe9656d83b59d58179ae9a9141dda9d2
add AssemblyInfo.cs
dotnetcore/CAP,dotnetcore/CAP,ouraspnet/cap,dotnetcore/CAP
src/DotNetCore.CAP.MongoDB/Properties/AssemblyInfo.cs
src/DotNetCore.CAP.MongoDB/Properties/AssemblyInfo.cs
// Copyright (c) .NET Core Community. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("DotNetCore.CAP.MongoDB.Test")]
mit
C#
1cf991a2d299e5cfdcab850647fc97c75d7608b4
Add missing default implementation of the IGraphOperationContext.
quartz-software/kephas,quartz-software/kephas
src/Kephas.Data/Capabilities/GraphOperationContext.cs
src/Kephas.Data/Capabilities/GraphOperationContext.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="GraphOperationContext.cs" company="Quartz Software SRL"> // Copyright (c) Quartz Software SRL. All rights reserved. // </copyright> // <summary> // Implements the graph operation context class. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Data.Capabilities { /// <summary> /// A graph operation context. /// </summary> public class GraphOperationContext : DataOperationContext, IGraphOperationContext { /// <summary> /// Initializes a new instance of the <see cref="GraphOperationContext"/> class. /// </summary> /// <param name="dataContext">Context for the data.</param> public GraphOperationContext(IDataContext dataContext) : base(dataContext) { } /// <summary> /// Gets or sets a value indicating whether the loose parts should be loaded. /// </summary> /// <value> /// <c>true</c> if loose parts should be loaded, <c>false</c> if not. /// </value> public bool LoadLooseParts { get; set; } } }
mit
C#
d950c0a2339914b7a575274cdacf614714282085
Create run.csx
he3/afunc
run.csx
run.csx
using System.Net; public static string Run(HttpRequestMessage req, TraceWriter log) { //log.Info($"C# Timer trigger function executed at: {DateTime.Now}"); string data; try { using (var client = new WebClient()) { data = client.DownloadString("https://api.ipify.org?format=json"); } } catch (Exception ex) { data = ex.ToString(); } return data; }
mit
C#
eef5b7bac3775683bec6485bd198dd35463caa36
add job project endpoints
mzrimsek/resume-site-api
Web/Controllers/JobProjectController.cs
Web/Controllers/JobProjectController.cs
using Microsoft.AspNetCore.Mvc; using Core.Interfaces; using Web.Mappers.JobProjectMappers; using Web.Models.JobProjectModels; namespace Web.Controllers { [Route("api/[controller]")] public class JobProjectController : Controller { private readonly IJobProjectRepository _jobProjectRepository; private readonly IJobRepository _jobRepository; public JobProjectController(IJobProjectRepository jobProjectRepository, IJobRepository jobRepository) { _jobProjectRepository = jobProjectRepository; _jobRepository = jobRepository; } [HttpGet] public IActionResult GetAllJobProjects() { var jobProjects = _jobProjectRepository.GetAll(); var jobProjectViews = JobProjectViewModelMapper.MapFrom(jobProjects); return Ok(jobProjectViews); } [HttpGet("{id}", Name = "GetJobProject")] public IActionResult GetJobProject(int id) { var jobProject = _jobProjectRepository.GetById(id); if (jobProject == null) { return NotFound(); } var jobProjectViewModel = JobProjectViewModelMapper.MapFrom(jobProject); return Ok(jobProjectViewModel); } [HttpGet("job/{jobId}")] public IActionResult GetJobProjectsForJob(int jobId) { var job = _jobRepository.GetById(jobId); if (job == null) { return NotFound(); } var jobProjects = _jobProjectRepository.GetByJobId(jobId); var jobProjectViews = JobProjectViewModelMapper.MapFrom(jobProjects); return Ok(jobProjectViews); } [HttpPost] public IActionResult AddJobProject([FromBody] AddUpdateJobProjectViewModel jobProject) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var domainModel = JobProjectDomainModelMapper.MapFrom(jobProject); var savedJobProject = _jobProjectRepository.Save(domainModel); var jobProjectViewModel = JobProjectViewModelMapper.MapFrom(savedJobProject); return CreatedAtRoute("GetJobProject", new { id = jobProjectViewModel.Id }, jobProjectViewModel); } [HttpDelete("{id}")] public IActionResult DeleteJobProject(int id) { var jobProject = _jobProjectRepository.GetById(id); if (jobProject == null) { return NotFound(); } _jobProjectRepository.Delete(id); return NoContent(); } [HttpPut("{id}")] public IActionResult UpdateJobProject(int id, [FromBody] AddUpdateJobProjectViewModel jobProject) { var foundJobProject = _jobProjectRepository.GetById(id); if (foundJobProject == null) { return NotFound(); } if (!ModelState.IsValid) { return BadRequest(ModelState); } var viewModel = JobProjectViewModelMapper.MapFrom(id, jobProject); var domainModel = JobProjectDomainModelMapper.MapFrom(viewModel); var updatedDomainModel = _jobProjectRepository.Update(domainModel); var updatedViewModel = JobProjectViewModelMapper.MapFrom(updatedDomainModel); return Ok(updatedViewModel); } } }
mit
C#
718d6484ddc2c18e4b269d69d1d60e719e8f0532
Add missing file for Map tests
LambdaSix/InfiniMap,LambdaSix/InfiniMap
InfiniMap.Test/MapTests.cs
InfiniMap.Test/MapTests.cs
using System; using NUnit.Framework; namespace InfiniMap.Test { [TestFixture] public class MapTests { private Map createMap(int chunkSize, int chunksToFill) { var map = new Map(chunkSize, chunkSize); for (int x = 0; x <= (chunksToFill * chunkSize-1); x++) { for (int y = 0; y <= (chunksToFill * chunkSize-1); y++) { map[x, y].BlockId = (ushort) x; map[x, y].BlockMeta = (ushort) y; } } return map; } [Test] public void FreesChunksProperly() { var map = createMap(16, 1); var dictionaryCount = map.Chunks.Count; map.UnloadArea(0, 0, 1); Assert.That(dictionaryCount > map.Chunks.Count); } } }
mit
C#
d97217e4454705fca28bae73aa87579d3298c16b
add ConsoleExporter extension methods (#468)
open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet
src/OpenTelemetry.Exporter.Console/TracerBuilderExtensions.cs
src/OpenTelemetry.Exporter.Console/TracerBuilderExtensions.cs
// <copyright file="TracerBuilderExtensions.cs" company="OpenTelemetry Authors"> // Copyright 2018, OpenTelemetry Authors // // 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. // </copyright> using System; using OpenTelemetry.Trace.Configuration; using OpenTelemetry.Trace.Export; namespace OpenTelemetry.Exporter.Console { public static class TracerBuilderExtensions { /// <summary> /// Registers a Console exporter. /// </summary> /// <param name="builder">Trace builder to use.</param> /// <param name="configure">Exporter configuration options.</param> /// <returns>The instance of <see cref="TracerBuilder"/> to chain the calls.</returns> public static TracerBuilder UseConsole(this TracerBuilder builder, Action<ConsoleExporterOptions> configure) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (configure == null) { throw new ArgumentNullException(nameof(configure)); } var options = new ConsoleExporterOptions(); configure(options); return builder.AddProcessorPipeline(b => b .SetExporter(new ConsoleExporter(options)) .SetExportingProcessor(e => new SimpleSpanProcessor(e))); } /// <summary> /// Registers Console exporter. /// </summary> /// <param name="builder">Trace builder to use.</param> /// <param name="configure">Exporter configuration options.</param> /// <param name="processorConfigure">Span processor configuration.</param> /// <returns>The instance of <see cref="TracerBuilder"/> to chain the calls.</returns> public static TracerBuilder UseConsole(this TracerBuilder builder, Action<ConsoleExporterOptions> configure, Action<SpanProcessorPipelineBuilder> processorConfigure) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (configure == null) { throw new ArgumentNullException(nameof(configure)); } if (processorConfigure == null) { throw new ArgumentNullException(nameof(processorConfigure)); } var options = new ConsoleExporterOptions(); configure(options); return builder.AddProcessorPipeline(b => { b.SetExporter(new ConsoleExporter(options)); processorConfigure.Invoke(b); }); } } }
apache-2.0
C#
64d5f5fa0aaee90a304a006ed5fb17e42eb34c1a
Add Ed25519 formatting tests
ektrah/nsec
tests/Formatting/Ed25519Tests.cs
tests/Formatting/Ed25519Tests.cs
using System; using System.Text; using NSec.Cryptography; using NSec.Cryptography.Formatting; using Xunit; namespace NSec.Tests.Formatting { public static class Ed25519Tests { private static readonly byte[] s_oid = { 0x2B, 0x65, 0x70 }; [Fact] public static void PkixPrivateKey() { var a = new Ed25519(); var b = Utilities.RandomBytes.Slice(0, a.PrivateKeySize); using (var k = Key.Import(a, b, KeyBlobFormat.RawPrivateKey, KeyFlags.AllowExport)) { var blob = new ReadOnlySpan<byte>(k.Export(KeyBlobFormat.PkixPrivateKey)); var reader = new Asn1Reader(ref blob); reader.BeginSequence(); Assert.Equal(0, reader.Integer32()); reader.BeginSequence(); Assert.Equal(s_oid, reader.ObjectIdentifier().ToArray()); reader.End(); var edPrivateKey = reader.OctetString(); reader.End(); Assert.True(reader.SuccessComplete); var reader2 = new Asn1Reader(ref edPrivateKey); Assert.Equal(b.ToArray(), reader2.OctetString().ToArray()); Assert.True(reader2.SuccessComplete); } } [Fact] public static void PkixPrivateKeyText() { var a = new Ed25519(); var b = Utilities.RandomBytes.Slice(0, a.PrivateKeySize); using (var k = Key.Import(a, b, KeyBlobFormat.RawPrivateKey, KeyFlags.AllowExport)) { var expected = Encoding.UTF8.GetBytes( "-----BEGIN PRIVATE KEY-----\r\n" + Convert.ToBase64String(k.Export(KeyBlobFormat.PkixPrivateKey)) + "\r\n" + "-----END PRIVATE KEY-----\r\n"); var actual = k.Export(KeyBlobFormat.PkixPrivateKeyText); Assert.Equal(expected, actual); } } [Fact] public static void PkixPublicKey() { var a = new Ed25519(); var b = Utilities.RandomBytes.Slice(0, a.PrivateKeySize); using (var k = Key.Import(a, b, KeyBlobFormat.RawPrivateKey)) { var publicKeyBytes = k.Export(KeyBlobFormat.RawPublicKey); var blob = new ReadOnlySpan<byte>(k.Export(KeyBlobFormat.PkixPublicKey)); var reader = new Asn1Reader(ref blob); reader.BeginSequence(); reader.BeginSequence(); Assert.Equal(s_oid, reader.ObjectIdentifier().ToArray()); reader.End(); Assert.Equal(publicKeyBytes, reader.BitString().ToArray()); reader.End(); Assert.True(reader.SuccessComplete); } } [Fact] public static void PkixPublicKeyText() { var a = new Ed25519(); var b = Utilities.RandomBytes.Slice(0, a.PrivateKeySize); using (var k = Key.Import(a, b, KeyBlobFormat.RawPrivateKey)) { var expected = Encoding.UTF8.GetBytes( "-----BEGIN PUBLIC KEY-----\r\n" + Convert.ToBase64String(k.Export(KeyBlobFormat.PkixPublicKey)) + "\r\n" + "-----END PUBLIC KEY-----\r\n"); var actual = k.Export(KeyBlobFormat.PkixPublicKeyText); Assert.Equal(expected, actual); } } } }
mit
C#
101b778139adb4fc64202a486cda1b805b37f5b1
Create Problem102.cs
fireheadmx/ProjectEuler,fireheadmx/ProjectEuler
Problems/Problem102.cs
Problems/Problem102.cs
using System; using System.Collections.Generic; using System.IO; namespace ProjectEuler.Problems { class Problem102 { private double sign(Point p1, Point p2, Point p3) { return (p1.X - p3.X) * (p2.Y - p3.Y) - (p2.X - p3.X) * (p1.Y - p3.Y); } private bool PointInTriangle(Point pt, Point v1, Point v2, Point v3) { bool b1, b2, b3; b1 = sign(pt, v1, v2) < 0.0; b2 = sign(pt, v2, v3) < 0.0; b3 = sign(pt, v3, v1) < 0.0; return ((b1 == b2) && (b2 == b3)); } public void Run() { int[][] input = new int[1000][]; using (StreamReader sr = new StreamReader("Input/p102_triangles.txt")) { string[] str_input; int i = 0; do { str_input = sr.ReadLine().Split(','); input[i] = new int[6]; input[i][0] = int.Parse(str_input[0]); input[i][1] = int.Parse(str_input[1]); input[i][2] = int.Parse(str_input[2]); input[i][3] = int.Parse(str_input[3]); input[i][4] = int.Parse(str_input[4]); input[i][5] = int.Parse(str_input[5]); i++; } while (i < 1000); } int count = 0; for (int i = 0; i < 1000; i++) { if(PointInTriangle(new Point(0, 0), new Point(input[i][0], input[i][1]),new Point(input[i][2], input[i][3]),new Point(input[i][4], input[i][5]))) { count++; } } Console.WriteLine(count); Console.ReadLine(); } } struct Point { public double X, Y; public Point(double x1, double y1) { this.X = x1; this.Y = y1; } } }
mit
C#
a155126afdbac4983b8fe593abbceb7d8db069ab
remove redundant module init
TomGillen/GitVersion,RaphHaddad/GitVersion,pascalberger/GitVersion,onovotny/GitVersion,JakeGinnivan/GitVersion,orjan/GitVersion,DanielRose/GitVersion,alexhardwicke/GitVersion,dpurge/GitVersion,alexhardwicke/GitVersion,openkas/GitVersion,RaphHaddad/GitVersion,TomGillen/GitVersion,GeertvanHorrik/GitVersion,asbjornu/GitVersion,ermshiperete/GitVersion,dazinator/GitVersion,ermshiperete/GitVersion,JakeGinnivan/GitVersion,GeertvanHorrik/GitVersion,MarkZuber/GitVersion,distantcam/GitVersion,onovotny/GitVersion,ParticularLabs/GitVersion,anobleperson/GitVersion,gep13/GitVersion,dpurge/GitVersion,GitTools/GitVersion,anobleperson/GitVersion,MarkZuber/GitVersion,Kantis/GitVersion,Kantis/GitVersion,anobleperson/GitVersion,ParticularLabs/GitVersion,Philo/GitVersion,FireHost/GitVersion,pascalberger/GitVersion,orjan/GitVersion,ermshiperete/GitVersion,asbjornu/GitVersion,gep13/GitVersion,pascalberger/GitVersion,JakeGinnivan/GitVersion,openkas/GitVersion,DanielRose/GitVersion,dpurge/GitVersion,FireHost/GitVersion,DanielRose/GitVersion,onovotny/GitVersion,ermshiperete/GitVersion,distantcam/GitVersion,dazinator/GitVersion,JakeGinnivan/GitVersion,Philo/GitVersion,dpurge/GitVersion,Kantis/GitVersion,GitTools/GitVersion
Tests/ModuleInitializer.cs
Tests/ModuleInitializer.cs
using System; using System.Diagnostics; using System.IO; using GitVersion; /// <summary> /// Used by the ModuleInit. All code inside the Initialize method is ran as soon as the assembly is loaded. /// </summary> public static class ModuleInitializer { /// <summary> /// Initializes the module. /// </summary> public static void Initialize() { Logger.WriteInfo = s => Trace.WriteLine(s); Logger.WriteError = s => Trace.WriteLine(s); Logger.WriteWarning = s => Trace.WriteLine(s); } }
using System; using System.Diagnostics; using System.IO; using GitVersion; /// <summary> /// Used by the ModuleInit. All code inside the Initialize method is ran as soon as the assembly is loaded. /// </summary> public static class ModuleInitializer { /// <summary> /// Initializes the module. /// </summary> public static void Initialize() { Logger.WriteInfo = s => Trace.WriteLine(s); var nativeBinaries = Path.Combine(AssemblyLocation.CurrentDirectory(), "NativeBinaries", GetProcessorArchitecture()); var existingPath = Environment.GetEnvironmentVariable("PATH"); if (existingPath.Contains(nativeBinaries)) { return; } var newPath = string.Concat(nativeBinaries, Path.PathSeparator, existingPath); Environment.SetEnvironmentVariable("PATH", newPath); } static string GetProcessorArchitecture() { if (Environment.Is64BitProcess) { return "amd64"; } return "x86"; } }
mit
C#
a2d01f972ffef082f0bd6032942c010b7728ce62
Add a direction enumeration
wrightg42/tron,It423/tron
Tron/Tron/Car/Direction.cs
Tron/Tron/Car/Direction.cs
// Direction.cs // <copyright file="Direction.cs"> This code is protected under the MIT License. </copyright> namespace Tron { /// <summary> /// An enumeration to represent the possible directions a car can travel. /// </summary> public enum Direction { /// <summary> /// The car is moving up. /// </summary> Up = 0, /// <summary> /// The car is moving right. /// </summary> Right = 1, /// <summary> /// The car is moving down. /// </summary> Down = 2, /// <summary> /// The car is moving left. /// </summary> Left = 3 } }
mit
C#
fbef533534e9ca4d1b6744816212cc7a1feb7cee
add mouse-assign configure.
fin-alice/Mystique,azyobuzin/Mystique
Inscribe/Configuration/Settings/MouseAssignProperty.cs
Inscribe/Configuration/Settings/MouseAssignProperty.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Inscribe.Configuration.Settings { /// <summary> /// マウスアサイン /// </summary> public class MouseAssignProperty { private ActionSet<ReplyMouseActionCandidates> replyActionSet; public ActionSet<ReplyMouseActionCandidates> ReplyActionSet { get { return replyActionSet ?? new ActionSet<ReplyMouseActionCandidates>(); } set { replyActionSet = value; } } private ActionSet<FavMouseActionCandidates> favActionSet; public ActionSet<FavMouseActionCandidates> FavActionSet { get { return favActionSet ?? new ActionSet<FavMouseActionCandidates>(); } set { favActionSet = value; } } private ActionSet<RetweetMouseActionCandidates> retweetActionSet; public ActionSet<RetweetMouseActionCandidates> RetweetActionSet { get { return retweetActionSet ?? new ActionSet<RetweetMouseActionCandidates>(); } set { retweetActionSet = value; } } private ActionSet<UnofficialRetweetQuoteMouseActionCandidates> unofficalRetweetActionSet; public ActionSet<UnofficialRetweetQuoteMouseActionCandidates> UnofficalRetweetActionSet { get { return unofficalRetweetActionSet ?? new ActionSet<UnofficialRetweetQuoteMouseActionCandidates>(); } set { unofficalRetweetActionSet = value; } } private ActionSet<UnofficialRetweetQuoteMouseActionCandidates> quoteTweetActionSet; public ActionSet<UnofficialRetweetQuoteMouseActionCandidates> QuoteTweetActionSet { get { return quoteTweetActionSet ?? new ActionSet<UnofficialRetweetQuoteMouseActionCandidates>(); } set { quoteTweetActionSet = value; } } } public class ActionSet<T> { public ActionDescription<T> NoneKeyAction { get; set; } public ActionDescription<T> ControlKeyAction { get; set; } public ActionDescription<T> AltKeyAction { get; set; } public ActionDescription<T> ShiftKeyAction { get; set; } } public class ActionDescription<T> { public T Action { get; set; } public string ActionArgs { get; set; } } public enum ReplyMouseActionCandidates { Reply, ReplyFromSpecificAccount, ReplyImmediately, } public enum FavMouseActionCandidates { FavToggle, FavAdd, FavRemove, FavToggleWithSpecificAccount, FavAddWithSpecificAccount, FavRemoveWithSpecificAccount, FavAddAll, FavRemoveAll, } public enum RetweetMouseActionCandidates { RetweetToggle, RetweetAdd, RetweetRemove, RetweetToggleWithSpecificAccount, RetweetAddWithSpecificAccount, RetweetRemoveWithSpecificAccount, RetweetAddAll, RetweetRemoveAll, } public enum UnofficialRetweetQuoteMouseActionCandidates { DefaultUnofficialRetweet, DefaultQuoteTweet, CustomUnofficialRetweet, CustomQuoteTweet, CustomUnofficialRetweetImmediately, CustomQuoteTweetImmediately, } }
mit
C#
f4397a1ee99ac78aa68a619d146b8bef6aba2119
Refactor var in Session to be consistent with rest of the plugins
Glimpse/Glimpse,flcdrg/Glimpse,elkingtonmcb/Glimpse,elkingtonmcb/Glimpse,SusanaL/Glimpse,sorenhl/Glimpse,dudzon/Glimpse,Glimpse/Glimpse,sorenhl/Glimpse,Glimpse/Glimpse,paynecrl97/Glimpse,rho24/Glimpse,rho24/Glimpse,paynecrl97/Glimpse,SusanaL/Glimpse,rho24/Glimpse,dudzon/Glimpse,paynecrl97/Glimpse,paynecrl97/Glimpse,rho24/Glimpse,flcdrg/Glimpse,gabrielweyer/Glimpse,gabrielweyer/Glimpse,codevlabs/Glimpse,codevlabs/Glimpse,SusanaL/Glimpse,sorenhl/Glimpse,codevlabs/Glimpse,elkingtonmcb/Glimpse,gabrielweyer/Glimpse,flcdrg/Glimpse,dudzon/Glimpse
source/Glimpse.AspNet/SerializationConverter/SessionModelConverter.cs
source/Glimpse.AspNet/SerializationConverter/SessionModelConverter.cs
using System.Collections.Generic; using Glimpse.AspNet.Extensions; using Glimpse.AspNet.Model; using Glimpse.Core.Extensibility; using Glimpse.Core.Plugin.Assist; namespace Glimpse.AspNet.SerializationConverter { public class SessionModelConverter : SerializationConverter<List<SessionModel>> { public override object Convert(List<SessionModel> obj) { var root = new TabSection("Key", "Value", "Type"); foreach (var item in obj) { root.AddRow().Column(item.Key).Column(item.Value).Column(item.Type); } return root.Build(); } } }
using System.Collections.Generic; using Glimpse.AspNet.Extensions; using Glimpse.AspNet.Model; using Glimpse.Core.Extensibility; namespace Glimpse.AspNet.SerializationConverter { public class SessionModelConverter : SerializationConverter<List<SessionModel>> { public override object Convert(List<SessionModel> obj) { var result = new List<object[]> { new[] { "Key", "Value", "Type" } }; foreach (var item in obj) { result.Add(new[] { item.Key, item.Value, item.Type }); } return result; } } }
apache-2.0
C#
95ba0401715417eed1a7388991ab061fa97b995f
add RegexHelper
jwldnr/VisualLinter
VisualLinter/Helpers/RegexHelper.cs
VisualLinter/Helpers/RegexHelper.cs
using System.Text.RegularExpressions; namespace jwldnr.VisualLinter.Helpers { internal static class RegexHelper { private const string Pattern = "^[\t ]*$|[^\\s\\/\\\\\\(\\)\"\':,\\.;<>~!@#\\$%\\^&\\*\\|\\+=\\[\\]\\{\\}`\\?\\-…]+"; internal static Match GetWord(string value) => Regex.Match(value, Pattern); } }
mit
C#
3b7106fed53cfd46da449727ae0dec6e5acc9c58
add Upgrade_20211027_UpdateNugets
signumsoftware/framework,signumsoftware/framework
Signum.Upgrade/Upgrades/Upgrade_20211027_UpdateNugets.cs
Signum.Upgrade/Upgrades/Upgrade_20211027_UpdateNugets.cs
using Signum.Utilities; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Signum.Upgrade.Upgrades { class Upgrade_20211027_UpdateNugets : CodeUpgradeBase { public override string Description => "Update nugets"; public override void Execute(UpgradeContext uctx) { uctx.ForeachCodeFile(@"*.csproj", file => { file.UpdateNugetReference("Azure.Storage.Files.Shares", "12.8.0"); file.UpdateNugetReference("Microsoft.TypeScript.MSBuild", "4.4.4"); file.UpdateNugetReference("Microsoft.NET.Test.Sdk", "17.0.0"); file.UpdateNugetReference("Selenium.WebDriver.ChromeDriver", "95.0.4638.1700"); }); } } }
mit
C#
9094691c492894c7a1129de16d988d5d85be4d44
Add unit tests for SingleDisposable.
StephenCleary/AsyncEx.Tasks
test/UnitTests/SingleDisposableUnitTests.cs
test/UnitTests/SingleDisposableUnitTests.cs
using System; using System.Threading.Tasks; using Nito.AsyncEx; using System.Linq; using System.Threading; using System.Diagnostics.CodeAnalysis; using Xunit; namespace UnitTests { public class SingleDisposableUnitTests { [Fact] public void ConstructedWithNullContext_DisposeIsANoop() { var disposable = new DelegateSingleDisposable<object>(null, _ => { Assert.False(true, "Callback invoked"); }); disposable.Dispose(); } [Fact] public void ConstructedWithContext_DisposeReceivesThatContext() { var providedContext = new object(); object seenContext = null; var disposable = new DelegateSingleDisposable<object>(providedContext, context => { seenContext = context; }); disposable.Dispose(); Assert.Same(providedContext, seenContext); } [Fact] public void DisposeOnlyCalledOnce() { var counter = 0; var disposable = new DelegateSingleDisposable<object>(new object(), _ => { ++counter; }); disposable.Dispose(); disposable.Dispose(); Assert.Equal(1, counter); } private sealed class DelegateSingleDisposable<T>: SingleDisposable<T> where T : class { private readonly Action<T> _callback; public DelegateSingleDisposable(T context, Action<T> callback) : base(context) { _callback = callback; } protected override void Dispose(T context) { _callback(context); } } } }
mit
C#
f8ca742e1dca9a25a493beba420c86902a99e242
Create Receiver.cs
Pharap/SpengyUtils
Examples/RemoteHangar/Receiver.cs
Examples/RemoteHangar/Receiver.cs
// Instructions: // 1. Group all hangar doors together in a group called "Hangar" // 2. Put this script in a progammable block // 3. Assign that programmable block to an Antenna void OpenHangarGroup(string groupName) { var hangarGroup = GridTerminalSystem.GetBlockGroupWithName(groupName); var doors = new List<IMyAirtightHangarDoor>(); hangarGroup.GetBlocksOfType(doors); for(int i = 0; i < doors.Count; ++i) { var door = doors[i]; door.ApplyAction("Open_On"); } } void CloseHangarGroup(string groupName) { var hangarGroup = GridTerminalSystem.GetBlockGroupWithName(groupName); var doors = new List<IMyAirtightHangarDoor>(); hangarGroup.GetBlocksOfType(doors); for(int i = 0; i < doors.Count; ++i) { var door = doors[i]; door.ApplyAction("Open_Off"); } } public void Main(string argument) { if (argument == "OpenHangar") { OpenHangarGroup("Hangar"); } if (argument == "CloseHangar") { CloseHangarGroup("Hangar"); } }
apache-2.0
C#
a38c33841a8b4cb46f07acc16ad5bdc79b635a58
add test scene wiki container
peppy/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,ppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu-new,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu
osu.Game.Tests/Visual/Online/TestSceneWikiMarkdownContainer.cs
osu.Game.Tests/Visual/Online/TestSceneWikiMarkdownContainer.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Overlays; using osu.Game.Overlays.Wiki.Markdown; namespace osu.Game.Tests.Visual.Online { public class TestSceneWikiMarkdownContainer : OsuTestScene { private WikiMarkdownContainer markdownContainer; [Cached] private readonly OverlayColourProvider overlayColour = new OverlayColourProvider(OverlayColourScheme.Orange); [SetUp] public void Setup() => Schedule(() => { Children = new Drawable[] { new Box { Colour = overlayColour.Background5, RelativeSizeAxes = Axes.Both, }, new BasicScrollContainer { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding(20), Child = markdownContainer = new WikiMarkdownContainer() { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, } } }; }); [Test] public void TestLink() { AddStep("set current path", () => markdownContainer.CurrentPath = "Article_styling_criteria/"); AddStep("set '/wiki/Main_Page''", () => markdownContainer.Text = "[wiki main page](/wiki/Main_Page)"); AddStep("set '../FAQ''", () => markdownContainer.Text = "[FAQ](../FAQ)"); AddStep("set './Writing''", () => markdownContainer.Text = "[wiki writing guidline](./Writing)"); AddStep("set 'Formatting''", () => markdownContainer.Text = "[wiki formatting guidline](Formatting)"); } } }
mit
C#
85a137f96e946dd05e4267c6822f6bc3053185f0
add Q174
txchen/localleet
csharp/Q174_DungeonGame.cs
csharp/Q174_DungeonGame.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; // The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess. // // The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately. // // Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers). // // In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. // // // Write a function to determine the knight's minimum initial health so that he is able to rescue the princess. // // For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN. // // -2 (K) -3 3 // -5 -10 1 // 10 30 -5 (P) // // Notes: // // The knight's health has no upper bound. // Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned. // https://leetcode.com/problems/dungeon-game/ namespace LocalLeet { public class Q174 { public int CalculateMinimumHP(int[][] dungeon) { int row = dungeon.Length; int col = dungeon[0].Length; int[][] answer = new int[row][]; for (int i = 0; i < row; i++) { answer[i] = new int[col]; } answer[row - 1][col - 1] = dungeon[row - 1][col - 1] > 0 ? 1 : 1 - dungeon[row - 1][col - 1]; // right edge for (int r = row -2; r >=0; r--) { answer[r][col - 1] = answer[r + 1][col - 1] - dungeon[r][col - 1]; answer[r][col - 1] = Math.Max(1, answer[r][col-1]); } // bottom edge for (int c = col - 2; c >= 0; c--) { answer[row - 1][c] = answer[row - 1][c + 1] - dungeon[row - 1][c]; answer[row - 1][c] = Math.Max(1, answer[row - 1][c]); } for (int c = col - 2; c >= 0; c--) { for (int r = row - 2; r >= 0; r--) { answer[r][c] = Math.Min(answer[r + 1][c], answer[r][c + 1]) - dungeon[r][c]; answer[r][c] = Math.Max(1, answer[r][c]); } } return answer[0][0]; } [Fact] public void Q174_DungeonGame() { TestHelper.Run(input => CalculateMinimumHP(input.EntireInput.ToIntArrayArray()).ToString()); } } }
mit
C#
f0c299f4dc45e833fdfa89252e3d2c5f2445c0b8
update GetNextIPAddress signature
shimingsg/corefx,zhenlan/corefx,ViktorHofer/corefx,zhenlan/corefx,zhenlan/corefx,Jiayili1/corefx,ptoonen/corefx,zhenlan/corefx,shimingsg/corefx,ericstj/corefx,ptoonen/corefx,mmitche/corefx,Jiayili1/corefx,shimingsg/corefx,Jiayili1/corefx,ericstj/corefx,mmitche/corefx,ptoonen/corefx,ViktorHofer/corefx,zhenlan/corefx,ericstj/corefx,Jiayili1/corefx,ravimeda/corefx,ptoonen/corefx,shimingsg/corefx,ravimeda/corefx,zhenlan/corefx,ViktorHofer/corefx,ravimeda/corefx,mmitche/corefx,ericstj/corefx,ptoonen/corefx,ravimeda/corefx,ericstj/corefx,shimingsg/corefx,ravimeda/corefx,Jiayili1/corefx,zhenlan/corefx,ravimeda/corefx,ericstj/corefx,wtgodbe/corefx,wtgodbe/corefx,Jiayili1/corefx,wtgodbe/corefx,wtgodbe/corefx,ravimeda/corefx,mmitche/corefx,BrennanConroy/corefx,ViktorHofer/corefx,mmitche/corefx,wtgodbe/corefx,mmitche/corefx,ptoonen/corefx,BrennanConroy/corefx,wtgodbe/corefx,ViktorHofer/corefx,mmitche/corefx,ViktorHofer/corefx,shimingsg/corefx,wtgodbe/corefx,shimingsg/corefx,ptoonen/corefx,ViktorHofer/corefx,ericstj/corefx,Jiayili1/corefx,BrennanConroy/corefx
src/Common/src/Interop/Unix/System.Native/Interop.HostEntry.cs
src/Common/src/Interop/Unix/System.Native/Interop.HostEntry.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; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Sys { internal const int NI_MAXHOST = 1025; internal const int NI_MAXSERV = 32; internal enum GetAddrInfoErrorFlags : int { EAI_AGAIN = 1, // Temporary failure in name resolution. EAI_BADFLAGS = 2, // Invalid value for `ai_flags' field. EAI_FAIL = 3, // Non-recoverable failure in name resolution. EAI_FAMILY = 4, // 'ai_family' not supported. EAI_NONAME = 5, // NAME or SERVICE is unknown. EAI_BADARG = 6, // One or more input arguments were invalid. EAI_NOMORE = 7, // No more entries are present in the list. } internal enum GetHostErrorCodes : int { HOST_NOT_FOUND = 1, TRY_AGAIN = 2, NO_RECOVERY = 3, NO_DATA = 4, NO_ADDRESS = NO_DATA, } //opaque structure to maintain consistency with native function signature internal unsafe struct addrinfo { } [StructLayout(LayoutKind.Sequential)] internal unsafe struct HostEntry { internal byte* CanonicalName; // Canonical Name of the Host internal byte** Aliases; // List of aliases for the host internal addrinfo* AddressListHandle; // Handle for socket address list internal int IPAddressCount; // Number of IP addresses in the list } [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetHostEntryForName")] internal static extern unsafe int GetHostEntryForName(string address, HostEntry* entry); [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetNextIPAddress")] internal static extern unsafe int GetNextIPAddress(HostEntry* entry, addrinfo** addressListHandle, IPAddress* endPoint); [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FreeHostEntry")] internal static extern unsafe void FreeHostEntry(HostEntry* entry); } }
// 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; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Sys { internal const int NI_MAXHOST = 1025; internal const int NI_MAXSERV = 32; internal enum GetAddrInfoErrorFlags : int { EAI_AGAIN = 1, // Temporary failure in name resolution. EAI_BADFLAGS = 2, // Invalid value for `ai_flags' field. EAI_FAIL = 3, // Non-recoverable failure in name resolution. EAI_FAMILY = 4, // 'ai_family' not supported. EAI_NONAME = 5, // NAME or SERVICE is unknown. EAI_BADARG = 6, // One or more input arguments were invalid. EAI_NOMORE = 7, // No more entries are present in the list. } internal enum GetHostErrorCodes : int { HOST_NOT_FOUND = 1, TRY_AGAIN = 2, NO_RECOVERY = 3, NO_DATA = 4, NO_ADDRESS = NO_DATA, } [StructLayout(LayoutKind.Sequential)] internal unsafe struct HostEntry { internal byte* CanonicalName; // Canonical Name of the Host internal byte** Aliases; // List of aliases for the host internal void* AddressListHandle; // Handle for socket address list internal int IPAddressCount; // Number of IP addresses in the list private int _handleType; // Opaque handle type information. } [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetHostEntryForName")] internal static extern unsafe int GetHostEntryForName(string address, HostEntry* entry); [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetNextIPAddress")] internal static extern unsafe int GetNextIPAddress(HostEntry* entry, void** addressListHandle, IPAddress* endPoint); [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FreeHostEntry")] internal static extern unsafe void FreeHostEntry(HostEntry* entry); } }
mit
C#
38c5f51c18f78b137d03e1fcb70a22f559cadef2
test to help display proper type usage for issue #211
starckgates/elasticsearch-net,UdiBen/elasticsearch-net,mac2000/elasticsearch-net,joehmchan/elasticsearch-net,SeanKilleen/elasticsearch-net,RossLieberman/NEST,tkirill/elasticsearch-net,robertlyson/elasticsearch-net,ststeiger/elasticsearch-net,adam-mccoy/elasticsearch-net,Grastveit/NEST,azubanov/elasticsearch-net,joehmchan/elasticsearch-net,ststeiger/elasticsearch-net,mac2000/elasticsearch-net,amyzheng424/elasticsearch-net,adam-mccoy/elasticsearch-net,faisal00813/elasticsearch-net,ststeiger/elasticsearch-net,starckgates/elasticsearch-net,DavidSSL/elasticsearch-net,gayancc/elasticsearch-net,CSGOpenSource/elasticsearch-net,UdiBen/elasticsearch-net,CSGOpenSource/elasticsearch-net,KodrAus/elasticsearch-net,robrich/elasticsearch-net,azubanov/elasticsearch-net,CSGOpenSource/elasticsearch-net,LeoYao/elasticsearch-net,LeoYao/elasticsearch-net,abibell/elasticsearch-net,cstlaurent/elasticsearch-net,wawrzyn/elasticsearch-net,TheFireCookie/elasticsearch-net,NickCraver/NEST,DavidSSL/elasticsearch-net,wawrzyn/elasticsearch-net,NickCraver/NEST,LeoYao/elasticsearch-net,Grastveit/NEST,robertlyson/elasticsearch-net,KodrAus/elasticsearch-net,alanprot/elasticsearch-net,tkirill/elasticsearch-net,abibell/elasticsearch-net,faisal00813/elasticsearch-net,gayancc/elasticsearch-net,alanprot/elasticsearch-net,TheFireCookie/elasticsearch-net,joehmchan/elasticsearch-net,RossLieberman/NEST,mac2000/elasticsearch-net,cstlaurent/elasticsearch-net,gayancc/elasticsearch-net,junlapong/elasticsearch-net,azubanov/elasticsearch-net,amyzheng424/elasticsearch-net,wawrzyn/elasticsearch-net,tkirill/elasticsearch-net,faisal00813/elasticsearch-net,abibell/elasticsearch-net,alanprot/elasticsearch-net,geofeedia/elasticsearch-net,robrich/elasticsearch-net,jonyadamit/elasticsearch-net,geofeedia/elasticsearch-net,robertlyson/elasticsearch-net,robrich/elasticsearch-net,cstlaurent/elasticsearch-net,elastic/elasticsearch-net,starckgates/elasticsearch-net,SeanKilleen/elasticsearch-net,SeanKilleen/elasticsearch-net,junlapong/elasticsearch-net,DavidSSL/elasticsearch-net,geofeedia/elasticsearch-net,TheFireCookie/elasticsearch-net,NickCraver/NEST,junlapong/elasticsearch-net,RossLieberman/NEST,jonyadamit/elasticsearch-net,alanprot/elasticsearch-net,elastic/elasticsearch-net,jonyadamit/elasticsearch-net,UdiBen/elasticsearch-net,Grastveit/NEST,amyzheng424/elasticsearch-net,KodrAus/elasticsearch-net,adam-mccoy/elasticsearch-net
src/Nest.Tests.Integration/Reproduce/IndexDefaultValueTests.cs
src/Nest.Tests.Integration/Reproduce/IndexDefaultValueTests.cs
using System; using System.Collections.Generic; using System.Linq; using Nest.Tests.MockData; using Nest.Tests.MockData.Domain; using NUnit.Framework; using System.Diagnostics; using FluentAssertions; namespace Nest.Tests.Integration.Reproduce { /// <summary> /// tests to reproduce reported errors /// </summary> [TestFixture] public class ReproduceTests : IntegrationTests { public class Post { public int Id { get; set; } public string Name { get; set; } } /// <summary> /// https://github.com/Mpdreamz/NEST/issues/211 /// </summary> [Test] public void NoSearchResults() { //test teardown will delete defaultindex_* indices //process id makes it so we can run these tests concurrently using NCrunch var index = ElasticsearchConfiguration.DefaultIndex + "_posts_" + Process.GetCurrentProcess().Id.ToString(); var list = new List<Post>(); for (int i = 0; i < 10; i++) { var post = new Post() { Id = 12 + i, Name = "tdd" }; list.Add(post); } this._client.IndexMany(list, index, "post"); //indexing is NRT so issueing a search //right after indexing might not return the documents just yet. this._client.Refresh(); var results = this._client.Search<Post>(s => s .Index(index) //by default nest will infer the typename for Post //by lowercasing it and pluralizing it //since we said the type is "post" we now have to explicitly //pass it to elasticsearch. .Type("post") .MatchAll() ); results.IsValid.Should().Be(true); results.Total.Should().BeGreaterThan(0); } } }
apache-2.0
C#
c909907a2aabffcf3d2eb63b3c969a895c046dd7
Create WebRequestWithCookie.cs
cpoDesign/web.tools
WebRequests/Examples/WebRequestWithCookie.cs
WebRequests/Examples/WebRequestWithCookie.cs
// SourceForExample http://stackoverflow.com/questions/10263082/how-to-pass-post-parameters-to-asp-net-web-request string email = "YOUR EMAIL"; string password = "YOUR PASSWORD"; string URLAuth = "https://accounts.craigslist.org/login"; string postString = string.Format("inputEmailHandle={0}&name={1}&inputPassword={2}", email, password); const string contentType = "application/x-www-form-urlencoded"; System.Net.ServicePointManager.Expect100Continue = false; CookieContainer cookies = new CookieContainer(); HttpWebRequest webRequest = WebRequest.Create(URLAuth) as HttpWebRequest; webRequest.Method = "POST"; webRequest.ContentType = contentType; webRequest.CookieContainer = cookies; webRequest.ContentLength = postString.Length; webRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1"; webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; webRequest.Referer = "https://accounts.craigslist.org"; StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream()); requestWriter.Write(postString); requestWriter.Close(); StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()); string responseData = responseReader.ReadToEnd(); responseReader.Close(); webRequest.GetResponse().Close();
mit
C#
07343a749ce4a67a530ef052c10ae604c42d78d6
Add SleepAsync
lerthe61/Snippets,lerthe61/Snippets
dotNet/Tasks/SleepAsync.cs
dotNet/Tasks/SleepAsync.cs
public Task SleepAsync(int millisecondsTimeout) { TaskCompletionSource<bool> tcs = null; var t = new Timer(delegate { tcs.TrySetResult(true); }, null, -1, -1); tcs = new TaskCompletionSource<bool>(t); t.Change(millisecondsTimeout, -1); return tcs.Task; }
unlicense
C#
7183a1f3aee32c87842f486b5947ddba982bc7c4
Update website and copyright year.
TheCloudlessSky/Harbour.RedisSessionStateStore,TaskStack/Harbour.RedisSessionStateStore,TheCloudlessSky/Harbour.RedisSessionStateStore,piotr-g/Harbour.RedisSessionStateStore,kharabasz/Harbour.RedisSessionStateStore,huyuezheng/Harbour.RedisSessionStateStore
src/CommonAssemblyInfo.cs
src/CommonAssemblyInfo.cs
using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyProduct("Harbour.RedisSessionStateStore")] [assembly: AssemblyCompany("http://github.com/TheCloudlessSky/Harbour.RedisSessionStateStore")] [assembly: AssemblyCopyright("Copyright © Harbour Inc. 2014")] [assembly: AssemblyDescription("An ASP.NET Redis SessionStateStoreProvider.")] [assembly: ComVisible(false)]
using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyProduct("Harbour.RedisSessionStateStore")] [assembly: AssemblyCompany("http://www.adrianphinney.com")] [assembly: AssemblyCopyright("Copyright © Harbour Inc. 2012")] [assembly: AssemblyDescription("An ASP.NET Redis SessionStateStoreProvider.")] [assembly: ComVisible(false)]
mit
C#
aa07482cbb2f48a193e9afd1dda3ccbea2140170
Add OsuMarkdownLinkText
ppy/osu,peppy/osu-new,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu
osu.Game/Graphics/Containers/Markdown/OsuMarkdownLinkText.cs
osu.Game/Graphics/Containers/Markdown/OsuMarkdownLinkText.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 Markdig.Syntax.Inlines; using osu.Framework.Allocation; using osu.Framework.Graphics.Containers.Markdown; using osu.Framework.Graphics.Sprites; using osu.Game.Overlays; namespace osu.Game.Graphics.Containers.Markdown { public class OsuMarkdownLinkText : MarkdownLinkText { private SpriteText spriteText; public OsuMarkdownLinkText(string text, LinkInline linkInline) : base(text, linkInline) { } [BackgroundDependencyLoader] private void load(OverlayColourProvider colourProvider) { spriteText.Colour = colourProvider.Light2; } public override SpriteText CreateSpriteText() { return spriteText = base.CreateSpriteText(); } } }
mit
C#
33e91286534fa9c146025ce1ffadb0695419a740
Create KnightsTour.cs
burnsba/scratch,burnsba/scratch,burnsba/scratch
KnightsTour.cs
KnightsTour.cs
public class Point { public int X { get; set; } public int Y { get; set; } public override bool Equals(Object obj) { Point p = obj as Point; if (Object.ReferenceEquals(null, p) || Object.ReferenceEquals(this, obj)) { return Object.ReferenceEquals(this, obj); } return X == p.X && Y == p.Y; } public static bool operator ==(Point p1, Point p2) { if (Object.ReferenceEquals(null, p1)) { return Object.ReferenceEquals(p1, p2); } return p1.Equals(p2); } public static bool operator !=(Point p1, Point p2) { return !(p1 == p2); } public override int GetHashCode() { return X ^ ~Y; } public override string ToString() { return $"{{{X}, {Y}}}"; } } public static class ApplicationSettings { public const int BoardX = 8; public const int BoardY = 8; } public class PotentialMove { public Point Position { get; set; } public List<Point> Available { get; set; } } public static bool IsWithinBoard(Point p) { if (Object.ReferenceEquals(null, p)) { return false; } return p.X >= 0 && p.X < ApplicationSettings.BoardX && p.Y >= 0 && p.Y < ApplicationSettings.BoardY; } public static List<Point> GetKnightMoves(Point startingPoint) { var results = new List<Point>(); if (Object.ReferenceEquals(null, startingPoint)) { return results; } Point p = null; p = new Point() { X = startingPoint.X + 2, Y = startingPoint.Y + 1 }; if (IsWithinBoard(p)) { results.Add(p); } p = new Point() { X = startingPoint.X + 2, Y = startingPoint.Y - 1 }; if (IsWithinBoard(p)) { results.Add(p); } p = new Point() { X = startingPoint.X - 2, Y = startingPoint.Y + 1 }; if (IsWithinBoard(p)) { results.Add(p); } p = new Point() { X = startingPoint.X - 2, Y = startingPoint.Y - 1 }; if (IsWithinBoard(p)) { results.Add(p); } p = new Point() { X = startingPoint.X + 1, Y = startingPoint.Y + 2 }; if (IsWithinBoard(p)) { results.Add(p); } p = new Point() { X = startingPoint.X + 1, Y = startingPoint.Y - 2 }; if (IsWithinBoard(p)) { results.Add(p); } p = new Point() { X = startingPoint.X - 1, Y = startingPoint.Y + 2 }; if (IsWithinBoard(p)) { results.Add(p); } p = new Point() { X = startingPoint.X - 1, Y = startingPoint.Y - 2 }; if (IsWithinBoard(p)) { results.Add(p); } return results; } public static void Visit() { var startingPoint = new Point() { X = 1, Y = 1 }; var startingMoves = GetKnightMoves(startingPoint); var currentPotentialMove = new PotentialMove() { Position = startingPoint, Available = startingMoves }; var visited = new List<Point>(); var travelPath = new List<PotentialMove>(); travelPath.Add(currentPotentialMove); visited.Add(startingPoint); while(true) { if (travelPath.Count < 1 || travelPath.Count > 63) { break; } var potential = travelPath.Last(); Point nextMove = null; while (Object.ReferenceEquals(null, nextMove) && potential.Available.Count > 0) { nextMove = potential.Available.First(); potential.Available.RemoveAt(0); if (visited.Contains(nextMove)) { nextMove = null; } } if (Object.ReferenceEquals(null, nextMove)) { visited.Remove(potential.Position); travelPath.RemoveAt(travelPath.Count - 1); continue; } var nextAvailable = GetKnightMoves(nextMove); var nextPotential = new PotentialMove() { Position = nextMove, Available = nextAvailable }; visited.Add(nextMove); travelPath.Add(nextPotential); } Console.WriteLine(String.Join(",", visited.Select(x => x.ToString()))); }
apache-2.0
C#