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 |
|---|---|---|---|---|---|---|---|---|
81848d6c4cf02bd755542989d7ae94b93e71e707 | add Fulfillment entity | vinhch/BizwebSharp | src/BizwebSharp/Entities/Fulfillment.cs | src/BizwebSharp/Entities/Fulfillment.cs | using System.Collections.Generic;
using Newtonsoft.Json;
namespace BizwebSharp.Entities
{
public class Fulfillment : BaseEntityWithTimeline
{
[JsonProperty("variant_inventory_management")]
public string VariantInventoryManagement { get; set; }
/// <summary>
/// A historical record of each item in the fulfillment.
/// </summary>
[JsonProperty("line_items")]
public IEnumerable<LineItem> LineItems { get; set; }
/// <summary>
/// The unique numeric identifier for the order.
/// </summary>
[JsonProperty("order_id")]
public long OrderId { get; set; }
/// <summary>
/// A textfield with information about the receipt.
/// </summary>
[JsonProperty("receipt")]
public object Receipt { get; set; }
/// <summary>
/// The status of the fulfillment. Valid values are 'pending', 'open', 'success', 'cancelled',
/// 'error' and 'failure'.
/// </summary>
[JsonProperty("status")]
public string Status { get; set; }
/// <summary>
/// The name of the shipping company.
/// </summary>
[JsonProperty("tracking_company")]
public string TrackingCompany { get; set; }
/// <summary>
/// The shipping number, provided by the shipping company. If multiple tracking numbers
/// exist (<see cref="TrackingNumbers"/>), returns the first number.
/// </summary>
[JsonProperty("tracking_number")]
public string TrackingNumber { get; set; }
/// <summary>
/// A list of shipping numbers, provided by the shipping company. May be null.
/// </summary>
[JsonProperty("tracking_numbers")]
public IEnumerable<string> TrackingNumbers { get; set; }
/// <summary>
/// The tracking url, provided by the shipping company. May be null. If multiple tracking URLs
/// exist (<see cref="TrackingUrls"/>), returns the first URL.
/// </summary>
[JsonProperty("tracking_url")]
public string TrackingUrl { get; set; }
/// <summary>
/// An array of one or more tracking urls, provided by the shipping company. May be null.
/// </summary>
[JsonProperty("tracking_urls")]
public IEnumerable<string> TrackingUrls { get; set; }
}
} | mit | C# | |
8e7aa0ccfdc73aa71c44c0de753cc86aa6396e2b | Solve Salary in c# | deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground | solutions/uri/1008/1008.cs | solutions/uri/1008/1008.cs | using System;
class Solution {
static void Main() {
int a, b;
double c;
a = Convert.ToInt16(Console.ReadLine());
b = Convert.ToInt16(Console.ReadLine());
c = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("NUMBER = {0}", a);
Console.WriteLine("SALARY = U$ {0:F2}", c * b);
}
}
| mit | C# | |
7561cfd431771c14e64dd258542de1ad3ecbea91 | Select start page by default instead of root | VoidPointerAB/n2cms,nicklv/n2cms,nimore/n2cms,nimore/n2cms,n2cms/n2cms,bussemac/n2cms,nicklv/n2cms,bussemac/n2cms,bussemac/n2cms,DejanMilicic/n2cms,SntsDev/n2cms,VoidPointerAB/n2cms,SntsDev/n2cms,nimore/n2cms,bussemac/n2cms,nicklv/n2cms,EzyWebwerkstaden/n2cms,EzyWebwerkstaden/n2cms,SntsDev/n2cms,VoidPointerAB/n2cms,EzyWebwerkstaden/n2cms,DejanMilicic/n2cms,DejanMilicic/n2cms,nicklv/n2cms,nicklv/n2cms,EzyWebwerkstaden/n2cms,n2cms/n2cms,EzyWebwerkstaden/n2cms,VoidPointerAB/n2cms,DejanMilicic/n2cms,nimore/n2cms,SntsDev/n2cms,n2cms/n2cms,bussemac/n2cms,n2cms/n2cms | src/wwwroot/Edit/Default.aspx.cs | src/wwwroot/Edit/Default.aspx.cs | using System;
using N2.Web.UI.WebControls;
namespace N2.Edit
{
[ToolbarPlugin("", "tpPreview", "{url}", ToolbarArea.Preview, Targets.Preview, "~/Edit/Img/Ico/Png/eye.png", 0, ToolTip = "edit", GlobalResourceClassName = "Toolbar")]
[ControlPanelLink("cpAdminister", "~/edit/img/ico/png/application_side_tree.png", "~/edit/?selected={Selected.Path}", "Administer site", -50, ControlPanelState.Visible, Target = Targets.Top)]
[ControlPanelSeparator(0, ControlPanelState.Visible)]
public partial class Default : Web.EditPage
{
string selectedPath;
string selectedUrl;
public string SelectedPath
{
get { return selectedPath ?? "/"; }
}
public string SelectedUrl
{
get { return selectedUrl ?? "~/"; }
}
protected override void OnInit(EventArgs e)
{
try
{
selectedPath = SelectedItem.Path;
selectedUrl = Engine.EditManager.GetPreviewUrl(SelectedItem);
}
catch(Exception ex)
{
Trace.Write(ex.ToString());
Response.Redirect("install/begin/default.aspx");
}
base.OnInit(e);
}
}
} | using System;
using N2.Web.UI.WebControls;
namespace N2.Edit
{
[ToolbarPlugin("", "tpPreview", "{url}", ToolbarArea.Preview, Targets.Preview, "~/Edit/Img/Ico/Png/eye.png", 0, ToolTip = "edit", GlobalResourceClassName = "Toolbar")]
[ControlPanelLink("cpAdminister", "~/edit/img/ico/png/application_side_tree.png", "~/edit/?selected={Selected.Path}", "Administer site", -50, ControlPanelState.Visible, Target = Targets.Top)]
[ControlPanelSeparator(0, ControlPanelState.Visible)]
public partial class Default : Web.EditPage
{
protected string SelectedPath = "/";
protected string SelectedUrl = "~/";
protected override void OnInit(EventArgs e)
{
try
{
SelectedPath = SelectedItem.Path;
SelectedPath = Engine.EditManager.GetPreviewUrl(SelectedItem);
}
catch(Exception ex)
{
Trace.Write(ex.ToString());
Response.Redirect("install/begin/default.aspx");
}
base.OnInit(e);
}
}
} | lgpl-2.1 | C# |
e1b2f25af4ab6cfb09b4b1a4356be3504145c963 | Revert "Delete FileOrganizationService.cs" | Sankra/DIPSbot,Sankra/DIPSbot | src/Hjerpbakk.DIPSbot/Services/FileOrganizationService.cs | src/Hjerpbakk.DIPSbot/Services/FileOrganizationService.cs | using System.CodeDom;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Hjerpbakk.DIPSbot.Services
{
public class FileOrganizationService : IOrganizationService
{
public async Task<IEnumerable<string>> GetDevelopers()
{
using (var reader = File.OpenText("/Users/sankra/Desktop/developerss.txt"))
{
var fileContent = await reader.ReadToEndAsync();
var lines = fileContent.Split(';');
return from developer in lines
let mailPosition = developer.IndexOf('@')
select new[] { developer[mailPosition - 3], developer[mailPosition - 2], developer[mailPosition - 1] }
into usernameChars
select new string(usernameChars);
}
}
}
} | mit | C# | |
9f98320236fee20fcab3cb3ba5a669c0359a0ff6 | test logging exceptions | Cayan-LLC/syslog4net,jbeats/syslog4net,akramsaleh/syslog4net,merchantwarehouse/syslog4net | src/test/unit/syslog4net.Tests/Converters/StructuredDataConverterTests.cs | src/test/unit/syslog4net.Tests/Converters/StructuredDataConverterTests.cs | using System;
using System.IO;
using log4net.Core;
using log4net.Util;
using log4net.Repository;
using syslog4net.Converters;
using NUnit.Framework;
using NSubstitute;
namespace syslog4net.Tests.Converters
{
[TestFixture]
public class StructuredDataConverterTests
{
[Test]
public void ConvertTestNoException()
{
var level = Level.Debug;
var testId = "9001";
var resultString = "[MW@55555 MessageId=\"" + testId + "\" EventSeverity=\"" + level.DisplayName + "\"]";
var writer = new StreamWriter(new MemoryStream());
var converter = new StructuredDataConverter();
var props = new PropertiesDictionary();
props["MessageId"] = testId;
props["log4net:StructuredDataPrefix"] = "MW@55555";
// Additional tests using stack data is prevented as the converter class only pulls from LoggingEvent.GetProperties()
// The data behind this method is setup by log4net itself so testing stack usage would not really apply properly here
//ThreadContext.Stacks["foo"].Push("bar");
var evt = new LoggingEvent(new LoggingEventData() { Properties = props, Level = level });
converter.Format(writer, evt);
writer.Flush();
var result = TestUtilities.GetStringFromStream(writer.BaseStream);
Assert.AreEqual(resultString, result);
}
[Test]
public void ConvertTestWithExceptionString()
{
var level = Level.Debug;
var testId = "9001";
var exceptionMessage = "exception occurred";
var resultString = "[MW@55555 MessageId=\"" + testId + "\" EventSeverity=\"" + level.DisplayName + "\" ExceptionMessage=\"" + exceptionMessage + "\"]";
var writer = new StreamWriter(new MemoryStream());
var converter = new StructuredDataConverter();
var props = new PropertiesDictionary();
props["MessageId"] = testId;
props["log4net:StructuredDataPrefix"] = "MW@55555";
var evt = new LoggingEvent(new LoggingEventData() { Properties = props, Level = level, ExceptionString = exceptionMessage });
converter.Format(writer, evt);
writer.Flush();
var result = TestUtilities.GetStringFromStream(writer.BaseStream);
Assert.AreEqual(resultString, result);
}
[Test]
public void ConvertTestWithExceptionObject()
{
var level = Level.Debug;
var testId = "9001";
var resultString = "[MW@55555 MessageId=\"9001\" EventSeverity=\"DEBUG\" ExceptionType=\"System.ArgumentNullException\" ExceptionMessage=\"Value cannot be null.\"]";
var writer = new StreamWriter(new MemoryStream());
var converter = new StructuredDataConverter();
var exception = new ArgumentNullException();
ILoggerRepository logRepository = Substitute.For<ILoggerRepository>();
var evt = new LoggingEvent(typeof(StructuredDataConverterTests), logRepository, "test logger", level, "test message", exception);
evt.Properties["MessageId"] = testId;
evt.Properties["log4net:StructuredDataPrefix"] = "MW@55555";
converter.Format(writer, evt);
writer.Flush();
var result = TestUtilities.GetStringFromStream(writer.BaseStream);
Assert.AreEqual(resultString, result);
}
}
} | using System.IO;
using log4net.Core;
using log4net.Util;
using syslog4net.Converters;
using NUnit.Framework;
namespace syslog4net.Tests.Converters
{
[TestFixture]
public class StrcturedDataConverterTests
{
[Test]
public void ConvertTestNoException()
{
var level = Level.Debug;
var testId = "9001";
var resultString = "[MW@55555 MessageId=\"" + testId + "\" EventSeverity=\"" + level.DisplayName + "\"]";
var writer = new StreamWriter(new MemoryStream());
var converter = new StructuredDataConverter();
var props = new PropertiesDictionary();
props["MessageId"] = testId;
props["log4net:StructuredDataPrefix"] = "MW@55555";
// Additional tests using stack data is prevented as the converter class only pulls from LoggingEvent.GetProperties()
// The data behind this method is setup by log4net itself so testing stack usage would not really apply properly here
//ThreadContext.Stacks["foo"].Push("bar");
var evt = new LoggingEvent(new LoggingEventData() { Properties = props, Level = level });
converter.Format(writer, evt);
writer.Flush();
var result = TestUtilities.GetStringFromStream(writer.BaseStream);
Assert.AreEqual(resultString, result);
}
}
} | apache-2.0 | C# |
caffd7eedde8873f33f7424fc57df01d0a4a2b97 | Add C# 7.0 Pattern variable with is-operator example | devlights/try-csharp | TryCSharp.Samples/CSharp7/PatternVariableWithIsOperator.cs | TryCSharp.Samples/CSharp7/PatternVariableWithIsOperator.cs | using System.Diagnostics.CodeAnalysis;
using TryCSharp.Common;
namespace TryCSharp.Samples.CSharp7
{
[Sample]
public class PatternVariableWithIsOperator : IExecutable
{
[SuppressMessage("ReSharper", "ConditionIsAlwaysTrueOrFalse")]
public void Execute()
{
// C# 7.0 から Pattern Variables の概念が導入された
// is 演算子とともに変数を宣言することが可能になった
object x = "hello world";
// C# 7.0 以前
// ReSharper disable once MergeCastWithTypeCheck
if (x is string)
{
// ReSharper disable once TryCastAlwaysSucceeds
var cs6 = x as string;
Output.WriteLine($"C# 6.0 val:{cs6}, length:{cs6.Length}");
}
// C# 7.0
if (x is string cs7)
{
Output.WriteLine($"C# 7.0 val:{cs7}, length:{cs7.Length}");
}
}
}
} | mit | C# | |
679fb3633d6b4cd25109ac1e18a71a5e3e870bcd | active vars - iter alg | DeKoyre/b8 | LYtest/ActiveVars/ActiveVarsIterAlg.cs | LYtest/ActiveVars/ActiveVarsIterAlg.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LYtest.CFG;
using LYtest.IterAlg;
using LYtest.LinearRepr.Values;
namespace LYtest.ActiveVars
{
public sealed class ActiveVarsIterAlg : IterativeCommonAlg<HashSet<LabelValue>>
{
protected override HashSet<LabelValue> Top => new HashSet<LabelValue>();
private readonly DefUseBuilder DefUse;
public ActiveVarsIterAlg(CFGraph g) : base(g)
{
DefUse = new DefUseBuilder(g.Blocks);
ReverseRun();
}
protected override bool ContCond(HashSet<LabelValue> a, HashSet<LabelValue> b)
{
return !a.SetEquals(b);
}
protected override HashSet<LabelValue> TransferFunc(CFGNode node)
{
var res = DefUse.UseLabels(node.Value);
res.UnionWith(Out[node].Except(DefUse.DefLabels(node.Value)));
return res;
}
protected override HashSet<LabelValue> MeetOp(List<CFGNode> nodes)
{
return new HashSet<LabelValue>(nodes.SelectMany(n => In[n]));
}
}
}
| mit | C# | |
8bb776edc02b81f26a99c45e73970fd018522852 | add test | linq2db/linq2db,MaceWindu/linq2db,linq2db/linq2db,MaceWindu/linq2db,LinqToDB4iSeries/linq2db,LinqToDB4iSeries/linq2db,ronnyek/linq2db | Tests/Linq/UserTests/Issue1222Tests.cs | Tests/Linq/UserTests/Issue1222Tests.cs | using System;
using System.Linq;
using System.Linq.Expressions;
using NUnit.Framework;
namespace Tests.UserTests
{
using LinqToDB;
using LinqToDB.Mapping;
[TestFixture]
public class Issue1222Tests : TestBase
{
[Table("stLinks")]
public class StLink
{
[Column("inId"), PrimaryKey, Identity] public int InId { get; set; } // int
[Column("inIdParent"), NotNull] public int InIdParent { get; set; } // int
[Column("inIdChild"), NotNull] public int InIdChild { get; set; } // int
[Column("inIdTypeRel"), NotNull] public int InIdTypeRel { get; set; } // int
[Column("inMaxQuantity"), Nullable] public double? InMaxQuantity { get; set; } // float
[Column("inMinQuantity"), Nullable] public double? InMinQuantity { get; set; } // float
[Column("inIdMeasure"), Nullable] public int? InIdMeasure { get; set; } // int
[Column("inIdUnit"), Nullable] public int? InIdUnit { get; set; } // int
[Column(), Nullable] public int? State { get; set; } // int
[Column("dtModified"), NotNull] public DateTime DtModified { get; set; } // datetime
[Column("inIdOrgOwner"), Nullable] public int? InIdOrgOwner { get; set; } // int
[Column("dtSynchDate"), Nullable] public DateTime? DtSynchDate { get; set; } // datetime
[Column("stGUID"), NotNull] public string StGUID { get; set; } // varchar(255)
[Association(ThisKey = "InIdTypeRel", OtherKey = "InId", CanBeNull = false, Relationship = Relationship.ManyToOne, KeyName = "FK_stLinks_inIdTypeRel_rlTypesAndTypes")]
public RlTypesAndType RlTypesAndType { get; set; }
}
[Table("rlTypesAndTypes")]
public class RlTypesAndType
{
[Column("inId"), PrimaryKey, Identity] public int InId { get; set; } // int
[Column("inIdLinkType"), NotNull] public int InIdLinkType { get; set; } // int
}
[Table("stVersions")]
public class StVersion
{
[Column("inId"), PrimaryKey, Identity] public int InId { get; set; } // int
[Column("inIdMain"), NotNull] public int InIdMain { get; set; } // int
}
[Test, Combinatorial]
public void Test([DataSources] string context)
{
using (var db = GetDataContext(context))
{
using (db.CreateLocalTable<StLink>())
//using (db.CreateLocalTable<TaskStage>())
{
var parentId = 111;
var query = from u in Queryable.Concat(
from link in db.GetTable<StLink>()
where link.InIdParent == parentId
select new { VersionId = link.InIdChild, Link = link },
from link in db.GetTable<StLink>()
where link.InIdChild == parentId
select new { VersionId = link.InIdParent, Link = link })
join version in db.GetTable<StVersion>() on u.VersionId equals version.InId
select new
{
//LinkTypeId = u.Link.RlTypesAndType.InIdLinkType,
LinkId = u.Link.InId,
MainId = version.InIdMain
};
query.ToList();
}
}
}
}
}
| mit | C# | |
0d1719e4e421aad60334ca8ffd3157c81d5ce406 | Add NorthEurope to location enum for Data Factories | bgold09/azure-sdk-for-net,dasha91/azure-sdk-for-net,felixcho-msft/azure-sdk-for-net,jasper-schneider/azure-sdk-for-net,abhing/azure-sdk-for-net,felixcho-msft/azure-sdk-for-net,gubookgu/azure-sdk-for-net,shuagarw/azure-sdk-for-net,ailn/azure-sdk-for-net,ailn/azure-sdk-for-net,kagamsft/azure-sdk-for-net,nemanja88/azure-sdk-for-net,AuxMon/azure-sdk-for-net,pomortaz/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,MabOneSdk/azure-sdk-for-net,amarzavery/azure-sdk-for-net,kagamsft/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,oburlacu/azure-sdk-for-net,vladca/azure-sdk-for-net,amarzavery/azure-sdk-for-net,pattipaka/azure-sdk-for-net,jtlibing/azure-sdk-for-net,vladca/azure-sdk-for-net,pattipaka/azure-sdk-for-net,yitao-zhang/azure-sdk-for-net,amarzavery/azure-sdk-for-net,Matt-Westphal/azure-sdk-for-net,bgold09/azure-sdk-for-net,Nilambari/azure-sdk-for-net,kagamsft/azure-sdk-for-net,shuagarw/azure-sdk-for-net,hovsepm/azure-sdk-for-net,shuagarw/azure-sdk-for-net,jasper-schneider/azure-sdk-for-net,rohmano/azure-sdk-for-net,oburlacu/azure-sdk-for-net,naveedaz/azure-sdk-for-net,ailn/azure-sdk-for-net,DeepakRajendranMsft/azure-sdk-for-net,jtlibing/azure-sdk-for-net,yitao-zhang/azure-sdk-for-net,MabOneSdk/azure-sdk-for-net,abhing/azure-sdk-for-net,herveyw/azure-sdk-for-net,hovsepm/azure-sdk-for-net,yitao-zhang/azure-sdk-for-net,pomortaz/azure-sdk-for-net,naveedaz/azure-sdk-for-net,dasha91/azure-sdk-for-net,MabOneSdk/azure-sdk-for-net,pattipaka/azure-sdk-for-net,juvchan/azure-sdk-for-net,herveyw/azure-sdk-for-net,Matt-Westphal/azure-sdk-for-net,pomortaz/azure-sdk-for-net,oburlacu/azure-sdk-for-net,vladca/azure-sdk-for-net,Matt-Westphal/azure-sdk-for-net,nacaspi/azure-sdk-for-net,DeepakRajendranMsft/azure-sdk-for-net,AuxMon/azure-sdk-for-net,felixcho-msft/azure-sdk-for-net,juvchan/azure-sdk-for-net,rohmano/azure-sdk-for-net,jtlibing/azure-sdk-for-net,juvchan/azure-sdk-for-net,hovsepm/azure-sdk-for-net,gubookgu/azure-sdk-for-net,nacaspi/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,AuxMon/azure-sdk-for-net,nemanja88/azure-sdk-for-net,bgold09/azure-sdk-for-net,gubookgu/azure-sdk-for-net,jasper-schneider/azure-sdk-for-net,rohmano/azure-sdk-for-net,Nilambari/azure-sdk-for-net,abhing/azure-sdk-for-net,naveedaz/azure-sdk-for-net,nemanja88/azure-sdk-for-net,Nilambari/azure-sdk-for-net,herveyw/azure-sdk-for-net,DeepakRajendranMsft/azure-sdk-for-net,dasha91/azure-sdk-for-net | src/ResourceManagement/DataFactory/DataFactoryManagement/Generated/Models/Location.cs | src/ResourceManagement/DataFactory/DataFactoryManagement/Generated/Models/Location.cs | //
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
namespace Microsoft.Azure.Management.DataFactories.Models
{
/// <summary>
/// Data center location of the data factory.
/// </summary>
public static partial class Location
{
/// <summary>
/// West US
/// </summary>
public const string WestUS = "westus";
/// <summary>
/// North Europe
/// </summary>
public const string NorthEurope = "northeurope";
}
}
| //
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
namespace Microsoft.Azure.Management.DataFactories.Models
{
/// <summary>
/// Data center location of the data factory.
/// </summary>
public static partial class Location
{
/// <summary>
/// West US
/// </summary>
public const string WestUS = "westus";
}
}
| apache-2.0 | C# |
7bc40ab13d027632b9ea7b716ea4f4a1822e1958 | Add test asserting reconnect works. | 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-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14 | Content.IntegrationTests/Tests/ReconnectTest.cs | Content.IntegrationTests/Tests/ReconnectTest.cs | using System.Threading.Tasks;
using NUnit.Framework;
using Robust.Client.Console;
using Robust.Shared.Interfaces.Network;
using Robust.Shared.IoC;
namespace Content.IntegrationTests.Tests
{
[TestFixture]
public class ReconnectTest : ContentIntegrationTest
{
[Test]
public async Task Test()
{
var client = StartClient();
var server = StartServer();
await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync());
// Connect.
client.SetConnectTarget(server);
client.Post(() => IoCManager.Resolve<IClientNetManager>().ClientConnect(null, 0, null));
// Run some ticks for the handshake to complete and such.
for (var i = 0; i < 10; i++)
{
server.RunTicks(1);
await server.WaitIdleAsync();
client.RunTicks(1);
await client.WaitIdleAsync();
}
await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync());
client.Post(() => IoCManager.Resolve<IClientConsole>().ProcessCommand("disconnect"));
// Run some ticks for the disconnect to complete and such.
for (var i = 0; i < 5; i++)
{
server.RunTicks(1);
await server.WaitIdleAsync();
client.RunTicks(1);
await client.WaitIdleAsync();
}
await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync());
// Reconnect.
client.SetConnectTarget(server);
client.Post(() => IoCManager.Resolve<IClientNetManager>().ClientConnect(null, 0, null));
// Run some ticks for the handshake to complete and such.
for (var i = 0; i < 10; i++)
{
server.RunTicks(1);
await server.WaitIdleAsync();
client.RunTicks(1);
await client.WaitIdleAsync();
}
await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync());
}
}
}
| mit | C# | |
2b8992d07547812882357d38d30e94c14dade518 | Add Email primitive type | joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net | src/JoinRpg.PrimitiveTypes/Email.cs | src/JoinRpg.PrimitiveTypes/Email.cs | using JoinRpg.Helpers;
namespace JoinRpg.PrimitiveTypes;
public record Email : SingleValueType<string>
{
public Email(string value)
: base(CheckEmail(value))
{
}
public static string CheckEmail(string value)
{
if (!value.Contains('@'))
{
throw new ArgumentException("Incorrect email", nameof(value));
}
return value;
}
public string UserPart => Value.TakeWhile(ch => ch != '@').AsString();
}
| mit | C# | |
dc2524c7dcb3a4558a6284ef58850b7b99597f10 | Add 'tabs' and header with converter on main page | jonstodle/Postolego | Postolego/Converters/TextDependentOnSelectedIndexConverter.cs | Postolego/Converters/TextDependentOnSelectedIndexConverter.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace Postolego.Converters {
public class TextDependentOnSelectedIndexConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
var invalue = (int)value;
string text = "";
if(invalue < 1) {
text = "UNREAD";
} else if(invalue == 1) {
text = "ARCHIVE";
} else {
text = "FAVORITES";
}
return text;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
return null;
}
}
}
| mit | C# | |
9760aeb7cddd746ae5c85b4a5c79f29ce8470465 | Create Program.cs | sobercoder/msbuild-api-hacks | Program.cs | Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Framework;
class Program
{
static void Main(string[] args)
{
string projectFileName = @"C:\Users\Sandipan\Documents\Visual Studio 2010\Projects\Base64\Base64\Base64.csproj";
var projectCollection = new ProjectCollection();
projectCollection.DefaultToolsVersion = "4.0";
// Console.WriteLine("Available Toolsets: " + string.Join(", ", projectCollection.Toolsets.Select(item => item.ToolsVersion)));
// Console.WriteLine("Toolset currently being used: " + projectCollection.DefaultToolsVersion);
Project project = projectCollection.LoadProject(projectFileName);
// ConsoleLogger logger = new ConsoleLogger();
MsBuildLogger logger = new MsBuildLogger();
// logger.Verbosity = LoggerVerbosity.Detailed;
List<ILogger> loggers = new List<ILogger>();
loggers.Add(logger);
projectCollection.RegisterLoggers(loggers);
// there are a lot of properties here, these map to the MsBuild CLI properties
//Dictionary<string, string> globalProperties = new Dictionary<string, string>();
//globalProperties.Add("Configuration", "Debug");
//globalProperties.Add("Platform", "x86");
//globalProperties.Add("OutputPath", @"D:\Output");
//BuildParameters buildParams = new BuildParameters(projectCollection);
//MsBuildLogger logger = new MsBuildLogger();
//// logger.Verbosity = LoggerVerbosity.Detailed;
//List<ILogger> loggers = new List<ILogger>() { logger };
//buildParams.Loggers = loggers;
//BuildRequestData buildRequest = new BuildRequestData(projectFileName, globalProperties, "4.0", new string[] { "Build" }, null);
//BuildResult buildResult = BuildManager.DefaultBuildManager.Build(buildParams, buildRequest); // this is where the magic happens - in process MSBuild
//buildResult.ResultsByTarget.ToList().ForEach(item => new Action(delegate() {
// Console.WriteLine(item.Key + ", " + item.Value.ResultCode.ToString());
// Console.WriteLine(string.Join(", ", item.Value.Items.ToList().Select(target => target.ItemSpec)));
//}).Invoke());
try {
project.Build();
} finally {
projectCollection.UnregisterAllLoggers();
Console.WriteLine("TARGETS\n" + string.Join("\n", logger.Targets.Select(item => string.Format("[{0}, {1}]", item.Name, item.Succeeded ? "Succeeded" : "Failed"))));
Console.WriteLine("ERRORS\n" + string.Join("\n", logger.Errors));
Console.WriteLine("WARNINGS\n" + string.Join("\n", logger.Warnings));
}
Console.ReadKey(true);
}
}
| unlicense | C# | |
86042e176387aaf259d1ac4a378058af74f4c6cb | Implement HitObjectContainerEventQueue | peppy/osu,smoogipooo/osu,NeoAdonis/osu,ppy/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu-new | osu.Game/Screens/Edit/Compose/HitObjectContainerEventQueue.cs | osu.Game/Screens/Edit/Compose/HitObjectContainerEventQueue.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.UI;
namespace osu.Game.Screens.Edit.Compose
{
/// <summary>
/// A queue which processes events from the many <see cref="HitObjectContainer"/>s in a nested <see cref="Playfield"/> hierarchy.
/// </summary>
internal class HitObjectContainerEventQueue : Component
{
/// <summary>
/// Invoked when a <see cref="HitObject"/> becomes used by a <see cref="DrawableHitObject"/>.
/// </summary>
/// <remarks>
/// If the ruleset uses pooled objects, this represents the time when the <see cref="HitObject"/>s become alive.
/// </remarks>
public event Action<HitObject, DrawableHitObject> HitObjectUsageBegan;
/// <summary>
/// Invoked when a <see cref="HitObject"/> becomes unused by a <see cref="DrawableHitObject"/>.
/// </summary>
/// <remarks>
/// If the ruleset uses pooled objects, this represents the time when the <see cref="HitObject"/>s become dead.
/// </remarks>
public event Action<HitObject> HitObjectUsageFinished;
/// <summary>
/// Invoked when a <see cref="HitObject"/> has been transferred to another <see cref="DrawableHitObject"/>.
/// </summary>
public event Action<HitObject, DrawableHitObject> HitObjectUsageTransferred;
private readonly Playfield playfield;
/// <summary>
/// Creates a new <see cref="HitObjectContainerEventQueue"/>.
/// </summary>
/// <param name="playfield">The most top-level <see cref="Playfield"/>.</param>
public HitObjectContainerEventQueue(Playfield playfield)
{
this.playfield = playfield;
bindPlayfieldRecursive(playfield);
}
private void bindPlayfieldRecursive(Playfield p)
{
p.HitObjectContainer.HitObjectUsageBegan += onHitObjectUsageBegan;
p.HitObjectContainer.HitObjectUsageFinished += onHitObjectUsageFinished;
foreach (var nested in p.NestedPlayfields)
bindPlayfieldRecursive(nested);
}
private readonly Dictionary<HitObject, int> pendingUsagesBegan = new Dictionary<HitObject, int>();
private readonly Dictionary<HitObject, int> pendingUsagesFinished = new Dictionary<HitObject, int>();
private void onHitObjectUsageBegan(HitObject hitObject) => pendingUsagesBegan[hitObject] = pendingUsagesBegan.GetValueOrDefault(hitObject, 0) + 1;
private void onHitObjectUsageFinished(HitObject hitObject) => pendingUsagesFinished[hitObject] = pendingUsagesFinished.GetValueOrDefault(hitObject, 0) + 1;
protected override void Update()
{
base.Update();
foreach (var (hitObject, countBegan) in pendingUsagesBegan)
{
if (pendingUsagesFinished.TryGetValue(hitObject, out int countFinished))
{
Debug.Assert(countFinished > 0);
if (countBegan > countFinished)
{
// The hitobject is still in use, but transferred to a different HOC.
HitObjectUsageTransferred?.Invoke(hitObject, playfield.AllHitObjects.Single(d => d.HitObject == hitObject));
pendingUsagesFinished.Remove(hitObject);
}
}
else
{
// This is a new usage of the hitobject.
HitObjectUsageBegan?.Invoke(hitObject, playfield.AllHitObjects.Single(d => d.HitObject == hitObject));
}
}
// Go through any remaining pending finished usages.
foreach (var (hitObject, _) in pendingUsagesFinished)
HitObjectUsageFinished?.Invoke(hitObject);
pendingUsagesBegan.Clear();
pendingUsagesFinished.Clear();
}
}
}
| mit | C# | |
3a3e49d9e063394f971182dab0e7e21d99392351 | add inline-instances testbed | MattWindsor91/roslyn,CaptainHayashi/roslyn,CaptainHayashi/roslyn,MattWindsor91/roslyn,MattWindsor91/roslyn,CaptainHayashi/roslyn,MattWindsor91/roslyn | concepts/code/InlineInstances/Program.cs | concepts/code/InlineInstances/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InlineInstances
{
public concept CStringify<T>
{
string AsString(this T t);
}
// The ': CStringify<IntPair>' here tells Concept-C# that IntPair has
// the right set of members to generate a completely autofilled
// instance. Concept-C#, behind the scenes, generates an unnamed
// instance to bounce into those members.
public class IntPair : CStringify<IntPair>
{
private int _x;
private int _y;
public IntPair(int x, int y)
{
_x = x;
_y = y;
}
public string AsString() => $"{_x}, {_y}";
}
class Program
{
static void Main(string[] args)
{
// Concept witness inference can pick up the inline instance,
// as seen here.
Console.WriteLine(CStringify<IntPair>.AsString(new IntPair(27, 53)));
}
}
}
| apache-2.0 | C# | |
9e9e88f09d42486f15b66aad0a6b85e0cd8ff8f2 | use Stream.WriteByte() to overwrite signature. | morkt/GARbro,dsp2003/GARbro,morkt/GARbro,dsp2003/GARbro,dsp2003/GARbro | ArcFormats/AudioOGV.cs | ArcFormats/AudioOGV.cs | //! \file AudioOGV.cs
//! \date Sat Apr 18 14:18:47 2015
//! \brief ShiinaRio Ogg/Vorbis audio format.
//
// Copyright (C) 2015 by morkt
//
// 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.ComponentModel.Composition;
using System.IO;
namespace GameRes.Formats.ShiinaRio
{
[Export(typeof(AudioFormat))]
public class OgvAudio : OggAudio
{
public override string Tag { get { return "OGV"; } }
public override string Description { get { return "ShiinaRio audio format (Ogg/Vorbis)"; } }
public override uint Signature { get { return 0x0056474f; } } // 'OGV'
public override SoundInput TryOpen (Stream file)
{
var input = file as MemoryStream;
if (null == input || !input.CanWrite)
{
input = new MemoryStream();
file.CopyTo (input);
}
input.Position = 1;
input.WriteByte ((byte)'g');
input.WriteByte ((byte)'g');
input.WriteByte ((byte)'S');
input.Position = 0;
var ogg = new OggInput (input);
if (file != input)
file.Dispose();
return ogg;
}
}
}
| //! \file AudioOGV.cs
//! \date Sat Apr 18 14:18:47 2015
//! \brief ShiinaRio Ogg/Vorbis audio format.
//
// Copyright (C) 2015 by morkt
//
// 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.ComponentModel.Composition;
using System.IO;
namespace GameRes.Formats.ShiinaRio
{
[Export(typeof(AudioFormat))]
public class OgvAudio : OggAudio
{
public override string Tag { get { return "OGV"; } }
public override string Description { get { return "ShiinaRio audio format (Ogg/Vorbis)"; } }
public override uint Signature { get { return 0x0056474f; } } // 'OGV'
public override SoundInput TryOpen (Stream file)
{
var input = file as MemoryStream;
if (null == input || !input.CanWrite)
{
input = new MemoryStream();
file.CopyTo (input);
}
// FIXME: doesn't work for memory streams with non-zero origin
var buf = input.GetBuffer();
buf[1] = (byte)'g';
buf[2] = (byte)'g';
buf[3] = (byte)'S';
input.Position = 0;
var ogg = new OggInput (input);
if (file != input)
file.Dispose();
return ogg;
}
}
}
| mit | C# |
8f3bedd47153ef2b33e71c09a5a9deeda025011f | Create util.cs | QetriX/CS | libs/util/util.cs | libs/util/util.cs | namespace com.qetrix.libs {
/* Copyright (c) 2015 QetriX. Licensed under MIT License, see /LICENSE.txt file.
* QetriX Utils Class
*/
using System;
using System.Text;
using System.Runtime.InteropServices;
public static class Util
{
#region String functions
public static String urlEncode(String inString)
{
StringBuilder sb = new StringBuilder();
int limit = 32000;
int loops = inString.Length / limit;
// EscapeDataString is limited, for larger Strings we have to break it down into smaller increments
for (int i = 0; i <= loops; i++) {
if (i < loops) sb.Append(Uri.EscapeDataString(inString.Substring(limit * i, limit)));
else sb.Append(Uri.EscapeDataString(inString.Substring(limit * i)));
}
return sb.ToString().Replace(" ", "+");
}
public static String urlDecode(String text)
{
text = text.Replace("+", " ");
return System.Uri.UnescapeDataString(text);
}
public static String crKey(String text)
{
String stFormD = text.Normalize(NormalizationForm.FormD);
int len = stFormD.Length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
System.Globalization.UnicodeCategory uc = System.Globalization.CharUnicodeInfo.GetUnicodeCategory(stFormD[i]);
if (uc != System.Globalization.UnicodeCategory.NonSpacingMark) sb.Append(stFormD[i]);
}
String output = (sb.ToString().Normalize(NormalizationForm.FormC)).Trim().ToLower();
output = output.Replace(":", "-").Replace("=", "-").Replace("(", "-").Replace(")", "-").Replace("{", "-").Replace("}", "-").Replace("!", "-").Replace(";", "-").Replace(" ", "-").Replace("+", "-").Replace("&", "-").Replace("_", "-").Replace("/", "-").Replace("@", "-at-").Replace("–", "-").Replace(".", "-").Replace(",", "-").Replace("?", "-");
output = output.Replace("\\", "").Replace("\"", "").Replace("°", "").Replace("„", "").Replace("“", "").Replace("`", "").Replace("ʻ", "").Replace("*", "").Replace("¨", "").Replace("™", "").Replace("®", "").Replace("§", "");
output = output.Replace("---", "-").Replace("--", "-").Replace("--", "-");
if (output.StartsWith("-", StringComparison.InvariantCultureIgnoreCase)) output = output.Substring(1, output.Length - 1);
if (output.EndsWith("-", StringComparison.InvariantCultureIgnoreCase)) output = output.Substring(0, output.Length - 1);
return output;
}
#endregion
[DllImport("kernel32")]
static extern bool AllocConsole();
public static String log(String str)
{
Console.WriteLine(str);
return "";
}
}
/// <summary>
/// Java-like NULL integers without using "int?" (nullable int).
/// Usage: Integer i = 77;
/// </summary>
public class Integer
{
private int Value;
private Integer(int val)
{
this.Value = val;
}
public static implicit operator Integer(int value)
{
return new Integer(value);
}
public static implicit operator int(Integer i)
{
return i.Value;
}
}
}
| mit | C# | |
934de224d9b90650e41a707724d8457a23417017 | Add CalcTests | Carbon/Css | src/Carbon.Css.Tests/CalcTests.cs | src/Carbon.Css.Tests/CalcTests.cs | using Xunit;
namespace Carbon.Css.Tests
{
public class CalcTests
{
[Fact]
public void A()
{
var css = StyleSheet.Parse(@"div {
width: calc(100vw - 380px - var(--cover-block-padding) * 2)
}");
Assert.Equal("div { width: calc(100vw - 380px - var(--cover-block-padding) * 2); }", css.ToString());
}
[Fact]
public void B()
{
var css = StyleSheet.Parse(@"
$containerWidth: 50px;
div {
width: calc(100vw - 380px - $containerWidth * 2)
}");
Assert.Equal("div { width: calc(100vw - 380px - 50px * 2); }", css.ToString());
}
[Fact]
public void C()
{
var css = StyleSheet.Parse(@"
$varName: --containerWidth;
div { width: calc(380px - var($varName) * 2); }");
Assert.Equal("div { width: calc(380px - var(--containerWidth) * 2); }", css.ToString());
}
[Fact]
public void D()
{
var css = StyleSheet.Parse(@"
$varName: --containerWidth;
div { width: calc(380px - 50px); }");
Assert.Equal("div { width: calc(380px - 50px); }", css.ToString());
}
[Fact]
public void E()
{
var css = StyleSheet.Parse(@"
div { width: 50px + 100px; } ");
Assert.Equal("div { width: 150px; }", css.ToString());
}
[Fact]
public void F()
{
var css = StyleSheet.Parse(@"
div { width: 50px * 2; } ");
Assert.Equal("div { width: 100px; }", css.ToString());
}
[Fact]
public void G()
{
var css = StyleSheet.Parse(@"
$width: 50px + 50px;
div { width: calc($width); } ");
Assert.Equal("div { width: calc(100px); }", css.ToString());
}
}
} | mit | C# | |
03d80bc2232724dc00c55e665efa027c3f95555d | Add an Rx-friendly HTTP downloader | rzhw/Squirrel.Windows,rzhw/Squirrel.Windows | src/NSync.Core/Http.cs | src/NSync.Core/Http.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text;
namespace NSync.Core
{
public static class Http
{
/// <summary>
/// Download data from an HTTP URL and insert the result into the
/// cache. If the data is already in the cache, this returns
/// a cached value. The URL itself is used as the key.
/// </summary>
/// <param name="url">The URL to download.</param>
/// <param name="headers">An optional Dictionary containing the HTTP
/// request headers.</param>
/// <returns>The data downloaded from the URL.</returns>
public static IObservable<byte[]> DownloadUrl(string url, Dictionary<string, string> headers = null)
{
var ret = makeWebRequest(new Uri(url), headers)
.SelectMany(processAndCacheWebResponse)
.Multicast(new AsyncSubject<byte[]>());
ret.Connect();
return ret;
}
static IObservable<byte[]> processAndCacheWebResponse(WebResponse wr)
{
var hwr = (HttpWebResponse)wr;
if ((int)hwr.StatusCode >= 400) {
return Observable.Throw<byte[]>(new WebException(hwr.StatusDescription));
}
var ms = new MemoryStream();
hwr.GetResponseStream().CopyTo(ms);
var ret = ms.ToArray();
return Observable.Return(ret);
}
static IObservable<WebResponse> makeWebRequest(
Uri uri,
Dictionary<string, string> headers = null,
string content = null,
int retries = 3,
TimeSpan? timeout = null)
{
var request = Observable.Defer(() => {
var hwr = WebRequest.Create(uri);
if (headers != null) {
foreach (var x in headers) {
hwr.Headers[x.Key] = x.Value;
}
}
if (content == null) {
return Observable.FromAsyncPattern<WebResponse>(hwr.BeginGetResponse, hwr.EndGetResponse)();
}
var buf = Encoding.UTF8.GetBytes(content);
return Observable.FromAsyncPattern<Stream>(hwr.BeginGetRequestStream, hwr.EndGetRequestStream)()
.SelectMany(x => Observable.FromAsyncPattern<byte[], int, int>(x.BeginWrite, x.EndWrite)(buf, 0, buf.Length))
.SelectMany(_ => Observable.FromAsyncPattern<WebResponse>(hwr.BeginGetResponse, hwr.EndGetResponse)());
});
return request.Timeout(timeout ?? TimeSpan.FromSeconds(15)).Retry(retries);
}
}
} | mit | C# | |
79c032b3721227724491559ea7617ca70c18236c | Update lock to version 7.11 | Amialc/auth0-aspnet-owin,jerriep/auth0-aspnet-owin,jerriep/auth0-aspnet-owin,auth0/auth0-aspnet-owin,Amialc/auth0-aspnet-owin,Amialc/auth0-aspnet-owin,auth0/auth0-aspnet-owin,jerriep/auth0-aspnet-owin,auth0/auth0-aspnet-owin | examples/basic-mvc-sample/BasicMvcSample/Views/Account/Login.cshtml | examples/basic-mvc-sample/BasicMvcSample/Views/Account/Login.cshtml | @using System.Configuration;
@{
ViewBag.Title = "Login";
}
<div id="root" style="width: 280px; margin: 40px auto;">
</div>
@Html.AntiForgeryToken()
<script src="https://cdn.auth0.com/js/lock-7.11.min.js"></script>
<script>
if (!window.location.origin) {
window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
}
var lock = new Auth0Lock('@ConfigurationManager.AppSettings["auth0:ClientId"]', '@ConfigurationManager.AppSettings["auth0:Domain"]');
var xsrf = document.getElementsByName("__RequestVerificationToken")[0].value;
lock.show({
container: 'root'
, callbackURL: window.location.origin + '/signin-auth0'
, responseType: 'code'
, authParams: {
scope: 'openid name email',
state: 'xsrf=' + xsrf + '&ru=' + '@ViewBag.ReturnUrl'
}
});
</script>
| @using System.Configuration;
@{
ViewBag.Title = "Login";
}
<div id="root" style="width: 280px; margin: 40px auto;">
</div>
@Html.AntiForgeryToken()
<script src="https://cdn.auth0.com/js/lock-7.9.min.js"></script>
<script>
if (!window.location.origin) {
window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
}
var lock = new Auth0Lock('@ConfigurationManager.AppSettings["auth0:ClientId"]', '@ConfigurationManager.AppSettings["auth0:Domain"]');
var xsrf = document.getElementsByName("__RequestVerificationToken")[0].value;
lock.show({
container: 'root'
, callbackURL: window.location.origin + '/signin-auth0'
, responseType: 'code'
, authParams: {
scope: 'openid name email',
state: 'xsrf=' + xsrf + '&ru=' + '@ViewBag.ReturnUrl'
}
});
</script>
| mit | C# |
58587855148a9b7b167db1b90820ddd12b4eecaf | Create FindWithTag.cs | carcarc/unity3d | FindWithTag.cs | FindWithTag.cs | //FindWithTag
GameObject gameControllerObject = GameObject.FindWithTag("GameController");
if (gameControllerObject != null)
{
gameGenerate = gameControllerObject.GetComponent<Generate>();
}
if (gameGenerate == null)
{
Debug.Log("Cannot find 'GameController' script");
}
| mit | C# | |
832729afefd9d59d0791eb53bd1455614dcd568a | Create IEdge. | DasAllFolks/SharpGraphs | Graph/IEdge.cs | Graph/IEdge.cs | namespace Graph
{
/// <summary>
/// Default interface for a graph edge, whether directed or undirected.
/// </summary>
public interface IEdge
{
}
}
| apache-2.0 | C# | |
b5f68efcb4c9db200a1db5e804a3adca97ce1957 | Create SessionList.cs | neilopet/TeamSpeak2-Session-Hijack | SessionList.cs | SessionList.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Numerics;
namespace TS2Terrorist
{
using System;
using System.Text;
using System.Numerics;
public class SessionList
{
public uint s1;
public uint s2;
public uint clid;
public uint xn;
public long modulus;
public uint seed = 0;
public uint iter = 0;
public uint iter_n = 0;
public SessionList(uint client_id, uint session_id_1, uint session_id_2)
{
this.clid = client_id;
this.s1 = session_id_1;
this.s2 = session_id_2;
this.xn = 0;
this.modulus = 4294967296;
}
public BigInteger next()
{
if (0 == this.iter)
this.iter = this.seed;
if (0 == this.iter || this.iter == 1)
return -1;
if (this.iter_n > this.clid)
return -1;
this.iter_n++;
this.iter = this.gen_x(this.iter);
return this.gen_session(this.iter);
}
public void getSeed(uint start)
{
uint x = start;
while (!this.vs1(this.s1, x) || !this.vs2(this.s2, x))
{
if (x == (this.modulus - 1))
return;
x++;
}
this.xn = x;
BigInteger seed = x;
uint multiplier = 3645876429;
uint n = this.clid;
while (n > 0)
{
seed = BigInteger.Multiply(multiplier, (seed - 1)) % this.modulus;
n--;
}
this.seed = (uint)seed;
}
public bool vs1(uint s1, uint i)
{
return (s1 == this.gen_session(i));
}
public bool vs2(uint s2, uint i)
{
return (s2 == this.gen_session(this.gen_x(i)));
}
public uint gen_x(BigInteger last)
{
return (uint)(
((last * 134775813) + 1) % this.modulus
);
}
public uint gen_session(uint x)
{
return Convert.ToUInt32((((long)x) * 16777215) >> 32);
}
}
}
| apache-2.0 | C# | |
da5a1819f5f6e90c58dcfe4c25490332f3ae43c7 | Create Ax.cs | APEdevelopment/APE,APEdevelopment/APE | APE.Bridge/APE.Bridge/Ax.cs | APE.Bridge/APE.Bridge/Ax.cs | apache-2.0 | C# | ||
18bd20600fc64b71010e7dbaa51b2e2679e73e71 | Add string.NullIfEmpty() | sharpjs/PSql,sharpjs/PSql | PSql.Core/_Utilities/StringExtensions.cs | PSql.Core/_Utilities/StringExtensions.cs | namespace PSql
{
internal static class StringExtensions
{
internal static string NullIfEmpty(this string s)
=> string.IsNullOrEmpty(s) ? null : s;
}
}
| isc | C# | |
4e55fd0d27db2f75e3622cf42aa67a5e486cdcca | Create Problem49.cs | fireheadmx/ProjectEuler,fireheadmx/ProjectEuler | Problems/Problem49.cs | Problems/Problem49.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProjectEuler.Problems
{
class Problem49
{
private Sieve s;
private int upper = 10000;
private int step = 3330;
public Problem49()
{
s = new Sieve(upper + step * 2);
}
private List<int> GetPermutations(int number)
{
List<int> numberList = new List<int>();
while (number > 0)
{
numberList.Add(number % 10);
number = number / 10;
}
numberList.Sort();
int[] permutable = numberList.ToArray();
List<int> result = new List<int>();
do
{
int permuted = 0;
for (int i = 0; i <= permutable.Length - 1; i++)
{
permuted += permutable[i] * (int)Math.Pow(10, (permutable.Length - 1 - i));
}
result.Add(permuted);
}
while (Permutation.NextPermutation(permutable));
return result;
}
public void Run()
{
List<int> permutablePrimes = new List<int>();
List<int> allPermutablePrimes = new List<int>();
for(int i = 1000; i < upper; i++) {
if (s.prime[i] && s.prime[i + step] && s.prime[i + 2 * step])
{
var foundPermutations = GetPermutations(i);
if(foundPermutations.Contains(i+step) && foundPermutations.Contains(i+2*step)) {
permutablePrimes.Add(i);
permutablePrimes.Add(i+step);
permutablePrimes.Add(i + 2*step);
}
}
}
foreach (int prime in permutablePrimes)
{
if (prime != 1487 && prime != 4817 && prime != 8147)
{
Console.Write(prime);
}
}
}
}
}
| mit | C# | |
efcc2257308744b77695b61ae95e5ea9b3e5bb3f | Create Problem95.cs | fireheadmx/ProjectEuler,fireheadmx/ProjectEuler | Problems/Problem95.cs | Problems/Problem95.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProjectEuler.Problems
{
class Problem95
{
private SortedSet<int> chain = new SortedSet<int>();
private int SumDivisors(int number)
{
int sum = 1;
double number_sqrt = Math.Sqrt(number);
for (int i = 2; i <= number_sqrt; i++)
{
if (number % i == 0)
{
sum += i;
if (number / i != i)
{
sum += number / i;
}
}
}
return sum;
}
private int[] Chain(int number)
{
int[] no_chain = new int[1] { 0 };
int orig_number = number;
chain.Clear();
int prev_chain_size;
do
{
prev_chain_size = chain.Count;
chain.Add(number);
number = SumDivisors(number);
if (number == orig_number)
{
return chain.ToArray();
}
else if (number > 1000000)
{
return no_chain;
}
}
while (prev_chain_size < chain.Count);
return no_chain;
}
public void Run()
{
int n = 12496;
int[] longest_chain = Chain(n);
int longest_n = n;
int[] chain_n;
do
{
n++;
chain_n = Chain(n);
if (chain_n.Count() > longest_chain.Count())
{
longest_chain = chain_n;
longest_n = n;
}
}
while (n < 1000000);
Console.WriteLine(longest_chain.First().ToString());
Console.ReadLine();
}
}
}
| mit | C# | |
d22081b1a026846318ab330cd98c2fe8083b9100 | Add CovalenceProvider | LaserHydra/Oxide,Visagalis/Oxide,Visagalis/Oxide,LaserHydra/Oxide | Games/Unity/Oxide.Game.FortressCraft/Libraries/Covalence/FortressCraftCovalenceProvider.cs | Games/Unity/Oxide.Game.FortressCraft/Libraries/Covalence/FortressCraftCovalenceProvider.cs | using Oxide.Core.Libraries.Covalence;
namespace Oxide.Game.FortressCraft.Libraries.Covalence
{
/// <summary>
/// Provides Covalence functionality for the game "FortressCraft"
/// </summary>
public class FortressCraftCovalenceProvider : ICovalenceProvider
{
/// <summary>
/// Gets the name of the game for which this provider provides
/// </summary>
public string GameName => "FortressCraft";
/// <summary>
/// Gets the Steam app ID of the game's client, if available
/// </summary>
public uint ClientAppId => 254200;
/// <summary>
/// Gets the Steam app ID of the game's server, if available
/// </summary>
public uint ServerAppId => 254200;
/// <summary>
/// Gets the singleton instance of this provider
/// </summary>
internal static FortressCraftCovalenceProvider Instance { get; private set; }
public FortressCraftCovalenceProvider()
{
Instance = this;
}
/// <summary>
/// Gets the player manager
/// </summary>
public FortressCraftPlayerManager PlayerManager { get; private set; }
/// <summary>
/// Gets the command system provider
/// </summary>
public FortressCraftCommandSystem CommandSystem { get; private set; }
/// <summary>
/// Creates the game-specific server object
/// </summary>
/// <returns></returns>
public IServer CreateServer() => new FortressCraftServer();
/// <summary>
/// Creates the game-specific player manager object
/// </summary>
/// <returns></returns>
public IPlayerManager CreatePlayerManager() => PlayerManager = new FortressCraftPlayerManager();
/// <summary>
/// Creates the game-specific command system provider object
/// </summary>
/// <returns></returns>
public ICommandSystem CreateCommandSystemProvider() => CommandSystem = new FortressCraftCommandSystem();
/// <summary>
/// Formats the text with markup as specified in Oxide.Core.Libraries.Covalence.Formatter
/// into the game-specific markup language
/// </summary>
/// <param name="text">text to format</param>
/// <returns>formatted text</returns>
public string FormatText(string text) => Formatter.ToUnity(text);
}
}
| mit | C# | |
f1b817d415dc0ed288c6dd9248a2603a7ad3f954 | Add Jenkins build server | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Core/BuildServers/Jenkins.cs | source/Nuke.Core/BuildServers/Jenkins.cs | using System;
using System.Linq;
namespace Nuke.Core.BuildServers
{
/// <summary>
/// Interface according to the
/// <a href="https://wiki.jenkins.io/display/JENKINS/Building+a+software+project">official website</a>.
/// </summary>
[BuildServer]
public class Jenkins
{
public static Jenkins Instance { get; } = EnvironmentInfo.Variable("JENKINS_URL") != null ? new Jenkins() : null;
private Jenkins ()
{
}
/// <summary>
/// The current build number, such as "153"
/// </summary>
public int BuildNumber => EnvironmentInfo.EnsureVariable<int>("BUILD_NUMBER");
/// <summary>
/// The current build id, such as "2005-08-22_23-59-59" (YYYY-MM-DD_hh-mm-ss,
/// <a href="https://issues.jenkins-ci.org/browse/JENKINS-26520">defunct</a> since version 1.597)
/// </summary>
public string BuildId => EnvironmentInfo.EnsureVariable("BUILD_ID");
/// <summary>
/// The URL where the results of this build can be found (e.g. http://buildserver/jenkins/job/MyJobName/666/)
/// </summary>
public string BuildUrl => EnvironmentInfo.EnsureVariable("BUILD_URL");
/// <summary>
/// The name of the node the current build is running on. Equals 'master' for master node.
/// </summary>
public string NodeName => EnvironmentInfo.EnsureVariable("NODE_NAME");
/// <summary>
/// Name of the project of this build. This is the name you gave your job when you first set it up. It's the third
/// column of the Jenkins Dashboard main page.
/// </summary>
public string JobName => EnvironmentInfo.EnsureVariable("JOB_NAME");
/// <summary>
/// String of jenkins-${JOB_NAME}-${BUILD_NUMBER}. Convenient to put into a resource file, a jar file, etc for easier
/// identification.
/// </summary>
public string BuildTag => EnvironmentInfo.EnsureVariable("BUILD_TAG");
/// <summary>
/// Set to the URL of the Jenkins master that's running the build. This value is used by Jenkins CLI for exampl
/// </summary>
public string JenkinsUrl => EnvironmentInfo.EnsureVariable("JENKINS_URL");
/// <summary>
/// The unique number that identifies the current executor (among executors of the same machine) that's carrying out
/// this build. This is the number you see in the "build executor status", except that the number starts from 0, not 1.
/// </summary>
public string ExecutorNumber => EnvironmentInfo.EnsureVariable("EXECUTOR_NUMBER");
}
}
| mit | C# | |
2e0d4cd40f8b7b0f54104d6facd62d84b6a848a1 | Add sorting order/layer comparison Also move comparer methods into a list | HattMarris1/HoloToolkit-Unity,NeerajW/HoloToolkit-Unity,paseb/HoloToolkit-Unity,paseb/MixedRealityToolkit-Unity,out-of-pixel/HoloToolkit-Unity,willcong/HoloToolkit-Unity | Assets/HoloToolkit/Utilities/Scripts/RaycastResultComparer.cs | Assets/HoloToolkit/Utilities/Scripts/RaycastResultComparer.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using UnityEngine.EventSystems;
namespace HoloToolkit.Unity
{
public class RaycastResultComparer : IComparer<RaycastResult>
{
private static readonly List<Func<RaycastResult, RaycastResult, int>> Comparers = new List<Func<RaycastResult, RaycastResult, int>>
{
CompareRaycastsBySortingLayer,
CompareRaycastsBySortingOrder,
CompareRaycastsByCanvasDepth,
CompareRaycastsByDistance,
};
public int Compare(RaycastResult left, RaycastResult right)
{
for (var i = 0; i < Comparers.Count; i++)
{
var result = Comparers[i](left, right);
if (result != 0)
{
return result;
}
}
return 0;
}
private static int CompareRaycastsBySortingOrder(RaycastResult left, RaycastResult right)
{
//Higher is better
return right.sortingOrder.CompareTo(left.sortingOrder);
}
private static int CompareRaycastsBySortingLayer(RaycastResult left, RaycastResult right)
{
//Higher is better
return right.sortingLayer.CompareTo(left.sortingLayer);
}
private static int CompareRaycastsByCanvasDepth(RaycastResult left, RaycastResult right)
{
//Module is the graphic raycaster on the canvases.
if (left.module.transform.IsParentOrChildOf(right.module.transform))
{
//Higher is better
return right.depth.CompareTo(left.depth);
}
return 0;
}
private static int CompareRaycastsByDistance(RaycastResult left, RaycastResult right)
{
//Lower is better
return left.distance.CompareTo(right.distance);
}
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Collections.Generic;
using UnityEngine.EventSystems;
namespace HoloToolkit.Unity
{
public class RaycastResultComparer : IComparer<RaycastResult>
{
public int Compare(RaycastResult left, RaycastResult right)
{
var result = CompareRaycastsByCanvasDepth(left, right);
if (result != 0) { return result; }
return CompareRaycastsByDistance(left, right);
}
private static int CompareRaycastsByCanvasDepth(RaycastResult left, RaycastResult right)
{
//Module is the graphic raycaster on the canvases.
if (left.module.transform.IsParentOrChildOf(right.module.transform))
{
return right.depth.CompareTo(left.depth);
}
return 0;
}
private static int CompareRaycastsByDistance(RaycastResult left, RaycastResult right)
{
return left.distance.CompareTo(right.distance);
}
}
}
| mit | C# |
2aa0f015b56de1b862c66c1cf6f3e09d03e086ba | Add missing file | davidsyntex/13th-Age-Monster-Generator | 13AMonsterGenerator/DefenseType.cs | 13AMonsterGenerator/DefenseType.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _13AMonsterGenerator
{
class DefenseType
{
public DefenseType(Type type)
{
switch (type)
{
case Type.Ac:
SetAc();
break;
case Type.Pd:
SetMd();
break;
case Type.Md:
SetPd();
break;
default:
SetAc();
break;
}
}
public DefenseType()
{
}
// ReSharper disable once UnusedAutoPropertyAccessor.Global
public string Name { get; private set; }
public string Shortname { get; private set; }
public int Weight { get; private set; }
private void SetAc()
{
Name = "Armour Class";
Shortname = "AC";
Weight = 12;
}
private void SetMd()
{
Name = "Mental Defense";
Shortname = "MD";
Weight = 4;
}
private void SetPd()
{
Name = "Physical Defense";
Shortname = "PD";
Weight = 4;
}
public enum Type
{
Ac,
Pd,
Md
}
}
}
| mit | C# | |
7ca8255d6f92470493cb24537967786d326acc78 | Add a default VS foregrounddispatcher | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.VisualStudio.LanguageServices.Razor/VisualStudioForegroundDispatcher.cs | src/Microsoft.VisualStudio.LanguageServices.Razor/VisualStudioForegroundDispatcher.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.Razor
{
[Export(typeof(ForegroundDispatcher))]
internal class VisualStudioForegroundDispatcher : ForegroundDispatcher
{
public override bool IsForegroundThread => ThreadHelper.CheckAccess();
}
}
| apache-2.0 | C# | |
161ac34c11a67c951aa18148fb1b67f6cd18f892 | Create MonsterDensityAroundCursor.cs | prrovoss/THUD | plugins/Prrovoss/MonsterDensityAroundCursor.cs | plugins/Prrovoss/MonsterDensityAroundCursor.cs | using Turbo.Plugins.Default;
namespace Turbo.Plugins.Prrovoss
{
public class MonsterDensityAroundCursor : BasePlugin
{
public bool DrawCursorCircle { get; set; }
public bool DrawCursorLabel { get; set; }
public bool DrawTopLabel { get; set; }
public int Distance { get; set; }
public TopLabelWithTitleDecorator CursorLabelDecorator { get; set; }
public TopLabelWithTitleDecorator TopLabelDecorator { get; set; }
public IBrush CursorCircleBrush { get; set; }
public float TopLabelXRatio { get; set; }
public float TopLabelYRatio { get; set; }
public float TopLabelWRatio { get; set; }
public float TopLabelHRatio { get; set; }
public float CursorLabelXOffset { get; set; }
public float CursorLabelYOffset { get; set; }
public float CursorLabelWRatio { get; set; }
public float CursorLabelHRatio { get; set; }
public MonsterDensityAroundCursor()
{
Enabled = true;
}
public override void Load(IController hud)
{
base.Load(hud);
CursorCircleBrush = Hud.Render.CreateBrush(200, 255, 255, 255, 4);
DrawCursorCircle = true;
DrawCursorLabel = true;
DrawTopLabel = true;
Distance = 12;
TopLabelDecorator = new TopLabelWithTitleDecorator(Hud)
{
TextFont = hud.Render.CreateFont("tahoma", 9, 255, 255, 255, 255, false, false, true),
BorderBrush = Hud.Render.CreateBrush(255, 255, 255, 255, -1),
BackgroundBrush = Hud.Render.CreateBrush(0, 0, 0, 0, 0),
};
TopLabelXRatio = 0.44f;
TopLabelYRatio = 0.001f;
TopLabelWRatio = 0.05f;
TopLabelHRatio = 0.015f;
CursorLabelDecorator = new TopLabelWithTitleDecorator(Hud)
{
TextFont = hud.Render.CreateFont("tahoma", 9, 255, 255, 255, 255, false, false, true),
BorderBrush = Hud.Render.CreateBrush(255, 255, 255, 255, -1),
BackgroundBrush = Hud.Render.CreateBrush(0, 0, 0, 0, 0),
};
CursorLabelXOffset = -10f;
CursorLabelYOffset = 35f;
CursorLabelWRatio = 0.025f;
CursorLabelHRatio = 0.015f;
}
public override void PaintWorld(WorldLayer layer)
{
if (!Hud.Game.Me.IsInTown)
{
IScreenCoordinate coord = Hud.Window.CreateScreenCoordinate(Hud.Window.CursorX, Hud.Window.CursorY);
IWorldCoordinate cursor = coord.ToWorldCoordinate();
int count = 0;
foreach (IMonster monster in Hud.Game.AliveMonsters)
{
if (monster.FloorCoordinate.XYDistanceTo(cursor) < Distance) count++;
}
if (DrawCursorCircle)
{
CursorCircleBrush.DrawWorldEllipse(Distance, -1, cursor);
}
if (DrawCursorLabel)
{
float width = Hud.Window.Size.Height * CursorLabelWRatio;
float height = Hud.Window.Size.Height * CursorLabelHRatio;
CursorLabelDecorator.Paint(coord.X + CursorLabelXOffset, coord.Y + CursorLabelYOffset, width, height, count.ToString(), null, "");
}
if (DrawTopLabel)
{
float x = Hud.Window.Size.Width * TopLabelXRatio;
float y = Hud.Window.Size.Height * TopLabelYRatio;
float width = Hud.Window.Size.Height * TopLabelWRatio;
float height = Hud.Window.Size.Height * TopLabelHRatio;
TopLabelDecorator.Paint(x - width / 2, y, width, height, count.ToString(), null, "");
}
}
}
}
}
| mit | C# | |
fa07dfd7ec10605e8e86f1cfa5fd6a0bc1b84e94 | Write various unit tests for CustomerData, Name, and StreetAddress | 0culus/ElectronicCash | ElectronicCash.Tests/CustomerDataTests.cs | ElectronicCash.Tests/CustomerDataTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace ElectronicCash.Tests
{
[TestFixture]
class CustomerDataTests
{
//private static DateTime _dateTime = new DateTime();
private static readonly Name CustomerName = new Name("Elmer", "T.", "Fudd", "Mr.");
private static readonly StreetAddress CustomerAddress = new StreetAddress("20 Bunny Rd.", "Rabbits, Rabbitville", "12345");
private readonly CustomerData _customerData = new CustomerData(CustomerName, "fudd@bunny.xyz",
CustomerAddress, DateTime.UtcNow, new Guid());
[Test]
public void OnConstruction_NameShouldNotBeNull()
{
Assert.IsNotNull(CustomerName);
}
[Test]
public void OnConstruction_NamePropertiesShouldNotBeNull()
{
Assert.IsNotNull(CustomerName.FirstName);
Assert.IsNotNull(CustomerName.MiddleName);
Assert.IsNotNull(CustomerName.LastName);
Assert.IsNotNull(CustomerName.Title);
}
[Test]
public void OnConstruction_CustomerAddressShouldNotBeNull()
{
Assert.IsNotNull(CustomerAddress);
}
[Test]
public void OnConstruction_CustomerAddressWithoutAptPropertiesShouldNotBeNull()
{
Assert.IsNotNull(CustomerAddress.CityState);
Assert.IsNotNull(CustomerAddress.Road);
Assert.IsNotNull(CustomerAddress.ZipCode);
}
[Test]
public void OnConstruction_CustomerDataObjectShouldNotBeNull()
{
Assert.IsNotNull(_customerData);
}
[Test]
public void OnConstruction_CustomerDataPropertiesShouldNotBeNull()
{
Assert.IsNotNull(_customerData.CreatedDateTime);
Assert.IsNotNull(_customerData.CustomerGuid);
Assert.IsNotNull(_customerData.CustomerName);
Assert.IsNotNull(_customerData.CustomerStreetAddress);
Assert.IsNotNull(_customerData.Email);
Assert.IsNotNull(_customerData.CreatedDateTime);
}
[Test]
public void OnSerialization_OutputShouldBeValidJson()
{
var serialized = _customerData.GetCustomerDataJson(_customerData);
var testRead =
}
}
}
| mit | C# | |
86db44c810e8c0e171303a7cce35c9bc53b4abff | Create TerminalBlockInspector.cs | Pharap/SpengyUtils | Utils/TerminalBlockInspector.cs | Utils/TerminalBlockInspector.cs | // Lists all actions and properties of a terminal block
public void Main(string argument)
{
var block = GridTerminalSystem.GetBlockWithName(argument) as IMyTerminalBlock;
var builder = new StringBuilder();
var actions = new List<ITerminalAction>();
block.GetActions(actions);
foreach(var action in actions)
builder.AppendFormat("{0} ({1})\n", action.Id, action.Name);
builder.Append("\n");
var properties = new List<ITerminalProperty>();
block.GetProperties(properties);
foreach(var prop in properties)
builder.AppendFormat("{0} : {1}\n", prop.Id, prop.TypeName);
Echo(builder.ToString());
}
| apache-2.0 | C# | |
f3d8322ddcefbd471197373359d6759ccaa4c02f | Add mappedimages view | feliwir/openSage,feliwir/openSage | src/OpenSage.Game/Diagnostics/AssetViews/MappedImageView.cs | src/OpenSage.Game/Diagnostics/AssetViews/MappedImageView.cs | using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using OpenSage.Graphics;
using OpenSage.Gui;
using OpenSage.Gui.Wnd.Images;
using OpenSage.Mathematics;
using Veldrid;
namespace OpenSage.Diagnostics.AssetViews
{
[AssetView(typeof(MappedImage))]
internal sealed class MappedImageView : AssetView
{
private readonly Texture _texture;
private readonly Dictionary<TextureViewDescription, Veldrid.TextureView> _textureViews;
public MappedImageView(DiagnosticViewContext context, MappedImage mappedImageAsset)
: base(context)
{
_texture = MappedImageUtility.CreateTexture(context.Game.GraphicsLoadContext, mappedImageAsset);
_textureViews = new Dictionary<TextureViewDescription, Veldrid.TextureView>();
}
public override void Draw()
{
var textureViewDescription = new TextureViewDescription(_texture, 0, 1, 0, 1);
if (!_textureViews.TryGetValue(textureViewDescription, out var textureView))
{
_textureViews.Add(textureViewDescription, textureView = AddDisposable(Context.Game.GraphicsDevice.ResourceFactory.CreateTextureView(ref textureViewDescription)));
}
var imagePointer = Context.ImGuiRenderer.GetOrCreateImGuiBinding(
Context.Game.GraphicsDevice.ResourceFactory,
textureView);
var availableSize = ImGui.GetContentRegionAvail();
var size = SizeF.CalculateSizeFittingAspectRatio(
new SizeF(_texture.Width, _texture.Height),
new Size((int) availableSize.X, (int) availableSize.Y));
ImGui.Image(
imagePointer,
new Vector2(size.Width, size.Height),
Vector2.Zero,
Vector2.One,
Vector4.One,
Vector4.Zero);
}
}
}
| mit | C# | |
0a2934f15ce2c8a67daf644b94a1b873109e9223 | Create OpeningEncryptedExcelFiles.cs | maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET | Examples/CSharp/Files/Handling/OpeningEncryptedExcelFiles.cs | Examples/CSharp/Files/Handling/OpeningEncryptedExcelFiles.cs | using System.IO;
using Aspose.Cells;
using System;
namespace Aspose.Cells.Examples.Files.Handling
{
public class OpeningEncryptedExcelFiles
{
public static void Main(string[] args)
{
//Exstart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Instantiate LoadOptions
LoadOptions loadOptions6 = new LoadOptions();
//Specify the password
loadOptions6.Password = "1234";
//Create a Workbook object and opening the file from its path
Workbook wbEncrypted = new Workbook(dataDir + "encryptedBook.xls", loadOptions6);
Console.WriteLine("Encrypted excel file opened successfully!");
//ExEnd:1
}
}
}
| mit | C# | |
b9d397e6a0a9c2ffe6d7e2160127cb1ea9052624 | Create server side API for single multiple answer question | Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist | Trappist/src/Promact.Trappist.Core/Controllers/QuestionsController.cs | Trappist/src/Promact.Trappist.Core/Controllers/QuestionsController.cs | using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;
namespace Promact.Trappist.Core.Controllers
{
[Route("api/question")]
public class QuestionsController : Controller
{
private readonly IQuestionRepository _questionsRepository;
public QuestionsController(IQuestionRepository questionsRepository)
{
_questionsRepository = questionsRepository;
}
[HttpGet]
/// <summary>
/// Gets all questions
/// </summary>
/// <returns>Questions list</returns>
public IActionResult GetQuestions()
{
var questions = _questionsRepository.GetAllQuestions();
return Json(questions);
}
[HttpPost]
/// <summary>
///
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <returns></returns>
public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion);
return Ok();
}
/// <summary>
///
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <returns></returns>
public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption);
return Ok();
}
}
}
| mit | C# | |
69e7edbfdc3d8b5905f84612b2541548f7cf6f96 | append _URL to AUTH0_AUDIENCE | StephenClearyExamples/FunctionsAuth0 | src/FunctionApp/Constants.cs | src/FunctionApp/Constants.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunctionApp
{
public static class Constants
{
public static string Auth0Domain => GetEnvironmentVariable("AUTH0_DOMAIN");
public static string Audience => GetEnvironmentVariable("AUTH0_AUDIENCE_URL");
private static string GetEnvironmentVariable(string name)
{
var result = Environment.GetEnvironmentVariable(name);
if (string.IsNullOrEmpty(result))
throw new InvalidOperationException($"Missing app setting {name}");
return result;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunctionApp
{
public static class Constants
{
public static string Auth0Domain => GetEnvironmentVariable("AUTH0_DOMAIN");
public static string Audience => GetEnvironmentVariable("AUTH0_AUDIENCE");
private static string GetEnvironmentVariable(string name)
{
var result = Environment.GetEnvironmentVariable(name);
if (string.IsNullOrEmpty(result))
throw new InvalidOperationException($"Missing app setting {name}");
return result;
}
}
}
| mit | C# |
71c2fe2ea1b4dfa92c9a85820fe912cb1f5fa0a2 | Add parameterless constructor to SingleCriteria | ronnymgm/csla-light,JasonBock/csla,JasonBock/csla,ronnymgm/csla-light,jonnybee/csla,rockfordlhotka/csla,rockfordlhotka/csla,rockfordlhotka/csla,jonnybee/csla,MarimerLLC/csla,BrettJaner/csla,BrettJaner/csla,jonnybee/csla,MarimerLLC/csla,MarimerLLC/csla,BrettJaner/csla,ronnymgm/csla-light,JasonBock/csla | cslalightcs/Csla/SingleCriteria.cs | cslalightcs/Csla/SingleCriteria.cs | using System;
using Csla.Serialization;
using Csla.Core.FieldManager;
using Csla.Serialization.Mobile;
using Csla.Core;
namespace Csla
{
/// <summary>
/// A single-value criteria used to retrieve business
/// objects that only require one criteria value.
/// </summary>
/// <typeparam name="B">
/// Type of business object to retrieve.
/// </typeparam>
/// <typeparam name="C">
/// Type of the criteria value.
/// </typeparam>
/// <remarks></remarks>
[Serializable()]
public class SingleCriteria<B, C> : CriteriaBase
{
private C _value;
/// <summary>
/// Gets the criteria value provided by the caller.
/// </summary>
public C Value
{
get
{
return _value;
}
}
/// <summary>
/// Creates an instance of the type,
/// initializing it with the criteria
/// value.
/// </summary>
/// <param name="value">
/// The criteria value.
/// </param>
public SingleCriteria(C value)
: base(typeof(B))
{
_value = value;
}
#if SILVERLIGHT
/// <summary>
/// Creates an instance of the type.
/// This is for use by the MobileFormatter,
/// you must provide a criteria value
/// parameter.
/// </summary>
public SingleCriteria()
{ }
#else
protected SingleCriteria()
{ }
#endif
#region MobileFormatter
/// <summary>
/// Override this method to insert your field values
/// into the MobileFormatter serialzation stream.
/// </summary>
/// <param name="info">
/// Object containing the data to serialize.
/// </param>
protected override void OnGetState(SerializationInfo info, StateMode mode)
{
base.OnGetState(info, mode);
info.AddValue("Csla.Silverlight.SingleCriteria._value", _value);
}
/// <summary>
/// Override this method to retrieve your field values
/// from the MobileFormatter serialzation stream.
/// </summary>
/// <param name="info">
/// Object containing the data to serialize.
/// </param>
protected override void OnSetState(SerializationInfo info, StateMode mode)
{
base.OnSetState(info, mode);
_value = info.GetValue<C>("Csla.Silverlight.SingleCriteria._value");
}
#endregion
}
}
| using System;
using Csla.Serialization;
using Csla.Core.FieldManager;
using Csla.Serialization.Mobile;
using Csla.Core;
namespace Csla
{
/// <summary>
/// A single-value criteria used to retrieve business
/// objects that only require one criteria value.
/// </summary>
/// <typeparam name="B">
/// Type of business object to retrieve.
/// </typeparam>
/// <typeparam name="C">
/// Type of the criteria value.
/// </typeparam>
/// <remarks></remarks>
[Serializable()]
public class SingleCriteria<B, C> : CriteriaBase
{
private C _value;
/// <summary>
/// Gets the criteria value provided by the caller.
/// </summary>
public C Value
{
get
{
return _value;
}
}
/// <summary>
/// Creates an instance of the type,
/// initializing it with the criteria
/// value.
/// </summary>
/// <param name="value">
/// The criteria value.
/// </param>
public SingleCriteria(C value)
: base(typeof(B))
{
_value = value;
}
#if SILVERLIGHT
/// <summary>
/// Creates an instance of the type.
/// This is for use by the MobileFormatter,
/// you must provide a criteria value
/// parameter.
/// </summary>
public SingleCriteria()
{ }
#else
private SingleCriteria()
{ }
#endif
#region MobileFormatter
/// <summary>
/// Override this method to insert your field values
/// into the MobileFormatter serialzation stream.
/// </summary>
/// <param name="info">
/// Object containing the data to serialize.
/// </param>
protected override void OnGetState(SerializationInfo info, StateMode mode)
{
base.OnGetState(info, mode);
info.AddValue("Csla.Silverlight.SingleCriteria._value", _value);
}
/// <summary>
/// Override this method to retrieve your field values
/// from the MobileFormatter serialzation stream.
/// </summary>
/// <param name="info">
/// Object containing the data to serialize.
/// </param>
protected override void OnSetState(SerializationInfo info, StateMode mode)
{
base.OnSetState(info, mode);
_value = info.GetValue<C>("Csla.Silverlight.SingleCriteria._value");
}
#endregion
}
}
| mit | C# |
9deffad98cb16fb3d5534761b89fa85a1682f874 | Add empty class to build something | alexandrnikitin/CircuitBreaker.Net,alexandrnikitin/CircuitBreaker.Net | src/CircuitBreaker.Net/CircuitBreaker.cs | src/CircuitBreaker.Net/CircuitBreaker.cs | namespace CircuitBreaker.Net
{
public class CircuitBreaker
{
}
} | mit | C# | |
b15976ae63716b01f74d55d31e7bc6090d8925dd | Implement some Tests for the HSL-Struct | ControlzEx/ControlzEx,punker76/Controlz | src/ControlzEx.Tests/Theming/HSLTests.cs | src/ControlzEx.Tests/Theming/HSLTests.cs | using ControlzEx.Theming;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
namespace ControlzEx.Tests.Theming
{
[TestFixture]
public class HSLTests
{
// This Test is very slow, so only run if really needed. Comment out the comment below to run this test
// [Test]
public void TestHslFromColor()
{
for (uint i = 0; i < uint.MaxValue; i++)
{
var color = (Color)ColorConverter.ConvertFromString("#" + i.ToString("X8"));
Assert.AreEqual(color, new HSLColor(color).ToColor());
}
}
[Test]
public void TestColorPerComponent()
{
Color color;
// Gray
for (byte i = 0; i < byte.MaxValue; i++)
{
color = Color.FromArgb(255, i, i, i);
Assert.AreEqual(color, new HSLColor(color).ToColor());
}
// A
for (byte i = 0; i < byte.MaxValue; i++)
{
color = Color.FromArgb(i, 255, 255, 255);
Assert.AreEqual(color, new HSLColor(color).ToColor());
}
// R
for (byte i = 0; i < byte.MaxValue; i++)
{
color = Color.FromArgb(255, i, 255, 255);
Assert.AreEqual(color, new HSLColor(color).ToColor());
}
// G
for (byte i = 0; i < byte.MaxValue; i++)
{
color = Color.FromArgb(255, 255, i, 255);
Assert.AreEqual(color, new HSLColor(color).ToColor());
}
// B
for (byte i = 0; i < byte.MaxValue; i++)
{
color = Color.FromArgb(255, 255, 255, i);
Assert.AreEqual(color, new HSLColor(color).ToColor());
}
}
[Test]
public void TestHslFromColor_BuildInColors()
{
foreach (var color in typeof(Colors).GetProperties().Where(x => x.PropertyType == typeof(Color)).Select(x => (Color)x.GetValue(null)))
{
Assert.AreEqual(color, new HSLColor(color).ToColor());
}
}
[Test]
public void TestHslFromInput()
{
// Transparent
Assert.AreEqual(Colors.Transparent, new HSLColor(0, 0, 0, 1).ToColor());
// Black
Assert.AreEqual(Colors.Black, new HSLColor(1, 0, 0, 0).ToColor());
// White
Assert.AreEqual(Colors.White, new HSLColor(1, 0, 0, 1).ToColor());
// Gray
Assert.AreEqual(Colors.Gray, new HSLColor(1, 0, 0, 0.5).ToColor());
// Red
Assert.AreEqual(Colors.Red, new HSLColor(1, 0, 1, 0.5).ToColor());
// Yellow
Assert.AreEqual(Colors.Yellow, new HSLColor(1, 60, 1, 0.5).ToColor());
// Lime (Green)
Assert.AreEqual(Colors.Lime, new HSLColor(1, 120, 1, 0.5).ToColor());
// Aqua
Assert.AreEqual(Colors.Aqua, new HSLColor(1, 180, 1, 0.5).ToColor());
// Blue
Assert.AreEqual(Colors.Blue, new HSLColor(1, 240, 1, 0.5).ToColor());
// Magenta
Assert.AreEqual(Colors.Magenta, new HSLColor(1, 300, 1, 0.5).ToColor());
}
}
}
| mit | C# | |
eec8f67c97e78a22d3c887b99bc76c98fbe7fa7c | print in test | kbilsted/LineCounter.Net | LineCounter.Tests/UnitTest.cs | LineCounter.Tests/UnitTest.cs | using System;
using System.Diagnostics;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TeamBinary.LineCounter;
namespace TeamBinary.LineCounter.Tests
{
[TestClass]
public class UnitTest1
{
/*
string lens 964 5.024630542
ordinal startswith 1015 18.99441341
ordnial rather than == 1253 1.338582677
string.length check 1270 0
master uden length check 1270 0
*/
[TestMethod]
public void run()
{
var files = DirWalker.GetFiles(@"C:\src\");
Console.WriteLine("number files*: " + files.Length);
Stopwatch w = Stopwatch.StartNew();
var res = new DirWalker().DoWork(files);
Console.WriteLine("Time: " + w.ElapsedMilliseconds);
Console.WriteLine(new WebFormatter().CreateGithubShields(res));
}
[TestMethod]
public void DirWalker2()
{
var res = new DirWalker().DoWork(@"C:\Users\kbg\Documents\GitHub\StatePrinter\");
Console.WriteLine(new WebFormatter().CreateGithubShields(res));
Assert.AreEqual(3257, res.CodeLines);
Assert.AreEqual(1376, res.DocumentationLines);
Console.WriteLine(new WebFormatter().CreateGithubShields(res));
}
[TestMethod]
public void Webformatter()
{
var stat = new Statistics() { CodeLines = 2399, DocumentationLines = 299 };
var res = new WebFormatter().CreateGithubShields(stat);
Console.WriteLine(res);
Assert.AreEqual(@"[]()
[]()", res);
}
}
}
| using System;
using System.Diagnostics;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TeamBinary.LineCounter;
namespace TeamBinary.LineCounter.Tests
{
[TestClass]
public class UnitTest1
{
/*
string lens 964 5.024630542
ordinal startswith 1015 18.99441341
ordnial rather than == 1253 1.338582677
string.length check 1270 0
master uden length check 1270 0
*/
[TestMethod]
public void run()
{
var files = DirWalker.GetFiles(@"C:\src\");
Stopwatch w = Stopwatch.StartNew();
var res = new DirWalker().DoWork(files);
Console.WriteLine("Time: " + w.ElapsedMilliseconds);
Console.WriteLine(new WebFormatter().CreateGithubShields(res));
}
[TestMethod]
public void DirWalker2()
{
var res = new DirWalker().DoWork(@"C:\Users\kbg\Documents\GitHub\StatePrinter\");
Console.WriteLine(new WebFormatter().CreateGithubShields(res));
Assert.AreEqual(3257, res.CodeLines);
Assert.AreEqual(1376, res.DocumentationLines);
Console.WriteLine(new WebFormatter().CreateGithubShields(res));
}
[TestMethod]
public void Webformatter()
{
var stat = new Statistics() { CodeLines = 2399, DocumentationLines = 299 };
var res = new WebFormatter().CreateGithubShields(stat);
Console.WriteLine(res);
Assert.AreEqual(@"[]()
[]()", res);
}
}
}
| apache-2.0 | C# |
2f32ca6408e68efc06717a0937d7859b3abb69a8 | Add JsonWriter impl. that defaults to using a RendererMap | smarts/log4net.Ext.Json.Serializers | shared/RendererMapJsonTextWriter.cs | shared/RendererMapJsonTextWriter.cs | using System.IO;
using log4net.ObjectRenderer;
using log4net.Util.Serializer;
namespace Newtonsoft.Json.Serialization
{
public class RendererMapJsonTextWriter : JsonTextWriter
{
private readonly RendererMap rendererMap;
private readonly TextWriter textWriter;
public RendererMapJsonTextWriter(RendererMap rendererMap, TextWriter textWriter) :
base(textWriter)
{
this.textWriter = textWriter;
this.rendererMap = rendererMap;
}
public override void WriteValue(object value)
{
if (value == null)
{
base.WriteValue(value);
}
else
{
var renderer = this.rendererMap.Get(value);
if (renderer == null)
{
base.WriteValue(value);
}
else
{
Render(value, renderer);
}
}
}
private void Render(object value, IObjectRenderer renderer)
{
var serializer = renderer as ISerializer;
if (serializer == null)
{
renderer.RenderObject(this.rendererMap, value, this.textWriter);
}
else
{
Serialize(value, serializer);
}
}
private void Serialize(object value, ISerializer serializer)
{
this.textWriter.Write(serializer.Serialize(value));
}
}
}
| mit | C# | |
37cc9fa2a667c37c26864d2f6bbc954c89fe43bf | Add CSharp (C#) Cycle sort | ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms | sort/cycle_sort/csharp/CycleSort.cs | sort/cycle_sort/csharp/CycleSort.cs | // C# program to implement cycle sort
using System;
class GFG {
// Function sort the array using Cycle sort
public static void CycleSort(int[] arr, int n)
{
// count number of memory writes
int writes = 0;
// traverse array elements and
// put it to on the right place
for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++)
{
// initialize item as starting point
int item = arr[cycle_start];
// Find position where we put the item.
// We basically count all smaller elements
// on right side of item.
int pos = cycle_start;
for (int i = cycle_start + 1; i < n; i++)
if (arr[i] < item)
pos++;
// If item is already in correct position
if (pos == cycle_start)
continue;
// ignore all duplicate elements
while (item == arr[pos])
pos += 1;
// put the item to it's right position
if (pos != cycle_start) {
int temp = item;
item = arr[pos];
arr[pos] = temp;
writes++;
}
// Rotate rest of the cycle
while (pos != cycle_start) {
pos = cycle_start;
// Find position where we put the element
for (int i = cycle_start + 1; i < n; i++)
if (arr[i] < item)
pos += 1;
// ignore all duplicate elements
while (item == arr[pos])
pos += 1;
// put the item to it's right position
if (item != arr[pos]) {
int temp = item;
item = arr[pos];
arr[pos] = temp;
writes++;
}
}
}
}
// Driver program to test above function
public static void Main()
{
int[] arr = { 1, 8, 3, 9, 10, 10, 2, 4 };
int n = arr.Length;
// Function calling
CycleSort(arr, n);
Console.Write("After sort : ");
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
}
// This code is contributed by Nitin Mittal
// https://www.geeksforgeeks.org/cycle-sort/ | cc0-1.0 | C# | |
2fd125c2127bc9579976e70b925e873f099b783e | Make VSWorkspace.GetProjectGuid accessible to XAML (#36225) | stephentoub/roslyn,CyrusNajmabadi/roslyn,tannergooding/roslyn,dotnet/roslyn,dotnet/roslyn,diryboy/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,nguerrera/roslyn,reaction1989/roslyn,diryboy/roslyn,brettfo/roslyn,heejaechang/roslyn,brettfo/roslyn,panopticoncentral/roslyn,mavasani/roslyn,davkean/roslyn,aelij/roslyn,jasonmalinowski/roslyn,AlekseyTs/roslyn,genlu/roslyn,reaction1989/roslyn,KevinRansom/roslyn,gafter/roslyn,stephentoub/roslyn,genlu/roslyn,weltkante/roslyn,agocke/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,AlekseyTs/roslyn,brettfo/roslyn,KirillOsenkov/roslyn,aelij/roslyn,tmat/roslyn,abock/roslyn,wvdd007/roslyn,nguerrera/roslyn,eriawan/roslyn,jmarolf/roslyn,AmadeusW/roslyn,AmadeusW/roslyn,KevinRansom/roslyn,stephentoub/roslyn,nguerrera/roslyn,jmarolf/roslyn,aelij/roslyn,tmat/roslyn,dotnet/roslyn,mgoertz-msft/roslyn,wvdd007/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,tmat/roslyn,AlekseyTs/roslyn,physhi/roslyn,bartdesmet/roslyn,davkean/roslyn,sharwell/roslyn,panopticoncentral/roslyn,physhi/roslyn,ErikSchierboom/roslyn,davkean/roslyn,heejaechang/roslyn,ErikSchierboom/roslyn,mavasani/roslyn,ErikSchierboom/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,abock/roslyn,KevinRansom/roslyn,KirillOsenkov/roslyn,panopticoncentral/roslyn,sharwell/roslyn,eriawan/roslyn,KirillOsenkov/roslyn,eriawan/roslyn,agocke/roslyn,mgoertz-msft/roslyn,gafter/roslyn,abock/roslyn,heejaechang/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,mavasani/roslyn,physhi/roslyn,mgoertz-msft/roslyn,agocke/roslyn,genlu/roslyn,gafter/roslyn,weltkante/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,bartdesmet/roslyn,reaction1989/roslyn,tannergooding/roslyn,bartdesmet/roslyn,jmarolf/roslyn | src/VisualStudio/Xaml/Impl/Extensions.cs | src/VisualStudio/Xaml/Impl/Extensions.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 Microsoft.VisualStudio.LanguageServices;
namespace Microsoft.CodeAnalysis.Editor.Xaml
{
internal static class Extensions
{
public static Guid GetProjectGuid(this VisualStudioWorkspace workspace, ProjectId projectId)
=> workspace.GetProjectGuid(projectId);
}
}
| mit | C# | |
fbcddd2008c690e5689474e058b18b0d0dfb2c9b | Remove error message giving away path location if not accessing from the local machine | rytmis/dotless,modulexcite/dotless,r2i-sitecore/dotless,rytmis/dotless,modulexcite/dotless,r2i-sitecore/dotless,modulexcite/dotless,r2i-sitecore/dotless,rytmis/dotless,dotless/dotless,rytmis/dotless,r2i-sitecore/dotless,r2i-sitecore/dotless,modulexcite/dotless,modulexcite/dotless,rytmis/dotless,modulexcite/dotless,rytmis/dotless,modulexcite/dotless,rytmis/dotless,r2i-sitecore/dotless,dotless/dotless,r2i-sitecore/dotless | src/dotless.AspNet/LessCssHttpHandler.cs | src/dotless.AspNet/LessCssHttpHandler.cs | namespace dotless.Core
{
using System.Web;
using System.Web.SessionState;
public class LessCssWithSessionHttpHandler : LessCssHttpHandler, IRequiresSessionState
{
}
public class LessCssHttpHandler : LessCssHttpHandlerBase, IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
try
{
var handler = Container.GetInstance<HandlerImpl>();
handler.Execute();
}
catch (System.IO.FileNotFoundException ex)
{
context.Response.StatusCode = 404;
if (context.Request.IsLocal)
{
context.Response.Write("/* File Not Found while parsing: " + ex.Message + " */");
}
else
{
context.Response.Write("/* Error Occurred. Consult log or view on local machine. */");
}
context.Response.End();
}
catch (System.IO.IOException ex)
{
context.Response.StatusCode = 500;
if (context.Request.IsLocal)
{
context.Response.Write("/* Error in less parsing: " + ex.Message + " */");
}
else
{
context.Response.Write("/* Error Occurred. Consult log or view on local machine. */");
}
context.Response.End();
}
}
public bool IsReusable
{
get { return true; }
}
}
}
| namespace dotless.Core
{
using System.Web;
using System.Web.SessionState;
public class LessCssWithSessionHttpHandler : LessCssHttpHandler, IRequiresSessionState
{
}
public class LessCssHttpHandler : LessCssHttpHandlerBase, IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
try
{
var handler = Container.GetInstance<HandlerImpl>();
handler.Execute();
}
catch (System.IO.FileNotFoundException ex)
{
context.Response.StatusCode = 404;
context.Response.Write("/* File Not Found while parsing: " + ex.Message + " */");
context.Response.End();
}
catch (System.IO.IOException ex)
{
context.Response.StatusCode = 500;
context.Response.Write("/* Error in less parsing: " + ex.Message + " */");
context.Response.End();
}
}
public bool IsReusable
{
get { return true; }
}
}
}
| apache-2.0 | C# |
067e18242d6a38e2fc9626ff2d37efc180f8a9d1 | refactor so the response model creation can be reused | half-ogre/qed,Haacked/qed | RequestHandlers/GetBuilds.cs | RequestHandlers/GetBuilds.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using fn = qed.Functions;
namespace qed
{
public static partial class Handlers
{
public static async Task GetBuilds(
IDictionary<string, object> environment,
dynamic @params,
Func<IDictionary<string, object>, Task> next)
{
var owner = @params.owner as string;
var name = @params.name as string;
var buildConfiguration = fn.GetBuildConfiguration(owner, name);
if (buildConfiguration == null)
{
environment.SetStatusCode(400);
return;
}
var responseModel = new
{
owner = buildConfiguration.Owner,
name = buildConfiguration.Name,
builds = CreateBuildsResponseModel(buildConfiguration)
};
await environment.Render(
"builds",
responseModel);
}
static object CreateBuildsResponseModel(BuildConfiguration buildConfiguration)
{
return fn.GetBuilds(buildConfiguration.Owner, buildConfiguration.Name)
.Reverse()
.Select(build => new
{
id = build.Id,
description = fn.GetBuildDescription(build, true),
status = GetBuildStatus(build)
});
}
static string GetBuildStatus(Build build)
{
if (build.Started == null)
return "queued";
if (build.Finished == null)
return "building";
if (build.Succeeded.HasValue && build.Succeeded.Value)
return "succeeded";
return "failed";
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using fn = qed.Functions;
namespace qed
{
public static partial class Handlers
{
public static async Task GetBuilds(
IDictionary<string, object> environment,
dynamic @params,
Func<IDictionary<string, object>, Task> next)
{
var owner = @params.owner as string;
var name = @params.name as string;
var buildConfiguration = fn.GetBuildConfiguration(owner, name);
if (buildConfiguration == null)
{
environment.SetStatusCode(400);
return;
}
var builds = fn.GetBuilds(buildConfiguration.Owner, buildConfiguration.Name)
.Reverse()
.Select(build => new {
id = build.Id,
description = fn.GetBuildDescription(build, true),
status = GetBuildStatus(build)
});
await environment.Render("builds", new
{
owner = buildConfiguration.Owner,
name = buildConfiguration.Name,
builds
});
}
static string GetBuildStatus(Build build)
{
if (build.Started == null)
return "queued";
if (build.Finished == null)
return "building";
if (build.Succeeded.HasValue && build.Succeeded.Value)
return "succeeded";
return "failed";
}
}
}
| mit | C# |
d495826e0448cd110d8b8564c52b75656ee027a9 | Add a C# style Point class | BillWagner/TourOfCSharp6 | TourOfCSharp6/Point.cs | TourOfCSharp6/Point.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TourOfCSharp6
{
public class Point
{
public double X { get; set; }
public double Y { get; set; }
public double Distance
{
get
{
return Math.Sqrt(X * X + Y * Y);
}
}
}
}
| mit | C# | |
da6fdb7be6a4cf377e7ea592531884b0b21f77f4 | Add a sanity check for exported types | Abc-Arbitrage/ZeroLog | src/ZeroLog.Tests/SanityChecks.cs | src/ZeroLog.Tests/SanityChecks.cs | using System.Linq;
using NUnit.Framework;
using ZeroLog.Tests.Support;
namespace ZeroLog.Tests;
[TestFixture]
public class SanityChecks
{
[Test]
public void should_export_expected_types()
{
// This test prevents mistakenly adding public types in the future.
var publicTypes = new[]
{
"ZeroLog.Appenders.Appender",
"ZeroLog.Appenders.ConsoleAppender",
"ZeroLog.Appenders.DateAndSizeRollingFileAppender",
"ZeroLog.Appenders.NoopAppender",
"ZeroLog.Appenders.StreamAppender",
"ZeroLog.Configuration.AppenderConfiguration",
"ZeroLog.Configuration.LoggerConfiguration",
"ZeroLog.Configuration.LogMessagePoolExhaustionStrategy",
"ZeroLog.Configuration.RootLoggerConfiguration",
"ZeroLog.Configuration.ZeroLogConfiguration",
"ZeroLog.Formatting.FormattedLogMessage",
"ZeroLog.Log",
"ZeroLog.Log+DebugInterpolatedStringHandler",
"ZeroLog.Log+ErrorInterpolatedStringHandler",
"ZeroLog.Log+FatalInterpolatedStringHandler",
"ZeroLog.Log+InfoInterpolatedStringHandler",
"ZeroLog.Log+TraceInterpolatedStringHandler",
"ZeroLog.Log+WarnInterpolatedStringHandler",
"ZeroLog.LogLevel",
"ZeroLog.LogManager",
"ZeroLog.LogMessage",
"ZeroLog.LogMessage+AppendInterpolatedStringHandler",
"ZeroLog.UnmanagedFormatterDelegate`1",
};
typeof(LogManager).Assembly
.ExportedTypes
.Select(i => i.FullName)
.ShouldBeEquivalentTo(publicTypes);
}
}
| mit | C# | |
87a9d293da8126390867235872a5c5d3b95c2edc | Add missing file from code config branch | kvr000/spring-net,zi1jing/spring-net,yonglehou/spring-net,djechelon/spring-net,djechelon/spring-net,spring-projects/spring-net,zi1jing/spring-net,spring-projects/spring-net,kvr000/spring-net,dreamofei/spring-net,likesea/spring-net,yonglehou/spring-net,likesea/spring-net,yonglehou/spring-net,likesea/spring-net,kvr000/spring-net,spring-projects/spring-net,dreamofei/spring-net | src/Spring/Spring.Core/Objects/Factory/Parsing/IProblemReporter.cs | src/Spring/Spring.Core/Objects/Factory/Parsing/IProblemReporter.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace Spring.Objects.Factory.Parsing
{
public interface IProblemReporter
{
void Fatal(Problem problem);
void Warning(Problem problem);
void Error(Problem problem);
}
}
| apache-2.0 | C# | |
a9c30df281ecf47a6ed0d7e78ed0fc4b740ced38 | Add simple snippet to get InformationalVersion | lerthe61/Snippets,lerthe61/Snippets | dotNet/Version/VersionHelper.cs | dotNet/Version/VersionHelper.cs | public static string GetProductVersion()
{
var attribute = (AssemblyVersionAttribute)Assembly
.GetExecutingAssembly()
.GetCustomAttributes( typeof(AssemblyVersionAttribute), true )
.Single();
return attribute.InformationalVersion;
} | unlicense | C# | |
e04b080ac6eeefa058a0aad13ce581acad5a1132 | Create MagicResistanceB.cs | Keripo/fgo-data | webservice/src/Models/Data/PassiveSkills/MagicResistanceB.cs | webservice/src/Models/Data/PassiveSkills/MagicResistanceB.cs | using FGOData.Models.Serialization;
using System.Collections.Generic;
namespace FGOData.Models.Data
{
public class MagicResistanceB : PassiveSkill
{
public MagicResistanceB()
{
Name_EN = "Magic Resistance B";
Name_JP = "対魔力 B";
Effects = new List<Effect>
{
new Effect()
{
EffectType = EffectType.DebuffResist,
EffectValuesType = EffectValueType.Percent,
EffectValues = new List<float>
{
17.5f
}
}
};
}
}
}
| apache-2.0 | C# | |
455e7dce970f1dc703270b808c25d1c1687a4ec5 | add the 4-th subchapter from ch 2 | ordinary-developer/education,ordinary-developer/education,ordinary-developer/education,ordinary-developer/education,ordinary-developer/education,ordinary-developer/education,ordinary-developer/education | books/techno/.net/c#_6.0_in_a_nutshell_6_ed_j_albahari/ch_2-c#_language_basics/04-boolean_type_and_operators/main.cs | books/techno/.net/c#_6.0_in_a_nutshell_6_ed_j_albahari/ch_2-c#_language_basics/04-boolean_type_and_operators/main.cs | using System;
class Test
{
class Dude
{
public string Name;
public Dude (string n) { Name = n; }
}
static void Example1_EqualityAndComparisonOperators()
{
int x = 1;
int y = 2;
int z = 1;
Console.WriteLine(x == y);
Console.WriteLine(x == z);
Dude d1 = new Dude("John");
Dude d2 = new Dude("John");
Console.WriteLine(d1 == d2);
Dude d3 = d1;
Console.WriteLine(d1 == d3);
}
static bool UseUmbrella1(bool rainy, bool sunny, bool windy)
{
return !windy && (rainy || sunny);
}
static bool UseUmbrella2(bool rainy, bool sunny, bool windy)
{
return !windy & (rainy | sunny);
}
static void Example2_ConditionalOperators()
{
bool toTakeUmbrella = UseUmbrella1(true, false, false);
Console.WriteLine(toTakeUmbrella);
toTakeUmbrella = UseUmbrella2(true, false, false);
Console.WriteLine(toTakeUmbrella);
}
static int Max(int a, int b)
{
return (a > b) ? a : b;
}
static void Example3_TernaryOperator()
{
Console.WriteLine(Max(3, 5));
}
static void Main()
{
Example1_EqualityAndComparisonOperators();
Example2_ConditionalOperators();
Example3_TernaryOperator();
}
}
| mit | C# | |
b3e420d423dd65cb4d9b1be6d0f2ac71e6ff3db9 | Bump to 1.6 | JustArchi/ArchiSteamFarm,KlappPc/ArchiSteamFarm,i3at/ArchiSteamFarm,JustArchi/ArchiSteamFarm,i3at/ArchiSteamFarm,JustArchi/ArchiSteamFarm,blackpanther989/ArchiSteamFarm,KlappPc/ArchiSteamFarm,blackpanther989/ArchiSteamFarm,JustArchi/ArchiSteamFarm,KlappPc/ArchiSteamFarm | ArchiSteamFarm/Properties/AssemblyInfo.cs | ArchiSteamFarm/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("ArchiSteamFarm")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ArchiSteamFarm")]
[assembly: AssemblyCopyright("Copyright © Łukasz Domeradzki 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("35af7887-08b9-40e8-a5ea-797d8b60b30c")]
// 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.6.0.0")]
[assembly: AssemblyFileVersion("1.6.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ArchiSteamFarm")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ArchiSteamFarm")]
[assembly: AssemblyCopyright("Copyright © Łukasz Domeradzki 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("35af7887-08b9-40e8-a5ea-797d8b60b30c")]
// 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.5.0.0")]
[assembly: AssemblyFileVersion("1.5.0.0")]
| apache-2.0 | C# |
1384a08976698f8fb282022f07418dceb7d83bc3 | Add a testcase for unknown frame types | Matthias247/http2dotnet | Http2Tests/ConnectionUnknownFrameTests.cs | Http2Tests/ConnectionUnknownFrameTests.cs | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
using Http2;
namespace Http2Tests
{
public class ConnectionUnknownFrameTests
{
[Theory]
[InlineData(true, 0)]
[InlineData(true, 512)]
[InlineData(false, 0)]
[InlineData(false, 512)]
public async Task ConnectionShouldIgnoreUnknownFramesWithPong(
bool isServer, int payloadLength)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var http2Con = await ConnectionUtils.BuildEstablishedConnection(
isServer, inPipe, outPipe);
// send an undefined frame type
var fh = new FrameHeader
{
Type = (FrameType)100,
Flags = 33,
Length = payloadLength,
StreamId = 0,
};
await inPipe.WriteFrameHeader(fh);
if (payloadLength != 0)
{
var payload = new byte[payloadLength];
await inPipe.WriteAsync(new ArraySegment<byte>(payload));
}
// Send a ping afterwards
// If we get a response the unknown frame in between was ignored
var pingData = new byte[8];
for (var i = 0; i < 8; i++) pingData[i] = (byte)i;
await inPipe.WritePing(pingData, false);
var res = await outPipe.ReadFrameHeaderWithTimeout();
Assert.Equal(FrameType.Ping, res.Type);
Assert.Equal(0u, res.StreamId);
Assert.Equal(8, res.Length);
Assert.Equal((byte)PingFrameFlags.Ack, res.Flags);
var pongData = new byte[8];
await outPipe.ReadAllWithTimeout(new ArraySegment<byte>(pongData));
}
}
} | mit | C# | |
71fb7c5b1b1c4d0de4dfa4d3feeb73234cdfb239 | Update WriteJSONTest to initialize TiledNavMesh with non-null parameter | unity-chicken/SharpNav,sangdaekim/SharpNav,sangdaekim/SharpNav,unity-chicken/SharpNav | SharpNavTests/JSONTests.cs | SharpNavTests/JSONTests.cs | #region License
/**
* Copyright (c) 2013-2014 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file).
* Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using SharpNav;
using SharpNav.Geometry;
#if MONOGAME || XNA
using Microsoft.Xna.Framework;
#elif OPENTK
using OpenTK;
#elif SHARPDX
using SharpDX;
#elif UNITY3D
using UnityEngine;
#endif
namespace SharpNavTests
{
[TestFixture]
public class JSONTests
{
[Test]
public void WriteJSONTest()
{
NavMeshGenerationSettings settings = NavMeshGenerationSettings.Default;
CompactHeightfield heightField = new CompactHeightfield(new Heightfield(
new BBox3(1, 1, 1, 5, 5, 5), settings), settings);
PolyMesh polyMesh = new PolyMesh(new ContourSet(heightField, settings), 8);
PolyMeshDetail polyMeshDetail = new PolyMeshDetail(polyMesh, heightField, settings);
NavMeshBuilder buildData = new NavMeshBuilder(polyMesh, polyMeshDetail, new SharpNav.Pathfinding.OffMeshConnection[0], settings);
TiledNavMesh mesh = new TiledNavMesh(buildData);
mesh.SaveJson("mesh.json");
}
[Test]
public void ReadJSONTest()
{
TiledNavMesh mesh = TiledNavMesh.LoadJson("mesh.json");
}
}
}
| #region License
/**
* Copyright (c) 2013-2014 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file).
* Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using SharpNav;
using SharpNav.Geometry;
#if MONOGAME || XNA
using Microsoft.Xna.Framework;
#elif OPENTK
using OpenTK;
#elif SHARPDX
using SharpDX;
#elif UNITY3D
using UnityEngine;
#endif
namespace SharpNavTests
{
[TestFixture]
public class JSONTests
{
[Test]
public void WriteJSONTest()
{
TiledNavMesh mesh = new TiledNavMesh(null);
mesh.SaveJson("mesh.json");
}
[Test]
public void ReadJSONTest()
{
TiledNavMesh mesh = TiledNavMesh.LoadJson("mesh.json");
}
}
}
| mit | C# |
ff421475da35461991799717d98490f57c53a914 | Create SnapshotExtension.cs | NMSLanX/Natasha | Natasha/ExtensionApi/SnapshotExtension.cs | Natasha/ExtensionApi/SnapshotExtension.cs | using System.Collections.Generic;
namespace Natasha.Snapshot
{
public static class SnapshotExtension
{
public static void MakeSnapshot<T>(this T instance)
{
SnapshotOperator.MakeSnapshot(instance);
}
public static Dictionary<string,DiffModel> Compare<T>(this T instance)
{
return SnapshotOperator.Compare(instance);
}
}
}
| mpl-2.0 | C# | |
25866da2b6d8618ebf683f550261238ccaf30d7d | Add test case | gep13/GitVersion,asbjornu/GitVersion,asbjornu/GitVersion,GitTools/GitVersion,gep13/GitVersion,GitTools/GitVersion | src/GitVersion.Core.Tests/Configuration/ConfigExtensionsTests.cs | src/GitVersion.Core.Tests/Configuration/ConfigExtensionsTests.cs | using GitVersion.Configuration;
using GitVersion.Core.Tests.Helpers;
using GitVersion.Model.Configuration;
using NUnit.Framework;
using Shouldly;
namespace GitVersion.Core.Tests.Configuration;
[TestFixture]
public class ConfigExtensionsTests : TestBase
{
[Test]
public void GetReleaseBranchConfigReturnsAllReleaseBranches()
{
var config = new Config()
{
Branches = new Dictionary<string, BranchConfig>
{
{ "foo", new BranchConfig { Name = "foo" } },
{ "bar", new BranchConfig { Name = "bar", IsReleaseBranch = true } },
{ "baz", new BranchConfig { Name = "baz", IsReleaseBranch = true } }
}
};
var result = config.GetReleaseBranchConfig();
result.Count.ShouldBe(2);
result.ShouldNotContain(b => b.Key == "foo");
}
}
| mit | C# | |
f8dc0b4022ed6616fdc8b63e10bec00ffd70965b | Create StringFrequencyChallenge.cs | Zephyr-Koo/sololearn-challenge | StringFrequencyChallenge.cs | StringFrequencyChallenge.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// https://www.sololearn.com/Discuss/654194/?ref=app
namespace SoloLearn
{
class Program
{
static void Main(string[] zephyr_koo)
{
var input = "PROGRAMMING"; // Console.ReadLine();
DisplayCharacterFrequency(input);
}
static void DisplayCharacterFrequency(string str)
{
foreach (var character in str.Distinct())
{
Console.WriteLine($"{ character } = { str.Count(c => c == character) }");
}
}
}
}
| apache-2.0 | C# | |
43923885b5d07ddcacfb0ae3b97a8bfd8694533f | Create SuperPerfectNumChallenge.cs | Zephyr-Koo/sololearn-challenge | SuperPerfectNumChallenge.cs | SuperPerfectNumChallenge.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//https://www.sololearn.com/Discuss/646305/?ref=app
namespace SoloLearn
{
class Program
{
static void Main(string[] zephyr_koo)
{
var input = Console.ReadLine();
int number;
if (Int32.TryParse(input, out number))
{
Console.WriteLine($"Superperfect number(s) within { number } : { string.Join(", ", GetSuperPerfectNumber(number)) }");
}
}
static IEnumerable<int> GetSuperPerfectNumber(int limit)
{
var perfNumberList = new List<int>();
for (int n = 1; n <= limit; n++)
{
if (GetSumOfFactors(GetSumOfFactors(n)) == n * 2)
{
perfNumberList.Add(n);
}
}
return perfNumberList;
}
static int GetSumOfFactors(int number)
{
var sqrt = Math.Sqrt(number);
return Enumerable
.Range(1, (int)sqrt)
.Where(n => (number % n == 0))
.Sum(n => n + (number / n)) -
(Math.Ceiling(sqrt) == Math.Floor(sqrt) ? (int)sqrt : 0); // remove double count for perfect square
}
}
}
| apache-2.0 | C# | |
1d6d843b4188f8ca231828f5b615931a88b83f3f | Create kod.cs | Nazarewicz/prywatnemw | kod.cs | kod.cs | int a = 2;
| mit | C# | |
2cb75380e138b52ac0a0b9341d44ac1103ce13dc | Add a test for #724 | riganti/dotvvm,riganti/dotvvm,riganti/dotvvm,riganti/dotvvm | src/DotVVM.Framework.Tests.Common/ViewModel/ValidationErrorFactoryTests.cs | src/DotVVM.Framework.Tests.Common/ViewModel/ValidationErrorFactoryTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using DotVVM.Framework.ViewModel.Validation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DotVVM.Framework.Tests.Common.ViewModel
{
[TestClass]
public class ValidationErrorFactoryTests
{
[TestMethod]
public void ValidationErrorFactory_GetPathFromExpression_WithLocalVariable()
{
var index = 1;
var expression = ValidationErrorFactory.GetPathFromExpression(
DotvvmTestHelper.DefaultConfig,
(Expression<Func<TestViewModel, int>>)(vm => vm.Numbers[index]));
}
private class TestViewModel
{
public int[] Numbers { get; set; } = new[] { 0, 1, 1, 2, 3, 5 };
}
}
}
| apache-2.0 | C# | |
874eebd87a9a3c90c8d208dfed8241f5f7e01aa2 | Create LegendaryDroppedPopup.cs | prrovoss/THUD | plugins/Prrovoss/LegendaryDroppedPopup.cs | plugins/Prrovoss/LegendaryDroppedPopup.cs | using Turbo.Plugins.Default;
namespace Turbo.Plugins.Prrovoss
{
public class LegendaryDroppedPopup : BasePlugin, ILootGeneratedHandler
{
public void OnLootGenerated(IItem item, bool gambled)
{
if (item.Quality >= ItemQuality.Legendary)
Hud.GetPlugin<PopupNotifications>().Show(item.SnoItem.NameLocalized + (item.AncientRank == 1 ? " (A)" : ""), "Legendary dropped", 10000, "my hint");
}
public LegendaryDroppedPopup()
{
Enabled = true;
}
}
}
| mit | C# | |
c17c806fb0ee84a9f3c5f8b65e0670ca80948296 | Add `PcscReaderStatus` class | Archie-Yang/PcscDotNet | src/PcscDotNet/PcscReaderStatus.cs | src/PcscDotNet/PcscReaderStatus.cs | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
namespace PcscDotNet
{
public delegate void PcscReaderStatusAction(PcscReaderStatus readerStatus);
public abstract class PcscReaderStatus : ReadOnlyCollection<PcscReaderState>
{
/// <summary>
/// This special reader name is used to be notified when a reader is added to or removed from the system through `SCardGetStatusChange`.
/// </summary>
public const string PnPReaderName = "\\\\?PnP?\\Notification";
protected readonly PcscContext Context;
public PcscReaderStatus(PcscContext context, IList<string> readerNames) : base(new List<PcscReaderState>(readerNames.Count))
{
Context = context;
foreach (var readerName in readerNames)
{
Items.Add(new PcscReaderState() { ReaderName = readerName });
}
}
public PcscReaderStatus Do(PcscReaderStatusAction action)
{
action(this);
return this;
}
public abstract PcscReaderStatus WaitForChanged(int timeout = Timeout.Infinite);
}
}
| mit | C# | |
30a466a2209835d195a79a664fef79b47d3e3586 | Create CollectionModeDescription.cs | MingLu8/Nancy.WebApi.HelpPages | src/Nancy.WebApi.HelpPages.Demo/HelpPage/ModelDescriptions/CollectionModeDescription.cs | src/Nancy.WebApi.HelpPages.Demo/HelpPage/ModelDescriptions/CollectionModeDescription.cs | namespace WebApplication1.Areas.HelpPage.ModelDescriptions
{
public class CollectionModelDescription : ModelDescription
{
public ModelDescription ElementDescription { get; set; }
}
}
| mit | C# | |
d7dec4ded2b8faa836c7fad5148f25fdab997296 | Add a test for TwoDigitYearMax to KoreanCalendar | shahid-pk/corefx,Petermarcu/corefx,alexperovich/corefx,shmao/corefx,mmitche/corefx,jlin177/corefx,ericstj/corefx,richlander/corefx,ptoonen/corefx,weltkante/corefx,cydhaselton/corefx,tijoytom/corefx,ptoonen/corefx,rahku/corefx,shimingsg/corefx,dsplaisted/corefx,mazong1123/corefx,krytarowski/corefx,adamralph/corefx,richlander/corefx,SGuyGe/corefx,twsouthwick/corefx,twsouthwick/corefx,axelheer/corefx,mazong1123/corefx,marksmeltzer/corefx,iamjasonp/corefx,tstringer/corefx,ellismg/corefx,fgreinacher/corefx,rubo/corefx,shahid-pk/corefx,richlander/corefx,SGuyGe/corefx,billwert/corefx,dotnet-bot/corefx,gkhanna79/corefx,MaggieTsang/corefx,manu-silicon/corefx,alexperovich/corefx,weltkante/corefx,iamjasonp/corefx,shimingsg/corefx,DnlHarvey/corefx,rahku/corefx,JosephTremoulet/corefx,billwert/corefx,dsplaisted/corefx,alexperovich/corefx,tstringer/corefx,wtgodbe/corefx,ViktorHofer/corefx,rubo/corefx,nchikanov/corefx,fgreinacher/corefx,jlin177/corefx,rjxby/corefx,yizhang82/corefx,jlin177/corefx,shmao/corefx,parjong/corefx,jlin177/corefx,jhendrixMSFT/corefx,dhoehna/corefx,billwert/corefx,Priya91/corefx-1,ViktorHofer/corefx,JosephTremoulet/corefx,ViktorHofer/corefx,wtgodbe/corefx,krk/corefx,rahku/corefx,yizhang82/corefx,axelheer/corefx,weltkante/corefx,dhoehna/corefx,nchikanov/corefx,fgreinacher/corefx,iamjasonp/corefx,DnlHarvey/corefx,JosephTremoulet/corefx,manu-silicon/corefx,SGuyGe/corefx,yizhang82/corefx,Ermiar/corefx,Priya91/corefx-1,dhoehna/corefx,jhendrixMSFT/corefx,richlander/corefx,ravimeda/corefx,ericstj/corefx,seanshpark/corefx,khdang/corefx,jlin177/corefx,shmao/corefx,shmao/corefx,seanshpark/corefx,axelheer/corefx,tijoytom/corefx,lggomez/corefx,rjxby/corefx,alphonsekurian/corefx,ellismg/corefx,khdang/corefx,elijah6/corefx,ViktorHofer/corefx,nchikanov/corefx,wtgodbe/corefx,alexperovich/corefx,iamjasonp/corefx,SGuyGe/corefx,alphonsekurian/corefx,MaggieTsang/corefx,yizhang82/corefx,elijah6/corefx,dotnet-bot/corefx,Chrisboh/corefx,nchikanov/corefx,stone-li/corefx,alexperovich/corefx,cydhaselton/corefx,Priya91/corefx-1,ViktorHofer/corefx,YoupHulsebos/corefx,nbarbettini/corefx,shahid-pk/corefx,dotnet-bot/corefx,khdang/corefx,rubo/corefx,khdang/corefx,billwert/corefx,gkhanna79/corefx,ptoonen/corefx,BrennanConroy/corefx,Petermarcu/corefx,YoupHulsebos/corefx,marksmeltzer/corefx,shmao/corefx,dotnet-bot/corefx,shahid-pk/corefx,YoupHulsebos/corefx,weltkante/corefx,nbarbettini/corefx,adamralph/corefx,jhendrixMSFT/corefx,jhendrixMSFT/corefx,krytarowski/corefx,ericstj/corefx,dhoehna/corefx,mmitche/corefx,manu-silicon/corefx,shimingsg/corefx,nbarbettini/corefx,krytarowski/corefx,the-dwyer/corefx,MaggieTsang/corefx,Jiayili1/corefx,marksmeltzer/corefx,iamjasonp/corefx,cydhaselton/corefx,cartermp/corefx,marksmeltzer/corefx,the-dwyer/corefx,manu-silicon/corefx,billwert/corefx,ravimeda/corefx,shimingsg/corefx,cartermp/corefx,tijoytom/corefx,manu-silicon/corefx,krk/corefx,parjong/corefx,krk/corefx,stone-li/corefx,DnlHarvey/corefx,gkhanna79/corefx,stephenmichaelf/corefx,Chrisboh/corefx,tstringer/corefx,rjxby/corefx,SGuyGe/corefx,tstringer/corefx,lggomez/corefx,dsplaisted/corefx,shahid-pk/corefx,marksmeltzer/corefx,dotnet-bot/corefx,Chrisboh/corefx,ravimeda/corefx,stone-li/corefx,shimingsg/corefx,Priya91/corefx-1,ravimeda/corefx,richlander/corefx,zhenlan/corefx,iamjasonp/corefx,alphonsekurian/corefx,wtgodbe/corefx,alexperovich/corefx,krytarowski/corefx,rahku/corefx,ravimeda/corefx,jhendrixMSFT/corefx,the-dwyer/corefx,ericstj/corefx,rahku/corefx,lggomez/corefx,Priya91/corefx-1,zhenlan/corefx,zhenlan/corefx,YoupHulsebos/corefx,DnlHarvey/corefx,wtgodbe/corefx,axelheer/corefx,twsouthwick/corefx,axelheer/corefx,parjong/corefx,Petermarcu/corefx,MaggieTsang/corefx,parjong/corefx,lggomez/corefx,ericstj/corefx,JosephTremoulet/corefx,ericstj/corefx,YoupHulsebos/corefx,alexperovich/corefx,twsouthwick/corefx,twsouthwick/corefx,ViktorHofer/corefx,zhenlan/corefx,elijah6/corefx,JosephTremoulet/corefx,tstringer/corefx,alphonsekurian/corefx,seanshpark/corefx,cartermp/corefx,shahid-pk/corefx,Jiayili1/corefx,stephenmichaelf/corefx,the-dwyer/corefx,tstringer/corefx,cartermp/corefx,marksmeltzer/corefx,Petermarcu/corefx,dhoehna/corefx,wtgodbe/corefx,nchikanov/corefx,jhendrixMSFT/corefx,stone-li/corefx,cydhaselton/corefx,ellismg/corefx,axelheer/corefx,Jiayili1/corefx,iamjasonp/corefx,yizhang82/corefx,mazong1123/corefx,elijah6/corefx,gkhanna79/corefx,Chrisboh/corefx,Ermiar/corefx,manu-silicon/corefx,seanshpark/corefx,seanshpark/corefx,ptoonen/corefx,stone-li/corefx,Ermiar/corefx,cydhaselton/corefx,Petermarcu/corefx,ellismg/corefx,MaggieTsang/corefx,richlander/corefx,rjxby/corefx,marksmeltzer/corefx,alphonsekurian/corefx,dotnet-bot/corefx,jlin177/corefx,mazong1123/corefx,twsouthwick/corefx,zhenlan/corefx,DnlHarvey/corefx,dhoehna/corefx,Ermiar/corefx,weltkante/corefx,mmitche/corefx,dotnet-bot/corefx,ptoonen/corefx,rahku/corefx,Petermarcu/corefx,weltkante/corefx,SGuyGe/corefx,seanshpark/corefx,nbarbettini/corefx,khdang/corefx,parjong/corefx,seanshpark/corefx,mazong1123/corefx,cydhaselton/corefx,rjxby/corefx,Jiayili1/corefx,manu-silicon/corefx,tijoytom/corefx,rjxby/corefx,Ermiar/corefx,JosephTremoulet/corefx,DnlHarvey/corefx,JosephTremoulet/corefx,krk/corefx,mmitche/corefx,krytarowski/corefx,stone-li/corefx,rjxby/corefx,mmitche/corefx,mazong1123/corefx,nbarbettini/corefx,khdang/corefx,shmao/corefx,parjong/corefx,mmitche/corefx,MaggieTsang/corefx,alphonsekurian/corefx,rubo/corefx,tijoytom/corefx,rubo/corefx,shimingsg/corefx,adamralph/corefx,the-dwyer/corefx,ravimeda/corefx,zhenlan/corefx,cydhaselton/corefx,shimingsg/corefx,yizhang82/corefx,nchikanov/corefx,billwert/corefx,Chrisboh/corefx,Chrisboh/corefx,the-dwyer/corefx,YoupHulsebos/corefx,krk/corefx,jlin177/corefx,krytarowski/corefx,alphonsekurian/corefx,ellismg/corefx,billwert/corefx,zhenlan/corefx,dhoehna/corefx,ptoonen/corefx,elijah6/corefx,DnlHarvey/corefx,ericstj/corefx,yizhang82/corefx,YoupHulsebos/corefx,nbarbettini/corefx,ellismg/corefx,jhendrixMSFT/corefx,MaggieTsang/corefx,shmao/corefx,krytarowski/corefx,lggomez/corefx,tijoytom/corefx,mazong1123/corefx,Jiayili1/corefx,lggomez/corefx,stephenmichaelf/corefx,stephenmichaelf/corefx,nchikanov/corefx,ptoonen/corefx,cartermp/corefx,gkhanna79/corefx,Ermiar/corefx,stone-li/corefx,ravimeda/corefx,BrennanConroy/corefx,Jiayili1/corefx,Petermarcu/corefx,stephenmichaelf/corefx,Jiayili1/corefx,cartermp/corefx,BrennanConroy/corefx,fgreinacher/corefx,wtgodbe/corefx,krk/corefx,weltkante/corefx,Ermiar/corefx,nbarbettini/corefx,ViktorHofer/corefx,gkhanna79/corefx,elijah6/corefx,twsouthwick/corefx,the-dwyer/corefx,stephenmichaelf/corefx,lggomez/corefx,elijah6/corefx,gkhanna79/corefx,richlander/corefx,rahku/corefx,parjong/corefx,Priya91/corefx-1,stephenmichaelf/corefx,mmitche/corefx,krk/corefx,tijoytom/corefx | src/System.Globalization.Calendars/tests/KoreanCalendar/KoreanCalendarTwoDigitYearMax.cs | src/System.Globalization.Calendars/tests/KoreanCalendar/KoreanCalendarTwoDigitYearMax.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 Xunit;
namespace System.Globalization.Tests
{
public class KoreanCalendarTwoDigitYearMax
{
[Fact]
public void TwoDigitYearMax_Get()
{
Assert.Equal(4362, new KoreanCalendar().TwoDigitYearMax);
}
[Theory]
[InlineData(99)]
[InlineData(2016)]
public void TwoDigitYearMax_Set(int newTwoDigitYearMax)
{
Calendar calendar = new KoreanCalendar();
calendar.TwoDigitYearMax = newTwoDigitYearMax;
Assert.Equal(newTwoDigitYearMax, calendar.TwoDigitYearMax);
}
}
}
| // 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 Xunit;
namespace System.Globalization.Tests
{
public class KoreanCalendarTwoDigitYearMax
{
[Fact]
public void TwoDigitYearMax()
{
Assert.Equal(4362, new KoreanCalendar().TwoDigitYearMax);
}
}
}
| mit | C# |
e44e083a51e46367b20d17df4bc70491b048b357 | Create StorageService.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D | src/Core2D/Services/StorageService.cs | src/Core2D/Services/StorageService.cs | using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Platform.Storage;
using Avalonia.VisualTree;
namespace Core2D.Services;
internal static class StorageService
{
public static FilePickerFileType All { get; } = new("All")
{
Patterns = new[] { "*.*" },
MimeTypes = new[] { "*/*" }
};
public static FilePickerFileType Json { get; } = new("Json")
{
Patterns = new[] { "*.json" },
AppleUniformTypeIdentifiers = new[] { "public.json" },
MimeTypes = new[] { "application/json" }
};
public static FilePickerFileType CSharp { get; } = new("C#")
{
Patterns = new[] { "*.cs" },
AppleUniformTypeIdentifiers = new[] { "public.csharp-source" },
MimeTypes = new[] { "text/plain" }
};
public static FilePickerFileType ImagePng { get; } = new("PNG image")
{
Patterns = new[] { "*.png" },
AppleUniformTypeIdentifiers = new[] { "public.png" },
MimeTypes = new[] { "image/png" }
};
public static FilePickerFileType ImageJpg { get; } = new("JPEG image")
{
Patterns = new[] { "*.jpg", "*.jpeg" },
AppleUniformTypeIdentifiers = new[] { "public.jpeg" },
MimeTypes = new[] { "image/jpeg" }
};
public static FilePickerFileType ImageSkp { get; } = new("SKP image")
{
Patterns = new[] { "*.skp" },
AppleUniformTypeIdentifiers = new[] { "com.google.skp" },
MimeTypes = new[] { "image/skp" }
};
public static FilePickerFileType ImageAll { get; } = new("All Images")
{
Patterns = new[] { "*.png", "*.jpg", "*.jpeg", "*.bmp" },
AppleUniformTypeIdentifiers = new[] { "public.image" },
MimeTypes = new[] { "image/*" }
};
public static FilePickerFileType ImageSvg { get; } = new("Svg")
{
Patterns = new[] { "*.svg" },
AppleUniformTypeIdentifiers = new[] { "public.svg-image" },
MimeTypes = new[] { "image/svg+xml" }
};
public static FilePickerFileType ImageSvgz { get; } = new("Svgz")
{
Patterns = new[] { "*.svgz" },
// TODO:
AppleUniformTypeIdentifiers = new[] { "public.svg-image" },
// TODO:
MimeTypes = new[] { "image/svg+xml" }
};
public static FilePickerFileType Xml { get; } = new("Xml")
{
Patterns = new[] { "*.xml" },
AppleUniformTypeIdentifiers = new[] { "public.xml" },
MimeTypes = new[] { "application/xaml" }
};
public static FilePickerFileType Xaml { get; } = new("Xaml")
{
Patterns = new[] { "*.xaml" },
// TODO:
AppleUniformTypeIdentifiers = new[] { "public.xaml" },
// TODO:
MimeTypes = new[] { "application/xaml" }
};
public static FilePickerFileType Axaml { get; } = new("Axaml")
{
Patterns = new[] { "*.axaml" },
// TODO:
AppleUniformTypeIdentifiers = new[] { "public.axaml" },
// TODO:
MimeTypes = new[] { "application/axaml" }
};
public static FilePickerFileType Pdf { get; } = new("PDF document")
{
Patterns = new[] { "*.pdf" },
AppleUniformTypeIdentifiers = new[] { "com.adobe.pdf" },
MimeTypes = new[] { "application/pdf" }
};
public static FilePickerFileType Xps { get; } = new("XPS document")
{
Patterns = new[] { "*.xps" },
AppleUniformTypeIdentifiers = new[] { "com.microsoft.xps" },
MimeTypes = new[] { "application/oxps", "application/vnd.ms-xpsdocument" }
};
public static IStorageProvider? GetStorageProvider()
{
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime { MainWindow: { } window })
{
return window.StorageProvider;
}
if (Application.Current?.ApplicationLifetime is ISingleViewApplicationLifetime { MainView: { } mainView })
{
var visualRoot = mainView.GetVisualRoot();
if (visualRoot is TopLevel topLevel)
{
return topLevel.StorageProvider;
}
}
return null;
}
}
| mit | C# | |
b5eec875b155496964187c97b7fda704c2b8b547 | Add failing test scene | peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework | osu.Framework.Tests/Visual/Sprites/TestSceneSpriteTextSizing.cs | osu.Framework.Tests/Visual/Sprites/TestSceneSpriteTextSizing.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Graphics.Sprites;
namespace osu.Framework.Tests.Visual.Sprites
{
public class TestSceneSpriteTextSizing : FrameworkTestScene
{
[Test]
public void TestNewSizeImmediatelyAvailableAfterTextChange()
{
SpriteText text = null!;
float initialSize = 0;
AddStep("add initial text and get size", () =>
{
Child = text = new SpriteText { Text = "First" };
initialSize = text.DrawWidth;
});
float updatedSize = 0;
AddStep("set new text and grab size", () =>
{
text.Text = "Second";
updatedSize = text.DrawWidth;
});
AddAssert("updated size is not equal to the initial size", () => updatedSize, () => Is.Not.EqualTo(initialSize));
}
}
}
| mit | C# | |
8c14c9e1c4eb36789b150d14e273e6b6ccf1f772 | Add basic test coverage | ppy/osu,NeoAdonis/osu,peppy/osu-new,ppy/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,ppy/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,smoogipooo/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu | osu.Game.Tests/Visual/Gameplay/TestSceneDrawableStoryboardSprite.cs | osu.Game.Tests/Visual/Gameplay/TestSceneDrawableStoryboardSprite.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osu.Game.Skinning;
using osu.Game.Storyboards;
using osu.Game.Storyboards.Drawables;
using osuTK;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneDrawableStoryboardSprite : SkinnableTestScene
{
protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset();
[Cached]
private Storyboard storyboard { get; set; } = new Storyboard();
[Test]
public void TestSkinSpriteDisallowedByDefault()
{
const string lookup_name = "hitcircleoverlay";
AddStep("allow skin lookup", () => storyboard.UseSkinSprites = false);
AddStep("create sprites", () => SetContents(
() => createSprite(lookup_name, Anchor.TopLeft, Vector2.Zero)));
assertSpritesFromSkin(false);
}
[Test]
public void TestAllowLookupFromSkin()
{
const string lookup_name = "hitcircleoverlay";
AddStep("allow skin lookup", () => storyboard.UseSkinSprites = true);
AddStep("create sprites", () => SetContents(
() => createSprite(lookup_name, Anchor.Centre, Vector2.Zero)));
assertSpritesFromSkin(true);
}
private DrawableStoryboardSprite createSprite(string lookupName, Anchor origin, Vector2 initialPosition)
=> new DrawableStoryboardSprite(
new StoryboardSprite(lookupName, origin, initialPosition)
).With(s =>
{
s.LifetimeStart = double.MinValue;
s.LifetimeEnd = double.MaxValue;
});
private void assertSpritesFromSkin(bool fromSkin) =>
AddAssert($"sprites are {(fromSkin ? "from skin" : "from storyboard")}",
() => this.ChildrenOfType<DrawableStoryboardSprite>()
.All(sprite => sprite.ChildrenOfType<SkinnableSprite>().Any() == fromSkin));
}
}
| mit | C# | |
2927b235dec25bc6c27cac9786e1d0736ccea593 | Add test coverage of mouse wheel scroll adjusting volume | ppy/osu,peppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu | osu.Game.Tests/Visual/Navigation/TestSceneMouseWheelVolumeAdjust.cs | osu.Game.Tests/Visual/Navigation/TestSceneMouseWheelVolumeAdjust.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Configuration;
using osu.Game.Screens.Play;
using osu.Game.Tests.Beatmaps.IO;
using osuTK.Input;
namespace osu.Game.Tests.Visual.Navigation
{
public class TestSceneMouseWheelVolumeAdjust : OsuGameTestScene
{
public override void SetUpSteps()
{
base.SetUpSteps();
// Headless tests are always at minimum volume. This covers interactive tests, matching that initial value.
AddStep("Set volume to min", () => Game.Audio.Volume.Value = 0);
AddAssert("Volume is min", () => Game.Audio.AggregateVolume.Value == 0);
AddStep("Move mouse to centre", () => InputManager.MoveMouseTo(Game.ScreenSpaceDrawQuad.Centre));
}
[Test]
public void TestAdjustVolumeFromMainMenu()
{
// First scroll makes volume controls appear, second adjusts volume.
AddRepeatStep("Adjust volume using mouse wheel", () => InputManager.ScrollVerticalBy(5), 2);
AddUntilStep("Volume is above zero", () => Game.Audio.AggregateVolume.Value > 0);
}
[Test]
public void TestAdjustVolumeFromPlayerWheelEnabled()
{
loadToPlayerNonBreakTime();
// First scroll makes volume controls appear, second adjusts volume.
AddRepeatStep("Adjust volume using mouse wheel", () => InputManager.ScrollVerticalBy(5), 2);
AddAssert("Volume is above zero", () => Game.Audio.Volume.Value > 0);
}
[Test]
public void TestAdjustVolumeFromPlayerWheelDisabled()
{
AddStep("disable wheel volume adjust", () => Game.LocalConfig.SetValue(OsuSetting.MouseDisableWheel, true));
loadToPlayerNonBreakTime();
// First scroll makes volume controls appear, second adjusts volume.
AddRepeatStep("Adjust volume using mouse wheel", () => InputManager.ScrollVerticalBy(5), 2);
AddAssert("Volume is still zero", () => Game.Audio.Volume.Value == 0);
}
[Test]
public void TestAdjustVolumeFromPlayerWheelDisabledHoldingAlt()
{
AddStep("disable wheel volume adjust", () => Game.LocalConfig.SetValue(OsuSetting.MouseDisableWheel, true));
loadToPlayerNonBreakTime();
// First scroll makes volume controls appear, second adjusts volume.
AddRepeatStep("Adjust volume using mouse wheel holding alt", () =>
{
InputManager.PressKey(Key.AltLeft);
InputManager.ScrollVerticalBy(5);
InputManager.ReleaseKey(Key.AltLeft);
}, 2);
AddAssert("Volume is above zero", () => Game.Audio.Volume.Value > 0);
}
private void loadToPlayerNonBreakTime()
{
Player player = null;
Screens.Select.SongSelect songSelect = null;
PushAndConfirm(() => songSelect = new TestSceneScreenNavigation.TestPlaySongSelect());
AddUntilStep("wait for song select", () => songSelect.BeatmapSetsLoaded);
AddStep("import beatmap", () => ImportBeatmapTest.LoadOszIntoOsu(Game, virtualTrack: true).Wait());
AddUntilStep("wait for selected", () => !Game.Beatmap.IsDefault);
AddStep("press enter", () => InputManager.Key(Key.Enter));
AddUntilStep("wait for player", () =>
{
// dismiss any notifications that may appear (ie. muted notification).
clickMouseInCentre();
return (player = Game.ScreenStack.CurrentScreen as Player) != null;
});
AddUntilStep("wait for play time active", () => !player.IsBreakTime.Value);
}
private void clickMouseInCentre()
{
InputManager.MoveMouseTo(Game.ScreenSpaceDrawQuad.Centre);
InputManager.Click(MouseButton.Left);
}
}
}
| mit | C# | |
7b148cb3b9859214f406efc2ca7bed5c31a7f130 | Add UnmanagedDataSource. | Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver | src/AsmResolver/IO/UnmanagedDataSource.cs | src/AsmResolver/IO/UnmanagedDataSource.cs | using System;
using System.Runtime.InteropServices;
namespace AsmResolver.IO
{
public sealed unsafe class UnmanagedDataSource : IDataSource
{
private readonly void* _basePointer;
public UnmanagedDataSource(void* basePointer, ulong length)
{
_basePointer = basePointer;
Length = length;
}
/// <inheritdoc />
public byte this[ulong address]
{
get
{
if (!IsValidAddress(address))
throw new ArgumentOutOfRangeException(nameof(address));
return *(byte*) address;
}
}
/// <inheritdoc />
public ulong Length
{
get;
}
/// <inheritdoc />
public bool IsValidAddress(ulong address) => address >= (ulong) _basePointer
&& address - (ulong) _basePointer < Length;
/// <inheritdoc />
public int ReadBytes(ulong address, byte[] buffer, int index, int count)
{
if (!IsValidAddress(address))
return 0;
ulong relativeIndex = address - (ulong) _basePointer;
int actualLength = (int) Math.Min((ulong) count, Length - relativeIndex);
Marshal.Copy((IntPtr) address, buffer, index, actualLength);
return actualLength;
}
}
}
| mit | C# | |
6324d4d23eeb49813c89422a6896e7328a822883 | Add tests for Factory.Email | inputfalken/Sharpy | Tests/Sharpy/FactoryTests/Email.cs | Tests/Sharpy/FactoryTests/Email.cs | using System;
using System.Linq;
using NUnit.Framework;
using Sharpy;
using Sharpy.Core.Linq;
namespace Tests.Sharpy.FactoryTests {
[TestFixture]
internal class Email {
[Test]
public void No_Args_Randomizes_Various_Domains() {
var mails = Factory
.Email()
.Select(s => s.Split('@'))
.Take(50)
.Select(strings => strings.Last())
.ToArray();
Assert.IsFalse(mails.Skip(1).Zip(mails, (s, s1) => s == s1).All(b => b));
}
[Test]
public void No_Args_Randomizes_Various_Names() {
var mails = Factory
.Email()
.Select(s => s.Split('@'))
.Take(50)
.Select(strings => strings.First())
.ToArray();
Assert.IsFalse(mails.Skip(1).Zip(mails, (s, s1) => s == s1).All(b => b));
}
[Test]
public void Supplied_Randomizer_With_Same_Seed_Are_Equal() {
const int seed = 20;
const int count = 200;
var mails1 = Factory.Email(random: new Random(seed)).Take(count);
var mails2 = Factory.Email(random: new Random(seed)).Take(count);
Assert.AreEqual(mails1, mails2);
}
[Test]
public void Supplied_Randomizer_With_Different_Seed_Are_Equal() {
const int count = 200;
var mails1 = Factory.Email(random: new Random(20)).Take(count);
var mails2 = Factory.Email(random: new Random(30)).Take(count);
Assert.AreNotEqual(mails1, mails2);
}
[Test]
public void Supplied_Domains_Is_Only_Used() {
const string gmailCom = "gmail.com";
var res = Factory.Email(new[] {gmailCom})
.Select(s => s.Split('@')[1])
.Take(200)
.All(s => s == gmailCom);
Assert.IsTrue(res);
}
[Test]
public void No_Supplied_Domains_Use_Random_Domain() {
const string gmailCom = "gmail.com";
var res = Factory.Email()
.Select(s => s.Split('@')[1])
.Take(200)
.All(s => s == gmailCom);
Assert.IsFalse(res);
}
}
} | mit | C# | |
3f54ef12653333c30649056c5678fa3a8e2f9ea1 | Add Func<Task> overload in TaskManager | agarbuno/SteamDatabaseBackend,GoeGaming/SteamDatabaseBackend,SteamDatabase/SteamDatabaseBackend,thecocce/SteamDatabaseBackend,SGColdSun/SteamDatabaseBackend,SGColdSun/SteamDatabaseBackend,SteamDatabase/SteamDatabaseBackend,GoeGaming/SteamDatabaseBackend,thecocce/SteamDatabaseBackend | Managers/TaskManager.cs | Managers/TaskManager.cs | /*
* Copyright (c) 2013-2015, SteamDB. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
using System;
using System.Threading.Tasks;
namespace SteamDatabaseBackend
{
static class TaskManager
{
public static Task Run(Func<Task> function)
{
var t = Task.Run(function);
RegisterErrorHandler(t);
return t;
}
public static Task Run(Action action)
{
var t = Task.Run(action);
RegisterErrorHandler(t);
return t;
}
private static void RegisterErrorHandler(Task t)
{
t.ContinueWith(task =>
{
task.Exception.Flatten().Handle(e =>
{
Log.WriteError("Task Manager", "Exception: {0}\n{1}", e.Message, e.StackTrace);
ErrorReporter.Notify(e);
return false;
});
}, TaskContinuationOptions.OnlyOnFaulted);
}
}
}
| /*
* Copyright (c) 2013-2015, SteamDB. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
using System;
using System.Threading.Tasks;
namespace SteamDatabaseBackend
{
static class TaskManager
{
public static Task Run(Action action)
{
var t = new Task(action);
t.ContinueWith(task =>
{
task.Exception.Flatten().Handle(e =>
{
Log.WriteError("Task Manager", "Exception: {0}\n{1}", e.Message, e.StackTrace);
ErrorReporter.Notify(e);
return false;
});
}, TaskContinuationOptions.OnlyOnFaulted);
t.Start();
return t;
}
}
}
| bsd-3-clause | C# |
6ca0019e6bf4fa60c8f63e9b1adc9e21c00c4f1b | Add C# library interface | john29917958/Cpp-Call-CSharp-Example,john29917958/Cpp-Call-CSharp-Example | CSharpLibrary/ICalculator.cs | CSharpLibrary/ICalculator.cs | namespace CSharpLibrary
{
public interface ICalculator
{
int Add(int a, int b);
int Minus(int a, int b);
int Multiply(int a, int b);
int Divide(int a, int b);
void PrintNumber(int number);
}
}
| mit | C# | |
deadf4066421463183cb3fd436cec9eb0a27bcb1 | Extend the Rotorz Tile System api | jguarShark/Unity2D-Components,cmilr/Unity2D-Components | Extensions/TileExtensions.cs | Extensions/TileExtensions.cs | // This set of methods extends the most excellent Rotorz api. I built this set because,
// while I love Rotorz, I find its method paramaters frustrating to use. Specifically,
// I tend to send x coordinates first in my params, followed by y coordinates; while
// Rotorz transposes this. It has lead to many crazy-making bugs in my code.
//
// These extensions also act as an interface to guarantee against future api changes, etc.
using Rotorz.Tile;
using System;
using UnityEngine;
namespace Matcha.Unity
{
public static class TileExtensions
{
public static void BulkEditBegin(this TileSystem map)
{
map.BeginBulkEdit();
}
public static void BulkEditEnd(this TileSystem map)
{
map.EndBulkEdit();
}
public static bool ClearTile(this TileSystem map, int x, int y)
{
return map.EraseTile(y, x);
}
public static TileData GetTileInfo(this TileSystem map, int x, int y)
{
return map.GetTile(y, x);
}
public static void RefreshNearbyTiles(this TileSystem map, int x, int y)
{
map.RefreshSurroundingTiles(y, x);
}
public static void RefreshTiles(this TileSystem map)
{
map.RefreshAllTiles();
}
public static TileData PaintTile(this Brush brush, TileSystem map, int x, int y)
{
return brush.Paint(map, y, x);
}
// transform extensions for checking nearby tile data
public static GameObject GetTileInfo(this Transform transform, TileSystem tileSystem, int xDirection, int yDirection)
{
// grabs tile info at a given transform:
// x = 0, y = 0 will get you the tile the transform occupies
// plus or minus x or y will get you tiles backwards, forwards, up or down
var convertedX = (int)Math.Floor(transform.position.x);
var convertedY = (int)Math.Ceiling(Math.Abs(transform.position.y));
TileData tile = tileSystem.GetTile(convertedY + yDirection, convertedX + xDirection);
if (tile != null)
{
return tile.gameObject;
}
return null;
}
public static GameObject GetTileBelow(this Transform transform, TileSystem tileSystem, int direction)
{
var convertedX = (int)Math.Floor(transform.position.x);
var convertedY = (int)Math.Floor(Math.Abs(transform.position.y));
TileData tile = tileSystem.GetTile(convertedY, convertedX + direction);
if (tile != null)
{
return tile.gameObject;
}
return null;
}
}
}
| mit | C# | |
0eaa4491bc3097e1b31ac37d651539847a5c6ad0 | Add CodeSamples forlder. | Levi9NS/SecureCompileWrapper | CodeSamples/NodeSelection.cs | CodeSamples/NodeSelection.cs | // Add nugget package Microsoft.CodeAnalysis
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Emit;
namespace SecureCompileWrapper
{
public class NodeSelection
{
private string _assemblyName;
private MetadataReference[] _metadataReferences;
private CSharpCompilation _compilation;
private SemanticModel _semanticModel;
private CompilationUnitSyntax _root;
public NodeSelection(string sourceCode)
{
if(sourceCode != null)
{
_assemblyName = Path.GetRandomFileName();
_metadataReferences = new MetadataReference[]{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location)
};
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(txInput.Text);
_compilation = CSharpCompilation.Create (
assemblyName,
syntaxTrees: new[] { syntaxTree },
references: references,
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
_semanticModel = ompilation.GetSemanticModel(_syntaxTree);
_root = (CompilationUnitSyntax)syntaxTree.GetRoot();
}
else
{
throw new ArgumentNullException(nameof(sourceCode));
}
}
private List<T> Select<T>() where T: PredefinedTypeSyntax, NullableTypeSyntax, GenericNameSyntax, IdentifierNameSyntax
{
return root.DescendantNodes().OfType<T>().ToList<T>;
}
// Gets full name of variable type in format Namespace.TypaName.
// For now only works for PredefinedTypeSyntax (example: System.Int32) and NullableTypeSyntax(example: System.Int32).
// For now DOESN'T WORK for GenericNameSyntax (example: Nullable<int>) and IdentifierNameSyntax (example: SomeUserDefinedClass).
private string GetVariableTypeName<T> (T variable) where T : PredefinedTypeSyntax, NullableTypeSyntax, GenericNameSyntax, IdentifierNameSyntax
{
if(variable != null)
{
SymbolDisplayFormat symbolDisplayFormat = new SymbolDisplayFormat(typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces);
TypeInfo variableModelInfo = semanticModel.GetTypeInfo(nullable);
return variableModelInfo.Type.ToDisplayString(symbolDisplayFormat);
}
else
{
throw new ArgumentNullException(nameof(variable));
}
}
public List<string> GetTypeNamesForSyntaxType<T>() where T : PredefinedTypeSyntax, NullableTypeSyntax, GenericNameSyntax, IdentifierNameSyntax
{
List<string> result = new List<string>();
List<T> variables = Select<T>();
if (variables != null && variables.Count > 0)
{
foreach(var variable in variables)
{
result.Add(GetVariableTypeName<T>(variable));
}
}
return result;
}
}
} | mit | C# | |
a64fbbda258a5951be2fc7631a14477de5b11cde | Create DeweyEditViwModel. | Programazing/Open-School-Library,Programazing/Open-School-Library | src/Open-School-Library/Models/DeweyViewModels/DeweyEditViewModel.cs | src/Open-School-Library/Models/DeweyViewModels/DeweyEditViewModel.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Open_School_Library.Models.DeweyViewModels
{
public class DeweyEditViewModel
{
}
}
| mit | C# | |
e29a30ad5d6a6a231af703f0aac380c60fc65132 | Create mycodeMain.cs | diarmuidclarke/my1st | mycodeMain.cs | mycodeMain.cs | #using system.io
void main(void)
{
MessageBox("hellow world");
exit;
}
| mit | C# | |
a71dd37c160a9d9927e893c75657a1afdfbc61f8 | add FollowingCamera | zyouyowa/Unity_cs | CameraScripts/FollowingCamera.cs | CameraScripts/FollowingCamera.cs | using UnityEngine;
using System.Collections;
//Edit->Project Settings->Script Excution OrderでこのスクリプトはDeffault Timeより後に行うように設定すること
public class FollowingCamera : MonoBehaviour {
public GameObject target; //カメラで追従したい対象のオブジェクト
public float angleLimit_y = 45f; //縦方向回転においてangleLimit度まで回転できる
public float distance = 1f; //対象からカメラまでの距離
//heightはいらないけど1とか入れてみたら面白い動作をしたのであえて残しました。
public float height = 0f; //回転の中心 + heightがカメラの高さ
public float rotateSpeed = 10f; //入力値*rotateSpeed[°/s]回転
public Vector3 offset = Vector3.up; //targetの座標+offsetの位置が回転の中心
//Vector2 value;にしなかったのは45,47行目あたりが面倒な気がしたからだけどそんなことはなかった。
private float value_x; //横方向旋回に使う入力値を入れる
private float usevalue_x; //横方向旋回を行うときに実際に使う値
private float value_y; //縦方向旋回に使う入力値を入れる
private float usevalue_y; //縦方向旋回で実際に使う値
void Start () {
//Inspectorでtargetに何もセットされていない場合はPlayerタグを持つオブジェクトをtargetとする
if (target == null) {
target = GameObject.FindGameObjectWithTag ("Player");
}
//初期化
value_x = 0;
usevalue_x = 0;
value_y = 0;
usevalue_y = 0;
}
//プレイヤーからの入力は取りこぼすといけないのでUpdateで行う
void Update () {
//Edit->Project Settings->InputのAxesの中から""の中身を選ぶ
value_x = Input.GetAxis ("Horizontal2");
value_y = Input.GetAxis("Vertical2");
}
//実行環境によって移動距離などに差が出ないようにゲームの処理は主にFixedUpdate内で行う
void FixedUpdate () {
//valueに旋回速度調整パラメータをかけ、
//fixedDeltaTimeをかけて1フレームあたりの値を出す。
usevalue_x += value_x * rotateSpeed * Time.fixedDeltaTime;
usevalue_y += value_y * rotateSpeed * Time.fixedDeltaTime;
//|usevalue_x|<360となるようにする。|・|は絶対値をとる。
usevalue_x = Mathf.Repeat (usevalue_x, 360f);
//usevalue_yの範囲を(-angleLimit < usevalue_y < angleLimit)とする
usevalue_y = Mathf.Clamp(usevalue_y, -angleLimit_y, angleLimit_y);
//回転の中心を設定
Vector3 lookPosition = target.transform.position + offset;
//(0,height,-distance)の点ををx軸についてusevalue_y度,y軸についてusevalue_x度回転移動させた点を求める。
Vector3 relativePos = Quaternion.Euler (usevalue_y, usevalue_x, 0) * new Vector3 (0, height, -distance);
//カメラの位置の更新
transform.position = lookPosition + relativePos;
//カメラの向き更新
transform.LookAt (lookPosition);
//playerとカメラお間の障害物避ける
RaycastHit hitInfo;
if (Physics.Linecast (lookPosition, transform.position, out hitInfo, 1 << LayerMask.NameToLayer ("Ground"))) {
transform.position = hitInfo.point;
}
}
}
| mit | C# | |
c97caea03dc188aabd7e929276cf62a87c11a3fe | Change properties to inherit from declarations. | xistoso/CppSharp,txdv/CppSharp,SonyaSa/CppSharp,SonyaSa/CppSharp,txdv/CppSharp,SonyaSa/CppSharp,nalkaro/CppSharp,genuinelucifer/CppSharp,ktopouzi/CppSharp,mono/CppSharp,mohtamohit/CppSharp,mono/CppSharp,mono/CppSharp,genuinelucifer/CppSharp,xistoso/CppSharp,inordertotest/CppSharp,zillemarco/CppSharp,KonajuGames/CppSharp,u255436/CppSharp,u255436/CppSharp,mono/CppSharp,mono/CppSharp,txdv/CppSharp,nalkaro/CppSharp,xistoso/CppSharp,ddobrev/CppSharp,txdv/CppSharp,mohtamohit/CppSharp,xistoso/CppSharp,ktopouzi/CppSharp,ddobrev/CppSharp,u255436/CppSharp,mohtamohit/CppSharp,KonajuGames/CppSharp,KonajuGames/CppSharp,u255436/CppSharp,ktopouzi/CppSharp,nalkaro/CppSharp,Samana/CppSharp,inordertotest/CppSharp,zillemarco/CppSharp,Samana/CppSharp,ktopouzi/CppSharp,zillemarco/CppSharp,SonyaSa/CppSharp,ddobrev/CppSharp,genuinelucifer/CppSharp,txdv/CppSharp,Samana/CppSharp,Samana/CppSharp,genuinelucifer/CppSharp,imazen/CppSharp,SonyaSa/CppSharp,u255436/CppSharp,ktopouzi/CppSharp,imazen/CppSharp,KonajuGames/CppSharp,KonajuGames/CppSharp,zillemarco/CppSharp,imazen/CppSharp,mydogisbox/CppSharp,inordertotest/CppSharp,nalkaro/CppSharp,Samana/CppSharp,ddobrev/CppSharp,mydogisbox/CppSharp,inordertotest/CppSharp,mydogisbox/CppSharp,mydogisbox/CppSharp,genuinelucifer/CppSharp,mono/CppSharp,mohtamohit/CppSharp,nalkaro/CppSharp,xistoso/CppSharp,mohtamohit/CppSharp,mydogisbox/CppSharp,imazen/CppSharp,zillemarco/CppSharp,inordertotest/CppSharp,imazen/CppSharp,ddobrev/CppSharp | src/Bridge/Property.cs | src/Bridge/Property.cs | using System;
using System.Collections.Generic;
namespace Cxxi
{
/// <summary>
/// Represents a C++ property.
/// </summary>
public class Property : Declaration
{
public Property(string name, Declaration type)
{
Name = name;
Type = type;
}
public Declaration Type
{
get;
set;
}
public Method GetMethod
{
get;
set;
}
public Method SetMethod
{
get;
set;
}
public override T Visit<T>(IDeclVisitor<T> visitor)
{
throw new NotImplementedException();
}
}
} | using System;
using System.Collections.Generic;
namespace Cxxi
{
/// <summary>
/// Represents a C++ property.
/// </summary>
public class Property
{
public Property(string name, Declaration type)
{
Name = name;
Type = type;
}
public string Name
{
get;
set;
}
public Declaration Type
{
get;
set;
}
public Method GetMethod
{
get;
set;
}
public Method SetMethod
{
get;
set;
}
}
} | mit | C# |
cf8801a66db8b01dd70fa5af3e6aeb8267382708 | Add AwaitInCatchAndFinally.cs | devlights/try-csharp | TryCSharp.Samples/CSharp6/AwaitInCatchAndFinally.cs | TryCSharp.Samples/CSharp6/AwaitInCatchAndFinally.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using TryCSharp.Common;
namespace TryCSharp.Samples.CSharp6
{
/// <summary>
/// C# 6 新機能についてのサンプルです。
/// </summary>
/// <remarks>
/// Await in Catch and Finally blocks (catch と finally ブロックの中での await) について
/// https://docs.microsoft.com/ja-jp/dotnet/csharp/whats-new/csharp-6#await-in-catch-and-finally-blocks
/// https://ufcpp.net/study/csharp/ap_ver6.html#await-in-catch
/// </remarks>
[Sample]
public class AwaitInCatchAndFinally : IAsyncExecutable
{
public async Task Execute()
{
// ------------------------------------------------------------------
// C# 5 では、await を catch, finally の中で使うことが出来なかった。
// C# 6 から、利用できるようになっている。
// ------------------------------------------------------------------
var mainThreadId = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine($"[main] threadId: {mainThreadId}");
await this.Log("Start");
try
{
await this.Log("Processing...");
}
catch (Exception ex)
{
// C# 5 だとこれはコンパイルエラーになる
await this.Log(ex.Message);
}
finally
{
// C# 5 だとこれはコンパイルエラーになる
await this.Log("End");
}
}
private async Task Log(string message)
{
await Task.Yield();
var threadId = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine($"[Log ] threadId: {threadId}\tmessage: {message}");
}
}
} | mit | C# | |
a0678d51dc52629b0d7b13f62a9f35fa0cd4ec6a | Move sort class to new file | DMagic1/KSP_Contract_Window | Source/ContractsWindow/contractSortClass.cs | Source/ContractsWindow/contractSortClass.cs |
namespace ContractsWindow
{
public enum contractSortClass
{
Difficulty = 1,
Expiration = 2,
Acceptance = 3,
Reward = 4,
Type = 5,
Planet = 6,
}
}
| mit | C# | |
95e8d5e1b29a61a4269a4596a455b7200a8a2974 | Add 'CascaraChar16' | whampson/bft-spec,whampson/cascara | Src/WHampson.Cascara/Types/CascaraChar16.cs | Src/WHampson.Cascara/Types/CascaraChar16.cs | #region License
/* Copyright (c) 2017 Wes Hampson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#endregion
using System;
using System.Runtime.InteropServices;
namespace WHampson.Cascara.Types
{
/// <summary>
/// A 16-bit character value.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct CascaraChar16 : ICascaraType,
IComparable, IComparable<CascaraChar16>, IEquatable<CascaraChar16>
{
private const int Size = 2;
private ushort m_value;
private CascaraChar16(char value)
{
m_value = value;
}
public int CompareTo(CascaraChar16 other)
{
if (m_value < other.m_value)
{
return -1;
}
else if (m_value > other.m_value)
{
return 1;
}
return 0;
}
public bool Equals(CascaraChar16 other)
{
return m_value == other.m_value;
}
int IComparable.CompareTo(object obj)
{
if (obj == null)
{
return 1;
}
if (!(obj is CascaraChar16))
{
string fmt = "Object is not an instance of {0}.";
string msg = string.Format(fmt, GetType().Name);
throw new ArgumentException(msg, "obj");
}
return CompareTo((CascaraChar16) obj);
}
byte[] ICascaraType.GetBytes()
{
return BitConverter.GetBytes(m_value);
}
int ICascaraType.GetSize()
{
return Size;
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return m_value | (m_value << 8);
}
public override string ToString()
{
return ((char) m_value).ToString();
}
public static implicit operator CascaraChar16(char value)
{
return new CascaraChar16(value);
}
public static explicit operator char(CascaraChar16 value)
{
return (char) value.m_value;
}
}
}
| mit | C# | |
2d589ee43aef48961e0462ee63095b1892321203 | Generalize number formatter to numbers smaller than 1 | default0/osu-framework,Nabile-Rahmani/osu-framework,DrabWeb/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,naoey/osu-framework,peppy/osu-framework,paparony03/osu-framework,naoey/osu-framework,Nabile-Rahmani/osu-framework,paparony03/osu-framework,ppy/osu-framework,default0/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework | osu.Framework/MathUtils/NumberFormatter.cs | osu.Framework/MathUtils/NumberFormatter.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
namespace osu.Framework.MathUtils
{
/// <summary>
/// Exposes functionality for formatting numbers.
/// </summary>
public static class NumberFormatter
{
/// <summary>
/// Prints the number with at most two decimal digits, followed by a magnitude suffic (k, M, G, T, etc.) depending on the magnitude of the number. If the number is
/// too large or small this will print the number using scientific notation instead.
/// </summary>
/// <param name="number">The number to print.</param>
/// <returns>The number with at most two decimal digits, followed by a magnitude suffic (k, M, G, T, etc.) depending on the magnitude of the number. If the number is
/// too large or small this will print the number using scientific notation instead.</returns>
public static string PrintWithSiSuffix(double number)
{
// The logarithm is undefined for zero.
if (number == 0)
return "0";
var isNeg = number < 0;
number = Math.Abs(number);
var strs = new[] { "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" };
int log1000 = (int)Math.Floor(Math.Log10(number) / 3);
int index = log1000 + 8;
if (index < 0 || index >= strs.Length)
return $"{number:E}";
return $"{(isNeg ? "-" : "")}{number / Math.Pow(1000, log1000):G3}{strs[index]}";
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
namespace osu.Framework.MathUtils
{
/// <summary>
/// Exposes functionality for formatting numbers.
/// </summary>
public static class NumberFormatter
{
/// <summary>
/// Prints the number with at most two decimal digits, followed by a magnitude suffic (k, M, G, T, etc.) depending on the magnitude of the number. If the number is
/// too large or small this will print the number using scientific notation instead.
/// </summary>
/// <param name="number">The number to print.</param>
/// <returns>The number with at most two decimal digits, followed by a magnitude suffic (k, M, G, T, etc.) depending on the magnitude of the number. If the number is
/// too large or small this will print the number using scientific notation instead.</returns>
public static string PrintWithSiSuffix(double number)
{
var isNeg = number < 0;
number = Math.Abs(number);
var strs = new[] { "", "k", "M", "G", "T", "P", "E", "Z", "Y" };
foreach (var str in strs)
{
if (number < 1000)
return $"{(isNeg ? "-" : "")}{Math.Round(number, 2):G}{str}";
number = number / 1000;
}
return $"{number:E}";
}
}
}
| mit | C# |
fa187cb601bc90ed688caf49b2e0880fbb839998 | Add Q179 | txchen/localleet | csharp/Q179_LargestNumber.cs | csharp/Q179_LargestNumber.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
// Given a list of non negative integers, arrange them such that they form the largest number.
//
// For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
//
// Note: The result may be very large, so you need to return a string instead of an integer.
// https://leetcode.com/problems/largest-number/
namespace LocalLeet
{
public class Q179
{
public string LargestNumber(int[] num)
{
Array.Sort(num,CompareNum);
if (num[0] == 0)
{
return "0";
}
return String.Concat(num);
}
private static int CompareNum(int a, int b)
{
string sa = b.ToString();
string sb = a.ToString();
return (sa + sb).CompareTo(sb + sa);
}
[Fact]
public void Q179_LargestNumber()
{
TestHelper.Run(input => "\"" + LargestNumber(input.EntireInput.ToIntArray()) + "\"");
}
}
}
| mit | C# | |
abf96db54535e8e24a818db00ee6d19e921217ce | Add regression test for the pattern of using DHO proxy in `LifetimeManagementContainer` | peppy/osu,peppy/osu-new,peppy/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,ppy/osu,smoogipooo/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu | osu.Game.Tests/Gameplay/TestSceneProxyContainer.cs | osu.Game.Tests/Gameplay/TestSceneProxyContainer.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 NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Testing;
using osu.Framework.Timing;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.UI;
using osu.Game.Tests.Visual;
namespace osu.Game.Tests.Gameplay
{
[HeadlessTest]
public class TestSceneProxyContainer : OsuTestScene
{
private HitObjectContainer hitObjectContainer;
private ProxyContainer proxyContainer;
private readonly ManualClock clock = new ManualClock();
[SetUp]
public void SetUp() => Schedule(() =>
{
Child = new Container
{
Children = new Drawable[]
{
hitObjectContainer = new HitObjectContainer(),
proxyContainer = new ProxyContainer()
},
Clock = new FramedClock(clock)
};
clock.CurrentTime = 0;
});
[Test]
public void TestProxyLifetimeManagement()
{
AddStep("Add proxy drawables", () =>
{
addProxy(new TestDrawableHitObject(1000));
addProxy(new TestDrawableHitObject(3000));
addProxy(new TestDrawableHitObject(5000));
});
AddStep($"time = 1000", () => clock.CurrentTime = 1000);
AddAssert("One proxy is alive", () => proxyContainer.AliveChildren.Count == 1);
AddStep($"time = 5000", () => clock.CurrentTime = 5000);
AddAssert("One proxy is alive", () => proxyContainer.AliveChildren.Count == 1);
AddStep($"time = 6000", () => clock.CurrentTime = 6000);
AddAssert("No proxy is alive", () => proxyContainer.AliveChildren.Count == 0);
}
private void addProxy(DrawableHitObject drawableHitObject)
{
hitObjectContainer.Add(drawableHitObject);
proxyContainer.AddProxy(drawableHitObject);
}
private class ProxyContainer : LifetimeManagementContainer
{
public IReadOnlyList<Drawable> AliveChildren => AliveInternalChildren;
public void AddProxy(Drawable d) => AddInternal(d.CreateProxy());
}
private class TestDrawableHitObject : DrawableHitObject
{
protected override double InitialLifetimeOffset => 100;
public TestDrawableHitObject(double startTime)
: base(new HitObject { StartTime = startTime })
{
}
protected override void UpdateInitialTransforms()
{
LifetimeEnd = LifetimeStart + 500;
}
}
}
}
| mit | C# | |
e4d0c59558ba9028d8f3e79fe8a0fef23e229f91 | Disable parallel test runs for Nancy.Tests | jeff-pang/Nancy,NancyFx/Nancy,khellang/Nancy,xt0rted/Nancy,khellang/Nancy,davidallyoung/Nancy,sadiqhirani/Nancy,xt0rted/Nancy,NancyFx/Nancy,sadiqhirani/Nancy,damianh/Nancy,danbarua/Nancy,NancyFx/Nancy,xt0rted/Nancy,davidallyoung/Nancy,danbarua/Nancy,danbarua/Nancy,davidallyoung/Nancy,jeff-pang/Nancy,blairconrad/Nancy,davidallyoung/Nancy,damianh/Nancy,khellang/Nancy,xt0rted/Nancy,blairconrad/Nancy,damianh/Nancy,JoeStead/Nancy,JoeStead/Nancy,sadiqhirani/Nancy,blairconrad/Nancy,JoeStead/Nancy,NancyFx/Nancy,jeff-pang/Nancy,jeff-pang/Nancy,khellang/Nancy,danbarua/Nancy,sadiqhirani/Nancy,JoeStead/Nancy,davidallyoung/Nancy,blairconrad/Nancy | test/Nancy.Tests/Properties/AssemblyInfo.cs | test/Nancy.Tests/Properties/AssemblyInfo.cs | using Xunit;
[assembly: CollectionBehavior(DisableTestParallelization = true)] | mit | C# | |
0360513f6f0db5703da70e9795d995a1a1473fac | Add SourcePosition class | maul-esel/CobaltAHK,maul-esel/CobaltAHK | CobaltAHK/SourcePosition.cs | CobaltAHK/SourcePosition.cs | using System;
namespace CobaltAHK
{
public struct SourcePosition
{
public SourcePosition(uint line, uint col, uint index)
{
this.line = line;
this.col = col;
this.index = index;
}
private uint line, col, index;
public uint Line { get { return line; } }
public uint Column { get { return col; } }
public uint Index { get { return index; } }
}
}
| mit | C# | |
12cf3c411aecd548a5048080e94458386dd01c5f | Fix caching in RuntimeInformation. | JosephTremoulet/corefx,dotnet-bot/corefx,MaggieTsang/corefx,cydhaselton/corefx,dotnet-bot/corefx,krk/corefx,jlin177/corefx,cydhaselton/corefx,parjong/corefx,shimingsg/corefx,shmao/corefx,ericstj/corefx,twsouthwick/corefx,Ermiar/corefx,Petermarcu/corefx,JosephTremoulet/corefx,elijah6/corefx,nchikanov/corefx,seanshpark/corefx,twsouthwick/corefx,DnlHarvey/corefx,rahku/corefx,the-dwyer/corefx,dhoehna/corefx,seanshpark/corefx,seanshpark/corefx,marksmeltzer/corefx,BrennanConroy/corefx,lggomez/corefx,mazong1123/corefx,rubo/corefx,krytarowski/corefx,nchikanov/corefx,MaggieTsang/corefx,tijoytom/corefx,iamjasonp/corefx,BrennanConroy/corefx,wtgodbe/corefx,krk/corefx,weltkante/corefx,rahku/corefx,stephenmichaelf/corefx,YoupHulsebos/corefx,Jiayili1/corefx,mmitche/corefx,Jiayili1/corefx,wtgodbe/corefx,Petermarcu/corefx,rjxby/corefx,parjong/corefx,elijah6/corefx,Ermiar/corefx,ptoonen/corefx,parjong/corefx,the-dwyer/corefx,ptoonen/corefx,cydhaselton/corefx,krk/corefx,YoupHulsebos/corefx,wtgodbe/corefx,tijoytom/corefx,manu-silicon/corefx,rahku/corefx,ViktorHofer/corefx,rjxby/corefx,yizhang82/corefx,manu-silicon/corefx,rjxby/corefx,iamjasonp/corefx,billwert/corefx,tijoytom/corefx,mazong1123/corefx,weltkante/corefx,JosephTremoulet/corefx,zhenlan/corefx,Ermiar/corefx,gkhanna79/corefx,alphonsekurian/corefx,yizhang82/corefx,gkhanna79/corefx,MaggieTsang/corefx,rjxby/corefx,ViktorHofer/corefx,ericstj/corefx,mmitche/corefx,stone-li/corefx,stephenmichaelf/corefx,alexperovich/corefx,twsouthwick/corefx,lggomez/corefx,shmao/corefx,alexperovich/corefx,rjxby/corefx,marksmeltzer/corefx,nbarbettini/corefx,MaggieTsang/corefx,jlin177/corefx,weltkante/corefx,JosephTremoulet/corefx,mmitche/corefx,nbarbettini/corefx,nchikanov/corefx,parjong/corefx,mmitche/corefx,marksmeltzer/corefx,axelheer/corefx,DnlHarvey/corefx,dotnet-bot/corefx,DnlHarvey/corefx,billwert/corefx,alphonsekurian/corefx,ericstj/corefx,shimingsg/corefx,mmitche/corefx,wtgodbe/corefx,stephenmichaelf/corefx,krytarowski/corefx,elijah6/corefx,the-dwyer/corefx,twsouthwick/corefx,DnlHarvey/corefx,ptoonen/corefx,gkhanna79/corefx,manu-silicon/corefx,krytarowski/corefx,krk/corefx,axelheer/corefx,manu-silicon/corefx,ericstj/corefx,zhenlan/corefx,seanshpark/corefx,alphonsekurian/corefx,Petermarcu/corefx,MaggieTsang/corefx,nchikanov/corefx,seanshpark/corefx,manu-silicon/corefx,iamjasonp/corefx,ravimeda/corefx,krk/corefx,tijoytom/corefx,weltkante/corefx,iamjasonp/corefx,yizhang82/corefx,shmao/corefx,parjong/corefx,lggomez/corefx,nchikanov/corefx,dhoehna/corefx,jhendrixMSFT/corefx,shmao/corefx,dhoehna/corefx,dhoehna/corefx,nbarbettini/corefx,mazong1123/corefx,shimingsg/corefx,rubo/corefx,ericstj/corefx,richlander/corefx,yizhang82/corefx,zhenlan/corefx,cydhaselton/corefx,iamjasonp/corefx,Ermiar/corefx,lggomez/corefx,Jiayili1/corefx,jhendrixMSFT/corefx,mazong1123/corefx,nbarbettini/corefx,YoupHulsebos/corefx,ViktorHofer/corefx,shmao/corefx,richlander/corefx,nbarbettini/corefx,elijah6/corefx,stone-li/corefx,seanshpark/corefx,gkhanna79/corefx,billwert/corefx,the-dwyer/corefx,alexperovich/corefx,krytarowski/corefx,dotnet-bot/corefx,Petermarcu/corefx,richlander/corefx,zhenlan/corefx,elijah6/corefx,stone-li/corefx,Jiayili1/corefx,jhendrixMSFT/corefx,elijah6/corefx,weltkante/corefx,Ermiar/corefx,jhendrixMSFT/corefx,zhenlan/corefx,alphonsekurian/corefx,krk/corefx,dhoehna/corefx,elijah6/corefx,YoupHulsebos/corefx,fgreinacher/corefx,billwert/corefx,tijoytom/corefx,stephenmichaelf/corefx,ptoonen/corefx,Jiayili1/corefx,Jiayili1/corefx,jlin177/corefx,billwert/corefx,zhenlan/corefx,iamjasonp/corefx,alphonsekurian/corefx,stephenmichaelf/corefx,ericstj/corefx,tijoytom/corefx,wtgodbe/corefx,twsouthwick/corefx,mazong1123/corefx,mazong1123/corefx,stone-li/corefx,ptoonen/corefx,alexperovich/corefx,ravimeda/corefx,rubo/corefx,YoupHulsebos/corefx,shimingsg/corefx,rahku/corefx,ptoonen/corefx,stone-li/corefx,rjxby/corefx,marksmeltzer/corefx,dotnet-bot/corefx,nbarbettini/corefx,weltkante/corefx,shimingsg/corefx,seanshpark/corefx,manu-silicon/corefx,lggomez/corefx,stone-li/corefx,Ermiar/corefx,mazong1123/corefx,DnlHarvey/corefx,ptoonen/corefx,jhendrixMSFT/corefx,stephenmichaelf/corefx,Petermarcu/corefx,fgreinacher/corefx,wtgodbe/corefx,BrennanConroy/corefx,gkhanna79/corefx,Ermiar/corefx,stephenmichaelf/corefx,shmao/corefx,MaggieTsang/corefx,lggomez/corefx,ravimeda/corefx,stone-li/corefx,ravimeda/corefx,krytarowski/corefx,rahku/corefx,ViktorHofer/corefx,billwert/corefx,jhendrixMSFT/corefx,ravimeda/corefx,Jiayili1/corefx,DnlHarvey/corefx,jlin177/corefx,twsouthwick/corefx,axelheer/corefx,shimingsg/corefx,alexperovich/corefx,manu-silicon/corefx,ravimeda/corefx,marksmeltzer/corefx,ravimeda/corefx,cydhaselton/corefx,alphonsekurian/corefx,axelheer/corefx,yizhang82/corefx,tijoytom/corefx,ViktorHofer/corefx,parjong/corefx,marksmeltzer/corefx,ViktorHofer/corefx,gkhanna79/corefx,yizhang82/corefx,jhendrixMSFT/corefx,krytarowski/corefx,fgreinacher/corefx,the-dwyer/corefx,JosephTremoulet/corefx,marksmeltzer/corefx,Petermarcu/corefx,yizhang82/corefx,rubo/corefx,krk/corefx,JosephTremoulet/corefx,billwert/corefx,weltkante/corefx,nbarbettini/corefx,YoupHulsebos/corefx,wtgodbe/corefx,dotnet-bot/corefx,the-dwyer/corefx,jlin177/corefx,cydhaselton/corefx,lggomez/corefx,JosephTremoulet/corefx,jlin177/corefx,ViktorHofer/corefx,cydhaselton/corefx,nchikanov/corefx,richlander/corefx,dhoehna/corefx,MaggieTsang/corefx,richlander/corefx,axelheer/corefx,gkhanna79/corefx,rjxby/corefx,mmitche/corefx,iamjasonp/corefx,twsouthwick/corefx,axelheer/corefx,shimingsg/corefx,ericstj/corefx,the-dwyer/corefx,richlander/corefx,nchikanov/corefx,parjong/corefx,alphonsekurian/corefx,alexperovich/corefx,alexperovich/corefx,rahku/corefx,jlin177/corefx,richlander/corefx,dhoehna/corefx,zhenlan/corefx,DnlHarvey/corefx,Petermarcu/corefx,krytarowski/corefx,shmao/corefx,mmitche/corefx,rubo/corefx,rahku/corefx,fgreinacher/corefx,dotnet-bot/corefx,YoupHulsebos/corefx | src/System.Runtime.InteropServices.RuntimeInformation/src/System/Runtime/InteropServices/RuntimeInformation/RuntimeInformation.cs | src/System.Runtime.InteropServices.RuntimeInformation/src/System/Runtime/InteropServices/RuntimeInformation/RuntimeInformation.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.Reflection;
using System.Diagnostics;
namespace System.Runtime.InteropServices
{
public static partial class RuntimeInformation
{
#if netcore50aot
private const string FrameworkName = ".NET Native";
#elif net45 || win8
private const string FrameworkName = ".NET Framework";
#else // netcore50 || wpa81 || other
private const string FrameworkName = ".NET Core";
#endif
private static string s_frameworkDescription;
public static string FrameworkDescription
{
get
{
if (s_frameworkDescription == null)
{
AssemblyFileVersionAttribute attr = (AssemblyFileVersionAttribute)(typeof(object).GetTypeInfo().Assembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute)));
Debug.Assert(attr != null);
s_frameworkDescription = $"{FrameworkName} {attr.Version}";
}
return s_frameworkDescription;
}
}
}
}
| // 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.Reflection;
using System.Diagnostics;
namespace System.Runtime.InteropServices
{
public static partial class RuntimeInformation
{
#if netcore50aot
private const string FrameworkName = ".NET Native";
#elif net45 || win8
private const string FrameworkName = ".NET Framework";
#else // netcore50 || wpa81 || other
private const string FrameworkName = ".NET Core";
#endif
private static string s_frameworkDescription;
public static string FrameworkDescription
{
get
{
AssemblyFileVersionAttribute attr = (AssemblyFileVersionAttribute)(typeof(object).GetTypeInfo().Assembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute)));
Debug.Assert(attr != null);
return s_frameworkDescription ??
(s_frameworkDescription = $"{FrameworkName} {attr.Version}");
}
}
}
}
| mit | C# |
10c81730e5f9112d12abcfa5893560e6b0cdc7f1 | Add waiting for updates. | masterrr/mobile,masterrr/mobile,eatskolnikov/mobile,eatskolnikov/mobile,ZhangLeiCharles/mobile,peeedge/mobile,eatskolnikov/mobile,ZhangLeiCharles/mobile,peeedge/mobile | Tests/Views/DataViewTest.cs | Tests/Views/DataViewTest.cs | using System;
using System.Linq;
using System.Threading.Tasks;
using Toggl.Phoebe.Data.DataObjects;
using Toggl.Phoebe.Data.Views;
namespace Toggl.Phoebe.Tests.Views
{
public abstract class DataViewTest : Test
{
protected DateTime MakeTime (int hour, int minute, int second = 0)
{
return Time.UtcNow.Date
.AddHours (hour)
.AddMinutes (minute)
.AddSeconds (second);
}
protected async Task<T> GetByRemoteId<T> (long remoteId)
where T : CommonData, new()
{
var rows = await DataStore.Table<T> ().QueryAsync (r => r.RemoteId == remoteId);
return rows.Single ();
}
protected async Task ChangeData<T> (long remoteId, Action<T> modifier)
where T : CommonData, new()
{
var model = await GetByRemoteId<T> (remoteId);
modifier (model);
await DataStore.PutAsync (model);
}
protected async Task WaitForLoaded<T> (IDataView<T> view)
{
if (!view.IsLoading)
return;
var tcs = new TaskCompletionSource<object> ();
EventHandler onUpdated = null;
onUpdated = delegate {
if (view.IsLoading)
return;
view.Updated -= onUpdated;
tcs.SetResult (null);
};
view.Updated += onUpdated;
await tcs.Task.ConfigureAwait (false);
}
protected async Task WaitForUpdates<T> (IDataView<T> view, int count = 1)
{
var tcs = new TaskCompletionSource<object> ();
EventHandler onUpdated = null;
onUpdated = delegate {
if (--count > 0)
return;
view.Updated -= onUpdated;
tcs.TrySetResult (null);
};
view.Updated += onUpdated;
await tcs.Task.ConfigureAwait (false);
}
}
}
| using System;
using System.Linq;
using System.Threading.Tasks;
using Toggl.Phoebe.Data.DataObjects;
using Toggl.Phoebe.Data.Views;
namespace Toggl.Phoebe.Tests.Views
{
public abstract class DataViewTest : Test
{
protected DateTime MakeTime (int hour, int minute, int second = 0)
{
return Time.UtcNow.Date
.AddHours (hour)
.AddMinutes (minute)
.AddSeconds (second);
}
protected async Task<T> GetByRemoteId<T> (long remoteId)
where T : CommonData, new()
{
var rows = await DataStore.Table<T> ().QueryAsync (r => r.RemoteId == remoteId);
return rows.Single ();
}
protected async Task ChangeData<T> (long remoteId, Action<T> modifier)
where T : CommonData, new()
{
var model = await GetByRemoteId<T> (remoteId);
modifier (model);
await DataStore.PutAsync (model);
}
protected async Task WaitForLoaded<T> (IDataView<T> view)
{
if (!view.IsLoading)
return;
var tcs = new TaskCompletionSource<object> ();
EventHandler onUpdated = null;
onUpdated = (s, e) => {
if (view.IsLoading)
return;
view.Updated -= onUpdated;
tcs.SetResult (null);
};
view.Updated += onUpdated;
await tcs.Task;
}
}
}
| bsd-3-clause | C# |
8906f8cffe46b128e2e5de6c2e1f71342ddca616 | Add EventListener for SelfDiagnostics (#2259) | Microsoft/ApplicationInsights-dotnet,pharring/ApplicationInsights-dotnet,pharring/ApplicationInsights-dotnet,pharring/ApplicationInsights-dotnet | BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/Tracing/SelfDiagnosticsInternals/SelfDiagnosticsEventListener.cs | BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/Tracing/SelfDiagnosticsInternals/SelfDiagnosticsEventListener.cs | namespace Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.SelfDiagnosticsInternals
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.Tracing;
using System.IO;
using System.Text;
using System.Threading;
/// <summary>
/// SelfDiagnosticsEventListener class enables the events from OpenTelemetry event sources
/// and write the events to a local file in a circular way.
/// </summary>
internal class SelfDiagnosticsEventListener : EventListener
{
private const string EventSourceNamePrefix = "Microsoft-ApplicationInsights-";
private readonly object lockObj = new object();
private readonly EventLevel logLevel;
// private readonly SelfDiagnosticsConfigRefresher configRefresher;
private readonly List<EventSource> eventSourcesBeforeConstructor = new List<EventSource>();
public SelfDiagnosticsEventListener(EventLevel logLevel/*, SelfDiagnosticsConfigRefresher configRefresher*/)
{
this.logLevel = logLevel;
// this.configRefresher = configRefresher ?? throw new ArgumentNullException(nameof(configRefresher));
List<EventSource> eventSources;
lock (this.lockObj)
{
eventSources = this.eventSourcesBeforeConstructor;
this.eventSourcesBeforeConstructor = null;
}
foreach (var eventSource in eventSources)
{
#if NET452
this.EnableEvents(eventSource, this.logLevel, (EventKeywords)(-1));
#else
this.EnableEvents(eventSource, this.logLevel, EventKeywords.All);
#endif
}
}
internal void WriteEvent(string eventMessage, ReadOnlyCollection<object> payload)
{
// TODO
}
protected override void OnEventSourceCreated(EventSource eventSource)
{
if (eventSource.Name.StartsWith(EventSourceNamePrefix, StringComparison.Ordinal))
{
// If there are EventSource classes already initialized as of now, this method would be called from
// the base class constructor before the first line of code in SelfDiagnosticsEventListener constructor.
// In this case logLevel is always its default value, "LogAlways".
// Thus we should save the event source and enable them later, when code runs in constructor.
if (this.eventSourcesBeforeConstructor != null)
{
lock (this.lockObj)
{
if (this.eventSourcesBeforeConstructor != null)
{
this.eventSourcesBeforeConstructor.Add(eventSource);
return;
}
}
}
#if NET452
this.EnableEvents(eventSource, this.logLevel, (EventKeywords)(-1));
#else
this.EnableEvents(eventSource, this.logLevel, EventKeywords.All);
#endif
}
base.OnEventSourceCreated(eventSource);
}
/// <summary>
/// This method records the events from event sources to a local file, which is provided as a stream object by
/// SelfDiagnosticsConfigRefresher class. The file size is bound to a upper limit. Once the write position
/// reaches the end, it will be reset to the beginning of the file.
/// </summary>
/// <param name="eventData">Data of the EventSource event.</param>
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
this.WriteEvent(eventData.Message, eventData.Payload);
}
}
}
| mit | C# | |
e9efc4f2e063a656ba4cb6d6d1992304ec4551ea | move getlisting sample | robinrodricks/FluentFTP,robinrodricks/FluentFTP,robinrodricks/FluentFTP | FluentFTP.Examples/GetListingWithLinks.cs | FluentFTP.Examples/GetListingWithLinks.cs | using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using FluentFTP;
namespace Examples {
internal static class GetListingWithLinksExample {
public static void GetListing() {
using (var conn = new FtpClient("127.0.0.1", "ftptest", "ftptest")) {
conn.Connect();
// get a listing of the files with their modified date & size
foreach (var item in conn.GetListing(conn.GetWorkingDirectory(),
FtpListOption.Modify | FtpListOption.Size)) {
switch (item.Type) {
case FtpFileSystemObjectType.Directory:
break;
case FtpFileSystemObjectType.File:
break;
case FtpFileSystemObjectType.Link:
// dereference symbolic links
if (item.LinkTarget != null) {
// see the DereferenceLink() example
// for more details about resolving links.
item.LinkObject = conn.DereferenceLink(item);
if (item.LinkObject != null) {
// switch (item.LinkObject.Type)...
}
}
break;
}
}
// same example except automatically dereference symbolic links.
// see the DereferenceLink() example for more details about resolving links.
foreach (var item in conn.GetListing(conn.GetWorkingDirectory(),
FtpListOption.Modify | FtpListOption.Size | FtpListOption.DerefLinks)) {
switch (item.Type) {
case FtpFileSystemObjectType.Directory:
break;
case FtpFileSystemObjectType.File:
break;
case FtpFileSystemObjectType.Link:
if (item.LinkObject != null) {
// switch (item.LinkObject.Type)...
}
break;
}
}
}
}
public static async Task GetListingAsync() {
var token = new CancellationToken();
using (var conn = new FtpClient("127.0.0.1", "ftptest", "ftptest")) {
await conn.ConnectAsync(token);
// get a listing of the files with their modified date & size
foreach (var item in await conn.GetListingAsync(conn.GetWorkingDirectory(),
FtpListOption.Modify | FtpListOption.Size, token)) {
switch (item.Type) {
case FtpFileSystemObjectType.Directory:
break;
case FtpFileSystemObjectType.File:
break;
case FtpFileSystemObjectType.Link:
// dereference symbolic links
if (item.LinkTarget != null) {
// see the DereferenceLink() example
// for more details about resolving links.
item.LinkObject = conn.DereferenceLink(item);
if (item.LinkObject != null) {
// switch (item.LinkObject.Type)...
}
}
break;
}
}
// same example except automatically dereference symbolic links.
// see the DereferenceLink() example for more details about resolving links.
foreach (var item in await conn.GetListingAsync(conn.GetWorkingDirectory(),
FtpListOption.Modify | FtpListOption.Size | FtpListOption.DerefLinks, token)) {
switch (item.Type) {
case FtpFileSystemObjectType.Directory:
break;
case FtpFileSystemObjectType.File:
break;
case FtpFileSystemObjectType.Link:
if (item.LinkObject != null) {
// switch (item.LinkObject.Type)...
}
break;
}
}
}
}
}
} | mit | C# | |
cb94366e5fd0346066a7aaed5682c3fbe8e296e5 | Add a platform detection mechanism to use in tests | shiftkey-tester/corefx,vs-team/corefx,Yanjing123/corefx,nchikanov/corefx,stormleoxia/corefx,the-dwyer/corefx,Chrisboh/corefx,jcme/corefx,dhoehna/corefx,misterzik/corefx,tstringer/corefx,Alcaro/corefx,seanshpark/corefx,alexandrnikitin/corefx,chenkennt/corefx,pallavit/corefx,Ermiar/corefx,jcme/corefx,shrutigarg/corefx,uhaciogullari/corefx,viniciustaveira/corefx,krk/corefx,tijoytom/corefx,ravimeda/corefx,JosephTremoulet/corefx,billwert/corefx,benjamin-bader/corefx,mmitche/corefx,janhenke/corefx,shana/corefx,bitcrazed/corefx,weltkante/corefx,Ermiar/corefx,wtgodbe/corefx,scott156/corefx,shahid-pk/corefx,alexperovich/corefx,parjong/corefx,vidhya-bv/corefx-sorting,richlander/corefx,zhenlan/corefx,alexperovich/corefx,uhaciogullari/corefx,adamralph/corefx,claudelee/corefx,gkhanna79/corefx,vijaykota/corefx,shmao/corefx,Alcaro/corefx,spoiledsport/corefx,ravimeda/corefx,ravimeda/corefx,krytarowski/corefx,MaggieTsang/corefx,brett25/corefx,Priya91/corefx-1,YoupHulsebos/corefx,krytarowski/corefx,heXelium/corefx,popolan1986/corefx,janhenke/corefx,akivafr123/corefx,MaggieTsang/corefx,janhenke/corefx,viniciustaveira/corefx,vidhya-bv/corefx-sorting,krk/corefx,oceanho/corefx,cartermp/corefx,jeremymeng/corefx,shimingsg/corefx,nbarbettini/corefx,dotnet-bot/corefx,alphonsekurian/corefx,shrutigarg/corefx,billwert/corefx,n1ghtmare/corefx,Petermarcu/corefx,rjxby/corefx,jmhardison/corefx,manu-silicon/corefx,claudelee/corefx,Ermiar/corefx,jhendrixMSFT/corefx,cartermp/corefx,SGuyGe/corefx,weltkante/corefx,gregg-miskelly/corefx,elijah6/corefx,Yanjing123/corefx,the-dwyer/corefx,PatrickMcDonald/corefx,elijah6/corefx,Jiayili1/corefx,JosephTremoulet/corefx,BrennanConroy/corefx,huanjie/corefx,dtrebbien/corefx,manu-silicon/corefx,rahku/corefx,VPashkov/corefx,cnbin/corefx,gkhanna79/corefx,nbarbettini/corefx,stephenmichaelf/corefx,benpye/corefx,alexperovich/corefx,dkorolev/corefx,gkhanna79/corefx,DnlHarvey/corefx,janhenke/corefx,CherryCxldn/corefx,Chrisboh/corefx,alphonsekurian/corefx,iamjasonp/corefx,krytarowski/corefx,manu-silicon/corefx,alexperovich/corefx,chaitrakeshav/corefx,ericstj/corefx,PatrickMcDonald/corefx,Ermiar/corefx,zhenlan/corefx,zmaruo/corefx,akivafr123/corefx,misterzik/corefx,erpframework/corefx,Petermarcu/corefx,shrutigarg/corefx,YoupHulsebos/corefx,parjong/corefx,khdang/corefx,lydonchandra/corefx,erpframework/corefx,twsouthwick/corefx,billwert/corefx,fffej/corefx,thiagodin/corefx,rubo/corefx,zhangwenquan/corefx,jcme/corefx,tstringer/corefx,benjamin-bader/corefx,gabrielPeart/corefx,shmao/corefx,anjumrizwi/corefx,YoupHulsebos/corefx,shahid-pk/corefx,oceanho/corefx,shiftkey-tester/corefx,brett25/corefx,kyulee1/corefx,marksmeltzer/corefx,rahku/corefx,claudelee/corefx,larsbj1988/corefx,stormleoxia/corefx,mokchhya/corefx,kkurni/corefx,mmitche/corefx,stormleoxia/corefx,nelsonsar/corefx,BrennanConroy/corefx,ravimeda/corefx,dhoehna/corefx,benjamin-bader/corefx,Yanjing123/corefx,Jiayili1/corefx,Priya91/corefx-1,JosephTremoulet/corefx,heXelium/corefx,adamralph/corefx,arronei/corefx,huanjie/corefx,iamjasonp/corefx,rjxby/corefx,popolan1986/corefx,CloudLens/corefx,SGuyGe/corefx,alexandrnikitin/corefx,jlin177/corefx,zhenlan/corefx,weltkante/corefx,cydhaselton/corefx,ptoonen/corefx,Chrisboh/corefx,Chrisboh/corefx,lggomez/corefx,stone-li/corefx,shmao/corefx,ericstj/corefx,kkurni/corefx,dtrebbien/corefx,ellismg/corefx,YoupHulsebos/corefx,690486439/corefx,spoiledsport/corefx,axelheer/corefx,kyulee1/corefx,shmao/corefx,ptoonen/corefx,zhangwenquan/corefx,weltkante/corefx,marksmeltzer/corefx,ravimeda/corefx,bpschoch/corefx,Frank125/corefx,rjxby/corefx,jmhardison/corefx,ViktorHofer/corefx,comdiv/corefx,ericstj/corefx,anjumrizwi/corefx,iamjasonp/corefx,twsouthwick/corefx,dsplaisted/corefx,DnlHarvey/corefx,mmitche/corefx,wtgodbe/corefx,mellinoe/corefx,shrutigarg/corefx,shmao/corefx,jmhardison/corefx,jhendrixMSFT/corefx,nelsonsar/corefx,richlander/corefx,cnbin/corefx,tstringer/corefx,josguil/corefx,jhendrixMSFT/corefx,VPashkov/corefx,andyhebear/corefx,krk/corefx,ravimeda/corefx,thiagodin/corefx,arronei/corefx,MaggieTsang/corefx,rahku/corefx,dhoehna/corefx,billwert/corefx,cydhaselton/corefx,mazong1123/corefx,ptoonen/corefx,thiagodin/corefx,dhoehna/corefx,rjxby/corefx,rajansingh10/corefx,VPashkov/corefx,pallavit/corefx,ellismg/corefx,heXelium/corefx,shahid-pk/corefx,seanshpark/corefx,anjumrizwi/corefx,s0ne0me/corefx,bitcrazed/corefx,jlin177/corefx,yizhang82/corefx,YoupHulsebos/corefx,DnlHarvey/corefx,wtgodbe/corefx,690486439/corefx,iamjasonp/corefx,690486439/corefx,nbarbettini/corefx,matthubin/corefx,fffej/corefx,lggomez/corefx,pallavit/corefx,kkurni/corefx,weltkante/corefx,nchikanov/corefx,matthubin/corefx,parjong/corefx,viniciustaveira/corefx,xuweixuwei/corefx,scott156/corefx,parjong/corefx,pallavit/corefx,cartermp/corefx,mazong1123/corefx,tijoytom/corefx,jlin177/corefx,dsplaisted/corefx,destinyclown/corefx,n1ghtmare/corefx,twsouthwick/corefx,KrisLee/corefx,nchikanov/corefx,comdiv/corefx,Winsto/corefx,ptoonen/corefx,dhoehna/corefx,JosephTremoulet/corefx,parjong/corefx,krk/corefx,iamjasonp/corefx,manu-silicon/corefx,vidhya-bv/corefx-sorting,jhendrixMSFT/corefx,jeremymeng/corefx,marksmeltzer/corefx,shiftkey-tester/corefx,cydhaselton/corefx,SGuyGe/corefx,Petermarcu/corefx,rjxby/corefx,MaggieTsang/corefx,richlander/corefx,KrisLee/corefx,nbarbettini/corefx,parjong/corefx,mafiya69/corefx,ericstj/corefx,fernando-rodriguez/corefx,billwert/corefx,oceanho/corefx,mmitche/corefx,the-dwyer/corefx,gabrielPeart/corefx,ptoonen/corefx,destinyclown/corefx,fgreinacher/corefx,scott156/corefx,690486439/corefx,stephenmichaelf/corefx,bpschoch/corefx,gabrielPeart/corefx,bitcrazed/corefx,mafiya69/corefx,elijah6/corefx,pgavlin/corefx,dkorolev/corefx,mmitche/corefx,spoiledsport/corefx,popolan1986/corefx,krytarowski/corefx,PatrickMcDonald/corefx,alexandrnikitin/corefx,stone-li/corefx,rahku/corefx,rubo/corefx,DnlHarvey/corefx,jcme/corefx,khdang/corefx,stephenmichaelf/corefx,uhaciogullari/corefx,matthubin/corefx,mokchhya/corefx,Jiayili1/corefx,ViktorHofer/corefx,stormleoxia/corefx,CloudLens/corefx,Ermiar/corefx,viniciustaveira/corefx,benpye/corefx,parjong/corefx,huanjie/corefx,dkorolev/corefx,ericstj/corefx,n1ghtmare/corefx,yizhang82/corefx,dhoehna/corefx,cydhaselton/corefx,Frank125/corefx,Frank125/corefx,stone-li/corefx,kkurni/corefx,elijah6/corefx,nchikanov/corefx,EverlessDrop41/corefx,iamjasonp/corefx,shana/corefx,CherryCxldn/corefx,Chrisboh/corefx,ericstj/corefx,the-dwyer/corefx,benjamin-bader/corefx,tstringer/corefx,billwert/corefx,ViktorHofer/corefx,uhaciogullari/corefx,khdang/corefx,seanshpark/corefx,janhenke/corefx,ptoonen/corefx,shana/corefx,benjamin-bader/corefx,axelheer/corefx,ellismg/corefx,khdang/corefx,gregg-miskelly/corefx,jeremymeng/corefx,alphonsekurian/corefx,690486439/corefx,yizhang82/corefx,shimingsg/corefx,gkhanna79/corefx,stone-li/corefx,andyhebear/corefx,marksmeltzer/corefx,alexperovich/corefx,mazong1123/corefx,alphonsekurian/corefx,Winsto/corefx,erpframework/corefx,shimingsg/corefx,shimingsg/corefx,shimingsg/corefx,lydonchandra/corefx,larsbj1988/corefx,mafiya69/corefx,mellinoe/corefx,vs-team/corefx,CherryCxldn/corefx,elijah6/corefx,oceanho/corefx,ellismg/corefx,chenkennt/corefx,rahku/corefx,jeremymeng/corefx,mazong1123/corefx,cartermp/corefx,akivafr123/corefx,wtgodbe/corefx,pgavlin/corefx,josguil/corefx,jcme/corefx,fernando-rodriguez/corefx,seanshpark/corefx,kyulee1/corefx,fgreinacher/corefx,gkhanna79/corefx,Priya91/corefx-1,elijah6/corefx,lggomez/corefx,axelheer/corefx,ViktorHofer/corefx,andyhebear/corefx,shiftkey-tester/corefx,EverlessDrop41/corefx,shahid-pk/corefx,anjumrizwi/corefx,stone-li/corefx,s0ne0me/corefx,krk/corefx,krk/corefx,tijoytom/corefx,the-dwyer/corefx,alphonsekurian/corefx,MaggieTsang/corefx,ericstj/corefx,misterzik/corefx,richlander/corefx,pallavit/corefx,jeremymeng/corefx,jmhardison/corefx,bpschoch/corefx,axelheer/corefx,krytarowski/corefx,tijoytom/corefx,rajansingh10/corefx,zmaruo/corefx,stephenmichaelf/corefx,dkorolev/corefx,seanshpark/corefx,larsbj1988/corefx,cydhaselton/corefx,seanshpark/corefx,ravimeda/corefx,stephenmichaelf/corefx,huanjie/corefx,twsouthwick/corefx,jlin177/corefx,claudelee/corefx,destinyclown/corefx,dotnet-bot/corefx,zhenlan/corefx,zhangwenquan/corefx,jlin177/corefx,ellismg/corefx,thiagodin/corefx,ellismg/corefx,lggomez/corefx,SGuyGe/corefx,manu-silicon/corefx,heXelium/corefx,cartermp/corefx,dhoehna/corefx,shahid-pk/corefx,twsouthwick/corefx,shmao/corefx,mellinoe/corefx,kkurni/corefx,Alcaro/corefx,dotnet-bot/corefx,benpye/corefx,mokchhya/corefx,pallavit/corefx,rahku/corefx,lggomez/corefx,Ermiar/corefx,vrassouli/corefx,yizhang82/corefx,rubo/corefx,erpframework/corefx,alexandrnikitin/corefx,VPashkov/corefx,lydonchandra/corefx,kkurni/corefx,kyulee1/corefx,shana/corefx,KrisLee/corefx,mafiya69/corefx,chaitrakeshav/corefx,rubo/corefx,xuweixuwei/corefx,wtgodbe/corefx,CherryCxldn/corefx,josguil/corefx,jlin177/corefx,manu-silicon/corefx,iamjasonp/corefx,rjxby/corefx,JosephTremoulet/corefx,mazong1123/corefx,gkhanna79/corefx,Petermarcu/corefx,alphonsekurian/corefx,mokchhya/corefx,shmao/corefx,shahid-pk/corefx,yizhang82/corefx,n1ghtmare/corefx,twsouthwick/corefx,tijoytom/corefx,vidhya-bv/corefx-sorting,krk/corefx,marksmeltzer/corefx,rubo/corefx,Petermarcu/corefx,pgavlin/corefx,jhendrixMSFT/corefx,mazong1123/corefx,benjamin-bader/corefx,jcme/corefx,lydonchandra/corefx,EverlessDrop41/corefx,cydhaselton/corefx,nbarbettini/corefx,richlander/corefx,janhenke/corefx,shimingsg/corefx,JosephTremoulet/corefx,Yanjing123/corefx,bitcrazed/corefx,benpye/corefx,gregg-miskelly/corefx,akivafr123/corefx,chaitrakeshav/corefx,shimingsg/corefx,nchikanov/corefx,vs-team/corefx,andyhebear/corefx,matthubin/corefx,alphonsekurian/corefx,Priya91/corefx-1,chenxizhang/corefx,fffej/corefx,vijaykota/corefx,richlander/corefx,Jiayili1/corefx,zmaruo/corefx,benpye/corefx,mmitche/corefx,vidhya-bv/corefx-sorting,fernando-rodriguez/corefx,nchikanov/corefx,axelheer/corefx,nbarbettini/corefx,gkhanna79/corefx,josguil/corefx,axelheer/corefx,marksmeltzer/corefx,s0ne0me/corefx,DnlHarvey/corefx,Ermiar/corefx,stone-li/corefx,rajansingh10/corefx,Jiayili1/corefx,ViktorHofer/corefx,tstringer/corefx,arronei/corefx,cnbin/corefx,the-dwyer/corefx,bitcrazed/corefx,richlander/corefx,khdang/corefx,josguil/corefx,dotnet-bot/corefx,rahku/corefx,nbarbettini/corefx,stone-li/corefx,PatrickMcDonald/corefx,Priya91/corefx-1,krytarowski/corefx,comdiv/corefx,zhenlan/corefx,chenxizhang/corefx,bpschoch/corefx,tstringer/corefx,benpye/corefx,tijoytom/corefx,YoupHulsebos/corefx,wtgodbe/corefx,jlin177/corefx,wtgodbe/corefx,Petermarcu/corefx,weltkante/corefx,cydhaselton/corefx,pgavlin/corefx,scott156/corefx,rajansingh10/corefx,josguil/corefx,gregg-miskelly/corefx,DnlHarvey/corefx,fffej/corefx,stephenmichaelf/corefx,Priya91/corefx-1,yizhang82/corefx,weltkante/corefx,vrassouli/corefx,alexperovich/corefx,mafiya69/corefx,zhenlan/corefx,SGuyGe/corefx,dotnet-bot/corefx,cnbin/corefx,xuweixuwei/corefx,adamralph/corefx,fgreinacher/corefx,MaggieTsang/corefx,KrisLee/corefx,marksmeltzer/corefx,Petermarcu/corefx,jhendrixMSFT/corefx,nelsonsar/corefx,akivafr123/corefx,DnlHarvey/corefx,Jiayili1/corefx,Frank125/corefx,chenxizhang/corefx,seanshpark/corefx,mokchhya/corefx,ViktorHofer/corefx,mellinoe/corefx,tijoytom/corefx,zhangwenquan/corefx,mellinoe/corefx,s0ne0me/corefx,gabrielPeart/corefx,brett25/corefx,khdang/corefx,ViktorHofer/corefx,lggomez/corefx,Yanjing123/corefx,vijaykota/corefx,Jiayili1/corefx,alexperovich/corefx,CloudLens/corefx,dtrebbien/corefx,Alcaro/corefx,twsouthwick/corefx,yizhang82/corefx,SGuyGe/corefx,fgreinacher/corefx,comdiv/corefx,dotnet-bot/corefx,PatrickMcDonald/corefx,elijah6/corefx,JosephTremoulet/corefx,alexandrnikitin/corefx,stephenmichaelf/corefx,zmaruo/corefx,n1ghtmare/corefx,ptoonen/corefx,cartermp/corefx,vrassouli/corefx,billwert/corefx,brett25/corefx,larsbj1988/corefx,mmitche/corefx,vrassouli/corefx,rjxby/corefx,vs-team/corefx,mafiya69/corefx,jhendrixMSFT/corefx,mazong1123/corefx,manu-silicon/corefx,nchikanov/corefx,mokchhya/corefx,dtrebbien/corefx,Chrisboh/corefx,CloudLens/corefx,dsplaisted/corefx,lggomez/corefx,BrennanConroy/corefx,MaggieTsang/corefx,nelsonsar/corefx,mellinoe/corefx,Winsto/corefx,YoupHulsebos/corefx,zhenlan/corefx,krytarowski/corefx,the-dwyer/corefx,chenkennt/corefx,chaitrakeshav/corefx,dotnet-bot/corefx | src/Common/src/Interop/Interop.PlatformDetection.cs | src/Common/src/Interop/Interop.PlatformDetection.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.InteropServices;
// TODO: This implementation is temporary until Environment.OSVersion is officially exposed,
// at which point that should be used instead.
internal static partial class Interop
{
internal enum OperatingSystem
{
Windows,
Linux,
OSX
}
internal static class PlatformDetection
{
internal static OperatingSystem OperatingSystem { get { return s_os.Value; } }
private static readonly Lazy<OperatingSystem> s_os = new Lazy<OperatingSystem>(() =>
{
if (Environment.NewLine != "\r\n")
{
unsafe
{
byte* buffer = stackalloc byte[8192]; // the size use with uname is platform specific; this should be large enough for any OS
if (uname(buffer) == 0)
{
return Marshal.PtrToStringAnsi((IntPtr)buffer) == "Darwin" ?
OperatingSystem.OSX :
OperatingSystem.Linux;
}
}
}
return OperatingSystem.Windows;
});
// not in src\Interop\Unix to avoiding pulling platform-dependent files into all projects
[DllImport("libc")]
private static extern unsafe uint uname(byte* buf);
}
}
| mit | C# | |
703ab59cbc64755acee4aa738c53af8fa1ac5ddf | Add enumerable-based methods | farity/farity | CSharp.Functional/Enumerable.cs | CSharp.Functional/Enumerable.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace CSharp.Functional
{
public static partial class F
{
public static IEnumerable<int> Range(int start, int end) => Enumerable.Range(start, end - start + 1);
public static IList<T> ToList<T>(IEnumerable<T> source) => source.ToList();
public static IEnumerable<T> Reverse<T>(IEnumerable<T> source) => source.Reverse();
public static IEnumerable<T> Drop<T>(int count, IEnumerable<T> source) => source.Skip(count);
public static IEnumerable<T> Take<T>(int count, IEnumerable<T> source) => source.Take(count);
public static IEnumerable<T> Sort<T>(IEnumerable<T> source) => source.OrderBy(x => x);
public static IEnumerable<T> Unique<T>(IEnumerable<T> source) => source.Distinct();
public static IEnumerable<T> SkipUntil<T>(int index, IEnumerable<T> source)
{
if (!(source is IReadOnlyList<T>))
{
var i = 0;
foreach (var item in source)
if (index >= i++) yield return item;
}
var list = (IReadOnlyList<T>) source;
for (var i = index; i < list.Count; i++)
yield return list[i];
}
public static IEnumerable<T> Filter<T>(Func<T, bool> predicate, IEnumerable<T> source)
=> source.Where(predicate);
public static IEnumerable<T> DefaultTo<T>(T value, IEnumerable<T> source) => source.DefaultIfEmpty(value);
public static T First<T>(IEnumerable<T> source) => source.First();
public static T Last<T>(IEnumerable<T> source) => source.Last();
}
} | mit | C# | |
066ec81e2acb2f88811e87fa3122bd7d9263007f | Add extension methods for logging timings | github/VisualStudio,github/VisualStudio,github/VisualStudio | src/GitHub.Logging/Logging/ILoggerExtensions.cs | src/GitHub.Logging/Logging/ILoggerExtensions.cs | using System;
using System.Globalization;
using System.Threading.Tasks;
using Serilog;
namespace GitHub.Logging
{
public static class ILoggerExtensions
{
public static void Assert(this ILogger logger, bool condition, string messageTemplate)
{
if (!condition)
{
messageTemplate = "Assertion Failed: " + messageTemplate;
#pragma warning disable Serilog004 // propertyValues might not be strings
logger.Warning(messageTemplate);
#pragma warning restore Serilog004
}
}
public static void Assert(this ILogger logger, bool condition, string messageTemplate, params object[] propertyValues)
{
if (!condition)
{
messageTemplate = "Assertion Failed: " + messageTemplate;
#pragma warning disable Serilog004 // propertyValues might not be strings
logger.Warning(messageTemplate, propertyValues);
#pragma warning restore Serilog004
}
}
public static void Time(this ILogger logger, string name, Action method)
{
var startTime = DateTime.Now;
method();
logger.Information("{Name} took {Seconds} seconds", name, FormatSeconds(DateTime.Now - startTime));
}
public static T Time<T>(this ILogger logger, string name, Func<T> method)
{
var startTime = DateTime.Now;
var value = method();
logger.Information("{Name} took {Seconds} seconds", name, FormatSeconds(DateTime.Now - startTime));
return value;
}
public static async Task TimeAsync(this ILogger logger, string name, Func<Task> methodAsync)
{
var startTime = DateTime.Now;
await methodAsync().ConfigureAwait(false);
logger.Information("{Name} took {Seconds} seconds", name, FormatSeconds(DateTime.Now - startTime));
}
public static async Task<T> TimeAsync<T>(this ILogger logger, string name, Func<Task<T>> methodAsync)
{
var startTime = DateTime.Now;
var value = await methodAsync().ConfigureAwait(false);
logger.Information("{Name} took {Seconds} seconds", name, FormatSeconds(DateTime.Now - startTime));
return value;
}
static string FormatSeconds(TimeSpan timeSpan) => timeSpan.TotalSeconds.ToString("0.##", CultureInfo.InvariantCulture);
}
}
| using Serilog;
namespace GitHub.Logging
{
public static class ILoggerExtensions
{
public static void Assert(this ILogger logger, bool condition, string messageTemplate)
{
if (!condition)
{
messageTemplate = "Assertion Failed: " + messageTemplate;
#pragma warning disable Serilog004 // propertyValues might not be strings
logger.Warning(messageTemplate);
#pragma warning restore Serilog004
}
}
public static void Assert(this ILogger logger, bool condition, string messageTemplate, params object[] propertyValues)
{
if (!condition)
{
messageTemplate = "Assertion Failed: " + messageTemplate;
#pragma warning disable Serilog004 // propertyValues might not be strings
logger.Warning(messageTemplate, propertyValues);
#pragma warning restore Serilog004
}
}
}
} | mit | C# |
af589322692f5371cc8026ece280d3a3877c9027 | Create TripPlanner.cs | jbengtson/ksp-precisenode | TripPlanner.cs | TripPlanner.cs | using System;
using System.Collections.Generic;
using UnityEngine;
using KSP.IO;
/******************************************************************************
* Copyright (c) 2013, Justin Bengtson
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
namespace RegexKSP {
public class TripPlanner {
private NodeTools tools = new NodeTools();
private Rect windowPos = new Rect(Screen.width / 3, Screen.width / 3, 400, 130);
public void drawTripPlannerWindow(int id) {
PatchedConicSolver solver = tools.getSolver();
Color defaultColor = GUI.backgroundColor;
// Close button
if(GUI.Button(new Rect(windowPos.width - 24, 2, 22, 18), "X")) {
this.show = false;
}
GUILayout.BeginVertical();
GUILayout.EndVertical();
GUI.DragWindow();
}
public bool show { get; set; }
}
}
| bsd-2-clause | C# | |
42e9df5bde0acdeb19dbdb2d2d3f1f231de66035 | Implement longest repeated pattern | cschen1205/cs-algorithms,cschen1205/cs-algorithms | Algorithms/Strings/Search/LongestRepeatedPattern.cs | Algorithms/Strings/Search/LongestRepeatedPattern.cs | using System;
using Algorithms.Sorting;
namespace Algorithms.Strings.Search
{
public class LongestRepeatedPattern
{
public static String Find(String text)
{
int N = text.Length;
String[] a = new String[N];
for (var i = 0; i < N; ++i)
{
a[i] = text.Substring(i, N);
}
QuickSort.Sort(a);
String result = "";
for (int i = 0; i < N-1; ++i)
{
var j = lcp(a[i], a[i + 1]);
if (result.Length < j)
{
result = a[i].Substring(0, j);
}
}
return result;
}
private static int lcp(String s1, String s2)
{
int k = Math.Min(s1.Length, s2.Length);
var i = 0;
for (i = 0; i < k; ++i)
{
if (s1[i] != s2[i])
{
break;
}
}
return i;
}
}
} | mit | C# | |
b81b9ab23fadf0c14e10189c84d83048fc8234da | Update #29 | lucasdavid/Gamedalf,lucasdavid/Gamedalf | Gamedalf.Services/PlayingService.cs | Gamedalf.Services/PlayingService.cs | using Gamedalf.Core.Data;
using Gamedalf.Core.Models;
using Gamedalf.Services.Infrastructure;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
namespace Gamedalf.Services
{
public class PlayingService : Service<Playing>
{
public PlayingService(ApplicationDbContext db) : base(db) { }
public async Task<Playing> Find(int id)
{
return await Db.Playings
.Where(p => p.Id == id)
.Include(p => p.Game).Include(p => p.Player)
.FirstAsync();
}
public async Task<ICollection<Playing>> Search(string q)
{
if (String.IsNullOrEmpty(q))
{
return await All();
}
return await Db.Playings
.Where(p =>
p.Player.Email.Contains(q)
|| p.Game.Developer.Email.Contains(q)
|| p.Game.Employee.Email.Contains(q))
.Include(p => p.Game).Include(p => p.Player)
.OrderBy(p => p.Id)
.ToListAsync();
}
public async Task<ICollection<Playing>> EvaluatedByMe(string id)
{
return await Db.Playings
.Where(p =>
p.PlayerId == id && p.ReviewDateCreated != null)
.ToListAsync();
}
public async Task<ICollection<Playing>> NotYetEvaluated(string id)
{
return await Db.Playings
.Where(p =>
p.PlayerId == id && p.ReviewDateCreated != null)
.ToListAsync();
}
public async Task<ICollection<Playing>> MyPlayings(string id, string q)
{
if (String.IsNullOrEmpty(q))
{
return await Db.Playings
.Where(p => p.PlayerId == id)
.Include(p => p.Player).Include(p => p.Game)
.ToListAsync();
}
return await Db.Playings
.Where(p =>
p.PlayerId == id
&& (p.Game.Title.Contains(q)
|| p.Game.Developer.Email.Contains(q)))
.Include(p => p.Player).Include(p => p.Game)
.OrderBy(p => p.Id)
.ToListAsync();
}
public async Task<Playing> Evaluate(Playing evaluation)
{
var playing = await base.Find(evaluation.Id);
playing.Review = evaluation.Review;
playing.Score = evaluation.Score;
playing.ReviewDateCreated = DateTime.Now;
await Update(playing);
return playing;
}
}
}
| mit | C# | |
3d5297d0c1ecaf2fdaabd5422a2f917f581e3d41 | Multiply strings | Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews | LeetCode/remote/multiply_strings.cs | LeetCode/remote/multiply_strings.cs | // https://leetcode.com/problems/multiply-strings/
//
// Given two numbers represented as strings, return multiplication of the numbers as a string.
//
// Note: The numbers can be arbitrarily large and are non-negative.
using System;
using System.Linq;
public class Solution {
//
// Submission Details
// 311 / 311 test cases passed.
// Status: Accepted
// Runtime: 344 ms Pretty slow
//
// Submitted: 0 minutes ago
//
// https://leetcode.com/submissions/detail/52847898/
public string Multiply(string num1, string num2) {
var result = String.Empty;
num1 = new String(num1.Reverse().ToArray());
num2 = new String(num2.Reverse().ToArray());
for (var i = 0; i < num2.Length; i++)
{
var current = String.Empty;
for (var k = 0; k < i; k++)
{
current += "0";
}
int carry = 0;
for (var j = 0; j < num1.Length; j++)
{
var localResult = carry + (num2[i] - '0') * (num1[j] - '0');
current += (localResult % 10).ToString();
carry = localResult / 10;
}
if (carry != 0)
{
current += carry.ToString();
}
result = Add(current, result, 0).TrimEnd(new [] {'0'}); // Corner case shaming - did not handle trailing zeroes
}
return String.IsNullOrEmpty(result) ? "0" : new String(result.Reverse().ToArray()); // Corner case shaming - did not handle empty string when
// handling trailing zeroes
}
public String Add(String num1, String num2, int carry)
{
if (String.IsNullOrEmpty(num1) && String.IsNullOrEmpty(num2))
{
return carry == 0 ? String.Empty : (carry % 10).ToString() + Add(num1, num2, carry / 10);
}
var local = carry +
(String.IsNullOrEmpty(num1) ? 0 : num1[0] - '0') +
(String.IsNullOrEmpty(num2) ? 0 : num2[0] - '0');
if (String.IsNullOrEmpty(num1))
{
return (local % 10).ToString() + Add(num1, num2.Substring(1), local / 10);
}
if (String.IsNullOrEmpty(num2))
{
return (local % 10).ToString() + Add(num1.Substring(1), num2, local / 10);
}
return (local % 10).ToString() + Add(num1.Substring(1), num2.Substring(1), local / 10);
}
static void Main()
{
Console.WriteLine(new Solution().Multiply("2", "3"));
Console.WriteLine(new Solution().Multiply("20", "3"));
Console.WriteLine(new Solution().Multiply("3", "6"));
Console.WriteLine(new Solution().Multiply("11", "323"));
Console.WriteLine(new Solution().Multiply("113", "0"));
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.