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 |
|---|---|---|---|---|---|---|---|---|
d35a0b83759ed1e1f7729b4c2a7b7b87ae29a4cc | Add `InstitutionNumber` and `TransitNumber` on `ChargePaymentMethodDetailsAcssDebit` | stripe/stripe-dotnet | src/Stripe.net/Entities/Charges/ChargePaymentMethodDetails/ChargePaymentMethodDetailsAcssDebit.cs | src/Stripe.net/Entities/Charges/ChargePaymentMethodDetails/ChargePaymentMethodDetailsAcssDebit.cs | namespace Stripe
{
using Newtonsoft.Json;
using Stripe.Infrastructure;
public class ChargePaymentMethodDetailsAcssDebit : StripeEntity<ChargePaymentMethodDetailsAcssDebit>
{
/// <summary>
/// Uniquely identifies this particular bank account. You can use this attribute to check
/// whether two bank accounts are the same.
/// </summary>
[JsonProperty("fingerprint")]
public string Fingerprint { get; set; }
/// <summary>
/// Institution number of the bank account.
/// </summary>
[JsonProperty("institution_number")]
public string InstitutionNumber { get; set; }
/// <summary>
/// Last four digits of the bank account number.
/// </summary>
[JsonProperty("last4")]
public string Last4 { get; set; }
/// <summary>
/// Transit number of the bank account.
/// </summary>
[JsonProperty("transit_number")]
public string TransitNumber { get; set; }
}
}
| namespace Stripe
{
using Newtonsoft.Json;
using Stripe.Infrastructure;
public class ChargePaymentMethodDetailsAcssDebit : StripeEntity<ChargePaymentMethodDetailsAcssDebit>
{
[JsonProperty("fingerprint")]
public string Fingerprint { get; set; }
[JsonProperty("last4")]
public string Last4 { get; set; }
}
}
| apache-2.0 | C# |
616d4fe011c4b383d98b335c227e4acd57c9197e | Add ResolvedTreeExperiments | riganti/dotvvm-samples-academy,riganti/dotvvm-samples-academy,riganti/dotvvm-samples-academy | test/DotvvmAcademy.Validation.Dothtml.Experiments/ResolvedTreeExperiments.cs | test/DotvvmAcademy.Validation.Dothtml.Experiments/ResolvedTreeExperiments.cs | using DotVVM.Framework.Compilation.ControlTree;
using DotVVM.Framework.Compilation.Parser.Dothtml.Parser;
using DotVVM.Framework.Compilation.Parser.Dothtml.Tokenizer;
using DotVVM.Framework.Configuration;
using DotVVM.Framework.Security;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DotvvmAcademy.Validation.Dothtml.Experiments
{
[TestClass]
public class ResolvedTreeExperiments
{
public const string Sample = @"
@viewModel System.Object
@service System.IServiceProvider
@import L=System.Linq
<!doctype html>
<html>
<body>
<dot:Literal Text=""SAMPLE"" />
</body>
</html>";
[TestMethod]
public void BasicCompilerExperiment()
{
var tokenizer = new DothtmlTokenizer();
var parser = new DothtmlParser();
var config = DotvvmConfiguration.CreateDefault(c => c.AddSingleton<IViewModelProtector, FakeProtector>());
var resolver = config.ServiceProvider.GetRequiredService<IControlTreeResolver>();
tokenizer.Tokenize(Sample);
var rootNode = parser.Parse(tokenizer.Tokens);
var root = resolver.ResolveTree(rootNode, "Test.dothtml");
}
[TestMethod]
public void HtmlAttributesExperiment()
{
var tokenizer = new DothtmlTokenizer();
var parser = new DothtmlParser();
var config = DotvvmConfiguration.CreateDefault(c => c.AddSingleton<IViewModelProtector, FakeProtector>());
var resolver = config.ServiceProvider.GetRequiredService<IControlTreeResolver>();
tokenizer.Tokenize("<meta charset=\"utf-8\" \\>");
var rootNode = parser.Parse(tokenizer.Tokens);
var root = resolver.ResolveTree(rootNode, "Test.dothtml");
}
}
}
| using DotVVM.Framework.Compilation.ControlTree;
using DotVVM.Framework.Compilation.Parser.Dothtml.Parser;
using DotVVM.Framework.Compilation.Parser.Dothtml.Tokenizer;
using DotVVM.Framework.Configuration;
using DotVVM.Framework.Security;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DotvvmAcademy.Validation.Dothtml.Experiments
{
[TestClass]
public class ResolvedTreeExperiments
{
public const string Sample = @"
@viewModel System.Object
@service System.IServiceProvider
@import L=System.Linq
<!doctype html>
<html>
<body>
<dot:Literal Text=""SAMPLE"" />
</body>
</html>";
[TestMethod]
public void BasicCompilerExperiment()
{
var tokenizer = new DothtmlTokenizer();
var parser = new DothtmlParser();
var config = DotvvmConfiguration.CreateDefault(c => c.AddSingleton<IViewModelProtector, FakeProtector>());
var resolver = config.ServiceProvider.GetRequiredService<IControlTreeResolver>();
tokenizer.Tokenize(Sample);
var rootNode = parser.Parse(tokenizer.Tokens);
var root = resolver.ResolveTree(rootNode, "Test.dothtml");
}
}
}
| apache-2.0 | C# |
13044d93bb3cf279bab1e9219b520e5145b9d6c5 | test renamed | Softlr/selenium-webdriver-extensions,Softlr/selenium-webdriver-extensions,Softlr/Selenium.WebDriver.Extensions,RaYell/selenium-webdriver-extensions | test/Selenium.WebDriver.Extensions.Tests/Extensions/StringExtensionsTests.cs | test/Selenium.WebDriver.Extensions.Tests/Extensions/StringExtensionsTests.cs | namespace OpenQA.Selenium.Tests.Extensions
{
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using OpenQA.Selenium.Extensions;
using Xunit;
[Trait("Category", "Unit")]
[ExcludeFromCodeCoverage]
public class StringExtensionsTests
{
public static IEnumerable<object[]> TestData
{
get
{
yield return new object[] { null, true };
yield return new object[] { string.Empty, true };
yield return new object[] { "\r\n\t", true };
yield return new object[] { " a ", false };
}
}
[Theory]
[MemberData("TestData")]
[SuppressMessage("ReSharper", "InvokeAsExtensionMethod")]
public void ShouldDetectNullsAndWhiteSpaces(string testValue, bool expected)
{
// Given
// When
var result = StringExtensions.IsNullOrWhiteSpace(testValue);
// Then
Assert.Equal(expected, result);
}
}
}
| namespace OpenQA.Selenium.Tests.Extensions
{
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using OpenQA.Selenium.Extensions;
using Xunit;
[Trait("Category", "Unit")]
[ExcludeFromCodeCoverage]
public class StringExtensionsTests
{
public static IEnumerable<object[]> TestData
{
get
{
yield return new object[] { null, true };
yield return new object[] { string.Empty, true };
yield return new object[] { "\r\n\t", true };
yield return new object[] { " a ", false };
}
}
[Theory]
[MemberData("TestData")]
[SuppressMessage("ReSharper", "InvokeAsExtensionMethod")]
public void ShouldCreateSelector(string testValue, bool expected)
{
// Given
// When
var result = StringExtensions.IsNullOrWhiteSpace(testValue);
// Then
Assert.Equal(expected, result);
}
}
}
| apache-2.0 | C# |
9fd4477dab5a0c16b70a7f0f545ea852e5053bf8 | make test more precise | SimonCropp/CaptureSnippets | Tests/CachedSnippetExtractorTests.cs | Tests/CachedSnippetExtractorTests.cs | using System.Diagnostics;
using System.IO;
using CaptureSnippets;
using NUnit.Framework;
using ObjectApproval;
[TestFixture]
public class CachedSnippetExtractorTests
{
[Test]
public void SecondReadShouldBeFasterThanFirstRead()
{
var directory = @"scenarios\".ToCurrentDirectory();
//warmup
new CachedSnippetExtractor(s => null, s => true, s => s.EndsWith(".cs")).FromDirectory(directory);
var cachedSnippetExtractor = new CachedSnippetExtractor(s => null, s => true, s => s.EndsWith(".cs"));
var firstRun = Stopwatch.StartNew();
cachedSnippetExtractor.FromDirectory(directory);
firstRun.Stop();
var secondRun = Stopwatch.StartNew();
cachedSnippetExtractor.FromDirectory(directory);
secondRun.Stop();
Assert.That(secondRun.ElapsedTicks, Is.LessThan(firstRun.ElapsedTicks));
Debug.WriteLine(firstRun.ElapsedTicks);
Debug.WriteLine(secondRun.ElapsedTicks);
}
[Test]
public void AssertOutput()
{
var directory = @"scenarios\".ToCurrentDirectory();
var cachedSnippetExtractor = new CachedSnippetExtractor(s => null, s => true, s => s.EndsWith(".cs"));
var readSnippets = cachedSnippetExtractor.FromDirectory(directory);
ObjectApprover.VerifyWithJson(readSnippets,s => s.Replace(directory.Replace("\\","\\\\"), ""));
}
} | using System.Diagnostics;
using System.IO;
using CaptureSnippets;
using NUnit.Framework;
using ObjectApproval;
[TestFixture]
public class CachedSnippetExtractorTests
{
[Test]
public void SecondReadShouldBeFasterThanFirstRead()
{
var directory = @"scenarios\".ToCurrentDirectory();
var cachedSnippetExtractor = new CachedSnippetExtractor(s => null, s => true, s => s.EndsWith(".cs"));
var firstRun = Stopwatch.StartNew();
cachedSnippetExtractor.FromDirectory(directory);
firstRun.Stop();
var secondRun = Stopwatch.StartNew();
cachedSnippetExtractor.FromDirectory(directory);
secondRun.Stop();
Assert.That(secondRun.ElapsedMilliseconds, Is.LessThan(firstRun.ElapsedMilliseconds));
Debug.WriteLine(firstRun.ElapsedMilliseconds);
Debug.WriteLine(secondRun.ElapsedMilliseconds);
}
[Test]
public void AssertOutput()
{
var directory = @"scenarios\".ToCurrentDirectory();
var cachedSnippetExtractor = new CachedSnippetExtractor(s => null, s => true, s => s.EndsWith(".cs"));
var readSnippets = cachedSnippetExtractor.FromDirectory(directory);
ObjectApprover.VerifyWithJson(readSnippets,s => s.Replace(directory.Replace("\\","\\\\"), ""));
}
} | mit | C# |
03facbe15a7b05f2a8049ee5a27118949a9aa66e | remove count property for Com-interface | diadoc/diadocsdk-csharp,halex2005/diadocsdk-csharp,ichaynikov/diadocsdk-csharp,diadoc/diadocsdk-csharp,basmus/diadocsdk-csharp,ichaynikov/diadocsdk-csharp,halex2005/diadocsdk-csharp,basmus/diadocsdk-csharp | src/DocumentsFilter.cs | src/DocumentsFilter.cs | using System;
using System.Runtime.InteropServices;
namespace Diadoc.Api
{
[ComVisible(true)]
[Guid("40EE5B76-5D17-424F-9AAD-7FC3334921B8")]
public interface IDocumentsFilter
{
string BoxId { get; set; }
string FilterCategory { get; set; }
string CounteragentBoxId { get; set; }
string FromDocumentDate { get; set; }
string ToDocumentDate { get; set; }
string DepartmentId { get; set; }
string DocumentNumber { get; set; }
string ToDepartmentId { get; set; }
bool ExcludeSubdepartments { get; set; }
string SortDirection { get; set; }
string AfterIndexKey { get; set; }
}
[ComVisible(true)]
[ProgId("Diadoc.Api.DocumentsFilter")]
[Guid("FEFDFA6F-E393-4D6E-B29B-6B35C0DEB1DA")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IDocumentsFilter))]
public class DocumentsFilter : SafeComObject, IDocumentsFilter
{
public string BoxId { get; set; }
public string FilterCategory { get; set; }
public string CounteragentBoxId { get; set; }
public DateTime? TimestampFrom { get; set; }
public DateTime? TimestampTo { get; set; }
public string FromDocumentDate { get; set; }
public string ToDocumentDate { get; set; }
public string DepartmentId { get; set; }
public string DocumentNumber { get; set; }
public string ToDepartmentId { get; set; }
public bool ExcludeSubdepartments { get; set; }
public string SortDirection { get; set; }
public string AfterIndexKey { get; set; }
public int? Count { get; set; }
}
} | using System;
using System.Runtime.InteropServices;
namespace Diadoc.Api
{
[ComVisible(true)]
[Guid("40EE5B76-5D17-424F-9AAD-7FC3334921B8")]
public interface IDocumentsFilter
{
string BoxId { get; set; }
string FilterCategory { get; set; }
string CounteragentBoxId { get; set; }
string FromDocumentDate { get; set; }
string ToDocumentDate { get; set; }
string DepartmentId { get; set; }
string DocumentNumber { get; set; }
string ToDepartmentId { get; set; }
bool ExcludeSubdepartments { get; set; }
string SortDirection { get; set; }
string AfterIndexKey { get; set; }
int? Count { get; set; }
}
[ComVisible(true)]
[ProgId("Diadoc.Api.DocumentsFilter")]
[Guid("FEFDFA6F-E393-4D6E-B29B-6B35C0DEB1DA")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IDocumentsFilter))]
public class DocumentsFilter : SafeComObject, IDocumentsFilter
{
public string BoxId { get; set; }
public string FilterCategory { get; set; }
public string CounteragentBoxId { get; set; }
public DateTime? TimestampFrom { get; set; }
public DateTime? TimestampTo { get; set; }
public string FromDocumentDate { get; set; }
public string ToDocumentDate { get; set; }
public string DepartmentId { get; set; }
public string DocumentNumber { get; set; }
public string ToDepartmentId { get; set; }
public bool ExcludeSubdepartments { get; set; }
public string SortDirection { get; set; }
public string AfterIndexKey { get; set; }
public int? Count { get; set; }
}
} | mit | C# |
e907f44dd03a86fb98be7473f10aea105af24ab2 | Fix Resolver.Resolve(TypeRef) | picrap/dnlib,jorik041/dnlib,kiootic/dnlib,Arthur2e5/dnlib,0xd4d/dnlib,ilkerhalil/dnlib,modulexcite/dnlib,yck1509/dnlib,ZixiangBoy/dnlib | src/DotNet/Resolver.cs | src/DotNet/Resolver.cs | using dot10.DotNet.MD;
namespace dot10.DotNet {
/// <summary>
/// Resolves types, methods, fields
/// </summary>
public class Resolver : IResolver {
IAssemblyResolver assemblyResolver;
/// <summary>
/// Constructor
/// </summary>
/// <param name="assemblyResolver">The assembly resolver</param>
public Resolver(IAssemblyResolver assemblyResolver) {
this.assemblyResolver = assemblyResolver;
}
/// <inheritdoc/>
public TypeDef Resolve(TypeRef typeRef) {
if (typeRef == null)
return null;
var nonNestedTypeRef = TypeRef.GetNonNestedTypeRef(typeRef);
if (nonNestedTypeRef == null)
return null;
var asmRef = nonNestedTypeRef.ResolutionScope as AssemblyRef;
if (asmRef != null) {
var asm = assemblyResolver.Resolve(asmRef, nonNestedTypeRef.OwnerModule);
return asm == null ? null : asm.Find(typeRef);
}
var moduleDef = nonNestedTypeRef.ResolutionScope as ModuleDef;
if (moduleDef != null)
return moduleDef.Find(typeRef);
var moduleRef = nonNestedTypeRef.ResolutionScope as ModuleRef;
if (moduleRef != null) {
if (nonNestedTypeRef.OwnerModule == null)
return null;
if (new SigComparer().Equals(moduleRef, nonNestedTypeRef.OwnerModule))
return nonNestedTypeRef.OwnerModule.Find(typeRef);
if (nonNestedTypeRef.OwnerModule.Assembly == null)
return null;
var resolvedModule = nonNestedTypeRef.OwnerModule.Assembly.FindModule(moduleRef.Name);
return resolvedModule == null ? null : resolvedModule.Find(typeRef);
}
return null;
}
/// <inheritdoc/>
public IMemberForwarded Resolve(MemberRef memberRef) {
var declaringType = GetDeclaringType(memberRef);
return declaringType == null ? null : declaringType.Resolve(memberRef);
}
TypeDef GetDeclaringType(MemberRef memberRef) {
if (memberRef == null)
return null;
var parent = memberRef.Class;
if (parent == null)
return null;
var declaringTypeDef = parent as TypeDef;
if (declaringTypeDef != null)
return declaringTypeDef;
var declaringTypeRef = parent as TypeRef;
if (declaringTypeRef != null)
return Resolve(declaringTypeRef);
// A module ref is used to reference the global type of a module in the same
// assembly as the current module.
var moduleRef = parent as ModuleRef;
if (moduleRef != null) {
var ownerModule = memberRef.OwnerModule;
if (ownerModule == null)
return null;
TypeDef globalType = null;
if (new SigComparer(0).Equals(ownerModule, moduleRef))
globalType = ownerModule.GlobalType;
if (globalType == null && ownerModule.Assembly != null) {
var moduleDef = ownerModule.Assembly.FindModule(moduleRef.Name);
if (moduleDef != null)
globalType = moduleDef.GlobalType;
}
return globalType;
}
// parent is Method or TypeSpec
return null;
}
}
}
| using dot10.DotNet.MD;
namespace dot10.DotNet {
/// <summary>
/// Resolves types, methods, fields
/// </summary>
public class Resolver : IResolver {
IAssemblyResolver assemblyResolver;
/// <summary>
/// Constructor
/// </summary>
/// <param name="assemblyResolver">The assembly resolver</param>
public Resolver(IAssemblyResolver assemblyResolver) {
this.assemblyResolver = assemblyResolver;
}
/// <inheritdoc/>
public TypeDef Resolve(TypeRef typeRef) {
if (typeRef == null)
return null;
var nonNestedTypeRef = TypeRef.GetNonNestedTypeRef(typeRef);
if (nonNestedTypeRef != null) {
var moduleDef = nonNestedTypeRef.ResolutionScope as ModuleDef;
if (moduleDef != null)
return moduleDef.Find(typeRef);
var moduleRef = nonNestedTypeRef.ResolutionScope as ModuleRef;
if (moduleRef != null && nonNestedTypeRef.OwnerModule != null) {
if (new SigComparer().Equals(moduleRef, nonNestedTypeRef.OwnerModule))
return nonNestedTypeRef.OwnerModule.Find(typeRef);
if (nonNestedTypeRef.OwnerModule.Assembly != null)
return nonNestedTypeRef.OwnerModule.Assembly.Find(typeRef);
}
}
var asm = assemblyResolver.Resolve(typeRef.DefinitionAssembly, typeRef.OwnerModule);
return asm == null ? null : asm.Find(typeRef);
}
/// <inheritdoc/>
public IMemberForwarded Resolve(MemberRef memberRef) {
var declaringType = GetDeclaringType(memberRef);
return declaringType == null ? null : declaringType.Resolve(memberRef);
}
TypeDef GetDeclaringType(MemberRef memberRef) {
if (memberRef == null)
return null;
var parent = memberRef.Class;
if (parent == null)
return null;
var declaringTypeDef = parent as TypeDef;
if (declaringTypeDef != null)
return declaringTypeDef;
var declaringTypeRef = parent as TypeRef;
if (declaringTypeRef != null)
return Resolve(declaringTypeRef);
// A module ref is used to reference the global type of a module in the same
// assembly as the current module.
var moduleRef = parent as ModuleRef;
if (moduleRef != null) {
var ownerModule = memberRef.OwnerModule;
if (ownerModule == null)
return null;
TypeDef globalType = null;
if (new SigComparer(0).Equals(ownerModule, moduleRef))
globalType = ownerModule.GlobalType;
if (globalType == null && ownerModule.Assembly != null) {
var moduleDef = ownerModule.Assembly.FindModule(moduleRef.Name);
if (moduleDef != null)
globalType = moduleDef.GlobalType;
}
return globalType;
}
// parent is Method or TypeSpec
return null;
}
}
}
| mit | C# |
846d94a39507cd7d3eb6577deecb8adbbdee4a97 | Add WordListWord object | Soulfire86/wordnik-net | src/Models/WordList.cs | src/Models/WordList.cs | using System;
using System.ComponentModel;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace wordnik_net.Models
{
public class WordList
{
[DefaultValue(0)]
public long Id { get; set; }
public string Permalink { get; set; }
public string Name { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime? CreatedAt { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime? UpdatedAt { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime? LastActivityAt { get; set; }
public string UserName { get; set; }
public long UserId { get; set; }
public string Description { get; set; }
public long NumberWordsInList { get; set; }
public string Type { get; set; }
}
public class WordListWord
{
public long Id { get; set; }
public string Word { get; set; }
public string Username { get; set; }
public long UserId { get; set; }
public DateTime CreatedAt { get; set; }
public long NumberCommentsOnWord { get; set; }
public long NumberLists { get; set; }
}
} | using System;
using System.ComponentModel;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace wordnik_net.Models
{
public class WordList
{
[DefaultValue(0)]
public long Id { get; set; }
public string Permalink { get; set; }
public string Name { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime? CreatedAt { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime? UpdatedAt { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime? LastActivityAt { get; set; }
public string UserName { get; set; }
public long UserId { get; set; }
public string Description { get; set; }
public long NumberWordsInList { get; set; }
public string Type { get; set; }
}
} | mit | C# |
7d301a351c618f5ed107c6a9f5f1bc2836cdec8f | Add voice option to ui test | glasseyes/libpalaso,marksvc/libpalaso,tombogle/libpalaso,glasseyes/libpalaso,tombogle/libpalaso,gtryus/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,ermshiperete/libpalaso,mccarthyrb/libpalaso,marksvc/libpalaso,ddaspit/libpalaso,chrisvire/libpalaso,andrew-polk/libpalaso,chrisvire/libpalaso,sillsdev/libpalaso,JohnThomson/libpalaso,hatton/libpalaso,ddaspit/libpalaso,marksvc/libpalaso,ermshiperete/libpalaso,tombogle/libpalaso,andrew-polk/libpalaso,gmartin7/libpalaso,glasseyes/libpalaso,gmartin7/libpalaso,gtryus/libpalaso,ddaspit/libpalaso,ermshiperete/libpalaso,andrew-polk/libpalaso,glasseyes/libpalaso,gtryus/libpalaso,darcywong00/libpalaso,mccarthyrb/libpalaso,ermshiperete/libpalaso,darcywong00/libpalaso,chrisvire/libpalaso,gmartin7/libpalaso,ddaspit/libpalaso,sillsdev/libpalaso,tombogle/libpalaso,sillsdev/libpalaso,hatton/libpalaso,gtryus/libpalaso,darcywong00/libpalaso,JohnThomson/libpalaso,mccarthyrb/libpalaso,hatton/libpalaso,andrew-polk/libpalaso,JohnThomson/libpalaso,mccarthyrb/libpalaso,chrisvire/libpalaso,hatton/libpalaso,JohnThomson/libpalaso | PalasoUIWindowsForms.Tests/WritingSystems/UITests.cs | PalasoUIWindowsForms.Tests/WritingSystems/UITests.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using NUnit.Framework;
using Palaso.TestUtilities;
using Palaso.UI.WindowsForms.WritingSystems;
using Palaso.UI.WindowsForms.WritingSystems.WSTree;
using Palaso.WritingSystems;
namespace PalasoUIWindowsForms.Tests.WritingSystems
{
[TestFixture]
public class UITests
{
[Test, Ignore("By hand only")]
public void WritingSystemSetupDialog()
{
using (var folder = new TemporaryFolder("WS-Test"))
{
var dlg = new WritingSystemSetupDialog(folder.Path);
dlg.WritingSystemSuggestor.SuggestVoice = true;
dlg.ShowDialog();
}
}
[Test, Ignore("By hand only")]
public void WritingSystemSetupViewWithComboAttached()
{
using (var folder = new TemporaryFolder("WS-Test"))
{
var f = new Form();
f.Size=new Size(800,600);
var model = new WritingSystemSetupModel(new LdmlInFolderWritingSystemStore(folder.Path));
var v = new WritingSystemSetupView(model);
var combo = new WSPickerUsingComboBox(model);
f.Controls.Add(combo);
f.Controls.Add(v);
f.ShowDialog();
}
}
}
} | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using NUnit.Framework;
using Palaso.TestUtilities;
using Palaso.UI.WindowsForms.WritingSystems;
using Palaso.WritingSystems;
namespace PalasoUIWindowsForms.Tests.WritingSystems
{
[TestFixture]
public class UITests
{
[Test, Ignore("By hand only")]
public void WritingSystemSetupDialog()
{
using (var folder = new TemporaryFolder("WS-Test"))
{
new WritingSystemSetupDialog(folder.Path).ShowDialog();
}
}
[Test, Ignore("By hand only")]
public void WritingSystemSetupViewWithComboAttached()
{
using (var folder = new TemporaryFolder("WS-Test"))
{
var f = new Form();
f.Size=new Size(800,600);
var model = new WritingSystemSetupModel(new LdmlInFolderWritingSystemStore(folder.Path));
var v = new WritingSystemSetupView(model);
var combo = new WSPickerUsingComboBox(model);
f.Controls.Add(combo);
f.Controls.Add(v);
f.ShowDialog();
}
}
}
} | mit | C# |
62fa23e83527e4dc52de1e4852a39713e12db2d6 | Change EventType property type | florinciubotariu/RiotSharp,Shidesu/RiotSharp,Oucema90/RiotSharp,jono-90/RiotSharp,Challengermode/RiotSharp,frederickrogan/RiotSharp,BenFradet/RiotSharp,JanOuborny/RiotSharp,oisindoherty/RiotSharp,aktai0/RiotSharp | RiotSharp/TournamentEndpoint/TournamentLobbyEvent.cs | RiotSharp/TournamentEndpoint/TournamentLobbyEvent.cs | using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace RiotSharp.TournamentEndpoint
{
/// <summary>
/// Represents a tournament lobby event in the Riot tournament API.
/// </summary>
public class TournamentLobbyEvent
{
internal TournamentLobbyEvent()
{
}
/// <summary>
/// The type of event that was triggered
/// </summary>
[JsonProperty("eventType")]
[JsonConverter(typeof(StringEnumConverter))]
public LobbyEvent EventType { get; set; }
/// <summary>
/// The summoner that triggered the event
/// </summary>
[JsonProperty("summonerId")]
public long SummonerId { get; set; }
/// <summary>
/// Timestamp from the event
/// </summary>
[JsonProperty("timestamp")]
[JsonConverter(typeof(DateTimeConverterFromStringTimestamp))]
public DateTime Timestamp { get; set; }
}
public enum LobbyEvent
{
PracticeGameCreatedEvent,
PlayerJoinedGameEvent,
PlayerSwitchedTeamEvent,
PlayerQuitGameEvent,
ChampSelectStartedEvent,
GameAllocationStartedEvent,
GameAllocatedToLsmEvent
}
}
| using System;
using Newtonsoft.Json;
namespace RiotSharp.TournamentEndpoint
{
/// <summary>
/// Represents a tournament lobby event in the Riot tournament API.
/// </summary>
public class TournamentLobbyEvent
{
internal TournamentLobbyEvent()
{
}
/// <summary>
/// The type of event that was triggered
/// </summary>
[JsonProperty("eventType")]
public string EventType { get; set; }
/// <summary>
/// The summoner that triggered the event
/// </summary>
[JsonProperty("summonerId")]
public long SummonerId { get; set; }
/// <summary>
/// Timestamp from the event
/// </summary>
[JsonProperty("timestamp")]
[JsonConverter(typeof(DateTimeConverterFromStringTimestamp))]
public DateTime Timestamp { get; set; }
}
}
| mit | C# |
0d39ef7c94484f266c7fbee1ae263247f72a0b1e | Access storage failure is readable. | modulexcite/lokad-cqrs | Framework/Lokad.Cqrs.Portable/Core.Inbox/Events/FailedToAccessStorage.cs | Framework/Lokad.Cqrs.Portable/Core.Inbox/Events/FailedToAccessStorage.cs | #region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License
// Copyright (c) Lokad 2010-2011, http://www.lokad.com
// This code is released as Open Source under the terms of the New BSD Licence
#endregion
using System;
namespace Lokad.Cqrs.Core.Inbox.Events
{
public sealed class FailedToAccessStorage : ISystemEvent
{
public Exception Exception { get; private set; }
public string QueueName { get; private set; }
public string MessageId { get; private set; }
public FailedToAccessStorage(Exception exception, string queueName, string messageId)
{
Exception = exception;
QueueName = queueName;
MessageId = messageId;
}
public override string ToString()
{
return string.Format("Failed to read '{0}' from '{1}': {2}", MessageId, QueueName, Exception.Message);
}
}
} | #region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License
// Copyright (c) Lokad 2010-2011, http://www.lokad.com
// This code is released as Open Source under the terms of the New BSD Licence
#endregion
using System;
namespace Lokad.Cqrs.Core.Inbox.Events
{
public sealed class FailedToAccessStorage : ISystemEvent
{
public Exception Exception { get; private set; }
public string QueueName { get; private set; }
public string MessageId { get; private set; }
public FailedToAccessStorage(Exception exception, string queueName, string messageId)
{
Exception = exception;
QueueName = queueName;
MessageId = messageId;
}
}
} | bsd-3-clause | C# |
f5182345c26e2925b9f94330022485322975f94a | Fix accidental change to copyright symbol | jason-roberts/FeatureToggle,jason-roberts/FeatureToggle | src/FeatureToggleSolution/SharedAssemblyInfo.cs | src/FeatureToggleSolution/SharedAssemblyInfo.cs | using System;
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("FeatureToggle")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("FeatureToggle")]
[assembly: AssemblyCopyright("Copyright © Jason Roberts 2011")]
[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("af0c0a8e-f50a-4803-b21e-5b3fa3a98414")]
// 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.*")]
// The Common Language Specification (CLS) defines naming restrictions, data types, and
// rules to which assemblies must conform if they will be used across programming languages.
// Good design dictates that all assemblies explicitly indicate CLS compliance with
// CLSCompliantAttribute. If the attribute is not present on an assembly, the assembly is not compliant.
[assembly: CLSCompliant(true)]
| using System;
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("FeatureToggle")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("FeatureToggle")]
[assembly: AssemblyCopyright("Copyright � Jason Roberts 2011")]
[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("af0c0a8e-f50a-4803-b21e-5b3fa3a98414")]
// 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.*")]
// The Common Language Specification (CLS) defines naming restrictions, data types, and
// rules to which assemblies must conform if they will be used across programming languages.
// Good design dictates that all assemblies explicitly indicate CLS compliance with
// CLSCompliantAttribute. If the attribute is not present on an assembly, the assembly is not compliant.
[assembly: CLSCompliant(true)]
| apache-2.0 | C# |
ba7dc795d0cba3045ef615d1f7a50862e3970cca | update of version for release | Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal | Master/Appleseed/Projects/Appleseed.Framework/Properties/AssemblyInfo.cs | Master/Appleseed/Projects/Appleseed.Framework/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
// 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("Appleseed.AppCode")]
[assembly: AssemblyDescription("Appleseed Portal and Content Management System : Framework.Web ")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ANANT Corporation")]
[assembly: AssemblyProduct("Appleseed Portal Core Framework")]
[assembly: AssemblyCopyright("Copyright © ANANT Corporation 2010-2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("03094a42-cc29-4a65-aead-e2f803e90931")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.4.131.463")]
[assembly: AssemblyFileVersion("1.4.131.463")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
// 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("Appleseed.AppCode")]
[assembly: AssemblyDescription("Appleseed Portal and Content Management System : Framework.Web ")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ANANT Corporation")]
[assembly: AssemblyProduct("Appleseed Portal Core Framework")]
[assembly: AssemblyCopyright("Copyright © ANANT Corporation 2010-2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("03094a42-cc29-4a65-aead-e2f803e90931")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.4.98.383")]
[assembly: AssemblyFileVersion("1.4.98.383")]
| apache-2.0 | C# |
b511126a775d068e1727c1b56615e52a80195a8d | Sort deployment groups in deployment list | Codestellation/Galaxy,Codestellation/Galaxy,Codestellation/Galaxy | src/Galaxy/WebEnd/Models/DeploymentListModel.cs | src/Galaxy/WebEnd/Models/DeploymentListModel.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Codestellation.Galaxy.Domain;
using Codestellation.Quarks.Collections;
using Nejdb.Bson;
namespace Codestellation.Galaxy.WebEnd.Models
{
public class DeploymentListModel
{
public readonly DeploymentModel[] Deployments;
public readonly KeyValuePair<ObjectId, string>[] AllFeeds;
public DeploymentListModel(DashBoard dashBoard)
{
AllFeeds = dashBoard.Feeds.ConvertToArray(feed => new KeyValuePair<ObjectId, string>(feed.Id, feed.Name), dashBoard.Feeds.Count);
Deployments = dashBoard.Deployments.ConvertToArray(x => new DeploymentModel(x, AllFeeds), dashBoard.Deployments.Count);
Groups = Deployments.Select(GetGroup).Distinct().OrderBy(x => x).ToArray();
}
public string[] Groups { get; set; }
public int Count
{
get { return Deployments.Length; }
}
public IEnumerable<DeploymentModel> GetModelsByGroup(string serviceGroup)
{
var modelsByGroup = Deployments
.Where(model => serviceGroup.Equals(GetGroup(model), StringComparison.Ordinal))
.OrderBy(x => x.ServiceFullName);
return modelsByGroup;
}
private static string GetGroup(DeploymentModel model)
{
return string.IsNullOrWhiteSpace(model.Group) ? "Everything Else" : model.Group;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using Codestellation.Galaxy.Domain;
using Codestellation.Quarks.Collections;
using Nejdb.Bson;
namespace Codestellation.Galaxy.WebEnd.Models
{
public class DeploymentListModel
{
public readonly DeploymentModel[] Deployments;
public readonly KeyValuePair<ObjectId, string>[] AllFeeds;
public DeploymentListModel(DashBoard dashBoard)
{
AllFeeds = dashBoard.Feeds.ConvertToArray(feed => new KeyValuePair<ObjectId, string>(feed.Id, feed.Name), dashBoard.Feeds.Count);
Deployments = dashBoard.Deployments.ConvertToArray(x => new DeploymentModel(x, AllFeeds), dashBoard.Deployments.Count);
Groups = Deployments.Select(GetGroup).Distinct().ToArray();
}
public string[] Groups { get; set; }
public int Count
{
get { return Deployments.Length; }
}
public IEnumerable<DeploymentModel> GetModelsByGroup(string serviceGroup)
{
var modelsByGroup = Deployments
.Where(model => serviceGroup.Equals(GetGroup(model), StringComparison.Ordinal))
.OrderBy(x => x.ServiceFullName);
return modelsByGroup;
}
private static string GetGroup(DeploymentModel model)
{
return string.IsNullOrWhiteSpace(model.Group) ? "Everything Else" : model.Group;
}
}
} | apache-2.0 | C# |
b6911a57069d614a84a0ef3f6c5a9b79876e6afd | update to use correct pipebind property | nishantpunetha/PnP,afsandeberg/PnP,vman/PnP,bhoeijmakers/PnP,werocool/PnP,briankinsella/PnP,OneBitSoftware/PnP,gautekramvik/PnP,worksofwisdom/PnP,PaoloPia/PnP,r0ddney/PnP,rahulsuryawanshi/PnP,perolof/PnP,joaopcoliveira/PnP,vman/PnP,SPDoctor/PnP,rencoreab/PnP,Anil-Lakhagoudar/PnP,OneBitSoftware/PnP,russgove/PnP,dalehhirt/PnP,machadosantos/PnP,r0ddney/PnP,andreasblueher/PnP,valt83/PnP,JonathanHuss/PnP,brennaman/PnP,NavaneethaDev/PnP,yagoto/PnP,PaoloPia/PnP,srirams007/PnP,gavinbarron/PnP,joaopcoliveira/PnP,NexploreDev/PnP-PowerShell,kendomen/PnP,aammiitt2/PnP,GSoft-SharePoint/PnP,kendomen/PnP,dalehhirt/PnP,werocool/PnP,valt83/PnP,rroman81/PnP,edrohler/PnP,tomvr2610/PnP,yagoto/PnP,lamills1/PnP,tomvr2610/PnP,JilleFloridor/PnP,brennaman/PnP,GSoft-SharePoint/PnP,andreasblueher/PnP,hildabarbara/PnP,darei-fr/PnP,erwinvanhunen/PnP,NexploreDev/PnP-PowerShell,8v060htwyc/PnP,rbarten/PnP,rgueldenpfennig/PnP,mauricionr/PnP,sndkr/PnP,baldswede/PnP,chrisobriensp/PnP,zrahui/PnP,gavinbarron/PnP,PieterVeenstra/PnP,OneBitSoftware/PnP,Rick-Kirkham/PnP,sandhyagaddipati/PnPSamples,joaopcoliveira/PnP,comblox/PnP,BartSnyckers/PnP,rahulsuryawanshi/PnP,baldswede/PnP,patrick-rodgers/PnP,bhoeijmakers/PnP,BartSnyckers/PnP,JonathanHuss/PnP,JBeerens/PnP,edrohler/PnP,JBeerens/PnP,werocool/PnP,PaoloPia/PnP,JonathanHuss/PnP,sndkr/PnP,machadosantos/PnP,spdavid/PnP,briankinsella/PnP,weshackett/PnP,biste5/PnP,edrohler/PnP,RickVanRousselt/PnP,narval32/Shp,svarukala/PnP,sandhyagaddipati/PnPSamples,pascalberger/PnP,russgove/PnP,rgueldenpfennig/PnP,kendomen/PnP,comblox/PnP,rroman81/PnP,ebbypeter/PnP,jeroenvanlieshout/PnP,rahulsuryawanshi/PnP,pdfshareforms/PnP,bstenberg64/PnP,rencoreab/PnP,OzMakka/PnP,svarukala/PnP,markcandelora/PnP,spdavid/PnP,pascalberger/PnP,SPDoctor/PnP,comblox/PnP,durayakar/PnP,bhoeijmakers/PnP,yagoto/PnP,patrick-rodgers/PnP,Claire-Hindhaugh/PnP,perolof/PnP,mauricionr/PnP,PieterVeenstra/PnP,sjuppuh/PnP,gautekramvik/PnP,IDTimlin/PnP,Rick-Kirkham/PnP,pascalberger/PnP,PieterVeenstra/PnP,RickVanRousselt/PnP,timschoch/PnP,selossej/PnP,timothydonato/PnP,8v060htwyc/PnP,OfficeDev/PnP,NexploreDev/PnP-PowerShell,darei-fr/PnP,SimonDoy/PnP,Chowdarysandhya/PnPTest,kendomen/PnP,OzMakka/PnP,sjuppuh/PnP,bstenberg64/PnP,nishantpunetha/PnP,Chowdarysandhya/PnPTest,dalehhirt/PnP,vnathalye/PnP,vman/PnP,SPDoctor/PnP,hildabarbara/PnP,andreasblueher/PnP,OfficeDev/PnP,srirams007/PnP,SimonDoy/PnP,bstenberg64/PnP,zrahui/PnP,nishantpunetha/PnP,russgove/PnP,IvanTheBearable/PnP,SuryaArup/PnP,IvanTheBearable/PnP,IDTimlin/PnP,JilleFloridor/PnP,JonathanHuss/PnP,svarukala/PnP,pdfshareforms/PnP,srirams007/PnP,RickVanRousselt/PnP,durayakar/PnP,valt83/PnP,markcandelora/PnP,durayakar/PnP,narval32/Shp,SteenMolberg/PnP,BartSnyckers/PnP,SuryaArup/PnP,OfficeDev/PnP,JBeerens/PnP,Claire-Hindhaugh/PnP,erwinvanhunen/PnP,perolof/PnP,markcandelora/PnP,NavaneethaDev/PnP,NavaneethaDev/PnP,rbarten/PnP,pdfshareforms/PnP,erwinvanhunen/PnP,IDTimlin/PnP,yagoto/PnP,sandhyagaddipati/PnPSamples,aammiitt2/PnP,afsandeberg/PnP,8v060htwyc/PnP,rencoreab/PnP,SimonDoy/PnP,MaurizioPz/PnP,weshackett/PnP,weshackett/PnP,briankinsella/PnP,rroman81/PnP,tomvr2610/PnP,vnathalye/PnP,mauricionr/PnP,narval32/Shp,baldswede/PnP,GSoft-SharePoint/PnP,selossej/PnP,timothydonato/PnP,OfficeDev/PnP,MaurizioPz/PnP,chrisobriensp/PnP,hildabarbara/PnP,timothydonato/PnP,OneBitSoftware/PnP,Anil-Lakhagoudar/PnP,jeroenvanlieshout/PnP,JilleFloridor/PnP,MaurizioPz/PnP,jlsfernandez/PnP,lamills1/PnP,lamills1/PnP,afsandeberg/PnP,PaoloPia/PnP,worksofwisdom/PnP,r0ddney/PnP,darei-fr/PnP,8v060htwyc/PnP,ebbypeter/PnP,ebbypeter/PnP,jlsfernandez/PnP,spdavid/PnP,Chowdarysandhya/PnPTest,SuryaArup/PnP,machadosantos/PnP,zrahui/PnP,rencoreab/PnP,biste5/PnP,vnathalye/PnP,Claire-Hindhaugh/PnP,IvanTheBearable/PnP,patrick-rodgers/PnP,aammiitt2/PnP,OzMakka/PnP,SteenMolberg/PnP,jlsfernandez/PnP,SteenMolberg/PnP,biste5/PnP,Rick-Kirkham/PnP,worksofwisdom/PnP,chrisobriensp/PnP,selossej/PnP,timschoch/PnP,timschoch/PnP,brennaman/PnP,gavinbarron/PnP,rbarten/PnP,sjuppuh/PnP,rgueldenpfennig/PnP,jeroenvanlieshout/PnP,Anil-Lakhagoudar/PnP,sndkr/PnP,gautekramvik/PnP | Solutions/PowerShell.Commands/Commands/ContentTypes/RemoveContentType.cs | Solutions/PowerShell.Commands/Commands/ContentTypes/RemoveContentType.cs | using System.Management.Automation;
using Microsoft.SharePoint.Client;
using OfficeDevPnP.PowerShell.CmdletHelpAttributes;
using OfficeDevPnP.PowerShell.Commands.Base.PipeBinds;
using Resources = OfficeDevPnP.PowerShell.Commands.Properties.Resources;
namespace OfficeDevPnP.PowerShell.Commands
{
[Cmdlet(VerbsCommon.Remove, "SPOContentType")]
[CmdletHelp("Removes a content type")]
[CmdletExample(
Code = @"PS:> Remove-SPOContentType -Identity ""Project Document""")]
public class RemoveContentType : SPOWebCmdlet
{
[Parameter(Mandatory = true, Position=0, ValueFromPipeline=true, HelpMessage="The name or ID of the content type to remove")]
public ContentTypePipeBind Identity;
[Parameter(Mandatory = false)]
public SwitchParameter Force;
protected override void ExecuteCmdlet()
{
if (Force || ShouldContinue(Resources.RemoveContentType, Resources.Confirm))
{
ContentType ct = null;
if (Identity.ContentType != null)
{
ct = Identity.ContentType;
}
else
{
if (!string.IsNullOrEmpty(Identity.Id))
{
ct = SelectedWeb.GetContentTypeById(Identity.Id);
}
else if (!string.IsNullOrEmpty(Identity.Name))
{
ct = SelectedWeb.GetContentTypeByName(Identity.Name);
}
}
if(ct != null)
{
ct.DeleteObject();
ClientContext.ExecuteQueryRetry();
}
}
}
}
}
| using System.Management.Automation;
using Microsoft.SharePoint.Client;
using OfficeDevPnP.PowerShell.CmdletHelpAttributes;
using OfficeDevPnP.PowerShell.Commands.Base.PipeBinds;
using Resources = OfficeDevPnP.PowerShell.Commands.Properties.Resources;
namespace OfficeDevPnP.PowerShell.Commands
{
[Cmdlet(VerbsCommon.Remove, "SPOContentType")]
[CmdletHelp("Removes a content type")]
[CmdletExample(
Code = @"PS:> Remove-SPOContentType -Identity ""Project Document""")]
public class RemoveContentType : SPOWebCmdlet
{
[Parameter(Mandatory = true, Position=0, ValueFromPipeline=true, HelpMessage="The name or ID of the content type to remove")]
public ContentTypePipeBind Identity;
[Parameter(Mandatory = false)]
public SwitchParameter Force;
protected override void ExecuteCmdlet()
{
if (Force || ShouldContinue(Resources.RemoveContentType, Resources.Confirm))
{
ContentType ct = null;
if (Identity.ContentType != null)
{
ct = Identity.ContentType;
}
else
{
if (!string.IsNullOrEmpty(Identity.Id))
{
ct = SelectedWeb.GetContentTypeById(Identity.Id);
}
else if (!string.IsNullOrEmpty(Identity.Name))
{
ct = SelectedWeb.GetContentTypeByName(Identity.Id);
}
}
if(ct != null)
{
ct.DeleteObject();
ClientContext.ExecuteQueryRetry();
}
}
}
}
}
| apache-2.0 | C# |
2797b714e58f4bfdbddeb1e2626e4b962158a2cc | trim 'Type' in property setter | lnu/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,lnu/nhibernate-core,livioc/nhibernate-core,hazzik/nhibernate-core,gliljas/nhibernate-core,nkreipke/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,fredericDelaporte/nhibernate-core,ManufacturingIntelligence/nhibernate-core,RogerKratz/nhibernate-core,nkreipke/nhibernate-core,nhibernate/nhibernate-core,ManufacturingIntelligence/nhibernate-core,fredericDelaporte/nhibernate-core,ngbrown/nhibernate-core,ngbrown/nhibernate-core,livioc/nhibernate-core,alobakov/nhibernate-core,hazzik/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,hazzik/nhibernate-core,nkreipke/nhibernate-core,ngbrown/nhibernate-core,livioc/nhibernate-core,alobakov/nhibernate-core,lnu/nhibernate-core,alobakov/nhibernate-core | src/NHibernate.Test/TypedManyToOne/AddressId.cs | src/NHibernate.Test/TypedManyToOne/AddressId.cs | using System;
namespace NHibernate.Test.TypedManyToOne
{
[Serializable]
public class AddressId
{
private string _type;
private int? requestedHash;
public virtual String Type
{
get { return _type; }
set
{
if (!string.IsNullOrWhiteSpace(value))
_type = value.Trim();
else
_type = value;
}
}
public virtual String Id { get; set; }
public AddressId(String type, String id)
{
Id = id;
_type = type;
}
public AddressId() { }
public override bool Equals(object obj)
{
return Equals(obj as AddressId);
}
public virtual bool Equals(AddressId other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return other.Id == Id && Equals(other.Type, Type);
}
public override int GetHashCode()
{
if (!requestedHash.HasValue)
{
unchecked
{
requestedHash = (Id.GetHashCode() * 397) ^ Type.GetHashCode();
}
}
return requestedHash.Value;
}
public override string ToString()
{
return Type + '#' + Id;
}
}
}
| using System;
namespace NHibernate.Test.TypedManyToOne
{
[Serializable]
public class AddressId
{
public virtual String Type { get; set; }
public virtual String Id { get; set; }
private int? requestedHash;
public AddressId(String type, String id)
{
Id = id;
Type = type;
}
public AddressId() { }
public override bool Equals(object obj)
{
return Equals(obj as AddressId);
}
public virtual bool Equals(AddressId other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return other.Id == Id && Equals(other.Type, Type);
}
public override int GetHashCode()
{
if (!requestedHash.HasValue)
{
unchecked
{
requestedHash = (Id.GetHashCode() * 397) ^ Type.GetHashCode();
}
}
return requestedHash.Value;
}
public override string ToString()
{
return Type + '#' + Id;
}
}
}
| lgpl-2.1 | C# |
449af51e3b44fb93f0957fbe67edf535c268a012 | fix missing path | LayoutFarm/PixelFarm | a_mini/projects/Tests/Test_BasicPixelFarm/Program.cs | a_mini/projects/Tests/Test_BasicPixelFarm/Program.cs | //Apache2, 2014-2017, WinterDev
using System;
using System.Windows.Forms;
namespace TestGraphicPackage2
{
static class Program
{
static LayoutFarm.Dev.FormDemoList formDemoList;
[STAThread]
static void Main()
{
OpenTK.Toolkit.Init();
//-------------------------------
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//temp
//TODO: fix this ,
//set data dir before load
Typography.TextBreak.CustomBreakerBuilder.DataDir = @"../../PixelFarm/Typography/Typography.TextBreak/icu58/brkitr_src/dictionaries";
LayoutFarm.Composers.Default.TextBreaker = new LayoutFarm.Composers.MyManagedTextBreaker();
//RootDemoPath.Path = @"..\Data";
//you can use your font loader
PixelFarm.Drawing.WinGdi.WinGdiPlusPlatform.SetFontLoader(YourImplementation.BootStrapWinGdi.myFontLoader);
PixelFarm.Drawing.GLES2.GLES2Platform.SetFontLoader(YourImplementation.BootStrapOpenGLES2.myFontLoader);
////-------------------------------
formDemoList = new LayoutFarm.Dev.FormDemoList();
formDemoList.LoadDemoList(typeof(Program));
Application.Run(formDemoList);
}
}
}
| //Apache2, 2014-2017, WinterDev
using System;
using System.Windows.Forms;
namespace TestGraphicPackage2
{
static class Program
{
static LayoutFarm.Dev.FormDemoList formDemoList;
[STAThread]
static void Main()
{
OpenTK.Toolkit.Init();
//-------------------------------
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//temp
//TODO: fix this ,
//set data dir before load
Typography.TextBreak.CustomBreakerBuilder.DataDir = @"../../Deps_I18N/LayoutFarm.TextBreak/icu58/brkitr_src/dictionaries";
LayoutFarm.Composers.Default.TextBreaker = new LayoutFarm.Composers.MyManagedTextBreaker();
//RootDemoPath.Path = @"..\Data";
//you can use your font loader
PixelFarm.Drawing.WinGdi.WinGdiPlusPlatform.SetFontLoader(YourImplementation.BootStrapWinGdi.myFontLoader);
PixelFarm.Drawing.GLES2.GLES2Platform.SetFontLoader(YourImplementation.BootStrapOpenGLES2.myFontLoader);
////-------------------------------
formDemoList = new LayoutFarm.Dev.FormDemoList();
formDemoList.LoadDemoList(typeof(Program));
Application.Run(formDemoList);
}
}
}
| bsd-2-clause | C# |
26f12966e33a6eba09d071451b2c60e3ea44047f | Update ParamArrayAttribute.cs (#4442) | russellhadley/coreclr,schellap/coreclr,YongseopKim/coreclr,vinnyrom/coreclr,martinwoodward/coreclr,naamunds/coreclr,hseok-oh/coreclr,qiudesong/coreclr,krk/coreclr,Dmitry-Me/coreclr,ragmani/coreclr,YongseopKim/coreclr,jamesqo/coreclr,yeaicc/coreclr,parjong/coreclr,Dmitry-Me/coreclr,ZhichengZhu/coreclr,tijoytom/coreclr,YongseopKim/coreclr,cydhaselton/coreclr,tijoytom/coreclr,rartemev/coreclr,JonHanna/coreclr,ZhichengZhu/coreclr,josteink/coreclr,yeaicc/coreclr,bartonjs/coreclr,krytarowski/coreclr,sjsinju/coreclr,YongseopKim/coreclr,wtgodbe/coreclr,poizan42/coreclr,sagood/coreclr,bartdesmet/coreclr,josteink/coreclr,Dmitry-Me/coreclr,sjsinju/coreclr,ragmani/coreclr,parjong/coreclr,cshung/coreclr,yizhang82/coreclr,AlexGhiondea/coreclr,ramarag/coreclr,cshung/coreclr,russellhadley/coreclr,pgavlin/coreclr,cydhaselton/coreclr,neurospeech/coreclr,yizhang82/coreclr,wtgodbe/coreclr,LLITCHEV/coreclr,ragmani/coreclr,parjong/coreclr,shahid-pk/coreclr,ramarag/coreclr,roncain/coreclr,kyulee1/coreclr,bartdesmet/coreclr,KrzysztofCwalina/coreclr,botaberg/coreclr,sejongoh/coreclr,mskvortsov/coreclr,jamesqo/coreclr,manu-silicon/coreclr,ruben-ayrapetyan/coreclr,yeaicc/coreclr,shahid-pk/coreclr,mskvortsov/coreclr,gkhanna79/coreclr,schellap/coreclr,naamunds/coreclr,shahid-pk/coreclr,James-Ko/coreclr,cydhaselton/coreclr,ragmani/coreclr,russellhadley/coreclr,LLITCHEV/coreclr,jhendrixMSFT/coreclr,bartonjs/coreclr,martinwoodward/coreclr,ZhichengZhu/coreclr,gkhanna79/coreclr,ramarag/coreclr,KrzysztofCwalina/coreclr,schellap/coreclr,sjsinju/coreclr,manu-silicon/coreclr,yizhang82/coreclr,cmckinsey/coreclr,josteink/coreclr,martinwoodward/coreclr,neurospeech/coreclr,JonHanna/coreclr,shahid-pk/coreclr,alexperovich/coreclr,wtgodbe/coreclr,James-Ko/coreclr,yizhang82/coreclr,James-Ko/coreclr,poizan42/coreclr,dasMulli/coreclr,vinnyrom/coreclr,mskvortsov/coreclr,krytarowski/coreclr,AlexGhiondea/coreclr,botaberg/coreclr,jhendrixMSFT/coreclr,dasMulli/coreclr,ruben-ayrapetyan/coreclr,gkhanna79/coreclr,botaberg/coreclr,bartdesmet/coreclr,jhendrixMSFT/coreclr,James-Ko/coreclr,shahid-pk/coreclr,josteink/coreclr,sejongoh/coreclr,sejongoh/coreclr,qiudesong/coreclr,sagood/coreclr,hseok-oh/coreclr,sjsinju/coreclr,mmitche/coreclr,bartonjs/coreclr,Dmitry-Me/coreclr,JonHanna/coreclr,martinwoodward/coreclr,qiudesong/coreclr,JonHanna/coreclr,schellap/coreclr,kyulee1/coreclr,ramarag/coreclr,manu-silicon/coreclr,gkhanna79/coreclr,ZhichengZhu/coreclr,bartdesmet/coreclr,kyulee1/coreclr,JosephTremoulet/coreclr,cydhaselton/coreclr,yeaicc/coreclr,sagood/coreclr,rartemev/coreclr,LLITCHEV/coreclr,poizan42/coreclr,cydhaselton/coreclr,roncain/coreclr,wateret/coreclr,roncain/coreclr,mmitche/coreclr,kyulee1/coreclr,jamesqo/coreclr,YongseopKim/coreclr,dasMulli/coreclr,JosephTremoulet/coreclr,wateret/coreclr,neurospeech/coreclr,vinnyrom/coreclr,parjong/coreclr,pgavlin/coreclr,russellhadley/coreclr,Dmitry-Me/coreclr,wateret/coreclr,yeaicc/coreclr,russellhadley/coreclr,ZhichengZhu/coreclr,alexperovich/coreclr,dpodder/coreclr,krk/coreclr,dpodder/coreclr,botaberg/coreclr,tijoytom/coreclr,rartemev/coreclr,schellap/coreclr,krytarowski/coreclr,yeaicc/coreclr,krytarowski/coreclr,jhendrixMSFT/coreclr,neurospeech/coreclr,mmitche/coreclr,naamunds/coreclr,krk/coreclr,cshung/coreclr,wateret/coreclr,alexperovich/coreclr,pgavlin/coreclr,JonHanna/coreclr,schellap/coreclr,mskvortsov/coreclr,AlexGhiondea/coreclr,josteink/coreclr,rartemev/coreclr,tijoytom/coreclr,LLITCHEV/coreclr,botaberg/coreclr,cmckinsey/coreclr,jhendrixMSFT/coreclr,sagood/coreclr,AlexGhiondea/coreclr,manu-silicon/coreclr,mskvortsov/coreclr,ruben-ayrapetyan/coreclr,JosephTremoulet/coreclr,krk/coreclr,gkhanna79/coreclr,wateret/coreclr,pgavlin/coreclr,pgavlin/coreclr,krytarowski/coreclr,cmckinsey/coreclr,kyulee1/coreclr,JosephTremoulet/coreclr,cmckinsey/coreclr,hseok-oh/coreclr,wtgodbe/coreclr,dasMulli/coreclr,vinnyrom/coreclr,roncain/coreclr,KrzysztofCwalina/coreclr,sejongoh/coreclr,dasMulli/coreclr,sagood/coreclr,naamunds/coreclr,vinnyrom/coreclr,ZhichengZhu/coreclr,rartemev/coreclr,James-Ko/coreclr,cshung/coreclr,hseok-oh/coreclr,wtgodbe/coreclr,manu-silicon/coreclr,schellap/coreclr,mmitche/coreclr,hseok-oh/coreclr,AlexGhiondea/coreclr,jamesqo/coreclr,Dmitry-Me/coreclr,poizan42/coreclr,shahid-pk/coreclr,LLITCHEV/coreclr,qiudesong/coreclr,naamunds/coreclr,yizhang82/coreclr,mskvortsov/coreclr,martinwoodward/coreclr,naamunds/coreclr,dasMulli/coreclr,krytarowski/coreclr,cmckinsey/coreclr,sejongoh/coreclr,JonHanna/coreclr,parjong/coreclr,qiudesong/coreclr,bartonjs/coreclr,KrzysztofCwalina/coreclr,cshung/coreclr,botaberg/coreclr,alexperovich/coreclr,JosephTremoulet/coreclr,sjsinju/coreclr,ruben-ayrapetyan/coreclr,russellhadley/coreclr,mmitche/coreclr,bartonjs/coreclr,ragmani/coreclr,tijoytom/coreclr,JosephTremoulet/coreclr,shahid-pk/coreclr,roncain/coreclr,sejongoh/coreclr,yizhang82/coreclr,cydhaselton/coreclr,Dmitry-Me/coreclr,gkhanna79/coreclr,ramarag/coreclr,sejongoh/coreclr,jamesqo/coreclr,LLITCHEV/coreclr,josteink/coreclr,YongseopKim/coreclr,kyulee1/coreclr,ramarag/coreclr,jhendrixMSFT/coreclr,wtgodbe/coreclr,mmitche/coreclr,bartdesmet/coreclr,ZhichengZhu/coreclr,James-Ko/coreclr,bartonjs/coreclr,krk/coreclr,LLITCHEV/coreclr,manu-silicon/coreclr,jhendrixMSFT/coreclr,poizan42/coreclr,martinwoodward/coreclr,vinnyrom/coreclr,neurospeech/coreclr,KrzysztofCwalina/coreclr,rartemev/coreclr,neurospeech/coreclr,dpodder/coreclr,cmckinsey/coreclr,dasMulli/coreclr,tijoytom/coreclr,sagood/coreclr,hseok-oh/coreclr,KrzysztofCwalina/coreclr,cmckinsey/coreclr,krk/coreclr,manu-silicon/coreclr,wateret/coreclr,ramarag/coreclr,bartonjs/coreclr,dpodder/coreclr,dpodder/coreclr,ruben-ayrapetyan/coreclr,bartdesmet/coreclr,KrzysztofCwalina/coreclr,poizan42/coreclr,vinnyrom/coreclr,parjong/coreclr,AlexGhiondea/coreclr,roncain/coreclr,alexperovich/coreclr,martinwoodward/coreclr,cshung/coreclr,ragmani/coreclr,ruben-ayrapetyan/coreclr,josteink/coreclr,roncain/coreclr,alexperovich/coreclr,bartdesmet/coreclr,yeaicc/coreclr,dpodder/coreclr,sjsinju/coreclr,naamunds/coreclr,qiudesong/coreclr,jamesqo/coreclr,pgavlin/coreclr | src/mscorlib/src/System/ParamArrayAttribute.cs | src/mscorlib/src/System/ParamArrayAttribute.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.
/*=============================================================================
**
**
**
** Purpose: Attribute for multiple parameters.
**
**
=============================================================================*/
namespace System
{
//This class contains only static members and does not need to be serializable
[AttributeUsage (AttributeTargets.Parameter, Inherited=true, AllowMultiple=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ParamArrayAttribute : Attribute
{
public ParamArrayAttribute () {}
}
}
| // 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.
/*=============================================================================
**
**
**
** Purpose: Container for assemblies.
**
**
=============================================================================*/
namespace System
{
//This class contains only static members and does not need to be serializable
[AttributeUsage (AttributeTargets.Parameter, Inherited=true, AllowMultiple=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ParamArrayAttribute : Attribute
{
public ParamArrayAttribute () {}
}
}
| mit | C# |
57889922d68240c29faea7587a1bb83135178f76 | Update DefaultBuild. | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | bootstrapping/DefaultBuild.cs | bootstrapping/DefaultBuild.cs | using System;
using System.Linq;
using Nuke.Common;
using Nuke.Common.Tools.MSBuild;
using Nuke.Core;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
using static Nuke.Common.Tools.MSBuild.MSBuildTasks;
using static Nuke.Common.Tools.NuGet.NuGetTasks;
using static Nuke.Core.IO.FileSystemTasks;
using static Nuke.Core.IO.PathConstruction;
using static Nuke.Core.EnvironmentInfo;
class DefaultBuild : GitHubBuild
{
// This is the application entry point for the build.
// It also defines the default target to execute.
public static int Main () => Execute<DefaultBuild>(x => x.Compile);
Target Clean => _ => _
// Disabled for safety.
.OnlyWhen(() => false)
.Executes(() => DeleteDirectories(GlobDirectories(SolutionDirectory, "**/bin", "**/obj")))
.Executes(() => EnsureCleanDirectory(OutputDirectory));
Target Restore => _ => _
.DependsOn(Clean)
.Executes(() =>
{
// Remove tasks as needed. They exist for compatibility.
DotNetRestore(SolutionDirectory);
if (MSBuildVersion == Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017)
MSBuild(s => DefaultSettings.MSBuildRestore);
NuGetRestore(SolutionFile);
});
Target Compile => _ => _
.DependsOn(Restore)
.Executes(() => MSBuild(s => DefaultSettings.MSBuildCompile
.SetMSBuildVersion(MSBuildVersion)));
// When having xproj-based projects, using VS2015 is necessary.
MSBuildVersion? MSBuildVersion =>
!IsUnix
? GlobFiles(SolutionDirectory, "*.xproj").Any()
? Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2015
: Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017
: default(MSBuildVersion?);
}
| using System;
using System.Linq;
using Nuke.Common;
using Nuke.Common.Tools.MSBuild;
using Nuke.Core;
using static Nuke.Common.IO.FileSystemTasks;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
using static Nuke.Common.Tools.MSBuild.MSBuildTasks;
using static Nuke.Common.Tools.NuGet.NuGetTasks;
using static Nuke.Core.EnvironmentInfo;
class DefaultBuild : GitHubBuild
{
// This is the application entry point for the build.
// It also defines the default target to execute.
public static int Main () => Execute<DefaultBuild>(x => x.Compile);
Target Clean => _ => _
// Disabled for safety.
.OnlyWhen(() => false)
.Executes(() => DeleteDirectories(GlobDirectories(SolutionDirectory, "**/bin", "**/obj")))
.Executes(() => PrepareCleanDirectory(OutputDirectory));
Target Restore => _ => _
.DependsOn(Clean)
.Executes(() =>
{
// Remove tasks as needed. They exist for compatibility.
DotNetRestore(SolutionDirectory);
if (MSBuildVersion == Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017)
MSBuild(s => DefaultSettings.MSBuildRestore);
NuGetRestore(SolutionFile);
});
Target Compile => _ => _
.DependsOn(Restore)
.Executes(() => MSBuild(s => DefaultSettings.MSBuildCompile
.SetMSBuildVersion(MSBuildVersion)));
// When having xproj-based projects, using VS2015 is necessary.
MSBuildVersion? MSBuildVersion =>
!IsUnix
? GlobFiles(SolutionDirectory, "*.xproj").Any()
? Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2015
: Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017
: default(MSBuildVersion?);
}
| mit | C# |
3a30117b89160cd5ae287fa2c44650e03d12e5ac | Update inventory type and status mappings | spiresystems/spire-api-example-csharp | api-example-csharp/Inventory.cs | api-example-csharp/Inventory.cs | using System.Collections.Generic;
namespace ApiTest.InventoryApi
{
public class UnitOfMeasure
{
public int id { get; set; }
public string code { get; set; }
}
public sealed class InventoryStatus
{
public static string Active = 0;
public static string OnHold = 1;
public static string Inactive = 2;
}
public sealed class InventoryType
{
public static string Normal = "N";
public static string NonPhysical = "V";
public static string Manufactured = "M";
public static string Kitted = "K";
public static string RawMaterial = "R";
}
public class Inventory
{
public int id { get; set; }
public string partNo { get; set; }
public string whse { get; set; }
public string description { get; set; }
public string type { get; set; }
public string status { get; set; }
public decimal onHandQty { get; set; }
public decimal committedQty { get; set; }
public decimal backorderQty { get; set; }
public Dictionary<string, UnitOfMeasure> unitOfMeasures { get; set; }
}
public class InventoryClient : BaseObjectClient<Inventory>
{
public InventoryClient(ApiClient client) : base(client) { }
public override string Resource
{
get
{
return "inventory/items/";
}
}
}
}
| using System.Collections.Generic;
namespace ApiTest.InventoryApi
{
public class UnitOfMeasure
{
public int id { get; set; }
public string code { get; set; }
}
public sealed class InventoryStatus
{
public static string Active = "active";
public static string OnHold = "onhold";
public static string Inactive = "inactive";
}
public sealed class InventoryType
{
public static string Normal = "normal";
public static string NonPhysical = "nonPhysical";
public static string Manufactured = "manufactured";
public static string Kitted = "kitted";
public static string RawMaterial = "rawMaterial";
}
public class Inventory
{
public int id { get; set; }
public string partNo { get; set; }
public string whse { get; set; }
public string description { get; set; }
public string type { get; set; }
public string status { get; set; }
public decimal onHandQty { get; set; }
public decimal committedQty { get; set; }
public decimal backorderQty { get; set; }
public Dictionary<string, UnitOfMeasure> unitOfMeasures { get; set; }
}
public class InventoryClient : BaseObjectClient<Inventory>
{
public InventoryClient(ApiClient client) : base(client) { }
public override string Resource
{
get
{
return "inventory/items/";
}
}
}
} | mit | C# |
e5bf9d591672069240366967f4ec4c6d17f7a37f | Update SmallAppliances.cs | jkanchelov/Telerik-OOP-Team-StarFruit | TeamworkStarFruit/CatalogueLib/Products/SmallAppliances.cs | TeamworkStarFruit/CatalogueLib/Products/SmallAppliances.cs | namespace CatalogueLib
{
using System.Text;
using CatalogueLib.Products.Enumerations;
public abstract class SmallAppliances : Product
{
public SmallAppliances()
{
}
public SmallAppliances(int ID, decimal price, bool isAvailable, Brand brand, double Capacity, double CableLength, int Affixes)
: base(ID, price, isAvailable, brand)
{
this.Capacity = Capacity;
this.CableLength = CableLength;
this.Affixes = Affixes;
}
public double Capacity { get; private set; }
public double CableLength { get; private set; }
public int Affixes { get; private set; }
public override string ToString()
{
StringBuilder stroitel = new StringBuilder();
stroitel = stroitel.Append(string.Format("{0}", base.ToString()));
stroitel = stroitel.Append(string.Format(" Capacity: {0}\n Cable length: {1}\n Affixes: {2}", this.Capacity, this.CableLength, this.Affixes));
return stroitel.AppendLine().ToString();
}
}
}
| namespace CatalogueLib
{
using CatalogueLib.Products.Enumerations;
public abstract class SmallAppliances : Product
{
public SmallAppliances()
{
}
public SmallAppliances(int ID, decimal price, bool isAvailable, Brand brand, double Capacity, double CableLength, int Affixes)
: base(ID, price, isAvailable, brand)
{
this.Capacity = Capacity;
this.CableLength = CableLength;
this.Affixes = Affixes;
}
public double Capacity { get; private set; }
public double CableLength { get; private set; }
public int Affixes { get; private set; }
public override string ToString()
{
StringBuilder stroitel = new StringBuilder();
stroitel = stroitel.Append(string.Format("{0}", base.ToString()));
stroitel = stroitel.Append(string.Format(" Capacity: {0}\n Cable length: {1}\n Affixes: {2}", this.Capacity, this.CableLength, this.Affixes));
return stroitel.AppendLine().ToString();
}
}
}
| mit | C# |
d09c7de52775c9275dc87fa881d5fa9889c0179f | remove some litter ;-) (they've been added as coments to the PR instead) | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerAccounts/DependencyResolution/AccountApiClientRegistry.cs | src/SFA.DAS.EmployerAccounts/DependencyResolution/AccountApiClientRegistry.cs | using SFA.DAS.EAS.Account.Api.Client;
using StructureMap;
namespace SFA.DAS.EmployerAccounts.DependencyResolution
{
public class AccountApiClientRegistry : Registry
{
public AccountApiClientRegistry()
{
For<IAccountApiClient>().Use<AccountApiClient>();
// config for the client is registered in ConfigurationRegistry
}
}
}
| using SFA.DAS.EAS.Account.Api.Client;
using StructureMap;
namespace SFA.DAS.EmployerAccounts.DependencyResolution
{
public class AccountApiClientRegistry : Registry
{
// we add this here, rather than in the client project, so we don't introduce a dependency on structuremap in the client
public AccountApiClientRegistry()
{
// the client's not very good, but the version of sfa.das.http currently in EAS isn't either, so we go with the client
For<IAccountApiClient>().Use<AccountApiClient>();
// config is registered in ConfigurationRegistry
}
}
}
| mit | C# |
b60c04b4b7ab657751ece59158c5fceadc832f07 | Update Promise.cs: Return this from success and error | drew-r/Maverick | Promise.cs | Promise.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Maverick
{
public class Promise
{
public Promise(Func<object> asyncOp)
{
Scheduler.Request();
task = new Task(() =>
{
result = asyncOp();
});
try
{
task.Start();
}
catch (Exception e)
{
raiseException(_taskException);
}
}
dynamic result = null;
readonly Task task;
public Promise success(Action<object> cb)
{
task.ContinueWith((t) => Scheduler.Enqueue((i) => cb(result)));
return this;
}
void raiseException(Exception e)
{
_taskException = e;
Scheduler.Enqueue(() => _exceptionCallback(_taskException));
}
Exception _taskException;
Action<object> _exceptionCallback;
public Promise error(Action<object> cb)
{
_exceptionCallback = cb;
if (_taskException != null) { raiseException(_taskException); }
return this;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Maverick
{
public class Promise
{
public Promise(Func<object> asyncOp)
{
Scheduler.Request();
task = new Task(() =>
{
result = asyncOp();
});
try
{
task.Start();
}
catch (Exception e)
{
raiseException(_taskException);
}
}
dynamic result = null;
readonly Task task;
public void success(Action<object> cb)
{
task.ContinueWith((t) => Scheduler.Enqueue((i) => cb(result)));
}
void raiseException(Exception e)
{
_taskException = e;
Scheduler.Enqueue(() => _exceptionCallback(_taskException));
}
Exception _taskException;
Action<object> _exceptionCallback;
public void error(Action<object> cb)
{
_exceptionCallback = cb;
if (_taskException != null) { raiseException(_taskException); }
}
}
}
| mit | C# |
5dacbf1d0acf30b3014894aec382dec0a63f22d8 | Update links | tuelsch/schreinerei-gfeller,tuelsch/schreinerei-gfeller,tuelsch/schreinerei-gfeller | schreinerei-gfeller/Views/Shared/_Header.cshtml | schreinerei-gfeller/Views/Shared/_Header.cshtml | <header class="main">
<div class="container">
@* Logo *@
<h1 class="logo">
<span>Schreinerei Gfeller - Startseite</span>
<a href="/">
<img src="/Assets/img/logo.png" alt="">
</a>
</h1>
@* Mobile toggler *@
<button class="nav-toggler">menu</button>
@* Navigation *@
<nav class="main">
<h1 class="sr-only">Hauptnavigation</h1>
<ul>
<li>
<a class="link" href="/Produkte">Produkte</a>
</li>
<li>
<a class="link" href="/Galerie">Galerie</a>
</li>
<li>
<a class="link" href="/Kontakt">Kontakt</a>
</li>
<li class="undertaker">
<a class="link color-blue" href="/Bestattungen">Bestattungen</a>
</li>
</ul>
</nav>
</div>
</header> | <header class="main">
<div class="container">
@* Logo *@
<h1 class="logo">
<span>Schreinerei Gfeller - Startseite</span>
<a href="/">
<img src="/Assets/img/logo.png" alt="">
</a>
</h1>
@* Mobile toggler *@
<button class="nav-toggler">menu</button>
@* Navigation *@
<nav class="main">
<h1 class="sr-only">Hauptnavigation</h1>
<ul>
<li>
<a class="link" href="/produkte">Produkte</a>
</li>
<li>
<a class="link" href="/galerie">Galerie</a>
</li>
<li>
<a class="link" href="/kontakt">Kontakt</a>
</li>
<li class="undertaker">
<a class="link color-blue" href="/bestattungen">Bestattungen</a>
</li>
</ul>
</nav>
</div>
</header> | mit | C# |
ea626c6c39060fdac6cb008cdc3b6cb8bfc9b859 | Modify to use factory methods for hash algorithm | emoacht/SnowyImageCopy | Source/SnowyImageCopy/Models/ImageFile/HashItem.cs | Source/SnowyImageCopy/Models/ImageFile/HashItem.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace SnowyImageCopy.Models.ImageFile
{
/// <summary>
/// Container for hash
/// </summary>
/// <remarks>This class should be immutable.</remarks>
internal class HashItem : IComparable<HashItem>
{
private static readonly HashAlgorithm _algorithm;
/// <summary>
/// Size (bytes) of underlying value
/// </summary>
public static int Size { get; }
static HashItem()
{
try
{
_algorithm = MD5.Create(); // MD5 is for less cost.
}
catch (InvalidOperationException)
{
_algorithm = SHA1.Create();
}
Size = _algorithm.HashSize / 8;
}
#region Constructor
private readonly byte[] _value;
private HashItem(byte[] value)
{
if (!(value?.Length == Size))
throw new ArgumentException(nameof(value));
this._value = value;
}
public static HashItem Compute(IEnumerable<byte> source)
{
var buffer = source as byte[] ?? source?.ToArray() ?? throw new ArgumentNullException(nameof(source));
return new HashItem(_algorithm.ComputeHash(buffer));
}
public static HashItem Restore(byte[] source)
{
return new HashItem(source?.ToArray());
}
#endregion
public byte[] ToByteArray() => _value.ToArray();
public override string ToString() => BitConverter.ToString(_value);
#region IComparable
public int CompareTo(HashItem other)
{
if (other is null)
return 1;
if (object.ReferenceEquals(this, other))
return 0;
for (int i = 0; i < Size; i++)
{
int comparison = this._value[i].CompareTo(other._value[i]);
if (comparison != 0)
return comparison;
}
return 0;
}
public override bool Equals(object obj) => this.Equals(obj as HashItem);
public bool Equals(HashItem other)
{
if (other is null)
return false;
if (object.ReferenceEquals(this, other))
return true;
return this._value.SequenceEqual(other._value);
}
public override int GetHashCode()
{
unchecked
{
int hash = 17;
foreach (byte element in this._value)
hash = hash * 31 + element.GetHashCode();
return hash;
}
}
#endregion
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace SnowyImageCopy.Models.ImageFile
{
/// <summary>
/// Container for hash
/// </summary>
/// <remarks>This class should be immutable.</remarks>
internal class HashItem : IComparable<HashItem>
{
private static readonly HashAlgorithm _algorithm;
/// <summary>
/// Size (bytes) of underlying value
/// </summary>
public static int Size { get; }
static HashItem()
{
try
{
_algorithm = new MD5CryptoServiceProvider(); // MD5 is for less cost.
}
catch (InvalidOperationException)
{
_algorithm = new SHA1CryptoServiceProvider();
}
Size = _algorithm.HashSize / 8;
}
#region Constructor
private readonly byte[] _value;
private HashItem(byte[] value)
{
if (!(value?.Length == Size))
throw new ArgumentException(nameof(value));
this._value = value;
}
public static HashItem Compute(IEnumerable<byte> source)
{
var buffer = source as byte[] ?? source?.ToArray() ?? throw new ArgumentNullException(nameof(source));
return new HashItem(_algorithm.ComputeHash(buffer));
}
public static HashItem Restore(byte[] source)
{
return new HashItem(source?.ToArray());
}
#endregion
public byte[] ToByteArray() => _value.ToArray();
public override string ToString() => BitConverter.ToString(_value);
#region IComparable
public int CompareTo(HashItem other)
{
if (other is null)
return 1;
if (object.ReferenceEquals(this, other))
return 0;
for (int i = 0; i < Size; i++)
{
int comparison = this._value[i].CompareTo(other._value[i]);
if (comparison != 0)
return comparison;
}
return 0;
}
public override bool Equals(object obj) => this.Equals(obj as HashItem);
public bool Equals(HashItem other)
{
if (other is null)
return false;
if (object.ReferenceEquals(this, other))
return true;
return this._value.SequenceEqual(other._value);
}
public override int GetHashCode()
{
unchecked
{
int hash = 17;
foreach (byte element in this._value)
hash = hash * 31 + element.GetHashCode();
return hash;
}
}
#endregion
}
} | mit | C# |
ad6f418d98d0476892504501074d0ddb78e4c2c5 | Add the simples notification test | Shaddix/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet,realm/realm-dotnet | Tests/IntegrationTests.Shared/NotificationTests.cs | Tests/IntegrationTests.Shared/NotificationTests.cs | using System;
using NUnit.Framework;
using Realms;
using System.Threading;
using System.IO;
namespace IntegrationTests.Shared
{
[TestFixture]
public class NotificationTests
{
private string _databasePath;
private Realm _realm;
private void WriteOnDifferentThread(Action<Realm> action)
{
var thread = new Thread(() =>
{
var r = Realm.GetInstance(_databasePath);
r.Write(() => action(r));
r.Close();
});
thread.Start();
thread.Join();
}
[SetUp]
private void Setup()
{
_databasePath = Path.GetTempFileName();
_realm = Realm.GetInstance(_databasePath);
}
[Test]
public void ShouldTriggerRealmChangedEvent()
{
// Arrange
var wasNotified = false;
_realm.RealmChanged += (sender, e) => { wasNotified = true; };
// Act
WriteOnDifferentThread((realm) =>
{
realm.CreateObject<Person>();
});
// Assert
Assert.That(wasNotified, "RealmChanged notification was not triggered");
}
}
}
| using System;
using NUnit.Framework;
using Realms;
using System.Threading;
namespace IntegrationTests.Shared
{
[TestFixture]
public class NotificationTests
{
private string _databasePath;
private Realm _realm;
private void WriteOnDifferentThread(Action<Realm> action)
{
var thread = new Thread(() =>
{
var r = Realm.GetInstance(_databasePath);
r.Write(() => action(r));
r.Close();
});
thread.Start();
thread.Join();
}
[Test]
public void SimpleTest()
{
// Arrange
// Act
}
}
}
| apache-2.0 | C# |
52572c9f00f140c45ebc4a08eb18bcf4dd93f005 | raise event outside of lock | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Models/ObservableConcurrentHashSet.cs | WalletWasabi/Models/ObservableConcurrentHashSet.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
namespace WalletWasabi.Models
{
public class ObservableConcurrentHashSet<T> : IReadOnlyCollection<T> // DO NOT IMPLEMENT INotifyCollectionChanged!!! That'll break and crash the software: https://github.com/AvaloniaUI/Avalonia/issues/1988#issuecomment-431691863
{
private ConcurrentHashSet<T> Set { get; }
private object Lock { get; }
public event EventHandler HashSetChanged; // Keep it as is! Unless with the modification this bug won't come out: https://github.com/AvaloniaUI/Avalonia/issues/1988#issuecomment-431691863
public ObservableConcurrentHashSet()
{
Set = new ConcurrentHashSet<T>();
Lock = new object();
}
// Don't lock here, it results deadlock at wallet loading when filters arent synced.
public int Count => Set.Count;
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
// Don't lock here, it results deadlock at wallet loading when filters arent synced.
public IEnumerator<T> GetEnumerator() => Set.GetEnumerator();
public bool TryAdd(T item)
{
var invoke = false;
lock (Lock)
{
if (Set.TryAdd(item))
{
HashSetChanged?.Invoke(this, EventArgs.Empty);
invoke = true;
}
}
if (invoke)
{
HashSetChanged?.Invoke(this, EventArgs.Empty);
}
return invoke;
}
public bool TryRemove(T item)
{
var invoke = false;
lock (Lock)
{
if (Set.TryRemove(item))
{
invoke = true;
}
}
if (invoke)
{
HashSetChanged?.Invoke(this, EventArgs.Empty);
}
return invoke;
}
public void Clear()
{
var invoke = false;
lock (Lock)
{
if (Set.Count > 0)
{
Set.Clear();
invoke = true;
}
}
if (invoke)
{
HashSetChanged?.Invoke(this, EventArgs.Empty);
}
}
// Don't lock here, it results deadlock at wallet loading when filters arent synced.
public bool Contains(T item) => Set.Contains(item);
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
namespace WalletWasabi.Models
{
public class ObservableConcurrentHashSet<T> : IReadOnlyCollection<T> // DO NOT IMPLEMENT INotifyCollectionChanged!!! That'll break and crash the software: https://github.com/AvaloniaUI/Avalonia/issues/1988#issuecomment-431691863
{
private ConcurrentHashSet<T> Set { get; }
private object Lock { get; }
public event EventHandler HashSetChanged; // Keep it as is! Unless with the modification this bug won't come out: https://github.com/AvaloniaUI/Avalonia/issues/1988#issuecomment-431691863
public ObservableConcurrentHashSet()
{
Set = new ConcurrentHashSet<T>();
Lock = new object();
}
// Don't lock here, it results deadlock at wallet loading when filters arent synced.
public int Count => Set.Count;
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
// Don't lock here, it results deadlock at wallet loading when filters arent synced.
public IEnumerator<T> GetEnumerator() => Set.GetEnumerator();
public bool TryAdd(T item)
{
lock (Lock)
{
if (Set.TryAdd(item))
{
HashSetChanged?.Invoke(this, EventArgs.Empty);
return true;
}
return false;
}
}
public bool TryRemove(T item)
{
lock (Lock)
{
if (Set.TryRemove(item))
{
HashSetChanged?.Invoke(this, EventArgs.Empty);
return true;
}
return false;
}
}
public void Clear()
{
lock (Lock)
{
if (Set.Count > 0)
{
Set.Clear();
HashSetChanged?.Invoke(this, EventArgs.Empty);
}
}
}
// Don't lock here, it results deadlock at wallet loading when filters arent synced.
public bool Contains(T item) => Set.Contains(item);
}
}
| mit | C# |
da37b4a9cdbf3f6ebe7ba4503cc299aa39d9eac9 | update sample to request two packages | eeaquino/DotNetShipping,kylewest/DotNetShipping | SampleApp/Program.cs | SampleApp/Program.cs | using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using DotNetShipping.ShippingProviders;
namespace DotNetShipping.SampleApp
{
internal class Program
{
#region Methods
private static void Main(string[] args)
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
// You will need a license #, userid and password to utilize the UPS provider.
string upsLicenseNumber = appSettings["UPSLicenseNumber"];
string upsUserId = appSettings["UPSUserId"];
string upsPassword = appSettings["UPSPassword"];
// You will need an account # and meter # to utilize the FedEx provider.
string fedexAccountNumber = appSettings["FedExAccountNumber"];
string fedexMeterNumber = appSettings["FedExMeterNumber"];
// You will need a userId and password to use the USPS provider. Your account will also need access to the production servers.
string uspsUserId = appSettings["USPSUserId"];
string uspsPassword = appSettings["USPSPassword"];
// Setup package and destination/origin addresses
var packages = new List<Package>();
packages.Add(new Package(0, 0, 0, 35, 0));
packages.Add(new Package(0, 0, 0, 15, 0));
var origin = new Address("", "", "06405", "US");
var destination = new Address("", "", "20852", "US"); // US Address
//var destination = new Address("", "", "L4W 1S2", "CA"); // Canada Address
//var destination = new Address("Bath", "", "BA11HX", "GB"); // European Address
// Create RateManager
var rateManager = new RateManager();
// Add desired DotNetShippingProviders
rateManager.AddProvider(new UPSProvider(upsLicenseNumber, upsUserId, upsPassword));
rateManager.AddProvider(new FedExProvider(fedexAccountNumber, fedexMeterNumber));
rateManager.AddProvider(new USPSProvider(uspsUserId, uspsPassword));
// Call GetRates()
Shipment shipment = rateManager.GetRates(origin, destination, packages);
// Iterate through the rates returned
foreach (Rate rate in shipment.Rates)
{
Console.WriteLine(rate);
}
}
#endregion
}
} | using System;
using System.Collections.Specialized;
using System.Configuration;
using DotNetShipping.ShippingProviders;
namespace DotNetShipping.SampleApp
{
internal class Program
{
#region Methods
private static void Main(string[] args)
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
// You will need a license #, userid and password to utilize the UPS provider.
string upsLicenseNumber = appSettings["UPSLicenseNumber"];
string upsUserId = appSettings["UPSUserId"];
string upsPassword = appSettings["UPSPassword"];
// You will need an account # and meter # to utilize the FedEx provider.
string fedexAccountNumber = appSettings["FedExAccountNumber"];
string fedexMeterNumber = appSettings["FedExMeterNumber"];
// You will need a userId and password to use the USPS provider. Your account will also need access to the production servers.
string uspsUserId = appSettings["USPSUserId"];
string uspsPassword = appSettings["USPSPassword"];
// Setup package and destination/origin addresses
var package = new Package(0, 0, 0, 35, 0);
var origin = new Address("", "", "06405", "US");
var destination = new Address("", "", "20852", "US"); // US Address
//var destination = new Address("", "", "L4W 1S2", "CA"); // Canada Address
//var destination = new Address("Bath", "", "BA11HX", "GB"); // European Address
// Create RateManager
var rateManager = new RateManager();
// Add desired DotNetShippingProviders
rateManager.AddProvider(new UPSProvider(upsLicenseNumber, upsUserId, upsPassword));
rateManager.AddProvider(new FedExProvider(fedexAccountNumber, fedexMeterNumber));
rateManager.AddProvider(new USPSProvider(uspsUserId, uspsPassword));
// Call GetRates()
Shipment shipment = rateManager.GetRates(origin, destination, package);
// Iterate through the rates returned
foreach (Rate rate in shipment.Rates)
{
Console.WriteLine(rate);
}
}
#endregion
}
} | mit | C# |
0358c22bfcd5a26d1552628c96d9d07582b8344e | Upgrade version. | tangxuehua/ecommon,Aaron-Liu/ecommon | src/ECommon/Properties/AssemblyInfo.cs | src/ECommon/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("ECommon")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ECommon")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("b3edf459-8725-465e-a484-410b9a68df1f")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.4.3")]
[assembly: AssemblyFileVersion("1.4.3")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("ECommon")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ECommon")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("b3edf459-8725-465e-a484-410b9a68df1f")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.4.2")]
[assembly: AssemblyFileVersion("1.4.2")]
| mit | C# |
69dca5f96432202f470ac961dbc3f0a92723d650 | Fix #187 - Support for generating 'new Image()' script | nikhilk/scriptsharp,x335/scriptsharp,nikhilk/scriptsharp,x335/scriptsharp,x335/scriptsharp,nikhilk/scriptsharp | src/Libraries/Web/Html/ImageElement.cs | src/Libraries/Web/Html/ImageElement.cs | // ImageElement.cs
// Script#/Libraries/Web
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Runtime.CompilerServices;
namespace System.Html {
[IgnoreNamespace]
[Imported]
[ScriptName("Image")]
public sealed class ImageElement : Element {
public ImageElement() {
}
public ImageElement(int width) {
}
public ImageElement(int width, int height) {
}
[IntrinsicProperty]
public string Alt {
get {
return null;
}
set {
}
}
[IntrinsicProperty]
public bool Complete {
get {
return false;
}
}
[IntrinsicProperty]
public string Src {
get {
return null;
}
set {
}
}
[IntrinsicProperty]
public int Height {
get {
return 0;
}
set {
}
}
[IntrinsicProperty]
public int NaturalHeight {
get {
return 0;
}
set {
}
}
[IntrinsicProperty]
public int NaturalWidth {
get {
return 0;
}
set {
}
}
[IntrinsicProperty]
public int Width {
get {
return 0;
}
set {
}
}
}
}
| // ImageElement.cs
// Script#/Libraries/Web
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Runtime.CompilerServices;
namespace System.Html {
[IgnoreNamespace]
[Imported]
public sealed class ImageElement : Element {
private ImageElement() {
}
[IntrinsicProperty]
public string Alt {
get {
return null;
}
set {
}
}
[IntrinsicProperty]
public bool Complete {
get {
return false;
}
}
[IntrinsicProperty]
public string Src {
get {
return null;
}
set {
}
}
[IntrinsicProperty]
public int Height {
get {
return 0;
}
set {
}
}
[IntrinsicProperty]
public int NaturalHeight {
get {
return 0;
}
set {
}
}
[IntrinsicProperty]
public int NaturalWidth {
get {
return 0;
}
set {
}
}
[IntrinsicProperty]
public int Width {
get {
return 0;
}
set {
}
}
}
}
| apache-2.0 | C# |
7aba596f39d45bca3cae370035c28a757283bf79 | Fix #5 (wrong PhotoSizeResponse null check) | LouisMT/TeleBotDotNet,Naxiz/TeleBotDotNet | Responses/Types/PhotoSizeResponse.cs | Responses/Types/PhotoSizeResponse.cs | using TeleBotDotNet.Json;
namespace TeleBotDotNet.Responses.Types
{
public class PhotoSizeResponse
{
public string FileId { get; private set; }
public int Width { get; private set; }
public int Height { get; private set; }
public int? FileSize { get; private set; }
internal static PhotoSizeResponse Parse(JsonData data)
{
if (data == null || !data.Has("file_id") || !data.Has("width") || !data.Has("height"))
{
return null;
}
return new PhotoSizeResponse
{
FileId = data.Get<string>("file_id"),
Width = data.Get<int>("width"),
Height = data.Get<int>("height"),
FileSize = data.Get<int?>("file_size")
};
}
}
} | using TeleBotDotNet.Json;
namespace TeleBotDotNet.Responses.Types
{
public class PhotoSizeResponse
{
public string FileId { get; private set; }
public int Width { get; private set; }
public int Height { get; private set; }
public int? FileSize { get; private set; }
internal static PhotoSizeResponse Parse(JsonData data)
{
if (data == null || !data.Has("file_id") || data.Has("width") || data.Has("height"))
{
return null;
}
return new PhotoSizeResponse
{
FileId = data.Get<string>("file_id"),
Width = data.Get<int>("width"),
Height = data.Get<int>("height"),
FileSize = data.Get<int?>("file_size")
};
}
}
} | mit | C# |
a972db2224ecb0172cbd7d6c752745918631c500 | Build and publish Rock.Core nuget package | peteraritchie/Rock.Core,RockFramework/Rock.Core | Rock.Core/Properties/AssemblyInfo.cs | Rock.Core/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("Rock.Core")]
[assembly: AssemblyDescription("Core classes and interfaces for Rock Framework.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Quicken Loans")]
[assembly: AssemblyProduct("Rock.Core")]
[assembly: AssemblyCopyright("Copyright © Quicken Loans 2014-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("6fb79d22-8ea3-4cb0-a704-8608d679cb95")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.9.0.0")]
[assembly: AssemblyFileVersion("0.9.8")]
[assembly: AssemblyInformationalVersion("0.9.8")]
[assembly: InternalsVisibleTo("Rock.Core.UnitTests")]
| 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("Rock.Core")]
[assembly: AssemblyDescription("Core classes and interfaces for Rock Framework.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Quicken Loans")]
[assembly: AssemblyProduct("Rock.Core")]
[assembly: AssemblyCopyright("Copyright © Quicken Loans 2014-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("6fb79d22-8ea3-4cb0-a704-8608d679cb95")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.9.0.0")]
[assembly: AssemblyFileVersion("0.9.7")]
[assembly: AssemblyInformationalVersion("0.9.7")]
[assembly: InternalsVisibleTo("Rock.Core.UnitTests")]
| mit | C# |
c8356454899daadc31d54822da3a378ce4d8472c | Fix other unit test. | mysticmind/marten,mysticmind/marten,JasperFx/Marten,JasperFx/Marten,ericgreenmix/marten,ericgreenmix/marten,ericgreenmix/marten,JasperFx/Marten,mysticmind/marten,ericgreenmix/marten,mdissel/Marten,mysticmind/marten,mdissel/Marten | src/Marten/Linq/DeserializeSelector.cs | src/Marten/Linq/DeserializeSelector.cs | using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
using Baseline;
using Marten.Services;
using Npgsql;
namespace Marten.Linq
{
public class DeserializeSelector<T> : BasicSelector, ISelector<T>
{
private readonly ISerializer _serializer;
public DeserializeSelector(ISerializer serializer) : base("data")
{
_serializer = serializer;
}
public DeserializeSelector(ISerializer serializer, params string[] selectFields) : base(selectFields)
{
_serializer = serializer;
}
public T Resolve(DbDataReader reader, IIdentityMap map, QueryStatistics stats)
{
if (!typeof(T).IsSimple())
{
var json = reader.As<DbDataReader>().GetTextReader(0);
return _serializer.FromJson<T>(json);
}
return reader.GetFieldValue<T>(0);
}
public async Task<T> ResolveAsync(DbDataReader reader, IIdentityMap map, QueryStatistics stats, CancellationToken token)
{
if (!typeof(T).IsSimple())
{
var json = await reader.As<NpgsqlDataReader>().GetTextReaderAsync(0).ConfigureAwait(false);
return _serializer.FromJson<T>(json);
}
return await reader.GetFieldValueAsync<T>(0, token).ConfigureAwait(false);
}
}
} | using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
using Baseline;
using Marten.Services;
using Npgsql;
namespace Marten.Linq
{
public class DeserializeSelector<T> : BasicSelector, ISelector<T>
{
private readonly ISerializer _serializer;
public DeserializeSelector(ISerializer serializer) : base("data")
{
_serializer = serializer;
}
public DeserializeSelector(ISerializer serializer, params string[] selectFields) : base(selectFields)
{
_serializer = serializer;
}
public T Resolve(DbDataReader reader, IIdentityMap map, QueryStatistics stats)
{
if (!typeof(T).IsSimple())
{
var json = reader.As<NpgsqlDataReader>().GetTextReader(0);
return _serializer.FromJson<T>(json);
}
return reader.GetFieldValue<T>(0);
}
public async Task<T> ResolveAsync(DbDataReader reader, IIdentityMap map, QueryStatistics stats, CancellationToken token)
{
if (!typeof(T).IsSimple())
{
var json = await reader.As<NpgsqlDataReader>().GetTextReaderAsync(0).ConfigureAwait(false);
return _serializer.FromJson<T>(json);
}
return await reader.GetFieldValueAsync<T>(0, token).ConfigureAwait(false);
}
}
} | mit | C# |
6b6322e390dc51a886680c8960eadd37e546e3c2 | Update #10 | uheerme/core,uheerme/core,uheerme/core | Samesound.Services/ChannelService.cs | Samesound.Services/ChannelService.cs | using Samesound.Core;
using Samesound.Data;
using Samesound.Services.Exceptions;
using Samesound.Services.Infrastructure;
using Samesound.Services.Providers;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
namespace Samesound.Services
{
public class ChannelService : Service<Channel>
{
public ChannelService(SamesoundContext db) : base(db) { }
public virtual async Task<ICollection<Channel>> Paginate(int skip, int take)
{
return await Db.Channels
.OrderBy(c => c.Id)
.Skip(skip)
.Take(take)
.ToListAsync();
}
public virtual async Task<int> Play(Channel channel, Music music)
{
if (!channel.Musics.Any(m => m.Id == music.Id))
{
throw new ApplicationException();
}
//channel.Playing = music;
return await Update(channel);
}
public override async Task<Channel> Add(Channel channel)
{
if (Db.Channels.Any(c =>
c.Owner == channel.Owner
&& c.DateDeactivated == null))
{
throw new OwnerAlreadyHasAnActiveChannelException(
"Owner already has an active channel ("+ channel.Name + "). To create a new channel, close this one first."
);
}
return await base.Add(channel);
}
public virtual async Task<int> Deactivate(Channel channel)
{
if (!channel.IsActive())
{
throw new ChannelIsAlreadyDeactivatedException("The channel #" + channel.Id + " cannot be deactivated, since its state is not active.");
}
MusicUploadProvider.RemoveAll(channel.Id);
channel.DateDeactivated = DateTime.Now;
return await Update(channel);
}
public override async Task<int> Delete(Channel channel)
{
MusicUploadProvider.RemoveAll(channel.Id);
return await base.Delete(channel);
}
}
}
| using Samesound.Core;
using Samesound.Data;
using Samesound.Services.Exceptions;
using Samesound.Services.Infrastructure;
using Samesound.Services.Providers;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
namespace Samesound.Services
{
public class ChannelService : Service<Channel>
{
public ChannelService(SamesoundContext db) : base(db) { }
public virtual async Task<ICollection<Channel>> Paginate(int skip, int take)
{
return await Db.Channels
.OrderBy(c => c.Id)
.Skip(skip)
.Take(take)
.ToListAsync();
}
public virtual async Task<int> Play(Channel channel, Music music)
{
if (!channel.Musics.Any(m => m.Id == music.Id))
{
throw new ApplicationException();
}
//channel.Playing = music;
return await Update(channel);
}
public override async Task<Channel> Add(Channel channel)
{
if (Db.Channels.Any(c =>
c.Owner == channel.Owner
&& channel.DateDeactivated == null))
{
throw new OwnerAlreadyHasAnActiveChannelException(
"Owner already has an active channel (channel's name:"+ channel.Name + "). To create a new channel, close this one first"
);
}
return await base.Add(channel);
}
public virtual async Task<int> Deactivate(Channel channel)
{
if (!channel.IsActive())
{
throw new ChannelIsAlreadyDeactivatedException("The channel #" + channel.Id + " cannot be deactivated, since its state is not active.");
}
MusicUploadProvider.RemoveAll(channel.Id);
channel.DateDeactivated = DateTime.Now;
return await Update(channel);
}
public override async Task<int> Delete(Channel channel)
{
MusicUploadProvider.RemoveAll(channel.Id);
return await base.Delete(channel);
}
}
}
| mit | C# |
bf788f415d57a5454e8a9b2d480e3ee2b711350e | update photo collection tests | bolorundurowb/vCardLib | vCardLib.Tests/PhotoCollectionTests.cs | vCardLib.Tests/PhotoCollectionTests.cs | using NUnit.Framework;
using System;
namespace vCardLib.Tests
{
[TestFixture]
class PhotoCollectionTests
{
[Test]
public void InsertAndRemove()
{
Assert.DoesNotThrow(delegate {
Photo photo = new Photo();
PhotoCollection photoCollection = new PhotoCollection();
photoCollection.Add(photo);
photoCollection[0] = photo;
photo = photoCollection[0];
photoCollection.Remove(photo);
});
}
[Test]
public void InsertAndRemoveNonExistentIndices()
{
PhotoCollection photoCollection = new PhotoCollection();
Assert.Throws<IndexOutOfRangeException>(delegate
{
var photo_ = photoCollection[0];
});
var photo = new Photo();
Assert.Throws<IndexOutOfRangeException>(delegate
{
photoCollection[0] = photo;
});
}
}
}
| using NUnit.Framework;
using System;
namespace vCardLib.Tests
{
[TestFixture]
class PhotoCollectionTests
{
[Test]
public void InsertAndRemove()
{
Assert.DoesNotThrow(delegate {
Photo photo = new Photo();
PhotoCollection photoCollection = new PhotoCollection();
photoCollection.Add(photo);
photoCollection[0] = photo;
photo = photoCollection[0];
});
}
[Test]
public void InsertAndRemoveNonExistentIndices()
{
PhotoCollection photoCollection = new PhotoCollection();
Assert.Throws<IndexOutOfRangeException>(delegate
{
var photo_ = photoCollection[0];
});
var photo = new Photo();
Assert.Throws<IndexOutOfRangeException>(delegate
{
photoCollection[0] = photo;
});
}
}
}
| mit | C# |
af5573afccc219a1e6ce0487d22674c940ee68cd | Refactor tests. | mrydengren/lumen | src/Lumen.Tests/PayloadValidationFilterTests.cs | src/Lumen.Tests/PayloadValidationFilterTests.cs | using FluentValidation;
using NUnit.Framework;
using Ninject;
namespace Lumen.Tests
{
[TestFixture]
public class PayloadValidationFilterTests
{
public class TestApplicationService : ApplicationService
{
public class TestPayload
{
public string Text { get; set; }
}
public class TestPayloadValidator : AbstractValidator<TestPayload>
{
public TestPayloadValidator()
{
RuleFor(x => x.Text).NotEmpty();
}
}
protected override void ExecuteCore() { }
}
[Test]
public void Can_throw_on_non_valid_payload()
{
// Arrange.
var kernel = new StandardKernel();
kernel.Bind<PayloadValidator>().ToSelf().InSingletonScope();
kernel.Bind<IValidator<TestApplicationService.TestPayload>>().To<TestApplicationService.TestPayloadValidator>().InSingletonScope();
kernel.Bind<PayloadValidationFilter<ApplicationServiceContext>>().ToSelf().InSingletonScope();
var filter = kernel.Get<PayloadValidationFilter<ApplicationServiceContext>>();
var service = new TestApplicationService();
var context = new ApplicationServiceContext(new TestApplicationService.TestPayload());
// Act & Assert.
Assert.Throws<PayloadValidationException>(() => filter.Process(new PipelineContext<TestApplicationService, object>(service), context));
}
}
} | using FluentValidation;
using NUnit.Framework;
using Ninject;
namespace Lumen.Tests
{
[TestFixture]
public class PayloadValidationFilterTests
{
public class TestContext : IPayload
{
public TestContext(dynamic payload)
{
Payload = payload;
}
public dynamic Payload { get; private set; }
}
public class TestApplicationService : ApplicationService
{
public class TestPayload
{
public string Text { get; set; }
}
public class TestPayloadValidator : AbstractValidator<TestPayload>
{
public TestPayloadValidator()
{
RuleFor(x => x.Text).NotEmpty();
}
}
protected override void ExecuteCore() { }
}
[Test]
public void Can_throw_on_non_valid_payload()
{
var kernel = new StandardKernel();
kernel.Bind<PayloadValidator>().ToSelf().InSingletonScope();
kernel.Bind<IValidator<TestApplicationService.TestPayload>>().To<TestApplicationService.TestPayloadValidator>().InSingletonScope();
kernel.Bind<PayloadValidationFilter<TestContext>>().ToSelf().InSingletonScope();
var context = new TestContext(new TestApplicationService.TestPayload());
var filter = kernel.Get<PayloadValidationFilter<TestContext>>();
var service = new TestApplicationService();
Assert.Throws<PayloadValidationException>(() => filter.Process(new PipelineContext<TestApplicationService, object>(service), context));
}
}
} | mit | C# |
ce4995eb204f55f8902f2eabc162f447193cf2a0 | Fix start index for string - sub mounting modules | jmptrader/manos,mdavid/manos-spdy,jacksonh/manos,jmptrader/manos,jacksonh/manos,mdavid/manos-spdy,mdavid/manos-spdy,mdavid/manos-spdy,jmptrader/manos,jmptrader/manos,jacksonh/manos,jmptrader/manos,jacksonh/manos,mdavid/manos-spdy,jacksonh/manos,jacksonh/manos,mdavid/manos-spdy,jmptrader/manos,jacksonh/manos,jmptrader/manos,jacksonh/manos,mdavid/manos-spdy,jmptrader/manos | src/Manos/Manos.Routing/StringMatchOperation.cs | src/Manos/Manos.Routing/StringMatchOperation.cs | //
// Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
using System.Collections.Specialized;
using Manos.Collections;
namespace Manos.Routing
{
public class StringMatchOperation : IMatchOperation
{
private string str;
public StringMatchOperation (string str)
{
String = str;
}
public string String {
get { return str; }
set {
if (value == null)
throw new ArgumentNullException ("value");
if (value.Length == 0)
throw new ArgumentException ("StringMatch operations should not use empty strings.");
str = value.ToLower();
}
}
public bool IsMatch (string input, int start, out DataDictionary data, out int end)
{
if (!StartsWith (input, start, String)) {
data = null;
end = start;
return false;
}
data = null;
end = start + String.Length;
return true;
}
public static bool StartsWith (string input, int start, string str)
{
if (input.Length < str.Length + start)
return false;
return String.Compare (input, start, str, 0, str.Length, StringComparison.OrdinalIgnoreCase) == 0;
}
}
}
| //
// Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
using System.Collections.Specialized;
using Manos.Collections;
namespace Manos.Routing
{
public class StringMatchOperation : IMatchOperation
{
private string str;
public StringMatchOperation (string str)
{
String = str;
}
public string String {
get { return str; }
set {
if (value == null)
throw new ArgumentNullException ("value");
if (value.Length == 0)
throw new ArgumentException ("StringMatch operations should not use empty strings.");
str = value.ToLower();
}
}
public bool IsMatch (string input, int start, out DataDictionary data, out int end)
{
if (!StartsWith (input, start, String)) {
data = null;
end = start;
return false;
}
data = null;
end = start + String.Length;
return true;
}
public static bool StartsWith (string input, int start, string str)
{
if (input.Length < str.Length + start)
return false;
return String.Compare (input, 0, str, 0, str.Length, StringComparison.OrdinalIgnoreCase) == 0;
}
}
}
| mit | C# |
8d99449b08f8717354fc432ed575847fe64261d0 | fix bug #791 (#795) | geffzhang/Ocelot,TomPallister/Ocelot,geffzhang/Ocelot,TomPallister/Ocelot | src/Ocelot/Configuration/LoadBalancerOptions.cs | src/Ocelot/Configuration/LoadBalancerOptions.cs | using Ocelot.LoadBalancer.LoadBalancers;
namespace Ocelot.Configuration
{
public class LoadBalancerOptions
{
public LoadBalancerOptions(string type, string key, int expiryInMs)
{
Type = string.IsNullOrWhiteSpace(type) ? nameof(NoLoadBalancer) : type;
Key = key;
ExpiryInMs = expiryInMs;
}
public string Type { get; }
public string Key { get; }
public int ExpiryInMs { get; }
}
}
| using Ocelot.LoadBalancer.LoadBalancers;
namespace Ocelot.Configuration
{
public class LoadBalancerOptions
{
public LoadBalancerOptions(string type, string key, int expiryInMs)
{
Type = type ?? nameof(NoLoadBalancer);
Key = key;
ExpiryInMs = expiryInMs;
}
public string Type { get; }
public string Key { get; }
public int ExpiryInMs { get; }
}
}
| mit | C# |
b9c0503edab35c08f26bf5498bd913d0e47561ef | Fix threading issue with StaticRandomGenerator | HelloKitty/317refactor | src/Rs317.Library/math/StaticRandomGenerator.cs | src/Rs317.Library/math/StaticRandomGenerator.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
//TODO: Add namespace
public static class StaticRandomGenerator
{
//TODO: If we do any async/await this will potentially fail? Maybe? TODO look into it.
//Unique per thread.
private static readonly System.Random internalRandomGenerator;
static StaticRandomGenerator()
{
internalRandomGenerator = new System.Random();
}
[MethodImpl(MethodImplOptions.Synchronized)]
public static int Next()
{
return internalRandomGenerator.Next();
}
[MethodImpl(MethodImplOptions.Synchronized)]
public static int Next(int max)
{
//.NET random doesn't support anything less than 0.
if (max < 0) throw new ArgumentOutOfRangeException(nameof(max));
return internalRandomGenerator.Next(max);
}
[MethodImpl(MethodImplOptions.Synchronized)]
public static double NextDouble()
{
return internalRandomGenerator.NextDouble();
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//TODO: Add namespace
public static class StaticRandomGenerator
{
//TODO: If we do any async/await this will potentially fail? Maybe? TODO look into it.
//Unique per thread.
[ThreadStatic]
private static readonly System.Random internalRandomGenerator;
static StaticRandomGenerator()
{
internalRandomGenerator = new System.Random();
}
public static int Next()
{
return internalRandomGenerator.Next();
}
public static int Next(int max)
{
//.NET random doesn't support anything less than 0.
if (max < 0) throw new ArgumentOutOfRangeException(nameof(max));
return internalRandomGenerator.Next(max);
}
public static double NextDouble()
{
return internalRandomGenerator.NextDouble();
}
}
| mit | C# |
223c89e9cba887617c5ca2e6e3bac6daa644df83 | Fix failing unit test | vbfox/KitsuneRoslyn | TestDiagnostics/RoslynExtensions/DiagnosticExtensions.cs | TestDiagnostics/RoslynExtensions/DiagnosticExtensions.cs | using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System;
namespace BlackFox.Roslyn.TestDiagnostics.RoslynExtensions
{
static class DiagnosticExtensions
{
public static TSyntaxNode GetAncestorSyntaxNode<TSyntaxNode>(this Diagnostic diagnostic, SyntaxNode root)
where TSyntaxNode : SyntaxNode
{
if (diagnostic == null)
{
throw new ArgumentNullException("diagnostic");
}
if (root == null)
{
throw new ArgumentNullException("root");
}
var diagnosticSpan = diagnostic.Location.SourceSpan;
return root.FindToken(diagnosticSpan.Start)
.Parent
.AncestorsAndSelf()
.Where(x => x.GetLocation().SourceSpan == diagnosticSpan)
.OfType<TSyntaxNode>()
.First();
}
}
}
| using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System;
namespace BlackFox.Roslyn.TestDiagnostics.RoslynExtensions
{
static class DiagnosticExtensions
{
public static TSyntaxNode GetAncestorSyntaxNode<TSyntaxNode>(this Diagnostic diagnostic, SyntaxNode root)
where TSyntaxNode : SyntaxNode
{
if (diagnostic == null)
{
throw new ArgumentNullException("diagnostic");
}
if (root == null)
{
throw new ArgumentNullException("root");
}
var diagnosticSpan = diagnostic.Location.SourceSpan;
return root.FindToken(diagnosticSpan.Start)
.Parent
.AncestorsAndSelf()
.OfType<TSyntaxNode>()
.First();
}
}
}
| bsd-2-clause | C# |
5efbb7319e5a197c6a784da841f6c61d72cf511d | Fix typo | GeorgDangl/WebDocu,GeorgDangl/WebDocu,GeorgDangl/WebDocu | src/Dangl.WebDocumentation/Views/Home/ManageAccount.cshtml | src/Dangl.WebDocumentation/Views/Home/ManageAccount.cshtml | @using Microsoft.Extensions.Options
@inject IOptions<AppSettings> AppSettings
<h1>Manage Account</h1>
<p>You user account is managed on Dangl<strong>.Identity</strong>. <a href="@AppSettings.Value.DanglIdentityBaseUrl.TrimEnd('/')/account">You can edit your account details there.</a></p>
| @using Microsoft.Extensions.Options
@inject IOptions<AppSettings> AppSettings
<h1>Manage Account</h1>
<p>You user account is managed on Dangl<strong>.Identity.</strong>. <a href="@AppSettings.Value.DanglIdentityBaseUrl.TrimEnd('/')/account">You can edit your account details there.</a></p>
| mit | C# |
35d105f53459854cd977833d1459be73c9637efb | add missing favicon | planetClaire/Orchard-LETS,planetClaire/Orchard-LETS,planetClaire/Orchard-LETS,planetClaire/Orchard-LETS,planetClaire/Orchard-LETS | src/Orchard.Web/Themes/LETSBootstrap/Views/Document.cshtml | src/Orchard.Web/Themes/LETSBootstrap/Views/Document.cshtml | @using Orchard.Localization
@using Orchard.Mvc.Html;
@{
string title = Convert.ToString(Model.Title);
string siteName = Convert.ToString(WorkContext.CurrentSite.SiteName);
bool isRtl = WorkContext.CurrentCultureInfo().TextInfo.IsRightToLeft;
Html.AddPageClassNames("dir-" + (isRtl ? "rtl" : "ltr"));
var pageTitle = Html.Title(title, siteName);
}
<!DOCTYPE html>
<html lang="@WorkContext.CurrentCulture" class="static @Html.ClassForPage()" dir="@(isRtl?"rtl":"ltr")">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta property="og:url" content='@Request.Url.AbsoluteUri.Replace("http://", "https://")' />
<meta property="og:title" content="@pageTitle" />
<link rel="shortcut icon" href="~/themes/LETSBootstrap/Content/logo.png" type="image/x-icon">
<title>@pageTitle</title>
@Display(Model.Head)
@*<script>(function (d) { d.className = "dyn" + d.className.substring(6, d.className.length); })(document.documentElement);</script>*@
</head>
<body>
@Display(Model.Body)
@Display(Model.Tail)
</body>
</html> | @using Orchard.Localization
@using Orchard.Mvc.Html;
@{
string title = Convert.ToString(Model.Title);
string siteName = Convert.ToString(WorkContext.CurrentSite.SiteName);
bool isRtl = WorkContext.CurrentCultureInfo().TextInfo.IsRightToLeft;
Html.AddPageClassNames("dir-" + (isRtl ? "rtl" : "ltr"));
var pageTitle = Html.Title(title, siteName);
}
<!DOCTYPE html>
<html lang="@WorkContext.CurrentCulture" class="static @Html.ClassForPage()" dir="@(isRtl?"rtl":"ltr")">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta property="og:url" content='@Request.Url.AbsoluteUri.Replace("http://", "https://")' />
<meta property="og:title" content="@pageTitle" />
<title>@pageTitle</title>
@Display(Model.Head)
@*<script>(function (d) { d.className = "dyn" + d.className.substring(6, d.className.length); })(document.documentElement);</script>*@
</head>
<body>
@Display(Model.Body)
@Display(Model.Tail)
</body>
</html> | bsd-3-clause | C# |
f3824da64b2596b49fe317fe784b30d831c9cc19 | Fix - Corretto reperimento codice chiamata | vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf | src/backend/SO115App.FakePersistenceJSon/GestioneIntervento/GetMaxCodice.cs | src/backend/SO115App.FakePersistenceJSon/GestioneIntervento/GetMaxCodice.cs | using Newtonsoft.Json;
using SO115App.API.Models.Classi.Soccorso;
using SO115App.API.Models.Servizi.Infrastruttura.GestioneSoccorso;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace SO115App.FakePersistenceJSon.GestioneIntervento
{
public class GetMaxCodice : IGetMaxCodice
{
public int GetMax()
{
int MaxIdSintesi;
string filepath = "Fake/ListaRichiesteAssistenza.json";
string json;
using (StreamReader r = new StreamReader(filepath))
{
json = r.ReadToEnd();
}
List<RichiestaAssistenzaRead> ListaRichieste = JsonConvert.DeserializeObject<List<RichiestaAssistenzaRead>>(json);
if (ListaRichieste != null)
MaxIdSintesi = Convert.ToInt16(ListaRichieste.OrderByDescending(x => x.Codice).FirstOrDefault().Codice.Split('-')[1]);
else
MaxIdSintesi = 0;
return MaxIdSintesi;
}
}
}
| using Newtonsoft.Json;
using SO115App.API.Models.Classi.Soccorso;
using SO115App.API.Models.Servizi.Infrastruttura.GestioneSoccorso;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace SO115App.FakePersistenceJSon.GestioneIntervento
{
public class GetMaxCodice : IGetMaxCodice
{
public int GetMax()
{
int MaxIdSintesi;
string filepath = "Fake/ListaRichiesteAssistenza.json";
string json;
using (StreamReader r = new StreamReader(filepath))
{
json = r.ReadToEnd();
}
List<RichiestaAssistenzaRead> ListaRichieste = JsonConvert.DeserializeObject<List<RichiestaAssistenzaRead>>(json);
if (ListaRichieste != null)
MaxIdSintesi = Convert.ToInt16(ListaRichieste.OrderByDescending(x => x.Codice).FirstOrDefault().Codice.Split('-')[1]);
else
MaxIdSintesi = 1;
return MaxIdSintesi;
}
}
}
| agpl-3.0 | C# |
8ec97762374f1fdc59c6606594fd60c4e4e201c2 | Set Mac DatePicker to calendar style. | TheBrainTech/xwt | Xwt.Mac/Xwt.Mac/DatePickerBackend.cs | Xwt.Mac/Xwt.Mac/DatePickerBackend.cs | //
// DatePickerBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2013 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using MonoMac.AppKit;
using MonoMac.Foundation;
namespace Xwt.Mac
{
public class DatePickerBackend: ViewBackend<NSDatePicker,IDatePickerEventSink>, IDatePickerBackend
{
public DatePickerBackend ()
{
}
public override void Initialize ()
{
base.Initialize ();
ViewObject = new MacDatePicker ();
NSDatePicker datePicker = (NSDatePicker)ViewObject;
datePicker.DatePickerStyle = NSDatePickerStyle.ClockAndCalendar;
datePicker.DatePickerElements = NSDatePickerElementFlags.YearMonthDate;
}
public override void EnableEvent (object eventId)
{
base.EnableEvent (eventId);
if (eventId is DatePickerEvent)
Widget.Activated += HandleActivated;
}
public override void DisableEvent (object eventId)
{
base.DisableEvent (eventId);
if (eventId is DatePickerEvent)
Widget.Activated -= HandleActivated;
}
void HandleActivated (object sender, EventArgs e)
{
ApplicationContext.InvokeUserCode (((IDatePickerEventSink)EventSink).ValueChanged);
}
#region IDatePickerBackend implementation
public DateTime DateTime {
get {
return (DateTime)Widget.DateValue;
}
set {
Widget.DateValue = value;
}
}
#endregion
}
class MacDatePicker: NSDatePicker, IViewObject
{
public NSView View { get { return this; } }
public ViewBackend Backend { get; set; }
}
}
| //
// DatePickerBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2013 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using MonoMac.AppKit;
using MonoMac.Foundation;
namespace Xwt.Mac
{
public class DatePickerBackend: ViewBackend<NSDatePicker,IDatePickerEventSink>, IDatePickerBackend
{
public DatePickerBackend ()
{
}
public override void Initialize ()
{
base.Initialize ();
ViewObject = new MacDatePicker ();
}
public override void EnableEvent (object eventId)
{
base.EnableEvent (eventId);
if (eventId is DatePickerEvent)
Widget.Activated += HandleActivated;
}
public override void DisableEvent (object eventId)
{
base.DisableEvent (eventId);
if (eventId is DatePickerEvent)
Widget.Activated -= HandleActivated;
}
void HandleActivated (object sender, EventArgs e)
{
ApplicationContext.InvokeUserCode (((IDatePickerEventSink)EventSink).ValueChanged);
}
#region IDatePickerBackend implementation
public DateTime DateTime {
get {
return (DateTime)Widget.DateValue;
}
set {
Widget.DateValue = value;
}
}
#endregion
}
class MacDatePicker: NSDatePicker, IViewObject
{
public NSView View { get { return this; } }
public ViewBackend Backend { get; set; }
}
}
| mit | C# |
246fc65b2e7daeaf2cf7b6b15ff43816fc77b019 | Update comments. | damianh/LimitsMiddleware,damianh/LimitsMiddleware | src/LimitsMiddleware.OwinAppBuilder/AppBuilderExtensions.MaxBandwidthGlobal.cs | src/LimitsMiddleware.OwinAppBuilder/AppBuilderExtensions.MaxBandwidthGlobal.cs | namespace Owin
{
using System;
using LimitsMiddleware;
using AppFunc = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>;
using MidFunc = System.Func<
System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>,
System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>
>;
public static partial class AppBuilderExtensions
{
/// <summary>
/// Limits the bandwith used globally by the subsequent stages in the owin pipeline.
/// </summary>
/// <param name="app">The IAppBuilder instance.</param>
/// <param name="maxBytesPerSecond">The maximum number of bytes per second to be transferred. Use 0 or a negative
/// number to specify infinite bandwidth.</param>
/// <returns>The IAppBuilder instance.</returns>
public static IAppBuilder MaxBandwidthGlobal(this IAppBuilder app, int maxBytesPerSecond)
{
app.MustNotNull("app");
return MaxBandwidthGlobal(app, () => maxBytesPerSecond);
}
/// <summary>
/// Limits the bandwith used globally by the subsequent stages in the owin pipeline.
/// </summary>
/// <param name="app">The IAppBuilder instance.</param>
/// <param name="getMaxBytesPerSecond">A delegate to retrieve the maximum number of bytes per second to be transferred.
/// Allows you to supply different values at runtime. Use 0 or a negative number to specify infinite bandwidth.</param>
/// <returns>The app instance.</returns>
public static IAppBuilder MaxBandwidthGlobal(this IAppBuilder app, Func<int> getMaxBytesPerSecond)
{
app.MustNotNull("app");
app.Use(Limits.MaxBandwidthGlobal(getMaxBytesPerSecond));
return app;
}
}
}
| namespace Owin
{
using System;
using LimitsMiddleware;
using AppFunc = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>;
using MidFunc = System.Func<
System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>,
System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>
>;
public static partial class AppBuilderExtensions
{
/// <summary>
/// Limits the bandwith used by the subsequent stages in the owin pipeline.
/// </summary>
/// <param name="app">The IAppBuilder instance.</param>
/// <param name="maxBytesPerSecond">The maximum number of bytes per second to be transferred. Use 0 or a negative
/// number to specify infinite bandwidth.</param>
/// <returns>The IAppBuilder instance.</returns>
public static IAppBuilder MaxBandwidthGlobal(this IAppBuilder app, int maxBytesPerSecond)
{
app.MustNotNull("app");
return MaxBandwidthGlobal(app, () => maxBytesPerSecond);
}
/// <summary>
/// Limits the bandwith used by the subsequent stages in the owin pipeline.
/// </summary>
/// <param name="app">The IAppBuilder instance.</param>
/// <param name="getMaxBytesPerSecond">A delegate to retrieve the maximum number of bytes per second to be transferred.
/// Allows you to supply different values at runtime. Use 0 or a negative number to specify infinite bandwidth.</param>
/// <returns>The app instance.</returns>
public static IAppBuilder MaxBandwidthGlobal(this IAppBuilder app, Func<int> getMaxBytesPerSecond)
{
app.MustNotNull("app");
app.Use(Limits.MaxBandwidthGlobal(getMaxBytesPerSecond));
return app;
}
}
}
| mit | C# |
356f37e4fd7cf32b2f596e685d0ce987ebb38bfc | Update text case for CreateSampleLesson | GGProductions/LetterStormUnitTests | Assetts/Classes/GGProduction/LetterStorm/Data/Collections/LessonBookTests.cs | Assetts/Classes/GGProduction/LetterStorm/Data/Collections/LessonBookTests.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using GGProductions.LetterStorm.Data.Collections;
namespace Test.GGProductions.LetterStorm.Data.Collections
{
[TestClass]
public class LessonBookTests
{
[TestMethod]
public void CreateSampleLessonTest()
{
// Create a lesson book with a sample lesson
LessonBook lessonBook = new LessonBook();
lessonBook.CreateSampleLessons();
// Verify a lesson was created and that it has the correct name
Assert.AreEqual(5, lessonBook.Lessons.Count);
Assert.AreEqual("K5 Sample", lessonBook.Lessons[0].Name);
// Verify the lesson's words were created
Assert.AreEqual(5, lessonBook.Lessons[0].Words.Count);
Assert.AreEqual("cat", lessonBook.Lessons[0].Words[0].Text);
Assert.AreEqual("dog", lessonBook.Lessons[0].Words[1].Text);
Assert.AreEqual("bug", lessonBook.Lessons[0].Words[2].Text);
Assert.AreEqual("fish", lessonBook.Lessons[0].Words[3].Text);
Assert.AreEqual("horse", lessonBook.Lessons[0].Words[4].Text);
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using GGProductions.LetterStorm.Data.Collections;
namespace Test.GGProductions.LetterStorm.Data.Collections
{
[TestClass]
public class LessonBookTests
{
[TestMethod]
public void CreateSampleLessonTest()
{
// Create a lesson book with a sample lesson
LessonBook lessonBook = new LessonBook();
lessonBook.CreateSampleLesson();
// Verify a lesson was created and that it has the correct name
Assert.AreEqual(1, lessonBook.Lessons.Count);
Assert.AreEqual("Sample Lesson", lessonBook.Lessons[0].Name);
// Verify the lesson's words were created
Assert.AreEqual(4, lessonBook.Lessons[0].Words.Count);
Assert.AreEqual("cat", lessonBook.Lessons[0].Words[0].Text);
Assert.AreEqual("dog", lessonBook.Lessons[0].Words[1].Text);
Assert.AreEqual("fish", lessonBook.Lessons[0].Words[2].Text);
Assert.AreEqual("horse", lessonBook.Lessons[0].Words[3].Text);
}
}
}
| mit | C# |
65f6f098c966f1b4b8c52dcdc1781e9784465c53 | Update _Navbar.cshtml | reactiveui/website,reactiveui/website,reactiveui/website,reactiveui/website | input/_Navbar.cshtml | input/_Navbar.cshtml | @{
List<Tuple<string, string>> pages = new List<Tuple<string, string>>
{
Tuple.Create("Blog", Context.GetLink("blog")),
Tuple.Create("Meetup", Context.GetLink("meetup")),
Tuple.Create("Training", Context.GetLink("training")),
Tuple.Create("Documentation", Context.GetLink("docs")),
Tuple.Create("API", Context.GetLink("api")),
Tuple.Create("Contribute", Context.GetLink("contribute")),
Tuple.Create("Support", Context.GetLink("support")),
Tuple.Create("About", Context.GetLink("about")),
};
foreach(Tuple<string, string> page in pages)
{
string active = Context.GetLink(Document).StartsWith(page.Item2) ? "active" : null;
<li class="@active"><a href="@page.Item2">@Html.Raw(page.Item1)</a></li>
}
}
| @{
List<Tuple<string, string>> pages = new List<Tuple<string, string>>
{
Tuple.Create("Blog", Context.GetLink("blog")),
Tuple.Create("Meetup", Context.GetLink("meetup")),
Tuple.Create("Training", Context.GetLink("training")),
Tuple.Create("Documentation", Context.GetLink("docs")),
Tuple.Create("API", Context.GetLink("api")),
Tuple.Create("Contribute", Context.GetLink("contribute")),
Tuple.Create("Donate", Context.GetLink("donate")),
Tuple.Create("Support", Context.GetLink("support")),
Tuple.Create("About", Context.GetLink("about")),
};
foreach(Tuple<string, string> page in pages)
{
string active = Context.GetLink(Document).StartsWith(page.Item2) ? "active" : null;
<li class="@active"><a href="@page.Item2">@Html.Raw(page.Item1)</a></li>
}
}
| mit | C# |
bb0db4c1a22235dd093570a09e282884ae7cba1a | Update GoogleAnalyticsPlatform.cs | KSemenenko/Google-Analytics-for-Xamarin-Forms,KSemenenko/GoogleAnalyticsForXamarinForms | Plugin.GoogleAnalytics/Plugin.GoogleAnalytics.Mac/GoogleAnalyticsPlatform.cs | Plugin.GoogleAnalytics/Plugin.GoogleAnalytics.Mac/GoogleAnalyticsPlatform.cs | using System;
using Plugin.GoogleAnalytics.Abstractions;
using Plugin.GoogleAnalytics.Abstractions.Model;
namespace Plugin.GoogleAnalytics
{
public partial class GoogleAnalytics
{
static GoogleAnalytics()
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (!Current.Config.ReportUncaughtExceptions)
return;
Current.Tracker.SendException(e.ExceptionObject as Exception, true);
}
}
}
| using System;
using Plugin.GoogleAnalytics.Abstractions;
using Plugin.GoogleAnalytics.Abstractions.Model;
namespace Plugin.GoogleAnalytics
{
public partial class GoogleAnalytics
{
static GoogleAnalytics()
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Current.Tracker.SendException(e.ExceptionObject as Exception, true);
}
}
} | mit | C# |
215885a43643ad1597534650d08f2d50ff98566b | Disable combat mode. | space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14-content | Content.Client/Input/ContentContexts.cs | Content.Client/Input/ContentContexts.cs | using Content.Shared.Input;
using Robust.Shared.Input;
namespace Content.Client.Input
{
/// <summary>
/// Contains a helper function for setting up all content
/// contexts, and modifying existing engine ones.
/// </summary>
public static class ContentContexts
{
public static void SetupContexts(IInputContextContainer contexts)
{
var common = contexts.GetContext("common");
common.AddFunction(ContentKeyFunctions.FocusChat);
common.AddFunction(ContentKeyFunctions.ExamineEntity);
var human = contexts.GetContext("human");
human.AddFunction(ContentKeyFunctions.SwapHands);
human.AddFunction(ContentKeyFunctions.Drop);
human.AddFunction(ContentKeyFunctions.ActivateItemInHand);
human.AddFunction(ContentKeyFunctions.OpenCharacterMenu);
human.AddFunction(ContentKeyFunctions.UseItemInHand);
human.AddFunction(ContentKeyFunctions.ActivateItemInWorld);
human.AddFunction(ContentKeyFunctions.ThrowItemInHand);
human.AddFunction(ContentKeyFunctions.OpenContextMenu);
// Disabled until there is feedback, so hitting tab doesn't suddenly break interaction.
// human.AddFunction(ContentKeyFunctions.ToggleCombatMode);
var ghost = contexts.New("ghost", "common");
ghost.AddFunction(EngineKeyFunctions.MoveUp);
ghost.AddFunction(EngineKeyFunctions.MoveDown);
ghost.AddFunction(EngineKeyFunctions.MoveLeft);
ghost.AddFunction(EngineKeyFunctions.MoveRight);
ghost.AddFunction(EngineKeyFunctions.Run);
ghost.AddFunction(ContentKeyFunctions.OpenContextMenu);
}
}
}
| using Content.Shared.Input;
using Robust.Shared.Input;
namespace Content.Client.Input
{
/// <summary>
/// Contains a helper function for setting up all content
/// contexts, and modifying existing engine ones.
/// </summary>
public static class ContentContexts
{
public static void SetupContexts(IInputContextContainer contexts)
{
var common = contexts.GetContext("common");
common.AddFunction(ContentKeyFunctions.FocusChat);
common.AddFunction(ContentKeyFunctions.ExamineEntity);
var human = contexts.GetContext("human");
human.AddFunction(ContentKeyFunctions.SwapHands);
human.AddFunction(ContentKeyFunctions.Drop);
human.AddFunction(ContentKeyFunctions.ActivateItemInHand);
human.AddFunction(ContentKeyFunctions.OpenCharacterMenu);
human.AddFunction(ContentKeyFunctions.UseItemInHand);
human.AddFunction(ContentKeyFunctions.ActivateItemInWorld);
human.AddFunction(ContentKeyFunctions.ThrowItemInHand);
human.AddFunction(ContentKeyFunctions.OpenContextMenu);
human.AddFunction(ContentKeyFunctions.ToggleCombatMode);
var ghost = contexts.New("ghost", "common");
ghost.AddFunction(EngineKeyFunctions.MoveUp);
ghost.AddFunction(EngineKeyFunctions.MoveDown);
ghost.AddFunction(EngineKeyFunctions.MoveLeft);
ghost.AddFunction(EngineKeyFunctions.MoveRight);
ghost.AddFunction(EngineKeyFunctions.Run);
ghost.AddFunction(ContentKeyFunctions.OpenContextMenu);
}
}
}
| mit | C# |
7860fce8a0642b22bc180f0ba1ad8819eb7269df | Add EOF newline to IDevice.Obsoletes.cs. | danpierce1/Colore,WolfspiritM/Colore,CoraleStudios/Colore | Corale.Colore/Core/IDevice.Obsoletes.cs | Corale.Colore/Core/IDevice.Obsoletes.cs | // ---------------------------------------------------------------------------------------
// <copyright file="IDevice.Obsoletes.cs" company="Corale">
// Copyright © 2015 by Adam Hellberg and Brandon Scott.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Disclaimer: Corale and/or Colore is in no way affiliated with Razer and/or any
// of its employees and/or licensors. Corale, Adam Hellberg, and/or Brandon Scott
// do not take responsibility for any harm caused, direct or indirect, to any
// Razer peripherals via the use of Colore.
//
// "Razer" is a trademark of Razer USA Ltd.
// </copyright>
// ---------------------------------------------------------------------------------------
namespace Corale.Colore.Core
{
using System;
using Corale.Colore.Annotations;
/// <summary>
/// Interface for functionality common with all devices.
/// </summary>
public partial interface IDevice
{
/// <summary>
/// Sets the color of all components on this device.
/// </summary>
/// <param name="color">Color to set.</param>
[Obsolete("Set is deprecated, please use SetAll(Color).", false)]
[PublicAPI]
void Set(Color color);
/// <summary>
/// Updates the device to use the effect pointed to by the specified GUID.
/// </summary>
/// <param name="guid">GUID to set.</param>
[Obsolete("Set is deprecated, please use SetGuid(Guid).", false)]
[PublicAPI]
void Set(Guid guid);
}
}
| // ---------------------------------------------------------------------------------------
// <copyright file="IDevice.Obsoletes.cs" company="Corale">
// Copyright © 2015 by Adam Hellberg and Brandon Scott.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Disclaimer: Corale and/or Colore is in no way affiliated with Razer and/or any
// of its employees and/or licensors. Corale, Adam Hellberg, and/or Brandon Scott
// do not take responsibility for any harm caused, direct or indirect, to any
// Razer peripherals via the use of Colore.
//
// "Razer" is a trademark of Razer USA Ltd.
// </copyright>
// ---------------------------------------------------------------------------------------
namespace Corale.Colore.Core
{
using System;
using Corale.Colore.Annotations;
/// <summary>
/// Interface for functionality common with all devices.
/// </summary>
public partial interface IDevice
{
/// <summary>
/// Sets the color of all components on this device.
/// </summary>
/// <param name="color">Color to set.</param>
[Obsolete("Set is deprecated, please use SetAll(Color).", false)]
[PublicAPI]
void Set(Color color);
/// <summary>
/// Updates the device to use the effect pointed to by the specified GUID.
/// </summary>
/// <param name="guid">GUID to set.</param>
[Obsolete("Set is deprecated, please use SetGuid(Guid).", false)]
[PublicAPI]
void Set(Guid guid);
}
} | mit | C# |
5603be33edd2521541c5cffffc0bb5d9f7b07be0 | Change "Note" widget default height | danielchalmers/DesktopWidgets | DesktopWidgets/Widgets/Note/Settings.cs | DesktopWidgets/Widgets/Note/Settings.cs | using System.ComponentModel;
using DesktopWidgets.Classes;
namespace DesktopWidgets.Widgets.Note
{
public class Settings : WidgetSettingsBase
{
public Settings()
{
Width = 160;
Height = 132;
}
[DisplayName("Saved Text")]
public string Text { get; set; }
}
} | using System.ComponentModel;
using DesktopWidgets.Classes;
namespace DesktopWidgets.Widgets.Note
{
public class Settings : WidgetSettingsBase
{
public Settings()
{
Width = 160;
Height = 200;
}
[DisplayName("Saved Text")]
public string Text { get; set; }
}
} | apache-2.0 | C# |
b3082d4389d21be92b02a2361adc1d9d34e53876 | Fix notimplemented exception | dolkensp/Dolkens.Framework | Dolkens.Framework.Caching.Stub/Cache.cs | Dolkens.Framework.Caching.Stub/Cache.cs | using System;
using Dolkens.Framework.Caching.Interfaces;
using ASP = System.Runtime.Caching;
namespace Dolkens.Framework.Caching.Stub
{
public class Cache : ICache
{
public Object this[String key]
{
get { return null; }
set { }
}
public Boolean Add(ASP.CacheItem item, ASP.CacheItemPolicy policy) { return false; }
public Object Get(String key, String regionName = null)
{
return null;
}
public Object Remove(String key, String regionName = null)
{
return null;
}
public ICacheDependency DefaultDependency
{
get { return new CacheDependency { }; }
}
public ICacheSettings DefaultSettings
{
get { return new CacheSettings { }; }
}
}
} | using System;
using Dolkens.Framework.Caching.Interfaces;
using ASP = System.Runtime.Caching;
namespace Dolkens.Framework.Caching.Stub
{
public class Cache : ICache
{
public Object this[String key]
{
get { return null; }
set { }
}
public Boolean Add(ASP.CacheItem item, ASP.CacheItemPolicy policy)
{
throw new NotImplementedException();
}
public Object Get(String key, String regionName = null)
{
return null;
}
public Object Remove(String key, String regionName = null)
{
return null;
}
public ICacheDependency DefaultDependency
{
get { return new CacheDependency { }; }
}
public ICacheSettings DefaultSettings
{
get { return new CacheSettings { }; }
}
}
} | mit | C# |
990ed090f91ac08d096b4f8d918732214d5bf81e | Add two book discount scenario | kirkchen/KataPotter.CSharp | KataPotter/KataPotterPriceCalculator.cs | KataPotter/KataPotterPriceCalculator.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KataPotter
{
public class KataPotterPriceCalculator
{
private static readonly double BOOK_UNIT_PRICE = 8;
private static readonly double TWO_BOOKS_DISCOUNT_RATE = 0.95;
public double Calculate(Dictionary<string, int> booksToBuy)
{
var totalCount = booksToBuy.Sum(i => i.Value);
var totalPrice = totalCount * BOOK_UNIT_PRICE;
if (totalCount > 1)
{
totalPrice = totalPrice * TWO_BOOKS_DISCOUNT_RATE;
}
return totalPrice;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KataPotter
{
public class KataPotterPriceCalculator
{
private static readonly double BOOK_UNIT_PRICE = 8;
public double Calculate(Dictionary<string, int> booksToBuy)
{
var totalCount = booksToBuy.Sum(i => i.Value);
var totalPrice = totalCount * BOOK_UNIT_PRICE;
return totalPrice;
}
}
}
| mit | C# |
be217e665e888972aa49df497fecd281ca82637a | Fix failing tests | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | resharper/resharper-yaml/test/src/UnityTestsSpecificYamlFileExtensionMapping.cs | resharper/resharper-yaml/test/src/UnityTestsSpecificYamlFileExtensionMapping.cs | using System;
using System.Collections.Generic;
using JetBrains.Application;
using JetBrains.Lifetimes;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Plugins.Yaml.ProjectModel;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Yaml.Tests
{
[ShellComponent]
public class UnityTestsSpecificYamlFileExtensionMapping : FileTypeDefinitionExtensionMapping
{
private static readonly string[] ourFileExtensions =
{
#if RIDER
// Rider doesn't register .yaml, as the frontend already provides support for it. But we need it for tests...
".yaml",
#endif
// This are registered by the Unity plugin, not the YAML plugin. But we need them for tests...
".meta",
".asset",
".unity"
};
public UnityTestsSpecificYamlFileExtensionMapping(Lifetime lifetime, IProjectFileTypes fileTypes)
: base(lifetime, fileTypes)
{
}
public override IEnumerable<ProjectFileType> GetFileTypes(string extension)
{
if (ourFileExtensions.Contains(extension, StringComparer.InvariantCultureIgnoreCase))
return new[] {YamlProjectFileType.Instance};
return base.GetFileTypes(extension);
}
public override IEnumerable<string> GetExtensions(ProjectFileType projectFileType)
{
if (Equals(projectFileType, YamlProjectFileType.Instance))
return base.GetExtensions(projectFileType).Concat(ourFileExtensions);
return base.GetExtensions(projectFileType);
}
}
} | using System;
using System.Collections.Generic;
using JetBrains.Application;
using JetBrains.Lifetimes;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Plugins.Yaml.ProjectModel;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Yaml.Tests
{
[ShellComponent]
public class UnityTestsSpecificYamlFileExtensionMapping : FileTypeDefinitionExtensionMapping
{
private static readonly string[] ourFileExtensions =
{
#if RIDER
// Rider doesn't register .yaml, as the frontend already provides support for it. But we need it for tests...
".yaml",
#endif
".meta",
".asset",
".unity"
};
public UnityTestsSpecificYamlFileExtensionMapping(Lifetime lifetime, IProjectFileTypes fileTypes)
: base(lifetime, fileTypes)
{
}
public override IEnumerable<ProjectFileType> GetFileTypes(string extension)
{
if (ourFileExtensions.Contains(extension, StringComparer.InvariantCultureIgnoreCase))
return new[] {YamlProjectFileType.Instance};
return EmptyList<ProjectFileType>.Enumerable;
}
public override IEnumerable<string> GetExtensions(ProjectFileType projectFileType)
{
if (Equals(projectFileType, YamlProjectFileType.Instance))
return ourFileExtensions;
return base.GetExtensions(projectFileType);
}
}
} | apache-2.0 | C# |
f6f1a4359287e94961eb766e744653121a23c266 | Fix - Corretta notifica delete utente | vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf | src/backend/SO115App.SignalR/Sender/GestioneRuoli/NotificationDeleteRuolo.cs | src/backend/SO115App.SignalR/Sender/GestioneRuoli/NotificationDeleteRuolo.cs | using Microsoft.AspNetCore.SignalR;
using SO115App.Models.Servizi.CQRS.Commands.GestioneUtenti.DeleteRuoliUtente;
using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.GetUtenti;
using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneUtenti.GestioneRuoli;
using System.Threading.Tasks;
namespace SO115App.SignalR.Sender.GestioneRuoli
{
public class NotificationDeleteRuolo : INotifyDeleteRuolo
{
private readonly IHubContext<NotificationHub> _notificationHubContext;
private readonly IGetUtenteByCF _getUtenteByCF;
public NotificationDeleteRuolo(IHubContext<NotificationHub> notificationHubContext, IGetUtenteByCF getUtenteByCF)
{
_notificationHubContext = notificationHubContext;
_getUtenteByCF = getUtenteByCF;
}
public async Task Notify(DeleteRuoliUtenteCommand command)
{
var utente = _getUtenteByCF.Get(command.CodFiscale);
//await _notificationHubContext.Clients.Group(utente.Sede.Codice).SendAsync("NotifyRefreshUtenti", utente.Id).ConfigureAwait(false);
await _notificationHubContext.Clients.All.SendAsync("NotifyModificatoRuoloUtente", utente.Id).ConfigureAwait(false);
}
}
}
| using Microsoft.AspNetCore.SignalR;
using SO115App.Models.Servizi.CQRS.Commands.GestioneUtenti.DeleteRuoliUtente;
using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.GetUtenti;
using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneUtenti.GestioneRuoli;
using System.Threading.Tasks;
namespace SO115App.SignalR.Sender.GestioneRuoli
{
public class NotificationDeleteRuolo : INotifyDeleteRuolo
{
private readonly IHubContext<NotificationHub> _notificationHubContext;
private readonly IGetUtenteByCF _getUtenteByCF;
public NotificationDeleteRuolo(IHubContext<NotificationHub> notificationHubContext, IGetUtenteByCF getUtenteByCF)
{
_notificationHubContext = notificationHubContext;
_getUtenteByCF = getUtenteByCF;
}
public async Task Notify(DeleteRuoliUtenteCommand command)
{
var utente = _getUtenteByCF.Get(command.CodFiscale);
await _notificationHubContext.Clients.Group(utente.Sede.Codice).SendAsync("NotifyRefreshUtenti", utente.Id).ConfigureAwait(false);
await _notificationHubContext.Clients.All.SendAsync("NotifyModificatoRuoloUtente", utente.Id).ConfigureAwait(false);
}
}
}
| agpl-3.0 | C# |
aa20519e2c423e25c8f54004c0c061d1aab8bf51 | Fix insertion unit test. | brendanjbaker/StraightSQL | test/StraightSql.Test/InsertQueryTest.cs | test/StraightSql.Test/InsertQueryTest.cs | namespace StraightSql.Test
{
using System;
using System.Threading.Tasks;
using Xunit;
public class InsertQueryTest
{
[Fact]
public async Task InsertQueryTestAsync()
{
var queryDispatcher =
new QueryDispatcher(
new CommandPreparer(),
new ConnectionFactory(ConnectionString.Default));
var queries = new String[]
{
"DROP TABLE IF EXISTS insert_query_test;",
"CREATE TABLE insert_query_test (value TEXT NOT NULL);",
"INSERT INTO insert_query_test VALUES ('StraightSql');"
};
foreach (var query in queries)
await queryDispatcher.ExecuteAsync(new Query(query));
var countQuery = "SELECT COUNT(*) FROM insert_query_test;";
var count = await queryDispatcher.CountAsync(new Query(countQuery));
Assert.Equal(count, 1);
}
}
}
| namespace StraightSql.Test
{
using System;
using System.Threading.Tasks;
using Xunit;
public class InsertQueryTest
{
[Fact]
public async Task InsertQueryTestAsync()
{
var queryDispatcher =
new QueryDispatcher(
new CommandPreparer(),
new ConnectionFactory(ConnectionString.Default));
var queries = new String[]
{
"DROP TABLE IF EXISTS insert_query_test;",
"CREATE TABLE insert_query_test (value TEXT NOT NULL);",
"INSERT INTO insert_query_test VALUES ('StraightSql');"
};
foreach (var query in queries)
await queryDispatcher.ExecuteAsync(new Query(query));
}
}
}
| mit | C# |
acac824c4e273227af2857a23021a2d04a6d4fdb | Improve usability | yonglehou/msgpack-rpc-cli,yfakariya/msgpack-rpc-cli | test/MsgPack.Rpc.Server.UnitTest/Rpc/Server/Protocols/NullServerTransport.cs | test/MsgPack.Rpc.Server.UnitTest/Rpc/Server/Protocols/NullServerTransport.cs | #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
// 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.
//
#endregion -- License Terms --
using System;
namespace MsgPack.Rpc.Server.Protocols
{
/// <summary>
/// The null object of <see cref="ServerTransport"/> class.
/// </summary>
internal sealed class NullServerTransport : ServerTransport
{
/// <summary>
/// Initializes a new instance of the <see cref="NullServerTransport"/> class.
/// </summary>
/// <param name="manager">The manager.</param>
public NullServerTransport( ServerTransportManager<NullServerTransport> manager ) : base( manager ) { }
/// <summary>
/// Performs protocol specific asynchronous 'Receive' operation.
/// </summary>
/// <param name="context">Context information.</param>
protected override void ReceiveCore( ServerRequestContext context )
{
return;
}
/// <summary>
/// Performs protocol specific asynchronous 'Send' operation.
/// </summary>
/// <param name="context">Context information.</param>
protected override void SendCore( ServerResponseContext context )
{
return;
}
}
}
| #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
// 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.
//
#endregion -- License Terms --
using System;
namespace MsgPack.Rpc.Server.Protocols
{
/// <summary>
/// The null object of <see cref="ServerTransport"/> class.
/// </summary>
internal sealed class NullServerTransport : ServerTransport
{
/// <summary>
/// Initializes a new instance of the <see cref="NullServerTransport"/> class.
/// </summary>
/// <param name="manager">The manager.</param>
public NullServerTransport( NullServerTransportManager manager ) : base( manager ) { }
/// <summary>
/// Performs protocol specific asynchronous 'Receive' operation.
/// </summary>
/// <param name="context">Context information.</param>
protected override void ReceiveCore( ServerRequestContext context )
{
return;
}
/// <summary>
/// Performs protocol specific asynchronous 'Send' operation.
/// </summary>
/// <param name="context">Context information.</param>
protected override void SendCore( ServerResponseContext context )
{
return;
}
}
}
| apache-2.0 | C# |
488dd250c68aba871ca4211e7bd73475f6c4267c | Fix TCol sync dialog report button when there is a book error (BL-10624) | gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop | src/BloomExe/CommonMessages.cs | src/BloomExe/CommonMessages.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using L10NSharp;
namespace Bloom
{
/// <summary>
/// A place to put messages that may be reusable
/// </summary>
public class CommonMessages
{
public static string GetPleaseClickHereForHelpMessage(string pathToProblemFile)
{
var template2 = LocalizationManager.GetString("Common.ClickHereForHelp",
"Please click [here] to get help from the Bloom support team.",
"[here] will become a link. Keep the brackets to mark the translated text that should form the link.");
var pattern = new Regex(@"\[(.*)\]");
if (!pattern.IsMatch(template2))
{
// If the translator messed up and didn't mark the bit that should be the hot link, we'll make the whole sentence hot.
// So it will be something like "Please click here to get help from the Bloom support team", and you can click anywhere
// on the sentence.
template2 = "[" + template2 + "]";
}
// If we leave backslashes in here, json will fail to parse it later. It works fine with forward slashes, even on Windows.
pathToProblemFile = pathToProblemFile.Replace("\\", "/");
var part2 = pattern.Replace(template2,
$"<a href='/bloom/api/teamCollection/reportBadZip?file={UrlPathString.CreateFromUnencodedString(pathToProblemFile).UrlEncoded}'>$1</a>");
return part2;
}
public static string GetProblemWithBookMessage(string bookName)
{
// Enhance (YAGNI): if we use this for book problems NOT in the TC system, this will need a param
// to allow leaving out that part of the message, probably an alternative L10N item.
var template = LocalizationManager.GetString("TeamCollection.ProblemWithBook",
"There is a problem with the book \"{0}\" in the Team Collection system.");
return String.Format(template, bookName);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using L10NSharp;
namespace Bloom
{
/// <summary>
/// A place to put messages that may be reusable
/// </summary>
public class CommonMessages
{
public static string GetPleaseClickHereForHelpMessage(string pathtoProblemFile)
{
var template2 = LocalizationManager.GetString("Common.ClickHereForHelp",
"Please click [here] to get help from the Bloom support team.",
"[here] will become a link. Keep the brackets to mark the translated text that should form the link.");
var pattern = new Regex(@"\[(.*)\]");
if (!pattern.IsMatch(template2))
{
// If the translator messed up and didn't mark the bit that should be the hot link, we'll make the whole sentence hot.
// So it will be something like "Please click here to get help from the Bloom support team", and you can click anywhere
// on the sentence.
template2 = "[" + template2 + "]";
}
var part2 = pattern.Replace(template2,
$"<a href='/bloom/api/teamCollection/reportBadZip?file={UrlPathString.CreateFromUnencodedString(pathtoProblemFile).UrlEncoded}'>$1</a>");
return part2;
}
public static string GetProblemWithBookMessage(string bookName)
{
// Enhance (YAGNI): if we use this for book problems NOT in the TC system, this will need a param
// to allow leaving out that part of the message, probably an alternative L10N item.
var template = LocalizationManager.GetString("TeamCollection.ProblemWithBook",
"There is a problem with the book \"{0}\" in the Team Collection system.");
return String.Format(template, bookName);
}
}
}
| mit | C# |
fad4ffa3f95f770651ab065198b0ccaacccec85d | Fix memory leak inside SpriteFont | k-t/SharpHaven | MonoHaven.Client/Graphics/SpriteFont.cs | MonoHaven.Client/Graphics/SpriteFont.cs | using System;
using System.Collections.Generic;
using System.Drawing;
using OpenTK.Graphics.OpenGL;
using SharpFont;
namespace MonoHaven.Graphics
{
public class SpriteFont : IDisposable
{
private readonly Face face;
private readonly TextureAtlas atlas;
private readonly Dictionary<char, Glyph> glyphs;
private readonly uint pixelSize;
private readonly int ascent;
private readonly int height;
public SpriteFont(Face face, uint pixelSize)
{
atlas = new TextureAtlas(512, 512);
glyphs = new Dictionary<char, Glyph>();
this.face = face;
this.pixelSize = pixelSize;
EnsureSize();
using (var size = face.Size)
{
ascent = size.Metrics.Ascender >> 6;
height = size.Metrics.Height >> 6;
}
}
public int Ascent
{
get { return ascent; }
}
public int Height
{
get { return height; }
}
public void Dispose()
{
atlas.Dispose();
}
public Glyph GetGlyph(char c)
{
Glyph glyph;
if (!glyphs.TryGetValue(c, out glyph))
{
glyph = LoadGlyph(c);
glyphs[c] = glyph;
}
return glyph;
}
private Glyph LoadGlyph(char c)
{
EnsureSize();
var index = face.GetCharIndex(c);
face.LoadGlyph(index, LoadFlags.Default, LoadTarget.Normal);
var sz = new Size(face.Glyph.Metrics.Width >> 6, face.Glyph.Metrics.Height >> 6);
if (sz == Size.Empty)
{
return new Glyph { Advance = face.Glyph.Advance.X / 64f };
}
face.Glyph.RenderGlyph(RenderMode.Normal);
using (var bitmap = face.Glyph.Bitmap)
{
var bufferData = bitmap.BufferData;
var glyphPixels = new byte[4 * sz.Width * sz.Height];
for (int j = 0; j < sz.Height; j++)
for (int i = 0; i < sz.Width; i++)
{
int k = (i + bitmap.Width * j) * 4;
glyphPixels[k] = 255;
glyphPixels[k + 1] = 255;
glyphPixels[k + 2] = 255;
glyphPixels[k + 3] = bufferData[i + bitmap.Width * j];
}
return new Glyph {
Advance = face.Glyph.Advance.X / 64f,
Offset = new Point(face.Glyph.BitmapLeft, -face.Glyph.BitmapTop),
Image = atlas.Add(glyphPixels, PixelFormat.Rgba, sz.Width, sz.Height)
};
}
}
private void EnsureSize()
{
face.SetPixelSizes(pixelSize, pixelSize);
}
}
}
| using System;
using System.Collections.Generic;
using System.Drawing;
using OpenTK.Graphics.OpenGL;
using SharpFont;
namespace MonoHaven.Graphics
{
public class SpriteFont : IDisposable
{
private readonly Face face;
private readonly TextureAtlas atlas;
private readonly Dictionary<char, Glyph> glyphs;
private readonly uint pixelSize;
public SpriteFont(Face face, uint pixelSize)
{
atlas = new TextureAtlas(512, 512);
glyphs = new Dictionary<char, Glyph>();
this.face = face;
this.pixelSize = pixelSize;
}
public int Ascent
{
get
{
EnsureSize();
return face.Size.Metrics.Ascender >> 6;
}
}
public int Height
{
get
{
EnsureSize();
return face.Size.Metrics.Height >> 6;
}
}
public void Dispose()
{
atlas.Dispose();
}
public Glyph GetGlyph(char c)
{
Glyph glyph;
if (!glyphs.TryGetValue(c, out glyph))
{
glyph = LoadGlyph(c);
glyphs[c] = glyph;
}
return glyph;
}
private Glyph LoadGlyph(char c)
{
EnsureSize();
var index = face.GetCharIndex(c);
face.LoadGlyph(index, LoadFlags.Default, LoadTarget.Normal);
var sz = new Size(face.Glyph.Metrics.Width >> 6, face.Glyph.Metrics.Height >> 6);
if (sz == Size.Empty)
{
return new Glyph { Advance = face.Glyph.Advance.X / 64f };
}
face.Glyph.RenderGlyph(RenderMode.Normal);
using (var bitmap = face.Glyph.Bitmap)
{
var bufferData = bitmap.BufferData;
var glyphPixels = new byte[4 * sz.Width * sz.Height];
for (int j = 0; j < sz.Height; j++)
for (int i = 0; i < sz.Width; i++)
{
int k = (i + bitmap.Width * j) * 4;
glyphPixels[k] = 255;
glyphPixels[k + 1] = 255;
glyphPixels[k + 2] = 255;
glyphPixels[k + 3] = bufferData[i + bitmap.Width * j];
}
return new Glyph {
Advance = face.Glyph.Advance.X / 64f,
Offset = new Point(face.Glyph.BitmapLeft, -face.Glyph.BitmapTop),
Image = atlas.Add(glyphPixels, PixelFormat.Rgba, sz.Width, sz.Height)
};
}
}
private void EnsureSize()
{
face.SetPixelSizes(pixelSize, pixelSize);
}
}
}
| mit | C# |
b6eb1456b9258bcd462a877b97f58f3687f8fc99 | Set lifetime scope of services to instance per request | erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner | Oogstplanner.Web/App_Start/IocConfig.cs | Oogstplanner.Web/App_Start/IocConfig.cs | using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Oogstplanner.Models;
using Oogstplanner.Data;
using Oogstplanner.Services;
namespace Oogstplanner.Web
{
public static class IocConfig
{
public static void RegisterDependencies()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<OogstplannerUnitOfWork>()
.As<IOogstplannerUnitOfWork>()
.InstancePerLifetimeScope();
builder.RegisterType<OogstplannerContext>()
.As<IOogstplannerContext>()
.InstancePerRequest();
var repositoryFactories = new RepositoryFactories();
builder.RegisterInstance(repositoryFactories)
.As<RepositoryFactories>()
.SingleInstance();
builder.RegisterType<RepositoryProvider>()
.As<IRepositoryProvider>()
.InstancePerRequest();
builder.RegisterAssemblyTypes(typeof(ServiceBase).Assembly)
.AsImplementedInterfaces()
.Except<UserService>()
.Except<AnonymousUserService>()
.InstancePerRequest();
builder.RegisterType<AnonymousUserService>()
.Keyed<IUserService>(AuthenticatedStatus.Anonymous)
.InstancePerRequest();
builder.RegisterType<UserService>()
.Keyed<IUserService>(AuthenticatedStatus.Authenticated)
.InstancePerRequest();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
}
| using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Oogstplanner.Models;
using Oogstplanner.Data;
using Oogstplanner.Services;
namespace Oogstplanner.Web
{
public static class IocConfig
{
public static void RegisterDependencies()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<OogstplannerUnitOfWork>()
.As<IOogstplannerUnitOfWork>()
.InstancePerLifetimeScope();
builder.RegisterType<OogstplannerContext>()
.As<IOogstplannerContext>()
.InstancePerRequest();
var repositoryInstances = new RepositoryFactories();
builder.RegisterInstance(repositoryInstances)
.As<RepositoryFactories>()
.SingleInstance();
builder.RegisterType<RepositoryProvider>()
.As<IRepositoryProvider>()
.InstancePerRequest();
builder.RegisterAssemblyTypes(typeof(ServiceBase).Assembly)
.AsImplementedInterfaces()
.Except<UserService>()
.Except<AnonymousUserService>();
builder.RegisterType<AnonymousUserService>()
.Keyed<IUserService>(AuthenticatedStatus.Anonymous);
builder.RegisterType<UserService>()
.Keyed<IUserService>(AuthenticatedStatus.Authenticated);
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
}
| mit | C# |
975d049f07300ebd9d351b110f4527885bc611f7 | load default setting if config.json is not found | TryItOnline/TioTests | Program.cs | Program.cs | using System;
using System.IO;
using Newtonsoft.Json;
namespace TioTests
{
public class Program
{
public static void Main(string[] args)
{
try
{
Execute(args);
}
catch (Exception e)
{
Logger.LogLine("Unexpected error: " + e);
Environment.Exit(-1);
}
}
private static void Execute(string[] args)
{
string configPath = "config.json";
Config config = File.Exists(configPath) ?
JsonConvert.DeserializeObject<Config>(File.ReadAllText(configPath)) :
new Config { TrimWhitespacesFromResults = true, DisplayDebugInfoOnError = true, UseConsoleCodes = true };
CommandLine.ApplyCommandLineArguments(args, config);
if (Directory.Exists(config.Test))
{
string[] files = Directory.GetFiles(config.Test, "*.json");
Array.Sort(files);
int counter = 0;
foreach (string file in files)
{
//Logger.Log($"[{++counter}/{files.Length}] ");
TestRunner.RunTest(file, config, $"[{++counter}/{files.Length}]");
}
}
else if (File.Exists(config.Test))
{
TestRunner.RunTest(config.Test, config,"[1/1]");
}
else if (File.Exists(config.Test + ".json"))
{
TestRunner.RunTest(config.Test + ".json", config,"1/1");
}
else
{
Logger.LogLine($"{config.Test} not found");
}
}
}
}
| using System;
using System.IO;
using Newtonsoft.Json;
namespace TioTests
{
public class Program
{
public static void Main(string[] args)
{
try
{
Execute(args);
}
catch (Exception e)
{
Logger.LogLine("Unexpected error: " + e);
Environment.Exit(-1);
}
}
private static void Execute(string[] args)
{
Config config = JsonConvert.DeserializeObject<Config>(File.ReadAllText("config.json"));
CommandLine.ApplyCommandLineArguments(args, config);
if (Directory.Exists(config.Test))
{
string[] files = Directory.GetFiles(config.Test, "*.json");
Array.Sort(files);
int counter = 0;
foreach (string file in files)
{
//Logger.Log($"[{++counter}/{files.Length}] ");
TestRunner.RunTest(file, config, $"[{++counter}/{files.Length}]");
}
}
else if (File.Exists(config.Test))
{
TestRunner.RunTest(config.Test, config,"[1/1]");
}
else if (File.Exists(config.Test + ".json"))
{
TestRunner.RunTest(config.Test + ".json", config,"1/1");
}
else
{
Logger.LogLine($"{config.Test} not found");
}
}
}
}
| mit | C# |
e734eeeeea7deabbb48c33137de82d08cffe894a | Fix CancelChanges | ciprianciurea/ObservableEntitiesLightTracking | ObservableEntitiesLightTracking/ObservableEntitiesLightTracking/OEEntityEntry.cs | ObservableEntitiesLightTracking/ObservableEntitiesLightTracking/OEEntityEntry.cs | using System.Collections.Generic;
using System.Linq;
namespace ObservableEntitiesLightTracking
{
public class OEEntityEntry
{
private readonly object _entity;
private readonly OEEntitySet _entitySet;
Dictionary<string, object> _originalValues;
internal OEEntityEntry(object entity, OEEntitySet entitySet)
{
_entity = entity;
_entitySet = entitySet;
_originalValues = new Dictionary<string, object>();
InitializeOriginalValues();
}
public object Entity
{
get { return _entity; }
}
public OEEntitySet EntitySet
{
get { return _entitySet; }
}
/// <summary>
/// Gets or sets the state of an entity.
/// </summary>
public OEEntityState State { get; set; }
/// <summary>
/// Properties on an entity that have been modified.
/// </summary>
public ICollection<string> ModifiedProperties { get; set; }
private void InitializeOriginalValues()
{
foreach (var property in _entity.GetType().GetProperties().Where(p => p.GetSetMethod() != null))
{
_originalValues.Add(property.Name, property.GetValue(_entity));
}
}
internal void CancelChanges()
{
foreach (var property in _entity.GetType().GetProperties().Where(p => p.GetSetMethod() != null))
{
if (_originalValues.ContainsKey(property.Name) && property.GetValue(_entity) != _originalValues[property.Name])
{
property.SetValue(_entity, _originalValues[property.Name]);
}
}
}
internal void ApplyChanges()
{
foreach (var property in _entity.GetType().GetProperties().Where(p => p.GetSetMethod() != null))
{
if (_originalValues.ContainsKey(property.Name) && property.GetValue(_entity) != _originalValues[property.Name])
_originalValues[property.Name] = property.GetValue(_entity);
}
}
}
}
| using System.Collections.Generic;
using System.Linq;
namespace ObservableEntitiesLightTracking
{
public class OEEntityEntry
{
private readonly object _entity;
private readonly OEEntitySet _entitySet;
Dictionary<string, object> _originalValues;
internal OEEntityEntry(object entity, OEEntitySet entitySet)
{
_entity = entity;
_entitySet = entitySet;
_originalValues = new Dictionary<string, object>();
InitializeOriginalValues();
}
public object Entity
{
get { return _entity; }
}
public OEEntitySet EntitySet
{
get { return _entitySet; }
}
/// <summary>
/// Gets or sets the state of an entity.
/// </summary>
public OEEntityState State { get; set; }
/// <summary>
/// Properties on an entity that have been modified.
/// </summary>
public ICollection<string> ModifiedProperties { get; set; }
private void InitializeOriginalValues()
{
foreach (var property in this.GetType().GetProperties().Where(p => p.GetSetMethod() != null))
{
_originalValues.Add(property.Name, property.GetValue(this));
}
}
internal void CancelChanges()
{
foreach (var property in _entity.GetType().GetProperties().Where(p => p.GetSetMethod() != null))
{
if (_originalValues.ContainsKey(property.Name) && property.GetValue(this) != _originalValues[property.Name])
{
property.SetValue(_entity, _originalValues[property.Name]);
}
}
}
internal void ApplyChanges()
{
foreach (var property in _entity.GetType().GetProperties().Where(p => p.GetSetMethod() != null))
{
if (_originalValues.ContainsKey(property.Name) && property.GetValue(_entity) != _originalValues[property.Name])
_originalValues[property.Name] = property.GetValue(_entity);
}
}
}
}
| mit | C# |
e14697938b5eb50ee92f2878cb4377ecd48ee224 | Add tests. | AlekseyTs/roslyn,OmarTawfik/roslyn,weltkante/roslyn,swaroop-sridhar/roslyn,CyrusNajmabadi/roslyn,eriawan/roslyn,bkoelman/roslyn,physhi/roslyn,xasx/roslyn,abock/roslyn,OmarTawfik/roslyn,jamesqo/roslyn,mavasani/roslyn,ErikSchierboom/roslyn,panopticoncentral/roslyn,swaroop-sridhar/roslyn,VSadov/roslyn,shyamnamboodiripad/roslyn,dpoeschl/roslyn,diryboy/roslyn,tmeschter/roslyn,davkean/roslyn,stephentoub/roslyn,MichalStrehovsky/roslyn,stephentoub/roslyn,Hosch250/roslyn,wvdd007/roslyn,paulvanbrenk/roslyn,DustinCampbell/roslyn,diryboy/roslyn,stephentoub/roslyn,tmeschter/roslyn,weltkante/roslyn,tmat/roslyn,davkean/roslyn,diryboy/roslyn,jcouv/roslyn,reaction1989/roslyn,dotnet/roslyn,KevinRansom/roslyn,KevinRansom/roslyn,VSadov/roslyn,VSadov/roslyn,ErikSchierboom/roslyn,MichalStrehovsky/roslyn,cston/roslyn,KevinRansom/roslyn,paulvanbrenk/roslyn,panopticoncentral/roslyn,Hosch250/roslyn,agocke/roslyn,aelij/roslyn,sharwell/roslyn,cston/roslyn,paulvanbrenk/roslyn,AmadeusW/roslyn,OmarTawfik/roslyn,bartdesmet/roslyn,reaction1989/roslyn,jcouv/roslyn,swaroop-sridhar/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,bartdesmet/roslyn,xasx/roslyn,bartdesmet/roslyn,gafter/roslyn,wvdd007/roslyn,bkoelman/roslyn,KirillOsenkov/roslyn,jasonmalinowski/roslyn,dpoeschl/roslyn,physhi/roslyn,gafter/roslyn,aelij/roslyn,heejaechang/roslyn,Hosch250/roslyn,bkoelman/roslyn,mgoertz-msft/roslyn,jmarolf/roslyn,gafter/roslyn,jmarolf/roslyn,KirillOsenkov/roslyn,jamesqo/roslyn,jmarolf/roslyn,reaction1989/roslyn,cston/roslyn,tmat/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,brettfo/roslyn,tannergooding/roslyn,genlu/roslyn,dpoeschl/roslyn,CyrusNajmabadi/roslyn,tannergooding/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,nguerrera/roslyn,mavasani/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,AlekseyTs/roslyn,genlu/roslyn,tannergooding/roslyn,abock/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,genlu/roslyn,tmat/roslyn,AlekseyTs/roslyn,brettfo/roslyn,xasx/roslyn,davkean/roslyn,agocke/roslyn,ErikSchierboom/roslyn,DustinCampbell/roslyn,eriawan/roslyn,sharwell/roslyn,nguerrera/roslyn,mgoertz-msft/roslyn,tmeschter/roslyn,abock/roslyn,brettfo/roslyn,mgoertz-msft/roslyn,AmadeusW/roslyn,jcouv/roslyn,panopticoncentral/roslyn,DustinCampbell/roslyn,wvdd007/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,KirillOsenkov/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,physhi/roslyn,heejaechang/roslyn,nguerrera/roslyn,mavasani/roslyn,dotnet/roslyn,weltkante/roslyn,jamesqo/roslyn,MichalStrehovsky/roslyn,aelij/roslyn,sharwell/roslyn,agocke/roslyn | src/EditorFeatures/CSharpTest/ConvertForToForEach/ConvertForToForEachTests.cs | src/EditorFeatures/CSharpTest/ConvertForToForEach/ConvertForToForEachTests.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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.ConvertForToForEach;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertForToForEach
{
public class ConvertForToForEachTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpConvertForToForEachCodeRefactoringProvider();
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)]
public async Task TestArray1()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void Test(string[] array)
{
[||]for (int i = 0; i < array.Length; i++)
{
Console.WriteLine(array[i]);
}
}
}",
@"using System;
class C
{
void Test(string[] array)
{
foreach (string {|Rename:v|} in array)
{
Console.WriteLine(v);
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)]
public async Task TestPostIncrement()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void Test(string[] array)
{
[||]for (int i = 0; i < array.Length; ++i)
{
Console.WriteLine(array[i]);
}
}
}",
@"using System;
class C
{
void Test(string[] array)
{
foreach (string {|Rename:v|} in array)
{
Console.WriteLine(v);
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)]
public async Task TestArrayPlusEqualsIncrementor()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void Test(string[] array)
{
[||]for (int i = 0; i < array.Length; i += 1)
{
Console.WriteLine(array[i]);
}
}
}",
@"using System;
class C
{
void Test(string[] array)
{
foreach (string {|Rename:v|} in array)
{
Console.WriteLine(v);
}
}
}");
}
}
}
| // 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.ConvertForToForEach;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertForToForEach
{
public class ConvertForToForEachTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpConvertForToForEachCodeRefactoringProvider();
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)]
public async Task TestArray1()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void Test(string[] array)
{
[||]for (int i = 0; i < array.Length; i++)
{
Console.WriteLine(array[i]);
}
}
}",
@"using System;
class C
{
void Test(string[] array)
{
foreach (string {|Rename:v|} in array)
{
Console.WriteLine(v);
}
}
}");
}
}
}
| mit | C# |
cc2976c69364d660a908911d02781db7bfcd3ffa | Update AbstractSourceData.cs | tsimafei-markhel/Fireworks.NET,sleshJdev/Fireworks.NET | src/FireworksNet.Tests/Explode/AbstractSourceData.cs | src/FireworksNet.Tests/Explode/AbstractSourceData.cs | using System;
using System.Collections.Generic;
using FireworksNet.Model;
using NSubstitute;
using FireworksNet.Algorithm.Implementation;
using FireworksNet.Distributions;
namespace FireworksNet.Tests.Explode
{
public abstract class AbstractSourceData
{
public static IEnumerable<object[]> DataForTestMethodExplodeOfParallelExploder
{
get
{
var epicenter = Substitute.For<Firework>(FireworkType.SpecificSpark, 0);
var qualities = Substitute.For<IEnumerable<double>>();
return new[]
{
new object[] { null, qualities, 0, typeof(ArgumentNullException), "epicenter"},
new object[] { epicenter, null, 0, typeof(ArgumentNullException), "currentFireworkQualities" },
new object[] { epicenter, qualities, -1, typeof(ArgumentOutOfRangeException), "currentStepNumber" }
};
}
}
public static IEnumerable<object[]> DataForTestCreationInstanceOfAttractRepulseGenerator
{
get
{
var bestSolution = Substitute.For<Solution>(0);
var dimensions = Substitute.For<IEnumerable<Dimension>>();
var algorithmSettings = Substitute.For<ParallelFireworksAlgorithmSettings>();
var distribution = Substitute.For<ContinuousUniformDistribution>(
algorithmSettings.Amplitude - algorithmSettings.Delta, algorithmSettings.Amplitude + algorithmSettings.Delta);
var randomizer = Substitute.For<System.Random>();
return new[]
{
new object[]{null, dimensions, distribution, randomizer, "bestSolution"},
new object[]{bestSolution, null, distribution, randomizer, "dimensions"},
new object[]{bestSolution, dimensions, null, randomizer, "distribution"},
new object[]{bestSolution, dimensions, distribution, null, "randomizer"},
};
}
}
}
}
| using System;
using System.Collections.Generic;
using FireworksNet.Model;
using NSubstitute;
using FireworksNet.Algorithm.Implementation;
using FireworksNet.Distributions;
namespace FireworksNet.Tests.Explode
{
public abstract class AbstractSourceData
{
public static IEnumerable<object[]> DataForTestMethodExploderOfParallelExploder
{
get
{
var epicenter = Substitute.For<Firework>(FireworkType.SpecificSpark, 0);
var qualities = Substitute.For<IEnumerable<double>>();
return new[]
{
new object[] { null, qualities, 0, typeof(ArgumentNullException), "epicenter"},
new object[] { epicenter, null, 0, typeof(ArgumentNullException), "currentFireworkQualities" },
new object[] { epicenter, qualities, -1, typeof(ArgumentOutOfRangeException), "currentStepNumber" }
};
}
}
public static IEnumerable<object[]> DataForTestCreationInstanceOfAttractRepulseGenerator
{
get
{
var bestSolution = Substitute.For<Solution>(0);
var dimensions = Substitute.For<IEnumerable<Dimension>>();
var algorithmSettings = Substitute.For<ParallelFireworksAlgorithmSettings>();
var distribution = Substitute.For<ContinuousUniformDistribution>(
algorithmSettings.Amplitude - algorithmSettings.Delta, algorithmSettings.Amplitude + algorithmSettings.Delta);
var randomizer = Substitute.For<System.Random>();
return new[]
{
new object[]{null, dimensions, distribution, randomizer, "bestSolution"},
new object[]{bestSolution, null, distribution, randomizer, "dimensions"},
new object[]{bestSolution, dimensions, null, randomizer, "distribution"},
new object[]{bestSolution, dimensions, distribution, null, "randomizer"},
};
}
}
}
}
| mit | C# |
8e7226e30eb2f1d607aab6b1ff7740f84cab89f9 | set parent to null after removing the tab from the handler | bbqchickenrobot/Eto-1,PowerOfCode/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,PowerOfCode/Eto,l8s/Eto,l8s/Eto,l8s/Eto | Source/Eto/Forms/Controls/TabControl.cs | Source/Eto/Forms/Controls/TabControl.cs | using System;
using System.Collections;
using System.Linq;
#if XAML
using System.Windows.Markup;
#endif
namespace Eto.Forms
{
public interface ITabControl : IControl
{
int SelectedIndex { get; set; }
void InsertTab (int index, TabPage page);
void ClearTabs ();
void RemoveTab (int index, TabPage page);
}
[ContentProperty("TabPages")]
public class TabControl : Control
{
TabPageCollection pages;
ITabControl handler;
public event EventHandler<EventArgs> SelectedIndexChanged;
public virtual void OnSelectedIndexChanged (EventArgs e)
{
if (SelectedIndexChanged != null)
SelectedIndexChanged (this, e);
}
public TabControl () : this (Generator.Current)
{
}
public TabControl (Generator g) : this (g, typeof(ITabControl))
{
}
protected TabControl (Generator generator, Type type, bool initialize = true)
: base (generator, type, initialize)
{
pages = new TabPageCollection (this);
handler = (ITabControl)base.Handler;
}
public int SelectedIndex {
get { return handler.SelectedIndex; }
set { handler.SelectedIndex = value; }
}
public TabPage SelectedPage {
get { return SelectedIndex < 0 ? null : TabPages [SelectedIndex]; }
set { SelectedIndex = pages.IndexOf (value); }
}
public TabPageCollection TabPages {
get { return pages; }
}
internal void InsertTab (int index, TabPage page)
{
if (Loaded) {
page.OnPreLoad (EventArgs.Empty);
page.OnLoad (EventArgs.Empty);
page.OnLoadComplete (EventArgs.Empty);
}
page.SetParent (this);
handler.InsertTab (index, page);
}
internal void RemoveTab (int index, TabPage page)
{
handler.RemoveTab (index, page);
page.SetParent (null);
}
internal void ClearTabs ()
{
handler.ClearTabs ();
}
public override void OnPreLoad (EventArgs e)
{
base.OnPreLoad (e);
foreach (var page in pages) {
page.OnPreLoad (e);
}
}
public override void OnLoad (EventArgs e)
{
base.OnLoad (e);
foreach (var page in pages) {
page.OnLoad (e);
}
}
public override void OnLoadComplete (EventArgs e)
{
base.OnLoadComplete (e);
foreach (var page in pages) {
page.OnLoadComplete (e);
}
}
internal protected override void OnDataContextChanged (EventArgs e)
{
base.OnDataContextChanged (e);
foreach (var tab in TabPages) {
tab.OnDataContextChanged (e);
}
}
public override void UpdateBindings ()
{
base.UpdateBindings ();
foreach (var tab in TabPages) {
tab.UpdateBindings ();
}
}
}
}
| using System;
using System.Collections;
using System.Linq;
#if XAML
using System.Windows.Markup;
#endif
namespace Eto.Forms
{
public interface ITabControl : IControl
{
int SelectedIndex { get; set; }
void InsertTab (int index, TabPage page);
void ClearTabs ();
void RemoveTab (int index, TabPage page);
}
[ContentProperty("TabPages")]
public class TabControl : Control
{
TabPageCollection pages;
ITabControl handler;
public event EventHandler<EventArgs> SelectedIndexChanged;
public virtual void OnSelectedIndexChanged (EventArgs e)
{
if (SelectedIndexChanged != null)
SelectedIndexChanged (this, e);
}
public TabControl () : this (Generator.Current)
{
}
public TabControl (Generator g) : this (g, typeof(ITabControl))
{
}
protected TabControl (Generator generator, Type type, bool initialize = true)
: base (generator, type, initialize)
{
pages = new TabPageCollection (this);
handler = (ITabControl)base.Handler;
}
public int SelectedIndex {
get { return handler.SelectedIndex; }
set { handler.SelectedIndex = value; }
}
public TabPage SelectedPage {
get { return SelectedIndex < 0 ? null : TabPages [SelectedIndex]; }
set { SelectedIndex = pages.IndexOf (value); }
}
public TabPageCollection TabPages {
get { return pages; }
}
internal void InsertTab (int index, TabPage page)
{
if (Loaded) {
page.OnPreLoad (EventArgs.Empty);
page.OnLoad (EventArgs.Empty);
page.OnLoadComplete (EventArgs.Empty);
}
page.SetParent (this);
handler.InsertTab (index, page);
}
internal void RemoveTab (int index, TabPage page)
{
//page.SetParent (null);
handler.RemoveTab (index, page);
}
internal void ClearTabs ()
{
handler.ClearTabs ();
}
public override void OnPreLoad (EventArgs e)
{
base.OnPreLoad (e);
foreach (var page in pages) {
page.OnPreLoad (e);
}
}
public override void OnLoad (EventArgs e)
{
base.OnLoad (e);
foreach (var page in pages) {
page.OnLoad (e);
}
}
public override void OnLoadComplete (EventArgs e)
{
base.OnLoadComplete (e);
foreach (var page in pages) {
page.OnLoadComplete (e);
}
}
internal protected override void OnDataContextChanged (EventArgs e)
{
base.OnDataContextChanged (e);
foreach (var tab in TabPages) {
tab.OnDataContextChanged (e);
}
}
public override void UpdateBindings ()
{
base.UpdateBindings ();
foreach (var tab in TabPages) {
tab.UpdateBindings ();
}
}
}
}
| bsd-3-clause | C# |
9e131c86d5d0facdab9333d5d48d6c2b95aefc5f | Use SdkManager addin to install platform-tools | Redth/Cake.Android.Adb | build.cake | build.cake | #tool nuget:?package=NUnit.ConsoleRunner&version=3.6.0
#addin nuget:?package=Cake.Android.SdkManager
var sln = "./Cake.Android.Adb.sln";
var nuspec = "./Cake.Android.Adb.nuspec";
var target = Argument ("target", "all");
var configuration = Argument ("configuration", "Release");
var NUGET_VERSION = Argument("nugetversion", "0.9999");
var SDK_URL_BASE = "https://dl.google.com/android/repository/tools_r{0}-{1}.zip";
var SDK_VERSION = "25.2.3";
Task ("externals")
.WithCriteria (!FileExists ("./android-sdk/android-sdk.zip"))
.Does (() =>
{
var url = string.Format (SDK_URL_BASE, SDK_VERSION, "macosx");
if (IsRunningOnWindows ())
url = string.Format (SDK_URL_BASE, SDK_VERSION, "windows");
EnsureDirectoryExists ("./android-sdk/");
DownloadFile (url, "./android-sdk/android-sdk.zip");
Unzip ("./android-sdk/android-sdk.zip", "./android-sdk/");
// Install platform-tools so we get adb
AndroidSdkManagerInstall (new [] { "platform-tools" }, new AndroidSdkManagerToolSettings {
SdkRoot = "./android-sdk/",
});
});
Task ("libs").IsDependentOn ("externals").Does (() =>
{
NuGetRestore (sln);
DotNetBuild (sln, c => c.Configuration = configuration);
});
Task ("nuget").IsDependentOn ("libs").Does (() =>
{
NuGetPack (nuspec, new NuGetPackSettings {
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./",
Version = NUGET_VERSION,
// NuGet messes up path on mac, so let's add ./ in front again
BasePath = "././",
});
});
Task("tests").IsDependentOn("libs").Does(() =>
{
NUnit3("./**/bin/" + configuration + "/*.Tests.dll");
});
Task ("clean").Does (() =>
{
CleanDirectories ("./**/bin");
CleanDirectories ("./**/obj");
CleanDirectories ("./**/Components");
CleanDirectories ("./**/tools");
CleanDirectories ("./android-sdk");
DeleteFiles ("./**/*.apk");
});
Task ("all").IsDependentOn("nuget").IsDependentOn ("tests");
RunTarget (target); | #tool nuget:?package=NUnit.ConsoleRunner&version=3.6.0
var sln = "./Cake.Android.Adb.sln";
var nuspec = "./Cake.Android.Adb.nuspec";
var target = Argument ("target", "all");
var configuration = Argument ("configuration", "Release");
var NUGET_VERSION = Argument("nugetversion", "0.9999");
var SDK_URL_BASE = "https://dl.google.com/android/repository/tools_r{0}-{1}.zip";
var SDK_VERSION = "25.2.3";
Task ("externals")
.WithCriteria (!FileExists ("./android-sdk/android-sdk.zip"))
.Does (() =>
{
var url = string.Format (SDK_URL_BASE, SDK_VERSION, "macosx");
if (IsRunningOnWindows ())
url = string.Format (SDK_URL_BASE, SDK_VERSION, "windows");
EnsureDirectoryExists ("./android-sdk/");
DownloadFile (url, "./android-sdk/android-sdk.zip");
Unzip ("./android-sdk/android-sdk.zip", "./android-sdk/");
var ext = "";
if (IsRunningOnWindows ())
ext = ".bat";
// Install platform-tools so we get adb
StartProcess ("./android-sdk/tools/bin/sdkmanager" + ext, new ProcessSettings { Arguments = "platform-tools" });
});
Task ("libs").IsDependentOn ("externals").Does (() =>
{
NuGetRestore (sln);
DotNetBuild (sln, c => c.Configuration = configuration);
});
Task ("nuget").IsDependentOn ("libs").Does (() =>
{
NuGetPack (nuspec, new NuGetPackSettings {
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./",
Version = NUGET_VERSION,
// NuGet messes up path on mac, so let's add ./ in front again
BasePath = "././",
});
});
Task("tests").IsDependentOn("libs").Does(() =>
{
NUnit3("./**/bin/" + configuration + "/*.Tests.dll");
});
Task ("clean").Does (() =>
{
CleanDirectories ("./**/bin");
CleanDirectories ("./**/obj");
CleanDirectories ("./**/Components");
CleanDirectories ("./**/tools");
CleanDirectories ("./android-sdk");
DeleteFiles ("./**/*.apk");
});
Task ("all").IsDependentOn("nuget").IsDependentOn ("tests");
RunTarget (target); | mit | C# |
6a4cab17f325c7baefae4de70aa9bd53596576bd | Write information about updating appveyor build version | Krusen/ErgastApi.Net | build.cake | build.cake | #addin "Cake.FileHelpers"
var target = Argument("target", "Default");
Task("Set-Build-Version")
.Does(() =>
{
var projectFile = "./src/ErgastApi/ErgastApi.csproj";
var versionPeekXpath = "/Project/PropertyGroup/Version/text()";
var versionPokeXpath = "/Project/PropertyGroup/Version";
var version = XmlPeek(projectFile, versionPeekXpath);
var parts = version.Split('.');
var buildNumber = 0;
if (BuildSystem.IsRunningOnAppVeyor)
{
buildNumber = AppVeyor.Environment.Build.Number;
}
version = string.Join(".", parts[0], parts[1], buildNumber);
if (BuildSystem.IsRunningOnAppVeyor)
{
AppVeyor.UpdateBuildVersion(version);
Information("Updated AppVeyor build version to " + version);
}
XmlPoke(projectFile, versionPokeXpath, version);
Information("Set project version to " + version);
});
Task("Default")
.IsDependentOn("Set-Build-Version");
RunTarget(target); | #addin "Cake.FileHelpers"
var target = Argument("target", "Default");
Task("Set-Build-Version")
.Does(() =>
{
var projectFile = "./src/ErgastApi/ErgastApi.csproj";
var versionPeekXpath = "/Project/PropertyGroup/Version/text()";
var versionPokeXpath = "/Project/PropertyGroup/Version";
var version = XmlPeek(projectFile, versionPeekXpath);
var parts = version.Split('.');
var buildNumber = 0;
if (BuildSystem.IsRunningOnAppVeyor)
{
buildNumber = AppVeyor.Environment.Build.Number;
}
version = string.Join(".", parts[0], parts[1], buildNumber);
XmlPoke(projectFile, versionPokeXpath, version);
if (BuildSystem.IsRunningOnAppVeyor)
{
AppVeyor.UpdateBuildVersion(version);
}
Information("Set project version to " + version);
});
Task("Default")
.IsDependentOn("Set-Build-Version");
RunTarget(target); | unlicense | C# |
7a1eb8c3ca9b2b21771a016d291b5ec227ee401d | Add missing ConfigureAwait to HttpGelfClient | mattwcole/gelf-extensions-logging | src/Gelf.Extensions.Logging/HttpGelfClient.cs | src/Gelf.Extensions.Logging/HttpGelfClient.cs | using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Gelf.Extensions.Logging
{
public class HttpGelfClient : IGelfClient
{
private readonly HttpClient _httpClient;
public HttpGelfClient(GelfLoggerOptions options)
{
var uriBuilder = new UriBuilder
{
Scheme = options.Protocol.ToString().ToLower(),
Host = options.Host,
Port = options.Port
};
_httpClient = new HttpClient
{
BaseAddress = uriBuilder.Uri,
Timeout = options.HttpTimeout
};
}
public async Task SendMessageAsync(GelfMessage message)
{
var content = new StringContent(message.ToJson(), Encoding.UTF8, "application/json");
var result = await _httpClient.PostAsync("gelf", content).ConfigureAwait(false);
result.EnsureSuccessStatusCode();
}
public void Dispose()
{
_httpClient.Dispose();
}
}
}
| using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Gelf.Extensions.Logging
{
public class HttpGelfClient : IGelfClient
{
private readonly HttpClient _httpClient;
public HttpGelfClient(GelfLoggerOptions options)
{
var uriBuilder = new UriBuilder
{
Scheme = options.Protocol.ToString().ToLower(),
Host = options.Host,
Port = options.Port
};
_httpClient = new HttpClient
{
BaseAddress = uriBuilder.Uri,
Timeout = options.HttpTimeout
};
}
public async Task SendMessageAsync(GelfMessage message)
{
var content = new StringContent(message.ToJson(), Encoding.UTF8, "application/json");
var result = await _httpClient.PostAsync("gelf", content);
result.EnsureSuccessStatusCode();
}
public void Dispose()
{
_httpClient.Dispose();
}
}
}
| mit | C# |
f6941f4c58059727da467b469a066586b4b45cef | bump explorer gui version | lysannschlegel/RDAExplorer | src/RDAExplorerGUI/Properties/AssemblyInfo.cs | src/RDAExplorerGUI/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RDAExplorerGUI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RDAExplorerGUI")]
[assembly: AssemblyCopyright("Copyright © 2010-2016 Ruman Gerst, D. Schneider, Lysann Schlegel")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.1.0")]
[assembly: AssemblyFileVersion("1.3.1.0")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RDAExplorerGUI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RDAExplorerGUI")]
[assembly: AssemblyCopyright("Copyright © 2010-2016 Ruman Gerst, D. Schneider, Lysann Schlegel")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
| bsd-3-clause | C# |
c7c2b1dfd45c8c5a6d0a71cb025b828487f6f6b4 | Update src/Umbraco.Core/Services/IKeyValueService.cs | arknu/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS | src/Umbraco.Core/Services/IKeyValueService.cs | src/Umbraco.Core/Services/IKeyValueService.cs | using System.Collections;
using System.Collections.Generic;
namespace Umbraco.Cms.Core.Services
{
/// <summary>
/// Manages the simplified key/value store.
/// </summary>
public interface IKeyValueService
{
/// <summary>
/// Gets a value.
/// </summary>
/// <remarks>Returns <c>null</c> if no value was found for the key.</remarks>
string GetValue(string key);
/// <summary>
/// Returns key/value pairs for all keys with the specified prefix.
/// </summary>
/// <param name="keyPrefix"></param>
/// <returns></returns>
IReadOnlyDictionary<string, string> FindByKeyPrefix(string keyPrefix);
/// <summary>
/// Sets a value.
/// </summary>
void SetValue(string key, string value);
/// <summary>
/// Sets a value.
/// </summary>
/// <remarks>Sets the value to <paramref name="newValue"/> if the value is <paramref name="originValue"/>,
/// and returns true; otherwise throws an exception. In other words, ensures that the value has not changed
/// before setting it.</remarks>
void SetValue(string key, string originValue, string newValue);
/// <summary>
/// Tries to set a value.
/// </summary>
/// <remarks>Sets the value to <paramref name="newValue"/> if the value is <paramref name="originValue"/>,
/// and returns true; otherwise returns false. In other words, ensures that the value has not changed
/// before setting it.</remarks>
bool TrySetValue(string key, string originValue, string newValue);
}
}
| using System.Collections;
using System.Collections.Generic;
namespace Umbraco.Cms.Core.Services
{
/// <summary>
/// Manages the simplified key/value store.
/// </summary>
public interface IKeyValueService
{
/// <summary>
/// Gets a value.
/// </summary>
/// <remarks>Returns <c>null</c> if no value was found for the key.</remarks>
string GetValue(string key);
/// <summary>
/// Returns key/value pairs for all keys with the specified prefix.
/// </summary>
/// <param name="keyPrefix"></param>
/// <returns></returns>
IReadOnlyDictionary<string, string> Find(string keyPrefix);
/// <summary>
/// Sets a value.
/// </summary>
void SetValue(string key, string value);
/// <summary>
/// Sets a value.
/// </summary>
/// <remarks>Sets the value to <paramref name="newValue"/> if the value is <paramref name="originValue"/>,
/// and returns true; otherwise throws an exception. In other words, ensures that the value has not changed
/// before setting it.</remarks>
void SetValue(string key, string originValue, string newValue);
/// <summary>
/// Tries to set a value.
/// </summary>
/// <remarks>Sets the value to <paramref name="newValue"/> if the value is <paramref name="originValue"/>,
/// and returns true; otherwise returns false. In other words, ensures that the value has not changed
/// before setting it.</remarks>
bool TrySetValue(string key, string originValue, string newValue);
}
}
| mit | C# |
fbad35aa9f25d46a8adb9eb1105aa22265a06d00 | Add expected answer for day 13 part 2 | martincostello/adventofcode,martincostello/adventofcode,martincostello/adventofcode,martincostello/adventofcode | tests/AdventOfCode.Tests/Puzzles/Y2017/Day13Tests.cs | tests/AdventOfCode.Tests/Puzzles/Y2017/Day13Tests.cs | // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.AdventOfCode.Puzzles.Y2017
{
using Xunit;
/// <summary>
/// A class containing tests for the <see cref="Day13"/> class. This class cannot be inherited.
/// </summary>
public static class Day13Tests
{
[Fact]
public static void Y2017_Day13_GetSeverityOfTrip_Returns_Correct_Value()
{
// Arrange
var depthRanges = new[]
{
"0: 3",
"1: 2",
"4: 4",
"6: 4",
};
// Act
int actual = Day13.GetSeverityOfTrip(depthRanges);
// Assert
Assert.Equal(24, actual);
}
[Fact]
public static void Y2017_Day13_GetShortestDelayForNeverCaught_Returns_Correct_Value()
{
// Arrange
var depthRanges = new[]
{
"0: 3",
"1: 2",
"4: 4",
"6: 4",
};
// Act
int actual = Day13.GetShortestDelayForNeverCaught(depthRanges);
// Assert
Assert.Equal(10, actual);
}
[Fact(Skip = "Too slow and not solved for part 2 yet.")]
public static void Y2017_Day13_Solve_Returns_Correct_Solution()
{
// Act
var puzzle = PuzzleTestHelpers.SolvePuzzle<Day13>();
// Assert
Assert.Equal(1612, puzzle.Severity);
Assert.Equal(3907994, puzzle.ShortestDelay);
}
}
}
| // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.AdventOfCode.Puzzles.Y2017
{
using Xunit;
/// <summary>
/// A class containing tests for the <see cref="Day13"/> class. This class cannot be inherited.
/// </summary>
public static class Day13Tests
{
[Fact]
public static void Y2017_Day13_GetSeverityOfTrip_Returns_Correct_Value()
{
// Arrange
var depthRanges = new[]
{
"0: 3",
"1: 2",
"4: 4",
"6: 4",
};
// Act
int actual = Day13.GetSeverityOfTrip(depthRanges);
// Assert
Assert.Equal(24, actual);
}
[Fact]
public static void Y2017_Day13_GetShortestDelayForNeverCaught_Returns_Correct_Value()
{
// Arrange
var depthRanges = new[]
{
"0: 3",
"1: 2",
"4: 4",
"6: 4",
};
// Act
int actual = Day13.GetShortestDelayForNeverCaught(depthRanges);
// Assert
Assert.Equal(10, actual);
}
[Fact(Skip = "Too slow and not solved for part 2 yet.")]
public static void Y2017_Day13_Solve_Returns_Correct_Solution()
{
// Act
var puzzle = PuzzleTestHelpers.SolvePuzzle<Day13>();
// Assert
Assert.Equal(1612, puzzle.Severity);
}
}
}
| apache-2.0 | C# |
d9b9bec52426904919f53ff3d132537716ca2341 | Add field to modifier roughness | Saduras/TerrainGeneration,Saduras/TerrainGeneration,Saduras/TerrainGeneration | Assets/TerrainGeneration/Scripts/Editor/TerrainGeneratorWindow.cs | Assets/TerrainGeneration/Scripts/Editor/TerrainGeneratorWindow.cs | using UnityEngine;
using UnityEditor;
using System.Collections;
public class TerrainGeneratorWindow : EditorWindow
{
Terrain m_terrain = null;
int m_detail = 8;
float m_roughness = 0.7f;
float m_smoothCenter = 0.5f;
float m_smoothGrade = 0.5f;
float m_smoothThreshold = 0.1f;
int m_smoothIterations = 2;
[MenuItem("Window/TerrainGenerator")]
static void Init()
{
GetWindow<TerrainGeneratorWindow>();
}
void OnGUI()
{
m_terrain = (Terrain)EditorGUILayout.ObjectField("Terrain",m_terrain, typeof(Terrain));
if (m_terrain != null) {
m_detail = EditorGUILayout.IntField("Detail", m_detail);
float mapSize = Mathf.Pow(2, m_detail) + 1;
EditorGUILayout.LabelField("HeightMap size: " + mapSize + "x" + mapSize);
m_roughness = EditorGUILayout.FloatField("Roughness", m_roughness);
// Default roughness function 2^(-H) for H := m_roughness
// does not depend on average, max or size i.e. the callback is constant
float roughnessResult = Mathf.Pow(2, -m_roughness);
if (GUILayout.Button("Generate")) {
DSANoise noise = new DSANoise(m_detail);
noise.SetRoughnessFunction((average, max, size) => {
return roughnessResult;
});
noise.Generate();
m_terrain.terrainData.SetHeights(0, 0, noise.GetNoiseMap());
}
m_smoothCenter = EditorGUILayout.FloatField("Smooth center", m_smoothCenter);
m_smoothGrade = EditorGUILayout.FloatField("Smooth grade", m_smoothGrade);
m_smoothThreshold = EditorGUILayout.FloatField("Smooth threshold", m_smoothThreshold);
m_smoothIterations = EditorGUILayout.IntField("Smooth iterations", m_smoothIterations);
if (GUILayout.Button("Smooth")) {
float[,] heightMap = m_terrain.terrainData.GetHeights(0, 0, m_terrain.terrainData.heightmapWidth, m_terrain.terrainData.heightmapHeight);
for (int i = 0; i < m_smoothIterations; i++) {
heightMap = SmoothHeightMap(heightMap);
}
m_terrain.terrainData.SetHeights(0,0,heightMap);
}
}
}
float[,] SmoothHeightMap(float[,] heightMap) {
for (int i = 0; i < heightMap.GetLength(0); i++) {
for (int j = 0; j < heightMap.GetLength(1); j++) {
float diffToCenter = m_smoothCenter - heightMap[i, j];
if ( Mathf.Abs(diffToCenter) < m_smoothThreshold) {
heightMap[i, j] = heightMap[i, j] + Mathf.Sign(diffToCenter) * (m_smoothThreshold - Mathf.Abs(diffToCenter)) * m_smoothGrade;
}
}
}
return heightMap;
}
}
| using UnityEngine;
using UnityEditor;
using System.Collections;
public class TerrainGeneratorWindow : EditorWindow
{
Terrain m_terrain = null;
int m_detail = 8;
float m_smoothCenter = 0.5f;
float m_smoothGrade = 0.5f;
float m_smoothThreshold = 0.1f;
int m_smoothIterations = 2;
[MenuItem("Window/TerrainGenerator")]
static void Init()
{
GetWindow<TerrainGeneratorWindow>();
}
void OnGUI()
{
m_terrain = (Terrain)EditorGUILayout.ObjectField("Terrain",m_terrain, typeof(Terrain));
if (m_terrain != null) {
m_detail = EditorGUILayout.IntField("Detail", m_detail);
float mapSize = Mathf.Pow(2, m_detail) + 1;
EditorGUILayout.LabelField("HeightMap size: " + mapSize + "x" + mapSize);
if (GUILayout.Button("Generate")) {
DSANoise noise = new DSANoise(m_detail);
noise.SetRoughnessFunction((average, max, size) => {
return Mathf.Pow(2, -0.5f);
});
noise.Generate();
m_terrain.terrainData.SetHeights(0, 0, noise.GetNoiseMap());
}
m_smoothCenter = EditorGUILayout.FloatField("Smooth center", m_smoothCenter);
m_smoothGrade = EditorGUILayout.FloatField("Smooth grade", m_smoothGrade);
m_smoothThreshold = EditorGUILayout.FloatField("Smooth threshold", m_smoothThreshold);
m_smoothIterations = EditorGUILayout.IntField("Smooth iterations", m_smoothIterations);
if (GUILayout.Button("Smooth")) {
float[,] heightMap = m_terrain.terrainData.GetHeights(0, 0, m_terrain.terrainData.heightmapWidth, m_terrain.terrainData.heightmapHeight);
for (int i = 0; i < m_smoothIterations; i++) {
heightMap = SmoothHeightMap(heightMap);
}
m_terrain.terrainData.SetHeights(0,0,heightMap);
}
}
}
float[,] SmoothHeightMap(float[,] heightMap) {
for (int i = 0; i < heightMap.GetLength(0); i++) {
for (int j = 0; j < heightMap.GetLength(1); j++) {
float diffToCenter = m_smoothCenter - heightMap[i, j];
if ( Mathf.Abs(diffToCenter) < m_smoothThreshold) {
heightMap[i, j] = heightMap[i, j] + Mathf.Sign(diffToCenter) * (m_smoothThreshold - Mathf.Abs(diffToCenter)) * m_smoothGrade;
}
}
}
return heightMap;
}
}
| mit | C# |
96c6d4c639a3bcf1c82d88e28fb1ad20e63ae746 | add missing model: ProGetPackageVersionExtended | lvermeulen/ProGet.Net | src/ProGet.Net/Native/Models/ProGetPackageVersionExtended.cs | src/ProGet.Net/Native/Models/ProGetPackageVersionExtended.cs | using System;
// ReSharper disable InconsistentNaming
namespace ProGet.Net.Native.Models
{
public class ProGetPackageVersionExtended
{
public int ProGetPackage_Id { get; set; }
public string Package_Name { get; set; }
public string Group_Name { get; set; }
public string Version_Text { get; set; }
public byte[] PackageHash_Bytes { get; set; }
public byte[] PackageMetadata_Bytes { get; set; }
public DateTime Published_Date { get; set; }
public long Package_Size { get; set; }
public int Download_Count { get; set; }
public bool Cached_Indicator { get; set; }
}
}
| namespace ProGet.Net.Native.Models
{
public class ProGetPackageVersionExtended
{
}
}
| mit | C# |
fb4b10def254fa10d3275b694f44ab99ea26ece8 | teste b | Thiago-Caramelo/patchsearch | Program.cs | Program.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace PatchSearch
{
// teste teste
class Program
{
static void Main(string[] args)
{
if (args == null || args.Length == 0)
{
return;
}
// obter todos os arquivos da pasta
string[] files = Directory.GetFiles(Directory.GetCurrentDirectory());
foreach (var item in files) //teste
{
using (StreamReader reader = new StreamReader(item))
{
string fileContent = reader.ReadToEnd();
int qt = 0;
foreach (var term in args)
{
if (fileContent.Contains(term))
{
qt++;
}
}
if (qt == args.Length)
{
Console.WriteLine(Path.GetFileName(item));
}
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace PatchSearch
{
// teste
class Program
{
static void Main(string[] args)
{
if (args == null || args.Length == 0)
{
return;
}
// obter todos os arquivos da pasta
string[] files = Directory.GetFiles(Directory.GetCurrentDirectory());
foreach (var item in files) //teste
{
using (StreamReader reader = new StreamReader(item))
{
string fileContent = reader.ReadToEnd();
int qt = 0;
foreach (var term in args)
{
if (fileContent.Contains(term))
{
qt++;
}
}
if (qt == args.Length)
{
Console.WriteLine(Path.GetFileName(item));
}
}
}
}
}
}
| mit | C# |
c4265a38f17d4c89807cf231f3573b464f52327d | add clean operation | tsolarin/dotnet-clean | Program.cs | Program.cs | using System;
using System.IO;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Cleaning...");
try
{
if (Directory.Exists("./bin"))
Directory.Delete("./bin", true);
if (Directory.Exists("./obj"))
Directory.Delete("./obj", true);
Console.WriteLine("Clean successful");
}
catch (System.Exception ex)
{
Console.WriteLine("Error while performing clean operation");
Console.WriteLine(ex.Message);
}
}
}
}
| using System;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
| mit | C# |
2b0b7d2d803f6a0b3e6ff159d9cefcd83edf11a1 | test commit | Zergatul/Injector | Program.cs | Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace Injector
{
class Program
{
// test
static void Main(string[] args)
{
string dllName = @"C:\Users\Zergatul\Documents\Visual Studio 2012\Projects\FakeFiles\Debug\FakeFiles.dll";
byte[] buf = new byte[dllName.Length + 1];
Array.Copy(Encoding.ASCII.GetBytes(dllName), buf, dllName.Length);
//var pp = Process.GetProcessesByName("ConsoleC++");
var pp = Process.GetProcessesByName("skype");
if (pp.Length == 0)
{
Console.WriteLine("no processes!");
Console.ReadLine();
return;
}
var process = WinAPI.OpenProcess(ProcessAccessFlags.All, false, pp[0].Id);
var remoteAddr = WinAPI.VirtualAllocEx(process, IntPtr.Zero, dllName.Length + 1, AllocationType.Commit, MemoryProtection.ReadWrite);
IntPtr bytesWritten;
var writeResult = WinAPI.WriteProcessMemory(process, remoteAddr, buf, buf.Length, out bytesWritten);
var kernel32 = WinAPI.GetModuleHandle("kernel32.dll");
var loadLibAddr = WinAPI.GetProcAddress(kernel32, "LoadLibraryA");
int threadId;
var thread = WinAPI.CreateRemoteThread(process, IntPtr.Zero, 0, loadLibAddr, remoteAddr, 0, out threadId);
Console.WriteLine(Marshal.GetLastWin32Error());
Console.ReadLine();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace Injector
{
class Program
{
static void Main(string[] args)
{
string dllName = @"C:\Users\Zergatul\Documents\Visual Studio 2012\Projects\FakeFiles\Debug\FakeFiles.dll";
byte[] buf = new byte[dllName.Length + 1];
Array.Copy(Encoding.ASCII.GetBytes(dllName), buf, dllName.Length);
//var pp = Process.GetProcessesByName("ConsoleC++");
var pp = Process.GetProcessesByName("skype");
if (pp.Length == 0)
{
Console.WriteLine("no processes!");
Console.ReadLine();
return;
}
var process = WinAPI.OpenProcess(ProcessAccessFlags.All, false, pp[0].Id);
var remoteAddr = WinAPI.VirtualAllocEx(process, IntPtr.Zero, dllName.Length + 1, AllocationType.Commit, MemoryProtection.ReadWrite);
IntPtr bytesWritten;
var writeResult = WinAPI.WriteProcessMemory(process, remoteAddr, buf, buf.Length, out bytesWritten);
var kernel32 = WinAPI.GetModuleHandle("kernel32.dll");
var loadLibAddr = WinAPI.GetProcAddress(kernel32, "LoadLibraryA");
int threadId;
var thread = WinAPI.CreateRemoteThread(process, IntPtr.Zero, 0, loadLibAddr, remoteAddr, 0, out threadId);
Console.WriteLine(Marshal.GetLastWin32Error());
Console.ReadLine();
}
}
}
| mit | C# |
e624ddd219b81131ebfa8f4b5d3e6000dd2e8a2c | Add completed with failures as a final end status (although it might not be) | MattFarm/BusinessPlatformApps,MattFarm/BusinessPlatformApps,MattFarm/BusinessPlatformApps,MattFarm/BusinessPlatformApps,MattFarm/BusinessPlatformApps | Source/Actions/Microsoft.Deployment.Actions.MsCrmActions/CrmGetProfileStatus.cs | Source/Actions/Microsoft.Deployment.Actions.MsCrmActions/CrmGetProfileStatus.cs | namespace Microsoft.Deployment.Common.Actions.MsCrm
{
using Microsoft.Deployment.Common.ActionModel;
using Microsoft.Deployment.Common.Actions;
using Microsoft.Deployment.Common.Helpers;
using Model;
using Newtonsoft.Json;
using System;
using System.ComponentModel.Composition;
using System.Net.Http.Headers;
using System.Threading.Tasks;
[Export(typeof(IAction))]
public class CrmGetProfileStatus : BaseAction
{
public override async Task<ActionResponse> ExecuteActionAsync(ActionRequest request)
{
string token = request.DataStore.GetValue("MsCrmToken");
string profileId = request.DataStore.GetValue("ProfileId");
RestClient rc = new RestClient(request.DataStore.GetValue("ConnectorUrl"), new AuthenticationHeaderValue("Bearer", token));
try
{
string response = await rc.Get(MsCrmEndpoints.URL_PROFILES + "/" + profileId, "status=true");
MsCrmProfile profile = JsonConvert.DeserializeObject<MsCrmProfile>(response);
bool done = true;
for (int i=0; done && i<profile.Entities.Length; i++)
{
done = done && (profile.Entities[i].Status.InitialSyncState.EqualsIgnoreCase("Completed") || profile.Entities[i].Status.InitialSyncState.EqualsIgnoreCase("CompletedWithFailures"));
}
if (done)
return new ActionResponse(ActionStatus.Success, JsonUtility.GetEmptyJObject());
else
return new ActionResponse(ActionStatus.BatchNoState, JsonUtility.GetEmptyJObject());
}
catch (Exception e)
{
return new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), e, "MsCrm_ErrorCreateProfile");
}
}
}
} | namespace Microsoft.Deployment.Common.Actions.MsCrm
{
using Microsoft.Deployment.Common.ActionModel;
using Microsoft.Deployment.Common.Actions;
using Microsoft.Deployment.Common.Helpers;
using Model;
using Newtonsoft.Json;
using System;
using System.ComponentModel.Composition;
using System.Net.Http.Headers;
using System.Threading.Tasks;
[Export(typeof(IAction))]
public class CrmGetProfileStatus : BaseAction
{
public override async Task<ActionResponse> ExecuteActionAsync(ActionRequest request)
{
string token = request.DataStore.GetValue("MsCrmToken");
string profileId = request.DataStore.GetValue("ProfileId");
RestClient rc = new RestClient(request.DataStore.GetValue("ConnectorUrl"), new AuthenticationHeaderValue("Bearer", token));
try
{
string response = await rc.Get(MsCrmEndpoints.URL_PROFILES + "/" + profileId, "status=true");
MsCrmProfile profile = JsonConvert.DeserializeObject<MsCrmProfile>(response);
bool done = true;
for (int i=0; done && i<profile.Entities.Length; i++)
{
done = done && profile.Entities[i].Status.InitialSyncState.EqualsIgnoreCase("Completed");
}
if (done)
return new ActionResponse(ActionStatus.Success, JsonUtility.GetEmptyJObject());
else
return new ActionResponse(ActionStatus.BatchNoState, JsonUtility.GetEmptyJObject());
}
catch (Exception e)
{
return new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), e, "MsCrm_ErrorCreateProfile");
}
}
}
} | mit | C# |
1aede57687c7d01fa434de82c6b5fbb9950bb23b | Add test cases. | niarora/Playground | Program.cs | Program.cs | namespace Playground
{
using System;
using System.Collections.Generic;
using System.Linq;
using Playground.Extensions;
public static class Program
{
public static void Main()
{
TestRemovingDuplicates(new int[] { 1, 10, 3, 4, 5, 7, 8, 10, 123, 14, 1, 5, 5, 3, 15, 1, 123 });
TestRemovingDuplicates(new int[] { 1, 1, 2, 2 });
TestRemovingDuplicates(new int[] { 2, 2, 2 });
TestRemovingDuplicates(new int[] { });
TestRemovingDuplicates(new int[] { 1 });
TestRemovingDuplicates(new int[] { 1,1 });
}
private static void TestRemovingDuplicates<T>(IEnumerable<T> testInput) where T : IEquatable<T>
{
testInput = testInput.OrderBy(t => t);
var linkedList = new LinkedList<T>(testInput);
Console.WriteLine();
Console.WriteLine("Before removing dups: ");
linkedList.Print();
linkedList.RemoveDuplicates();
Console.WriteLine("After removing dups: ");
linkedList.Print();
Console.WriteLine();
}
}
} | namespace Playground
{
using System;
using System.Collections.Generic;
using System.Linq;
using Playground.Extensions;
public static class Program
{
public static void Main()
{
TestRemovingDuplicates(new int[] { 1, 10, 3, 4, 5, 7, 8, 10, 123, 14, 1, 5, 5, 3, 15, 1, 123 });
TestRemovingDuplicates(new int[] { 1, 1, 2, 2 });
TestRemovingDuplicates(new int[] { 2, 2, 2 });
TestRemovingDuplicates(new int[] { });
}
private static void TestRemovingDuplicates<T>(IEnumerable<T> testInput) where T : IEquatable<T>
{
testInput = testInput.OrderBy(t => t);
var linkedList = new LinkedList<T>(testInput);
Console.WriteLine();
Console.WriteLine("Before removing dups: ");
linkedList.Print();
linkedList.RemoveDuplicates();
Console.WriteLine("After removing dups: ");
linkedList.Print();
Console.WriteLine();
}
}
} | mit | C# |
08cf2ba52a7b96fb2bcd6d99443758a46b170834 | Update test | AmadeusW/roslyn,wvdd007/roslyn,reaction1989/roslyn,AmadeusW/roslyn,stephentoub/roslyn,weltkante/roslyn,weltkante/roslyn,bartdesmet/roslyn,mavasani/roslyn,wvdd007/roslyn,physhi/roslyn,aelij/roslyn,brettfo/roslyn,mgoertz-msft/roslyn,KirillOsenkov/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,mgoertz-msft/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,aelij/roslyn,AlekseyTs/roslyn,genlu/roslyn,KirillOsenkov/roslyn,eriawan/roslyn,reaction1989/roslyn,weltkante/roslyn,panopticoncentral/roslyn,physhi/roslyn,tannergooding/roslyn,KevinRansom/roslyn,panopticoncentral/roslyn,bartdesmet/roslyn,eriawan/roslyn,tmat/roslyn,jasonmalinowski/roslyn,genlu/roslyn,CyrusNajmabadi/roslyn,davkean/roslyn,dotnet/roslyn,panopticoncentral/roslyn,physhi/roslyn,AmadeusW/roslyn,sharwell/roslyn,heejaechang/roslyn,tmat/roslyn,eriawan/roslyn,aelij/roslyn,AlekseyTs/roslyn,diryboy/roslyn,sharwell/roslyn,KevinRansom/roslyn,gafter/roslyn,mgoertz-msft/roslyn,dotnet/roslyn,ErikSchierboom/roslyn,mavasani/roslyn,heejaechang/roslyn,jasonmalinowski/roslyn,jasonmalinowski/roslyn,stephentoub/roslyn,brettfo/roslyn,dotnet/roslyn,jmarolf/roslyn,jmarolf/roslyn,gafter/roslyn,davkean/roslyn,bartdesmet/roslyn,diryboy/roslyn,davkean/roslyn,KevinRansom/roslyn,stephentoub/roslyn,AlekseyTs/roslyn,ErikSchierboom/roslyn,CyrusNajmabadi/roslyn,ErikSchierboom/roslyn,brettfo/roslyn,gafter/roslyn,KirillOsenkov/roslyn,mavasani/roslyn,jmarolf/roslyn,sharwell/roslyn,diryboy/roslyn,reaction1989/roslyn,wvdd007/roslyn,tannergooding/roslyn,heejaechang/roslyn,shyamnamboodiripad/roslyn,genlu/roslyn,tmat/roslyn | src/Features/LanguageServer/ProtocolUnitTests/Initialize/InitializeTests.cs | src/Features/LanguageServer/ProtocolUnitTests/Initialize/InitializeTests.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.Threading;
using System.Threading.Tasks;
using Roslyn.Test.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Initialize
{
public class InitializeTests : AbstractLanguageServerProtocolTests
{
[Fact]
public async Task TestInitializeAsync()
{
var (solution, _) = CreateTestSolution(string.Empty);
var results = await RunInitializeAsync(solution, new LSP.InitializeParams());
AssertServerCapabilities(results.Capabilities);
}
private static async Task<LSP.InitializeResult> RunInitializeAsync(Solution solution, LSP.InitializeParams request)
=> await GetLanguageServer(solution).InitializeAsync(solution, request, new LSP.ClientCapabilities(), CancellationToken.None);
private static void AssertServerCapabilities(LSP.ServerCapabilities actual)
{
Assert.True(actual.DefinitionProvider);
Assert.True(actual.ImplementationProvider);
Assert.True(actual.DocumentSymbolProvider);
Assert.True(actual.WorkspaceSymbolProvider);
Assert.True(actual.DocumentFormattingProvider);
Assert.True(actual.DocumentRangeFormattingProvider);
Assert.True(actual.DocumentHighlightProvider);
Assert.True(actual.CompletionProvider.ResolveProvider);
Assert.Equal(new[] { ".", " ", "#", "<", ">", "\"", ":", "[", "(", "~" }, actual.CompletionProvider.TriggerCharacters);
Assert.Equal(new[] { "(", "," }, actual.SignatureHelpProvider.TriggerCharacters);
Assert.Equal("}", actual.DocumentOnTypeFormattingProvider.FirstTriggerCharacter);
Assert.Equal(new[] { ";", "\n" }, actual.DocumentOnTypeFormattingProvider.MoreTriggerCharacter);
}
}
}
| // 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.Threading;
using System.Threading.Tasks;
using Roslyn.Test.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Initialize
{
public class InitializeTests : AbstractLanguageServerProtocolTests
{
[Fact]
public async Task TestInitializeAsync()
{
var (solution, _) = CreateTestSolution(string.Empty);
var results = await RunInitializeAsync(solution, new LSP.InitializeParams());
AssertServerCapabilities(results.Capabilities);
}
private static async Task<LSP.InitializeResult> RunInitializeAsync(Solution solution, LSP.InitializeParams request)
=> await GetLanguageServer(solution).InitializeAsync(solution, request, new LSP.ClientCapabilities(), CancellationToken.None);
private static void AssertServerCapabilities(LSP.ServerCapabilities actual)
{
Assert.True(actual.DefinitionProvider);
Assert.True(actual.ImplementationProvider);
Assert.True(actual.DocumentSymbolProvider);
Assert.True(actual.WorkspaceSymbolProvider);
Assert.True(actual.DocumentFormattingProvider);
Assert.True(actual.DocumentRangeFormattingProvider);
Assert.True(actual.DocumentHighlightProvider);
Assert.True(actual.CompletionProvider.ResolveProvider);
Assert.Equal(new[] { "." }, actual.CompletionProvider.TriggerCharacters);
Assert.Equal(new[] { "(", "," }, actual.SignatureHelpProvider.TriggerCharacters);
Assert.Equal("}", actual.DocumentOnTypeFormattingProvider.FirstTriggerCharacter);
Assert.Equal(new[] { ";", "\n" }, actual.DocumentOnTypeFormattingProvider.MoreTriggerCharacter);
}
}
}
| mit | C# |
15b2f30a760356fe3f4f24a4daac354bf268cf28 | Add missing route | laurentkempe/HipChatConnect,laurentkempe/HipChatConnect | src/HipChatConnect/Controllers/Listeners/Github/GithubListenerController.cs | src/HipChatConnect/Controllers/Listeners/Github/GithubListenerController.cs | using System.Net;
using System.Threading.Tasks;
using HipChatConnect.Controllers.Listeners.Github.Models;
using MediatR;
using Microsoft.AspNetCore.Mvc;
namespace HipChatConnect.Controllers.Listeners.Github
{
[Route("/github/listener")]
public class GithubListenerController : Controller
{
private readonly IMediator _mediator;
public GithubListenerController(IMediator mediator)
{
_mediator = mediator;
}
[HttpPost]
public async Task<HttpStatusCode> Build([FromBody] GithubModel githubModel)
{
await _mediator.Publish(new GithubPushNotification(githubModel));
return HttpStatusCode.OK;
}
}
}
| using System.Net;
using System.Threading.Tasks;
using HipChatConnect.Controllers.Listeners.Github.Models;
using MediatR;
using Microsoft.AspNetCore.Mvc;
namespace HipChatConnect.Controllers.Listeners.Github
{
public class GithubListenerController : Controller
{
private readonly IMediator _mediator;
public GithubListenerController(IMediator mediator)
{
_mediator = mediator;
}
[HttpPost]
public async Task<HttpStatusCode> Build([FromBody] GithubModel githubModel)
{
await _mediator.Publish(new GithubPushNotification(githubModel));
return HttpStatusCode.OK;
}
}
}
| mit | C# |
577d703f03288a4e88d8a0e77e876e2922842584 | Set version to 1.0 | ALyman/Synapse | source/Synapse/Properties/AssemblyInfo.cs | source/Synapse/Properties/AssemblyInfo.cs | #region LICENSE
// Copyright (c) 2011, Alex Lyman
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// Neither the name of Synapse 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;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Synapse")]
[assembly: AssemblyDescription("The Synapse Parser Framework")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Alex Lyman")]
[assembly: AssemblyProduct("Synapse")]
[assembly: AssemblyCopyright("Copyright © Alex Lyman 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: Guid("7f0b0cf1-4e43-4bc6-9409-67370e93d524")]
[assembly: AssemblyVersion("1.0.*")] | #region LICENSE
// Copyright (c) 2011, Alex Lyman
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// Neither the name of Synapse 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;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Synapse")]
[assembly: AssemblyDescription("The Synapse Parser Framework")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Alex Lyman")]
[assembly: AssemblyProduct("Synapse")]
[assembly: AssemblyCopyright("Copyright © Alex Lyman 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: Guid("7f0b0cf1-4e43-4bc6-9409-67370e93d524")]
[assembly: AssemblyVersion("0.1.*")] | bsd-3-clause | C# |
f8874cf0992e2e952318edcdc4d072efe1b102f0 | Fix AssemblyFileVersion that got messed up in merge | sillsdev/icu-dotnet,conniey/icu-dotnet,ermshiperete/icu-dotnet,ermshiperete/icu-dotnet,conniey/icu-dotnet,sillsdev/icu-dotnet | source/icu.net/Properties/AssemblyInfo.cs | source/icu.net/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("icu.net")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SIL International")]
[assembly: AssemblyProduct("icu.net")]
[assembly: AssemblyCopyright("Copyright © SIL International 2007")]
[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("3439151b-347b-4321-9f2f-d5fa28b46477")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
// (The AssemblyVersion needs to match the version that Palaso builds against.)
// (The AssemblyFileVersion matches the ICU version number we're building against.)
[assembly: AssemblyVersion("4.2.1.0")]
#if ICU_VERSION_40
[assembly: AssemblyFileVersion("4.2.1.*")]
#elif ICU_VERSION_48
[assembly: AssemblyFileVersion("4.8.1.1")]
#else
[assembly: AssemblyFileVersion("5.0.0.2")]
#endif
| 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("icu.net")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SIL International")]
[assembly: AssemblyProduct("icu.net")]
[assembly: AssemblyCopyright("Copyright © SIL International 2007")]
[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("3439151b-347b-4321-9f2f-d5fa28b46477")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| mit | C# |
88bfa0dab7ba9794ea7b7803a123215c82473e57 | Remove unnecessary fields/methods for lsp push diagnostics | mavasani/roslyn,gafter/roslyn,ErikSchierboom/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,KevinRansom/roslyn,wvdd007/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,stephentoub/roslyn,AmadeusW/roslyn,physhi/roslyn,wvdd007/roslyn,AmadeusW/roslyn,stephentoub/roslyn,tmat/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,KirillOsenkov/roslyn,ErikSchierboom/roslyn,heejaechang/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,dotnet/roslyn,gafter/roslyn,panopticoncentral/roslyn,weltkante/roslyn,KirillOsenkov/roslyn,bartdesmet/roslyn,AlekseyTs/roslyn,panopticoncentral/roslyn,eriawan/roslyn,jasonmalinowski/roslyn,tmat/roslyn,panopticoncentral/roslyn,weltkante/roslyn,stephentoub/roslyn,tannergooding/roslyn,diryboy/roslyn,heejaechang/roslyn,mavasani/roslyn,eriawan/roslyn,dotnet/roslyn,mgoertz-msft/roslyn,mgoertz-msft/roslyn,tmat/roslyn,KevinRansom/roslyn,diryboy/roslyn,bartdesmet/roslyn,physhi/roslyn,mgoertz-msft/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,mavasani/roslyn,sharwell/roslyn,jasonmalinowski/roslyn,KirillOsenkov/roslyn,bartdesmet/roslyn,dotnet/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,tannergooding/roslyn,physhi/roslyn,jasonmalinowski/roslyn,gafter/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,AlekseyTs/roslyn,eriawan/roslyn,tannergooding/roslyn | src/VisualStudio/Xaml/Impl/Implementation/LanguageClient/XamlLanguageServerClient.cs | src/VisualStudio/Xaml/Impl/Implementation/LanguageClient/XamlLanguageServerClient.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.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.LanguageServer.Client;
using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService;
using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Xaml
{
[ContentType(ContentTypeNames.XamlContentType)]
[DisableUserExperience(disableUserExperience: true)] // Remove this when we are ready to use LSP everywhere
[Export(typeof(ILanguageClient))]
internal class XamlLanguageServerClient : AbstractLanguageServerClient
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, true)]
public XamlLanguageServerClient(XamlLanguageServerProtocol languageServerProtocol, VisualStudioWorkspace workspace, IAsynchronousOperationListenerProvider listenerProvider, ILspSolutionProvider solutionProvider)
: base(languageServerProtocol, workspace, listenerProvider, solutionProvider, diagnosticsClientName: null)
{
}
/// <summary>
/// Gets the name of the language client (displayed to the user).
/// </summary>
public override string Name => Resources.Xaml_Language_Server_Client;
}
}
| // 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.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.LanguageServer.Client;
using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService;
using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Xaml
{
[ContentType(ContentTypeNames.XamlContentType)]
[DisableUserExperience(disableUserExperience: true)] // Remove this when we are ready to use LSP everywhere
[Export(typeof(ILanguageClient))]
internal class XamlLanguageServerClient : AbstractLanguageServerClient
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, true)]
public XamlLanguageServerClient(XamlLanguageServerProtocol languageServerProtocol, VisualStudioWorkspace workspace, IDiagnosticService diagnosticService, IAsynchronousOperationListenerProvider listenerProvider, ILspSolutionProvider solutionProvider)
: base(languageServerProtocol, workspace, diagnosticService, listenerProvider, solutionProvider, diagnosticsClientName: null)
{
}
/// <summary>
/// Gets the name of the language client (displayed to the user).
/// </summary>
public override string Name => Resources.Xaml_Language_Server_Client;
}
}
| mit | C# |
1193dd3d1cdad1a25c5fc7fe075b3d24990914d7 | Rollback a change | dotMorten/AllJoynDotNet | src/AllJoynDotNet/Shared/AboutListener.cs | src/AllJoynDotNet/Shared/AboutListener.cs | using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace AllJoynDotNet
{
public partial class AboutListener : AllJoynWrapper
{
private alljoyn_aboutlistener_callback callback;
private AboutListener(alljoyn_aboutlistener_callback callback) : base(IntPtr.Zero)
{
this.callback = callback;
}
public AboutListener() : base(IntPtr.Zero)
{
callback = new alljoyn_aboutlistener_callback()
{
//about_listener_announced = Marshal.GetFunctionPointerForDelegate<alljoyn_about_announced_ptr>((alljoyn_about_announced_ptr)alljoyn_about_announced_delegate)
about_listener_announced = alljoyn_about_announced_delegate
};
//GCHandle gch = GCHandle.Alloc(callback, GCHandleType.Pinned);
//var handle = alljoyn_aboutlistener_create(gch.AddrOfPinnedObject(), IntPtr.Zero);
var handle = alljoyn_aboutlistener_create(callback, IntPtr.Zero);
SetHandle(handle);
//gch.Free();
}
private void alljoyn_about_announced_delegate(IntPtr context, string busName, UInt16 version, UInt16 port, IntPtr objectDescriptionArg, IntPtr aboutDataArg)
{
AboutAnnounced?.Invoke(this, EventArgs.Empty); // (busName, version);
}
public event EventHandler AboutAnnounced;
}
} | using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace AllJoynDotNet
{
public partial class AboutListener : AllJoynWrapper
{
private alljoyn_aboutlistener_callback callback;
private AboutListener(alljoyn_aboutlistener_callback callback) : base(IntPtr.Zero)
{
this.callback = callback;
}
public AboutListener() : base(IntPtr.Zero)
{
callback = new alljoyn_aboutlistener_callback()
{
about_listener_announced = Marshal.GetFunctionPointerForDelegate<alljoyn_about_announced_ptr>((alljoyn_about_announced_ptr)alljoyn_about_announced_delegate)
};
GCHandle gch = GCHandle.Alloc(callback, GCHandleType.Pinned);
var handle = alljoyn_aboutlistener_create(gch.AddrOfPinnedObject(), IntPtr.Zero);
SetHandle(handle);
gch.Free();
}
private void alljoyn_about_announced_delegate(IntPtr context, string busName, UInt16 version, UInt16 port, IntPtr objectDescriptionArg, IntPtr aboutDataArg)
{
AboutAnnounced?.Invoke(this, EventArgs.Empty); // (busName, version);
}
public event EventHandler AboutAnnounced;
}
} | apache-2.0 | C# |
acbb1ab6091d072365a18522a11b8020b16ff586 | remove debug log | runceel/ReactiveProperty,runceel/ReactiveProperty,runceel/ReactiveProperty | Sample/XamarinAndroid/Views/ReactivePropertyBasicsActivity.cs | Sample/XamarinAndroid/Views/ReactivePropertyBasicsActivity.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reactive.Linq;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Reactive.Bindings;
using Reactive.Bindings.Extensions;
using Sample.ViewModels;
using Android.Util;
namespace XamarinAndroid.Views
{
[Activity(Label = "ReactivePropertyBasicsActivity")]
public class ReactivePropertyBasicsActivity : Activity
{
private ReactivePropertyBasicsViewModel viewModel;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
this.SetContentView(Resource.Layout.ReactivePropertyBasics);
this.viewModel = new ReactivePropertyBasicsViewModel();
this.FindViewById<EditText>(Resource.Id.EditTextInput)
.SetBinding(
x => x.Text,
this.viewModel.InputText,
x => x.TextChangedAsObservable().ToUnit());
this.FindViewById<TextView>(Resource.Id.TextViewOutput)
.SetBinding(
x => x.Text,
this.viewModel.DisplayText);
var buttonReplaceText = this.FindViewById<Button>(Resource.Id.ButtonReplaceText);
buttonReplaceText
.ClickAsObservable()
.SetCommand(this.viewModel.ReplaceTextCommand);
buttonReplaceText
.SetBinding(
x => x.Enabled,
this.viewModel.ReplaceTextCommand
.CanExecuteChangedAsObservable()
.Select(_ => this.viewModel.ReplaceTextCommand.CanExecute())
.ToReactiveProperty());
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reactive.Linq;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Reactive.Bindings;
using Reactive.Bindings.Extensions;
using Sample.ViewModels;
using Android.Util;
namespace XamarinAndroid.Views
{
[Activity(Label = "ReactivePropertyBasicsActivity")]
public class ReactivePropertyBasicsActivity : Activity
{
private ReactivePropertyBasicsViewModel viewModel;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
this.SetContentView(Resource.Layout.ReactivePropertyBasics);
this.viewModel = new ReactivePropertyBasicsViewModel();
this.FindViewById<EditText>(Resource.Id.EditTextInput)
.SetBinding(
x => x.Text,
this.viewModel.InputText,
x => x.TextChangedAsObservable().ToUnit());
this.FindViewById<TextView>(Resource.Id.TextViewOutput)
.SetBinding(
x => x.Text,
this.viewModel.DisplayText);
this.viewModel.DisplayText.Subscribe(x => Log.Info("Debug", x));
var buttonReplaceText = this.FindViewById<Button>(Resource.Id.ButtonReplaceText);
buttonReplaceText
.ClickAsObservable()
.SetCommand(this.viewModel.ReplaceTextCommand);
buttonReplaceText
.SetBinding(
x => x.Enabled,
this.viewModel.ReplaceTextCommand
.CanExecuteChangedAsObservable()
.Select(_ => this.viewModel.ReplaceTextCommand.CanExecute())
.ToReactiveProperty());
}
}
} | mit | C# |
268a4f33ce74a528b28f46c01b0a49ecc171d518 | Fix typo error | aloneguid/config | src/Config.Net/TypeParsers/ShortParser.cs | src/Config.Net/TypeParsers/ShortParser.cs | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace Config.Net.TypeParsers
{
class ShortParser : ITypeParser
{
public IEnumerable<Type> SupportedTypes => new[] { typeof(short) };
public bool TryParse(string value, Type t, out object result)
{
short ir;
bool parsed = short.TryParse(value, NumberStyles.Integer, TypeParserSettings.DefaultCulture, out ir);
result = ir;
return parsed;
}
public string ToRawString(object value)
{
return ((short)value).ToString(TypeParserSettings.DefaultNumericFormat, TypeParserSettings.DefaultCulture);
}
}
}
| using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace Config.Net.TypeParsers
{
class ShortParser : ITypeParser
{
public IEnumerable<Type> SupportedTypes => new[] { typeof(int) };
public bool TryParse(string value, Type t, out object result)
{
short ir;
bool parsed = short.TryParse(value, NumberStyles.Integer, TypeParserSettings.DefaultCulture, out ir);
result = ir;
return parsed;
}
public string ToRawString(object value)
{
return ((short)value).ToString(TypeParserSettings.DefaultNumericFormat, TypeParserSettings.DefaultCulture);
}
}
}
| mit | C# |
8ef50ff42dab85eaae680274ccd7d3b25a78de2f | Add safety to ensure `RealmLiveUnmanaged` is not used with managed instances | ppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu | osu.Game/Database/RealmLiveUnmanaged.cs | osu.Game/Database/RealmLiveUnmanaged.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 Realms;
#nullable enable
namespace osu.Game.Database
{
/// <summary>
/// Provides a method of working with unmanaged realm objects.
/// Usually used for testing purposes where the instance is never required to be managed.
/// </summary>
/// <typeparam name="T">The underlying object type.</typeparam>
public class RealmLiveUnmanaged<T> : ILive<T> where T : RealmObjectBase, IHasGuidPrimaryKey
{
/// <summary>
/// Construct a new instance of live realm data.
/// </summary>
/// <param name="data">The realm data.</param>
public RealmLiveUnmanaged(T data)
{
if (data.IsManaged)
throw new InvalidOperationException($"Cannot use {nameof(RealmLiveUnmanaged<T>)} with managed instances");
Value = data;
}
public bool Equals(ILive<T>? other) => ID == other?.ID;
public override string ToString() => Value.ToString();
public Guid ID => Value.ID;
public void PerformRead(Action<T> perform) => perform(Value);
public TReturn PerformRead<TReturn>(Func<T, TReturn> perform) => perform(Value);
public void PerformWrite(Action<T> perform) => throw new InvalidOperationException(@"Can't perform writes on a non-managed underlying value");
public bool IsManaged => false;
/// <summary>
/// The original live data used to create this instance.
/// </summary>
public T Value { get; }
}
}
| // 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 Realms;
#nullable enable
namespace osu.Game.Database
{
/// <summary>
/// Provides a method of working with unmanaged realm objects.
/// Usually used for testing purposes where the instance is never required to be managed.
/// </summary>
/// <typeparam name="T">The underlying object type.</typeparam>
public class RealmLiveUnmanaged<T> : ILive<T> where T : RealmObjectBase, IHasGuidPrimaryKey
{
/// <summary>
/// Construct a new instance of live realm data.
/// </summary>
/// <param name="data">The realm data.</param>
public RealmLiveUnmanaged(T data)
{
Value = data;
}
public bool Equals(ILive<T>? other) => ID == other?.ID;
public override string ToString() => Value.ToString();
public Guid ID => Value.ID;
public void PerformRead(Action<T> perform) => perform(Value);
public TReturn PerformRead<TReturn>(Func<T, TReturn> perform) => perform(Value);
public void PerformWrite(Action<T> perform) => throw new InvalidOperationException(@"Can't perform writes on a non-managed underlying value");
public bool IsManaged => false;
/// <summary>
/// The original live data used to create this instance.
/// </summary>
public T Value { get; }
}
}
| mit | C# |
a6c6f1984936431ebb39cb823f374b3f1b02052c | Clean up using. | sjp/Schematic,sjp/Schematic,sjp/Schematic,sjp/SJP.Schema,sjp/Schematic | src/SJP.Schematic.Core/Utilities/Empty.cs | src/SJP.Schematic.Core/Utilities/Empty.cs | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace SJP.Schematic.Core.Utilities
{
public static class Empty
{
public static Task<IReadOnlyCollection<IRelationalDatabaseTable>> Tables { get; } = Task.FromResult<IReadOnlyCollection<IRelationalDatabaseTable>>(Array.Empty<IRelationalDatabaseTable>());
public static Task<IReadOnlyCollection<IDatabaseCheckConstraint>> Checks { get; } = Task.FromResult<IReadOnlyCollection<IDatabaseCheckConstraint>>(Array.Empty<IDatabaseCheckConstraint>());
public static Task<IReadOnlyCollection<IDatabaseView>> Views { get; } = Task.FromResult<IReadOnlyCollection<IDatabaseView>>(Array.Empty<IDatabaseView>());
public static Task<IReadOnlyCollection<IDatabaseSequence>> Sequences { get; } = Task.FromResult<IReadOnlyCollection<IDatabaseSequence>>(Array.Empty<IDatabaseSequence>());
public static Task<IReadOnlyCollection<IDatabaseSynonym>> Synonyms { get; } = Task.FromResult<IReadOnlyCollection<IDatabaseSynonym>>(Array.Empty<IDatabaseSynonym>());
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace SJP.Schematic.Core.Utilities
{
public static class Empty
{
public static Task<IReadOnlyCollection<IRelationalDatabaseTable>> Tables { get; } = Task.FromResult<IReadOnlyCollection<IRelationalDatabaseTable>>(Array.Empty<IRelationalDatabaseTable>());
public static Task<IReadOnlyCollection<IDatabaseCheckConstraint>> Checks { get; } = Task.FromResult<IReadOnlyCollection<IDatabaseCheckConstraint>>(Array.Empty<IDatabaseCheckConstraint>());
public static Task<IReadOnlyCollection<IDatabaseView>> Views { get; } = Task.FromResult<IReadOnlyCollection<IDatabaseView>>(Array.Empty<IDatabaseView>());
public static Task<IReadOnlyCollection<IDatabaseSequence>> Sequences { get; } = Task.FromResult<IReadOnlyCollection<IDatabaseSequence>>(Array.Empty<IDatabaseSequence>());
public static Task<IReadOnlyCollection<IDatabaseSynonym>> Synonyms { get; } = Task.FromResult<IReadOnlyCollection<IDatabaseSynonym>>(Array.Empty<IDatabaseSynonym>());
}
}
| mit | C# |
451eac594d35fc681e4431e093a0d985e2359626 | Debug output on throttled throughput | OpenStreamDeck/StreamDeckSharp | src/StreamDeckSharp/Internals/Throttle.cs | src/StreamDeckSharp/Internals/Throttle.cs | using System;
using System.Diagnostics;
using System.Threading;
namespace StreamDeckSharp.Internals
{
internal class Throttle
{
private readonly Stopwatch stopwatch = Stopwatch.StartNew();
private long sumBytesInWindow = 0;
private int sleepCount = 0;
public double BytesPerSecondLimit { get; set; } = double.PositiveInfinity;
public void MeasureAndBlock(int bytes)
{
sumBytesInWindow += bytes;
var elapsedSeconds = stopwatch.Elapsed.TotalSeconds;
var estimatedSeconds = sumBytesInWindow / BytesPerSecondLimit;
if (elapsedSeconds < estimatedSeconds)
{
var delta = Math.Max(1, (int)((estimatedSeconds - elapsedSeconds) * 1000));
Thread.Sleep(delta);
sleepCount++;
}
if (elapsedSeconds >= 1)
{
if (sleepCount > 1)
{
Debug.WriteLine($"[Throttle] {sumBytesInWindow / elapsedSeconds}");
}
stopwatch.Restart();
sumBytesInWindow = 0;
sleepCount = 0;
}
}
}
}
| using System;
using System.Diagnostics;
using System.Threading;
namespace StreamDeckSharp.Internals
{
internal class Throttle
{
private readonly Stopwatch stopwatch = Stopwatch.StartNew();
private long sumBytesInWindow = 0;
public double BytesPerSecondLimit { get; set; } = double.PositiveInfinity;
public void MeasureAndBlock(int bytes)
{
sumBytesInWindow += bytes;
var elapsedSeconds = stopwatch.Elapsed.TotalSeconds;
var estimatedSeconds = sumBytesInWindow / BytesPerSecondLimit;
if (elapsedSeconds < estimatedSeconds)
{
var delta = Math.Max(1, (int)((estimatedSeconds - elapsedSeconds) * 1000));
Thread.Sleep(delta);
}
if (elapsedSeconds >= 1)
{
stopwatch.Restart();
sumBytesInWindow = 0;
}
}
}
}
| mit | C# |
d5403032a94a956c8d91b934e4f4ef19894960c4 | Fix CVC4 support (requires a new version that supports the reset command). | symbooglix/symbooglix,symbooglix/symbooglix,symbooglix/symbooglix | src/Symbooglix/Solver/CVC4SMTLIBSolver.cs | src/Symbooglix/Solver/CVC4SMTLIBSolver.cs | using System;
using Symbooglix.Solver;
namespace Symbooglix
{
namespace Solver
{
public class CVC4SMTLIBSolver : SimpleSMTLIBSolver
{
SMTLIBQueryPrinter.Logic LogicToUse = SMTLIBQueryPrinter.Logic.ALL_SUPPORTED; // Non standard
public CVC4SMTLIBSolver(bool useNamedAttributes, string pathToSolver, bool persistentProcess) :
base(useNamedAttributes, pathToSolver, "--lang smt2 --incremental", persistentProcess) // CVC4 specific command line flags
{
}
// HACK:
public CVC4SMTLIBSolver(bool useNamedAttributes, string pathToSolver, bool persistentProcess, SMTLIBQueryPrinter.Logic logic) :
this(useNamedAttributes, pathToSolver, persistentProcess)
{
// We should not use DO_NOT_SET because CVC4 complains if no
// logic is set which causes a SolverErrorException to be raised.
if (logic != SMTLIBQueryPrinter.Logic.DO_NOT_SET)
LogicToUse = logic;
}
protected override void SetSolverOptions()
{
Printer.PrintSetLogic(LogicToUse);
}
}
}
}
| using System;
using Symbooglix.Solver;
namespace Symbooglix
{
namespace Solver
{
public class CVC4SMTLIBSolver : SimpleSMTLIBSolver
{
SMTLIBQueryPrinter.Logic LogicToUse = SMTLIBQueryPrinter.Logic.ALL_SUPPORTED; // Non standard
public CVC4SMTLIBSolver(bool useNamedAttributes, string pathToSolver, bool persistentProcess) :
base(useNamedAttributes, pathToSolver, "--lang smt2 --incremental", persistentProcess) // CVC4 specific command line flags
{
}
// HACK:
public CVC4SMTLIBSolver(bool useNamedAttributes, string pathToSolver, bool persistentProcess, SMTLIBQueryPrinter.Logic logic) :
this(useNamedAttributes, pathToSolver, persistentProcess)
{
LogicToUse = logic;
}
protected override void SetSolverOptions()
{
Printer.PrintSetLogic(LogicToUse);
}
}
}
}
| bsd-2-clause | C# |
3cb095327b6d9e301c9d0bcd923bfc599348627e | Clean up Process.cs | Cyberboss/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server | src/Tgstation.Server.Host/Core/Process.cs | src/Tgstation.Server.Host/Core/Process.cs | using System;
using System.Text;
using System.Threading.Tasks;
namespace Tgstation.Server.Host.Core
{
/// <inheritdoc />
sealed class Process : IProcess
{
/// <inheritdoc />
public int Id { get; }
/// <inheritdoc />
public Task Startup { get; }
/// <inheritdoc />
public Task<int> Lifetime { get; }
readonly System.Diagnostics.Process handle;
readonly StringBuilder outputStringBuilder;
readonly StringBuilder errorStringBuilder;
readonly StringBuilder combinedStringBuilder;
public Process(System.Diagnostics.Process handle, Task<int> lifetime, StringBuilder outputStringBuilder, StringBuilder errorStringBuilder, StringBuilder combinedStringBuilder)
{
this.handle = handle ?? throw new ArgumentNullException(nameof(handle));
Lifetime = lifetime ?? throw new ArgumentNullException(nameof(lifetime));
this.outputStringBuilder = outputStringBuilder;
this.errorStringBuilder = errorStringBuilder;
this.combinedStringBuilder = combinedStringBuilder;
Id = handle.Id;
Startup = Task.Factory.StartNew(() =>
{
try
{
handle.WaitForInputIdle();
}
catch (InvalidOperationException) { }
}, default, TaskCreationOptions.LongRunning, TaskScheduler.Current);
}
/// <inheritdoc />
public void Dispose() => handle.Dispose();
/// <inheritdoc />
public string GetCombinedOutput()
{
if (combinedStringBuilder == null)
throw new InvalidOperationException("Output/Error reading was not enabled!");
return combinedStringBuilder.ToString();
}
/// <inheritdoc />
public string GetErrorOutput()
{
if (errorStringBuilder == null)
throw new InvalidOperationException("Error reading was not enabled!");
return errorStringBuilder.ToString();
}
/// <inheritdoc />
public string GetStandardOutput()
{
if (outputStringBuilder == null)
throw new InvalidOperationException("Output reading was not enabled!");
return errorStringBuilder.ToString();
}
/// <inheritdoc />
public void Terminate()
{
try
{
handle.Kill();
handle.WaitForExit();
}
catch (InvalidOperationException) { }
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Tgstation.Server.Host.Core
{
/// <inheritdoc />
sealed class Process : IProcess
{
public int Id { get; }
public Task Startup { get; }
public Task<int> Lifetime { get; }
readonly System.Diagnostics.Process handle;
readonly StringBuilder outputStringBuilder;
readonly StringBuilder errorStringBuilder;
readonly StringBuilder combinedStringBuilder;
public Process(System.Diagnostics.Process handle, Task<int> lifetime, StringBuilder outputStringBuilder, StringBuilder errorStringBuilder, StringBuilder combinedStringBuilder)
{
this.handle = handle ?? throw new ArgumentNullException(nameof(handle));
Lifetime = lifetime ?? throw new ArgumentNullException(nameof(lifetime));
this.outputStringBuilder = outputStringBuilder;
this.errorStringBuilder = errorStringBuilder;
this.combinedStringBuilder = combinedStringBuilder;
Id = handle.Id;
Startup = Task.Factory.StartNew(() =>
{
try
{
handle.WaitForInputIdle();
}
catch (InvalidOperationException) { }
}, default, TaskCreationOptions.LongRunning, TaskScheduler.Current);
}
public void Dispose() => handle.Dispose();
public string GetCombinedOutput()
{
if (combinedStringBuilder == null)
throw new InvalidOperationException("Output/Error reading was not enabled!");
return combinedStringBuilder.ToString();
}
public string GetErrorOutput()
{
if (errorStringBuilder == null)
throw new InvalidOperationException("Error reading was not enabled!");
return errorStringBuilder.ToString();
}
public string GetStandardOutput()
{
if (outputStringBuilder == null)
throw new InvalidOperationException("Output reading was not enabled!");
return errorStringBuilder.ToString();
}
public void Terminate()
{
try
{
handle.Kill();
handle.WaitForExit();
}
catch (InvalidOperationException) { }
}
}
}
| agpl-3.0 | C# |
945b34fe76a6892c9dce388f111d1fc5822d28af | fix typo | lesovsky/uber-scripts,lesovsky/uber-scripts,lesovsky/uber-scripts | cheatsheets/megacli.cs | cheatsheets/megacli.cs | MegaCli is a RAID utility For LSI MegaRAID Controllers
LD - LogicalDrive
PD - PhysicalDrive
BBU - Backup Battery Unit
# Get Info
megacli adpcount # get controllers count
megacli adpallinfo aall # get information about all adapters
megacli adpbbucmd aall # get BBU information
megacli ldinfo lall aall # get LogicalDrives information from all adapters
magacli pdlist aall # get PhysicalDrives information from all adapters
megacli pdinfo physdrv [32:2] a0 # get info about specified drive
megacli pdrbld showprog physdrv [32:2] a0 # get info about rebuild progress
megacli pdlocate start|stop physdrv [32:2] a0 # start/stop flashing on specified drive
# Get/Set Logical Drives Properties
megacli ldgetprop cache lall aall # get LogicalDrives cache information
megacli ldgetprop dskcache lall aall # get PhysicalDrive cache status
MegaCli ldinfo lall aall |grep -E '(Virtual Drive|RAID Level|Cache Policy|Access Policy)' # get LD cache and PD cache information
megacli ldsetprop WB RA DisDskCache NoCachedBadBBU lall aall # set WriteBack, Adaptive ReadAhead, disable Disk Cache, Disable Cache when bad BBU
# Misc
megacli adpfwflash -f filename aN # flash adapter firmware from image
megacli phyerrorcounters aN # get error counters for physical media
# EventLog
MegaCli -AdpEventLog -GetEventLogInfo -aN|-a0,1,2|-aALL
MegaCli -AdpEventLog -GetEvents {-info -warning -critical -fatal} {-f <fileName>} -aN|-a0,1,2|-aALL
MegaCli -AdpEventLog -GetSinceShutdown {-info -warning -critical -fatal} {-f <fileName>} -aN|-a0,1,2|-aALL
MegaCli -AdpEventLog -GetSinceReboot {-info -warning -critical -fatal} {-f <fileName>} -aN|-a0,1,2|-aALL
MegaCli -AdpEventLog -IncludeDeleted {-info -warning -critical -fatal} {-f <fileName>} -aN|-a0,1,2|-aALL
MegaCli -AdpEventLog -GetLatest n {-info -warning -critical -fatal} {-f <fileName>} -aN|-a0,1,2|-aALL
MegaCli -AdpEventLog -GetCCIncon -f <fileName> -LX|-L0,2,5...|-LALL -aN|-a0,1,2|-aALL
MegaCli -AdpEventLog -Clear -aN|-a0,1,2|-aALL
# Diagnose
megacli fwtermlog dsply aall > /tmp/out.log
| MegaCli is a RAID utility For LSI MegaRAID Controllers
LD - LogicalDrive
PD - PhysicalDrive
BBU - Backup Battery Unit
# Get Info
megacli adpcount # get controllers count
megacli adpallinfo aall # get information about all adapters
megacli adpbbucmd aall # get BBU information
megacli ldinfo lall aall # get LogicalDrives information from all adapters
magacli pdlist aall # get PhysicalDrives information from all adapters
megacli pdinfo physdrv [32:2] a0 # get info about specified drive
megacli pdrbld showprog physdrv [32:2] a0 # get info about rebuild progress
megacli pdlocate start|stop physdrv [32:2] a0 # start/stop flashing on specified drive
# Get/Set Logical Drives Properties
megacli ldgetprop cache lall aall # get LogicalDrives cache information
megacli ldgetprop dskcache lall aall # get PhysicalDrive cache status
MegaCli ldinfo lall aall |grep -E '(Virtual Drive|RAID Level|Cache Policy|Access Policy)' # get LD cache and PD cache information
megacli ldsetprop WB RA DisDskCache NoCachedBadBBU lall aall # set WriteBack, Adaptive ReadAhead, disable Disk Cache, Disable Cache when bad BBU
# Misc
megacli adpfwflash -f filename aN # flash adapter firmware from image
megacli phyerrorcounters aN # get error counters for physical media
# EventLog
MegaCli -AdpEventLog -GetEventLogInfo -aN|-a0,1,2|-aALL
MegaCli -AdpEventLog -GetEvents {-info -warning -critical -fatal} {-f <fileName>} -aN|-a0,1,2|-aALL
MegaCli -AdpEventLog -GetSinceShutdown {-info -warning -critical -fatal} {-f <fileName>} -aN|-a0,1,2|-aALL
MegaCli -AdpEventLog -GetSinceReboot {-info -warning -critical -fatal} {-f <fileName>} -aN|-a0,1,2|-aALL
MegaCli -AdpEventLog -IncludeDeleted {-info -warning -critical -fatal} {-f <fileName>} -aN|-a0,1,2|-aALL
MegaCli -AdpEventLog -GetLatest n {-info -warning -critical -fatal} {-f <fileName>} -aN|-a0,1,2|-aALL
MegaCli -AdpEventLog -GetCCIncon -f <fileName> -LX|-L0,2,5...|-LALL -aN|-a0,1,2|-aALL
MegaCli -AdpEventLog -Clear -aN|-a0,1,2|-aALL
# Disgnose
megacli fwtermlogdsply aall > /tmp/out.log
| mit | C# |
a0ddbfb0b064f3597b5baf06f6378940c27618cc | Make sure the SafeChildProcessHandle is never GC'd by accident | red-gate/RedGate.AppHost | RedGate.AppHost.Client/SafeChildProcessHandle.cs | RedGate.AppHost.Client/SafeChildProcessHandle.cs | using System;
using System.Windows.Threading;
using RedGate.AppHost.Interfaces;
using RedGate.AppHost.Remoting.WPF;
namespace RedGate.AppHost.Client
{
internal class SafeChildProcessHandle : MarshalByRefObject, ISafeChildProcessHandle
{
private readonly Dispatcher m_UiThreadDispatcher;
private readonly IOutOfProcessEntryPoint m_EntryPoint;
public SafeChildProcessHandle(Dispatcher uiThreadDispatcher, IOutOfProcessEntryPoint entryPoint)
{
if (uiThreadDispatcher == null)
throw new ArgumentNullException("uiThreadDispatcher");
if (entryPoint == null)
throw new ArgumentNullException("entryPoint");
m_UiThreadDispatcher = uiThreadDispatcher;
m_EntryPoint = entryPoint;
}
public IRemoteElement CreateElement(IAppHostServices services)
{
Func<IRemoteElement> createRemoteElement = () => m_EntryPoint.CreateElement(services).ToRemotedElement();
return (IRemoteElement)m_UiThreadDispatcher.Invoke(createRemoteElement);
}
public override object InitializeLifetimeService()
{
return null;
}
}
} | using System;
using System.Windows;
using System.Windows.Threading;
using RedGate.AppHost.Interfaces;
using RedGate.AppHost.Remoting.WPF;
namespace RedGate.AppHost.Client
{
internal class SafeChildProcessHandle : MarshalByRefObject, ISafeChildProcessHandle
{
private readonly Dispatcher m_UiThreadDispatcher;
private readonly IOutOfProcessEntryPoint m_EntryPoint;
public SafeChildProcessHandle(Dispatcher uiThreadDispatcher, IOutOfProcessEntryPoint entryPoint)
{
if (uiThreadDispatcher == null)
throw new ArgumentNullException("uiThreadDispatcher");
if (entryPoint == null)
throw new ArgumentNullException("entryPoint");
m_UiThreadDispatcher = uiThreadDispatcher;
m_EntryPoint = entryPoint;
}
public IRemoteElement CreateElement(IAppHostServices services)
{
Func<IRemoteElement> createRemoteElement = () => m_EntryPoint.CreateElement(services).ToRemotedElement();
return (IRemoteElement)m_UiThreadDispatcher.Invoke(createRemoteElement);
}
}
} | apache-2.0 | C# |
db9f9aaa13b4054755b69a607a0f398d9d268cd1 | Bump version. | JohanLarsson/Gu.Wpf.NumericInput | Gu.Wpf.NumericInput/Properties/AssemblyInfo.cs | Gu.Wpf.NumericInput/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Markup;
[assembly: AssemblyTitle("Gu.Wpf.NumericInput")]
[assembly: AssemblyDescription("WPF textboxes for numeric input")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Johan Larsson")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
[assembly: AssemblyVersion("0.5.1.5")]
[assembly: AssemblyFileVersion("0.5.1.5")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: Guid("2026010E-5005-413E-BA3F-18CF88F28B0F")]
[assembly: InternalsVisibleTo("Gu.Wpf.NumericInput.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001004962EFBEDF32E591E12D98026DE0EC2762B77C24E0FB41E3A262213A7A0DEBEADDECDB31D33CBA1D5F09F083EDD6912469B1C256E85DBE2E571483C034F156600D0481C7385778CA380D86CEEDE8EFC5945C2499DE1853A5E7DD7FF0C88D35E07EB613921391EC7B5F8701935E13E74F5D886D6FE477B041937EC949A8FF83D7", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("Gu.Wpf.NumericInput.UITests, PublicKey=00240000048000009400000006020000002400005253413100040000010001004962EFBEDF32E591E12D98026DE0EC2762B77C24E0FB41E3A262213A7A0DEBEADDECDB31D33CBA1D5F09F083EDD6912469B1C256E85DBE2E571483C034F156600D0481C7385778CA380D86CEEDE8EFC5945C2499DE1853A5E7DD7FF0C88D35E07EB613921391EC7B5F8701935E13E74F5D886D6FE477B041937EC949A8FF83D7", AllInternalsVisible = true)]
[assembly: XmlnsDefinition("http://gu.se/NumericInput", "Gu.Wpf.NumericInput")]
[assembly: XmlnsPrefix("http://gu.se/NumericInput", "numeric")]
[assembly: XmlnsDefinition("http://gu.se/Select", "Gu.Wpf.NumericInput.Select")]
[assembly: XmlnsPrefix("http://gu.se/Select", "select")]
[assembly: XmlnsDefinition("http://gu.se/Touch", "Gu.Wpf.NumericInput.Touch")]
[assembly: XmlnsPrefix("http://gu.se/Touch", "touch")] | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Markup;
[assembly: AssemblyTitle("Gu.Wpf.NumericInput")]
[assembly: AssemblyDescription("WPF textboxes for numeric input")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Johan Larsson")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
[assembly: AssemblyVersion("0.5.1.4")]
[assembly: AssemblyFileVersion("0.5.1.4")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: Guid("2026010E-5005-413E-BA3F-18CF88F28B0F")]
[assembly: InternalsVisibleTo("Gu.Wpf.NumericInput.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001004962EFBEDF32E591E12D98026DE0EC2762B77C24E0FB41E3A262213A7A0DEBEADDECDB31D33CBA1D5F09F083EDD6912469B1C256E85DBE2E571483C034F156600D0481C7385778CA380D86CEEDE8EFC5945C2499DE1853A5E7DD7FF0C88D35E07EB613921391EC7B5F8701935E13E74F5D886D6FE477B041937EC949A8FF83D7", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("Gu.Wpf.NumericInput.UITests, PublicKey=00240000048000009400000006020000002400005253413100040000010001004962EFBEDF32E591E12D98026DE0EC2762B77C24E0FB41E3A262213A7A0DEBEADDECDB31D33CBA1D5F09F083EDD6912469B1C256E85DBE2E571483C034F156600D0481C7385778CA380D86CEEDE8EFC5945C2499DE1853A5E7DD7FF0C88D35E07EB613921391EC7B5F8701935E13E74F5D886D6FE477B041937EC949A8FF83D7", AllInternalsVisible = true)]
[assembly: XmlnsDefinition("http://gu.se/NumericInput", "Gu.Wpf.NumericInput")]
[assembly: XmlnsPrefix("http://gu.se/NumericInput", "numeric")]
[assembly: XmlnsDefinition("http://gu.se/Select", "Gu.Wpf.NumericInput.Select")]
[assembly: XmlnsPrefix("http://gu.se/Select", "select")]
[assembly: XmlnsDefinition("http://gu.se/Touch", "Gu.Wpf.NumericInput.Touch")]
[assembly: XmlnsPrefix("http://gu.se/Touch", "touch")] | mit | C# |
06ffc916f97dab59ba0aa6c322e805e9b1b0dd93 | Remove unused code and updated directory location. | emiranda04/aes | Utility.cs | Utility.cs | using System;
using System.IO;
namespace Cipher {
class Utility {
public static string directory = "/Users/emiranda/Documents/code/c#/cipher_files/";
/// <summary>
/// Allows user to choose to display the password on the screen as is being typed.
/// </summary>
/// <param name="displayPassword">
/// Indicates whether or not password displays on the screen.
/// </param>
/// <returns>
/// A password string.
/// </returns>
public static string GetPassword(string displayPassword) {
string password = "";
if (displayPassword == "y" || displayPassword == "") {
password = Console.ReadLine();
}
if (displayPassword == "n") {
while (true) {
var pressedKey = System.Console.ReadKey(true);
// Get all typed keys until 'Enter' is pressed.
if (pressedKey.Key == ConsoleKey.Enter) {
Console.WriteLine("");
break;
}
password += pressedKey.KeyChar;
}
}
return password;
}
public static void SaveFileToDisk(string fileName, byte[] fileContents) {
File.WriteAllBytes(fileName, fileContents);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Cipher {
class Utility {
public static string directory = @"c:\code\cypher_files";
/// <summary>
/// Allows user to choose to display the password on the screen as is being typed.
/// </summary>
/// <param name="displayPassword">
/// Indicates whether or not password displays on the screen.
/// </param>
/// <returns>
/// A password string.
/// </returns>
public static string GetPassword(string displayPassword) {
string password = "";
if (displayPassword == "y" || displayPassword == "") {
password = Console.ReadLine();
}
if (displayPassword == "n") {
while (true) {
var pressedKey = System.Console.ReadKey(true);
// Get all typed keys until 'Enter' is pressed.
if (pressedKey.Key == ConsoleKey.Enter) {
Console.WriteLine("");
break;
}
password += pressedKey.KeyChar;
}
}
return password;
}
public static void SaveFileToDisk(string fileName, byte[] fileContents) {
File.WriteAllBytes(fileName, fileContents);
}
}
}
| mit | C# |
fa7ab1cfe16fc50fef71185153ff005ecf59441d | Downgrade version for @Cyberboss | tgstation/tgstation-server,tgstation/tgstation-server-tools,Cyberboss/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server | Version.cs | Version.cs | using System.Reflection;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
//It's impossible to make these a define, don't say I didn't warn you
[assembly: AssemblyVersion("3.0.90.2")]
[assembly: AssemblyFileVersion("3.0.90.2")]
[assembly: AssemblyInformationalVersion("3.0.90.2")]
| 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.*")]
//It's impossible to make these a define, don't say I didn't warn you
[assembly: AssemblyVersion("3.0.90.4")]
[assembly: AssemblyFileVersion("3.0.90.4")]
[assembly: AssemblyInformationalVersion("3.0.90.4")]
| agpl-3.0 | C# |
8a3fa53c2661662272a62699eed7d7a1f04407ea | Change mod description and settings labels | peppy/osu-new,smoogipoo/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu,ppy/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu | osu.Game/Rulesets/Mods/ModRandomOsu.cs | osu.Game/Rulesets/Mods/ModRandomOsu.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osu.Framework.Graphics.Sprites;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Graphics;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModRandomOsu : Mod, IApplicableToBeatmap
{
public override string Name => "Random";
public override string Acronym => "RD";
public override IconUsage? Icon => OsuIcon.Dice;
public override ModType Type => ModType.Fun;
public override string Description => "Practice your reaction time!";
public override double ScoreMultiplier => 1;
public override bool Ranked => false;
[SettingSource("Circles", "Hit circles appear at random positions")]
public Bindable<bool> RandomiseCirclePositions { get; } = new BindableBool
{
Default = true,
Value = true,
};
[SettingSource("Sliders", "Sliders appear at random positions")]
public Bindable<bool> RandomiseSliderPositions { get; } = new BindableBool
{
Default = true,
Value = true,
};
[SettingSource("Spinners", "Spinners appear at random positions")]
public Bindable<bool> RandomiseSpinnerPositions { get; } = new BindableBool
{
Default = true,
Value = true,
};
public void ApplyToBeatmap(IBeatmap beatmap) => RandomiseHitObjectPositions(beatmap);
protected abstract void RandomiseHitObjectPositions(IBeatmap beatmap);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osu.Framework.Graphics.Sprites;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Graphics;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModRandomOsu : Mod, IApplicableToBeatmap
{
public override string Name => "Random";
public override string Acronym => "RD";
public override IconUsage? Icon => OsuIcon.Dice;
public override ModType Type => ModType.Fun;
public override string Description => "Hit objects appear at random positions";
public override double ScoreMultiplier => 1;
public override bool Ranked => false;
[SettingSource("Randomise circle positions", "Hit circles appear at random positions")]
public Bindable<bool> RandomiseCirclePositions { get; } = new BindableBool
{
Default = true,
Value = true,
};
[SettingSource("Randomise slider positions", "Sliders appear at random positions")]
public Bindable<bool> RandomiseSliderPositions { get; } = new BindableBool
{
Default = true,
Value = true,
};
[SettingSource("Randomise spinner positions", "Spinners appear at random positions")]
public Bindable<bool> RandomiseSpinnerPositions { get; } = new BindableBool
{
Default = true,
Value = true,
};
public void ApplyToBeatmap(IBeatmap beatmap) => RandomiseHitObjectPositions(beatmap);
protected abstract void RandomiseHitObjectPositions(IBeatmap beatmap);
}
}
| mit | C# |
a36c80868247ff5a7fe1c180378e34e95732a905 | Use Fit FillFode | NeoAdonis/osu,2yangk23/osu,ZLima12/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,smoogipooo/osu,ppy/osu,ZLima12/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,peppy/osu,peppy/osu-new,johnneijzen/osu,peppy/osu,johnneijzen/osu,ppy/osu,EVAST9919/osu,EVAST9919/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,2yangk23/osu | osu.Game/Screens/Play/DimmableVideo.cs | osu.Game/Screens/Play/DimmableVideo.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Video;
using osu.Game.Graphics.Containers;
namespace osu.Game.Screens.Play
{
public class DimmableVideo : UserDimContainer
{
private readonly VideoSprite video;
private DrawableVideo drawableVideo;
public DimmableVideo(VideoSprite video)
{
this.video = video;
}
[BackgroundDependencyLoader]
private void load()
{
initializeVideo(false);
}
protected override void LoadComplete()
{
ShowVideo.BindValueChanged(_ => initializeVideo(true), true);
base.LoadComplete();
}
protected override bool ShowDimContent => ShowVideo.Value && DimLevel < 1;
private void initializeVideo(bool async)
{
if (video == null)
return;
if (drawableVideo != null)
return;
if (!ShowVideo.Value)
return;
drawableVideo = new DrawableVideo(video);
if (async)
LoadComponentAsync(drawableVideo, Add);
else
Add(drawableVideo);
}
private class DrawableVideo : Container
{
public DrawableVideo(VideoSprite video)
{
RelativeSizeAxes = Axes.Both;
Masking = true;
video.RelativeSizeAxes = Axes.Both;
video.FillMode = FillMode.Fit;
video.Anchor = Anchor.Centre;
video.Origin = Anchor.Centre;
AddInternal(video);
}
[BackgroundDependencyLoader]
private void load(GameplayClock clock)
{
if (clock != null)
Clock = clock;
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Video;
using osu.Game.Graphics.Containers;
namespace osu.Game.Screens.Play
{
public class DimmableVideo : UserDimContainer
{
private readonly VideoSprite video;
private DrawableVideo drawableVideo;
public DimmableVideo(VideoSprite video)
{
this.video = video;
}
[BackgroundDependencyLoader]
private void load()
{
initializeVideo(false);
}
protected override void LoadComplete()
{
ShowVideo.BindValueChanged(_ => initializeVideo(true), true);
base.LoadComplete();
}
protected override bool ShowDimContent => ShowVideo.Value && DimLevel < 1;
private void initializeVideo(bool async)
{
if (video == null)
return;
if (drawableVideo != null)
return;
if (!ShowVideo.Value)
return;
drawableVideo = new DrawableVideo(video);
if (async)
LoadComponentAsync(drawableVideo, Add);
else
Add(drawableVideo);
}
private class DrawableVideo : Container
{
public DrawableVideo(VideoSprite video)
{
RelativeSizeAxes = Axes.Both;
Masking = true;
video.RelativeSizeAxes = Axes.Both;
video.FillMode = FillMode.Fill;
video.Anchor = Anchor.Centre;
video.Origin = Anchor.Centre;
AddInternal(video);
}
[BackgroundDependencyLoader]
private void load(GameplayClock clock)
{
if (clock != null)
Clock = clock;
}
}
}
}
| mit | C# |
a290f7eeec4ecefb46dc4288eb98f94c909f492b | Revert left-over type change in SkinConfiguration | peppy/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,ppy/osu,smoogipooo/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu-new,UselessToucan/osu,ppy/osu | osu.Game/Skinning/SkinConfiguration.cs | osu.Game/Skinning/SkinConfiguration.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 osu.Game.Beatmaps.Formats;
using osuTK.Graphics;
namespace osu.Game.Skinning
{
/// <summary>
/// An empty skin configuration.
/// </summary>
public class SkinConfiguration : IHasComboColours, IHasCustomColours
{
public readonly SkinInfo SkinInfo = new SkinInfo();
/// <summary>
/// Whether to allow <see cref="DefaultComboColours"/> as a fallback list for when no combo colours are provided.
/// </summary>
internal bool AllowDefaultComboColoursFallback = true;
public static List<Color4> DefaultComboColours { get; } = new List<Color4>
{
new Color4(255, 192, 0, 255),
new Color4(0, 202, 0, 255),
new Color4(18, 124, 255, 255),
new Color4(242, 24, 57, 255),
};
private readonly List<Color4> comboColours = new List<Color4>();
public IReadOnlyList<Color4> ComboColours
{
get
{
if (comboColours.Count > 0)
return comboColours;
if (AllowDefaultComboColoursFallback)
return DefaultComboColours;
return null;
}
}
public void AddComboColours(params Color4[] colours) => comboColours.AddRange(colours);
public Dictionary<string, Color4> CustomColours { get; set; } = new Dictionary<string, Color4>();
public readonly Dictionary<string, string> ConfigDictionary = new Dictionary<string, string>();
}
}
| // 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 osu.Game.Beatmaps.Formats;
using osuTK.Graphics;
namespace osu.Game.Skinning
{
/// <summary>
/// An empty skin configuration.
/// </summary>
public class SkinConfiguration : IHasComboColours, IHasCustomColours
{
public readonly SkinInfo SkinInfo = new SkinInfo();
/// <summary>
/// Whether to allow <see cref="DefaultComboColours"/> as a fallback list for when no combo colours are provided.
/// </summary>
internal bool AllowDefaultComboColoursFallback = true;
public static List<Color4> DefaultComboColours { get; } = new List<Color4>
{
new Color4(255, 192, 0, 255),
new Color4(0, 202, 0, 255),
new Color4(18, 124, 255, 255),
new Color4(242, 24, 57, 255),
};
private readonly List<Color4> comboColours = new List<Color4>();
public IReadOnlyList<Color4> ComboColours
{
get
{
if (comboColours.Count > 0)
return comboColours;
if (AllowDefaultComboColoursFallback)
return DefaultComboColours;
return null;
}
}
public void AddComboColours(params Color4[] colours) => comboColours.AddRange(colours);
public Dictionary<string, Color4> CustomColours { get; set; } = new Dictionary<string, Color4>();
public readonly SortedDictionary<string, string> ConfigDictionary = new SortedDictionary<string, string>();
}
}
| mit | C# |
84bd467cd8e906a67d4a6961ada8d59e2fac3022 | Validate nodes in ProjectCommandBase. | TyOverby/roslyn,gafter/roslyn,jmarolf/roslyn,abock/roslyn,kelltrick/roslyn,genlu/roslyn,stephentoub/roslyn,AlekseyTs/roslyn,DustinCampbell/roslyn,KiloBravoLima/roslyn,physhi/roslyn,bartdesmet/roslyn,bkoelman/roslyn,jamesqo/roslyn,physhi/roslyn,diryboy/roslyn,dpoeschl/roslyn,KevinH-MS/roslyn,amcasey/roslyn,physhi/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,Hosch250/roslyn,AnthonyDGreen/roslyn,OmarTawfik/roslyn,drognanar/roslyn,eriawan/roslyn,akrisiun/roslyn,mattwar/roslyn,sharwell/roslyn,budcribar/roslyn,Hosch250/roslyn,khyperia/roslyn,MattWindsor91/roslyn,swaroop-sridhar/roslyn,stephentoub/roslyn,Shiney/roslyn,nguerrera/roslyn,xasx/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,gafter/roslyn,tannergooding/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,CaptainHayashi/roslyn,CyrusNajmabadi/roslyn,khyperia/roslyn,reaction1989/roslyn,tmeschter/roslyn,agocke/roslyn,budcribar/roslyn,balajikris/roslyn,mgoertz-msft/roslyn,bbarry/roslyn,aelij/roslyn,mattscheffer/roslyn,OmarTawfik/roslyn,jaredpar/roslyn,jaredpar/roslyn,MattWindsor91/roslyn,mavasani/roslyn,KiloBravoLima/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,KevinH-MS/roslyn,MatthieuMEZIL/roslyn,michalhosala/roslyn,wvdd007/roslyn,ericfe-ms/roslyn,swaroop-sridhar/roslyn,AArnott/roslyn,jmarolf/roslyn,jeffanders/roslyn,leppie/roslyn,MichalStrehovsky/roslyn,ljw1004/roslyn,bartdesmet/roslyn,leppie/roslyn,xoofx/roslyn,sharwell/roslyn,KevinRansom/roslyn,nguerrera/roslyn,Hosch250/roslyn,mattwar/roslyn,jasonmalinowski/roslyn,akrisiun/roslyn,ericfe-ms/roslyn,lorcanmooney/roslyn,ErikSchierboom/roslyn,mmitche/roslyn,amcasey/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,bkoelman/roslyn,srivatsn/roslyn,mmitche/roslyn,davkean/roslyn,VSadov/roslyn,ericfe-ms/roslyn,zooba/roslyn,mgoertz-msft/roslyn,shyamnamboodiripad/roslyn,jamesqo/roslyn,MatthieuMEZIL/roslyn,mattscheffer/roslyn,kelltrick/roslyn,paulvanbrenk/roslyn,mattscheffer/roslyn,jeffanders/roslyn,srivatsn/roslyn,wvdd007/roslyn,balajikris/roslyn,jmarolf/roslyn,jkotas/roslyn,kelltrick/roslyn,jamesqo/roslyn,MatthieuMEZIL/roslyn,mattwar/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,yeaicc/roslyn,cston/roslyn,reaction1989/roslyn,srivatsn/roslyn,sharwell/roslyn,natidea/roslyn,ljw1004/roslyn,KevinRansom/roslyn,MichalStrehovsky/roslyn,Pvlerick/roslyn,Shiney/roslyn,jhendrixMSFT/roslyn,mmitche/roslyn,nguerrera/roslyn,AArnott/roslyn,KevinH-MS/roslyn,cston/roslyn,tannergooding/roslyn,dotnet/roslyn,tvand7093/roslyn,jkotas/roslyn,KirillOsenkov/roslyn,leppie/roslyn,ljw1004/roslyn,heejaechang/roslyn,zooba/roslyn,tmat/roslyn,swaroop-sridhar/roslyn,akrisiun/roslyn,MichalStrehovsky/roslyn,orthoxerox/roslyn,heejaechang/roslyn,Giftednewt/roslyn,cston/roslyn,michalhosala/roslyn,CyrusNajmabadi/roslyn,bbarry/roslyn,aelij/roslyn,xasx/roslyn,robinsedlaczek/roslyn,drognanar/roslyn,genlu/roslyn,robinsedlaczek/roslyn,khyperia/roslyn,tvand7093/roslyn,MattWindsor91/roslyn,genlu/roslyn,AmadeusW/roslyn,balajikris/roslyn,AArnott/roslyn,orthoxerox/roslyn,tmeschter/roslyn,natidea/roslyn,agocke/roslyn,a-ctor/roslyn,dpoeschl/roslyn,a-ctor/roslyn,paulvanbrenk/roslyn,eriawan/roslyn,lorcanmooney/roslyn,heejaechang/roslyn,reaction1989/roslyn,brettfo/roslyn,MattWindsor91/roslyn,mgoertz-msft/roslyn,AnthonyDGreen/roslyn,yeaicc/roslyn,jcouv/roslyn,mavasani/roslyn,a-ctor/roslyn,orthoxerox/roslyn,VSadov/roslyn,abock/roslyn,Shiney/roslyn,dpoeschl/roslyn,panopticoncentral/roslyn,TyOverby/roslyn,TyOverby/roslyn,dotnet/roslyn,tannergooding/roslyn,wvdd007/roslyn,vslsnap/roslyn,ErikSchierboom/roslyn,xasx/roslyn,KirillOsenkov/roslyn,aelij/roslyn,jasonmalinowski/roslyn,michalhosala/roslyn,abock/roslyn,DustinCampbell/roslyn,pdelvo/roslyn,KevinRansom/roslyn,budcribar/roslyn,vslsnap/roslyn,ErikSchierboom/roslyn,xoofx/roslyn,Giftednewt/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,bbarry/roslyn,KirillOsenkov/roslyn,agocke/roslyn,jcouv/roslyn,Pvlerick/roslyn,jcouv/roslyn,weltkante/roslyn,KiloBravoLima/roslyn,mavasani/roslyn,brettfo/roslyn,Giftednewt/roslyn,diryboy/roslyn,brettfo/roslyn,panopticoncentral/roslyn,xoofx/roslyn,gafter/roslyn,stephentoub/roslyn,panopticoncentral/roslyn,tmeschter/roslyn,amcasey/roslyn,tmat/roslyn,robinsedlaczek/roslyn,VSadov/roslyn,CaptainHayashi/roslyn,Pvlerick/roslyn,zooba/roslyn,davkean/roslyn,lorcanmooney/roslyn,pdelvo/roslyn,AlekseyTs/roslyn,CaptainHayashi/roslyn,dotnet/roslyn,paulvanbrenk/roslyn,bkoelman/roslyn,yeaicc/roslyn,weltkante/roslyn,davkean/roslyn,tmat/roslyn,weltkante/roslyn,diryboy/roslyn,jeffanders/roslyn,AlekseyTs/roslyn,jhendrixMSFT/roslyn,jhendrixMSFT/roslyn,drognanar/roslyn,jkotas/roslyn,DustinCampbell/roslyn,vslsnap/roslyn,AnthonyDGreen/roslyn,jaredpar/roslyn,natidea/roslyn,pdelvo/roslyn,tvand7093/roslyn,OmarTawfik/roslyn | src/VisualStudio/ProjectSystem/Microsoft.VisualStudio.ProjectSystem.Managed/VisualStudio/ProjectSystem/Designers/Input/ProjectCommandBase.cs | src/VisualStudio/ProjectSystem/Microsoft.VisualStudio.ProjectSystem.Managed/VisualStudio/ProjectSystem/Designers/Input/ProjectCommandBase.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.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.Threading;
using Microsoft.VisualStudio.ProjectSystem.Designers;
namespace Microsoft.VisualStudio.ProjectSystem.Designers.Input
{
/// <summary>
/// Provides the base <see langword="abstract"/> class for all commands that operate on <see cref="IProjectTree"/> nodes.
/// </summary>
internal abstract class ProjectCommandBase : IAsyncCommandGroupHandler
{
private readonly Lazy<long[]> _commandIds;
protected ProjectCommandBase()
{
_commandIds = new Lazy<long[]>(() => GetCommandIds(this));
}
public Task<CommandStatusResult> GetCommandStatusAsync(IImmutableSet<IProjectTree> nodes, long commandId, bool focused, string commandText, CommandStatus progressiveStatus)
{
Requires.NotNull(nodes, nameof(nodes));
foreach (long otherCommandId in _commandIds.Value)
{
if (otherCommandId == commandId)
return GetCommandStatusAsync(nodes, focused, commandText, progressiveStatus);
}
return GetCommandStatusResult.Unhandled;
}
public Task<bool> TryHandleCommandAsync(IImmutableSet<IProjectTree> nodes, long commandId, bool focused, long commandExecuteOptions, IntPtr variantArgIn, IntPtr variantArgOut)
{
Requires.NotNull(nodes, nameof(nodes));
foreach (long otherCommandId in _commandIds.Value)
{
if (otherCommandId == commandId)
return TryHandleCommandAsync(nodes, focused, commandExecuteOptions, variantArgIn, variantArgOut);
}
return TaskResult.False;
}
protected abstract Task<CommandStatusResult> GetCommandStatusAsync(IImmutableSet<IProjectTree> nodes, bool focused, string commandText, CommandStatus progressiveStatus);
protected abstract Task<bool> TryHandleCommandAsync(IImmutableSet<IProjectTree> nodes, bool focused, long commandExecuteOptions, IntPtr variantArgIn, IntPtr variantArgOut);
private static long[] GetCommandIds(ProjectCommandBase command)
{
ProjectCommandAttribute attribute = (ProjectCommandAttribute)Attribute.GetCustomAttribute(command.GetType(), typeof(ProjectCommandAttribute));
if (attribute == null)
return Array.Empty<long>();
return attribute.CommandIds;
}
}
}
| // 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.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.Threading;
using Microsoft.VisualStudio.ProjectSystem.Designers;
namespace Microsoft.VisualStudio.ProjectSystem.Designers.Input
{
/// <summary>
/// Provides the base <see langword="abstract"/> class for all commands that operate on <see cref="IProjectTree"/> nodes.
/// </summary>
internal abstract class ProjectCommandBase : IAsyncCommandGroupHandler
{
private readonly Lazy<long[]> _commandIds;
protected ProjectCommandBase()
{
_commandIds = new Lazy<long[]>(() => GetCommandIds(this));
}
public Task<CommandStatusResult> GetCommandStatusAsync(IImmutableSet<IProjectTree> nodes, long commandId, bool focused, string commandText, CommandStatus progressiveStatus)
{
foreach (long otherCommandId in _commandIds.Value)
{
if (otherCommandId == commandId)
return GetCommandStatusAsync(nodes, focused, commandText, progressiveStatus);
}
return GetCommandStatusResult.Unhandled;
}
public Task<bool> TryHandleCommandAsync(IImmutableSet<IProjectTree> nodes, long commandId, bool focused, long commandExecuteOptions, IntPtr variantArgIn, IntPtr variantArgOut)
{
foreach (long otherCommandId in _commandIds.Value)
{
if (otherCommandId == commandId)
return TryHandleCommandAsync(nodes, focused, commandExecuteOptions, variantArgIn, variantArgOut);
}
return TaskResult.False;
}
protected abstract Task<CommandStatusResult> GetCommandStatusAsync(IImmutableSet<IProjectTree> nodes, bool focused, string commandText, CommandStatus progressiveStatus);
protected abstract Task<bool> TryHandleCommandAsync(IImmutableSet<IProjectTree> nodes, bool focused, long commandExecuteOptions, IntPtr variantArgIn, IntPtr variantArgOut);
private static long[] GetCommandIds(ProjectCommandBase command)
{
ProjectCommandAttribute attribute = (ProjectCommandAttribute)Attribute.GetCustomAttribute(command.GetType(), typeof(ProjectCommandAttribute));
if (attribute == null)
return Array.Empty<long>();
return attribute.CommandIds;
}
}
}
| mit | C# |
8d17e61119804993a816aaaee150000c9b6aa021 | Add 0.9 and 0.95 handling to TCAPIVersion | RusticiSoftware/TinCan.NET,limey98/TinCan.NET,brianjmiller/TinCan.NET,nagyistoce/TinCan.NET | TinCan/TCAPIVersion.cs | TinCan/TCAPIVersion.cs | /*
Copyright 2014 Rustici Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
namespace TinCan
{
public sealed class TCAPIVersion
{
//public static readonly TCAPIVersion V102 = new TCAPIVersion("1.0.2");
public static readonly TCAPIVersion V101 = new TCAPIVersion("1.0.1");
public static readonly TCAPIVersion V100 = new TCAPIVersion("1.0.0");
public static readonly TCAPIVersion V095 = new TCAPIVersion("0.95");
public static readonly TCAPIVersion V090 = new TCAPIVersion("0.9");
public static TCAPIVersion latest()
{
return V101;
}
private static Dictionary<String, TCAPIVersion> known;
private static Dictionary<String, TCAPIVersion> supported;
public static Dictionary<String, TCAPIVersion> GetKnown()
{
if (known != null) {
return known;
}
known = new Dictionary<String, TCAPIVersion>();
//known.Add("1.0.2", V102);
known.Add("1.0.1", V101);
known.Add("1.0.0", V100);
known.Add("0.95", V095);
known.Add("0.9", V090);
return known;
}
public static Dictionary<String, TCAPIVersion> GetSupported()
{
if (supported != null) {
return supported;
}
supported = new Dictionary<String, TCAPIVersion>();
//supported.Add("1.0.2", V102);
supported.Add("1.0.1", V101);
supported.Add("1.0.0", V100);
return supported;
}
public static explicit operator TCAPIVersion(String vStr)
{
var s = GetKnown();
if (!s.ContainsKey(vStr))
{
throw new ArgumentException("Unrecognized version: " + vStr);
}
return s[vStr];
}
private String text;
private TCAPIVersion(String value)
{
text = value;
}
public override String ToString()
{
return text;
}
}
}
| /*
Copyright 2014 Rustici Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
namespace TinCan
{
public sealed class TCAPIVersion
{
//public static readonly TCAPIVersion V102 = new TCAPIVersion("1.0.2");
public static readonly TCAPIVersion V101 = new TCAPIVersion("1.0.1");
public static readonly TCAPIVersion V100 = new TCAPIVersion("1.0.0");
public static TCAPIVersion latest()
{
return V101;
}
private static Dictionary<String, TCAPIVersion> supported;
public static Dictionary<String, TCAPIVersion> GetSupported()
{
if (supported != null) {
return supported;
}
supported = new Dictionary<String, TCAPIVersion>();
//supported.Add("1.0.2", V102);
supported.Add("1.0.1", V101);
supported.Add("1.0.0", V100);
return supported;
}
public static explicit operator TCAPIVersion(String vStr)
{
var s = GetSupported();
if (!s.ContainsKey(vStr))
{
throw new ArgumentException("Unsupported version: " + vStr);
}
return s[vStr];
}
private String text;
private TCAPIVersion(String value)
{
text = value;
}
public override String ToString()
{
return text;
}
}
}
| apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.