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
cf0f30e92663fcad060d09297e5eca384256b2ff
Increase version info
ZEISS-PiWeb/PiWeb-Formplots
SDK/Formplots/Properties/AssemblyInfo.cs
SDK/Formplots/Properties/AssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("PiWeb Formplots")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyCompany("Carl Zeiss Innovationszentrum für Messtechnik GmbH")] [assembly: AssemblyProduct("PiWeb")] [assembly: AssemblyCopyright("Copyright © 2017 Carl Zeiss Innovationszentrum für Messtechnik GmbH")] [assembly: AssemblyTrademark("PiWeb")] [assembly: AssemblyCulture("")]
using System.Reflection; [assembly: AssemblyTitle("PiWeb Formplots")] [assembly: AssemblyVersion("1.0.3.0")] [assembly: AssemblyCompany("Carl Zeiss Innovationszentrum für Messtechnik GmbH")] [assembly: AssemblyProduct("PiWeb")] [assembly: AssemblyCopyright("Copyright © 2017 Carl Zeiss Innovationszentrum für Messtechnik GmbH")] [assembly: AssemblyTrademark("PiWeb")] [assembly: AssemblyCulture("")]
bsd-3-clause
C#
7358d784ddf44f90fd96163e2f7a7a3c741966d4
Fix a bug that caused the sensor host to crash
rossdargan/PRTG-Sensors
Sensors/UpsSensor/UpsSensor/UPSSensor.cs
Sensors/UpsSensor/UpsSensor/UPSSensor.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PowerChuteCS; using SensorHost.Shared; namespace UpsSensor { public class UPSSensor : SensorHost.Shared.SensorBase { private PowerChuteData _dataFactory; public UPSSensor() { Console.WriteLine("Created instance of PowerChute"); _dataFactory = PowerChuteData.getInstance(); } public override IEnumerable<Result> Results() { return GetData(); } public List<Result> GetData() { List<Result> results = new List<Result>(); try { var currentStatusData = _dataFactory.GetCurrentStatusData(); double energyUsage = currentStatusData.m_percentLoad / 100.0 * currentStatusData.m_config_active_power; results.Add(new Result("Load Percent", currentStatusData.m_percentLoad) { Unit = UnitTypes.Percent }); results.Add(new Result("Energy Usage", energyUsage) { Unit = UnitTypes.Custom, CustomUnit = "Watts" }); return results; } catch (Exception err) { Console.WriteLine($"Error getting data from UPS: {err}"); } return results; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PowerChuteCS; using SensorHost.Shared; namespace UpsSensor { public class UPSSensor : SensorHost.Shared.SensorBase { public override IEnumerable<Result> Results() { return GetData(); } public List<Result> GetData() { PowerChuteData dataFactory = PowerChuteData.getInstance(); var currentStatusData = dataFactory.GetCurrentStatusData(); double energyUsage = currentStatusData.m_percentLoad / 100.0 * currentStatusData.m_config_active_power; List<Result> results = new List<Result>(); results.Add(new Result("Load Percent", currentStatusData.m_percentLoad) { Unit = UnitTypes.Percent }); results.Add(new Result("Energy Usage", energyUsage) { Unit = UnitTypes.Custom, CustomUnit = "Watts" }); return results; } } }
apache-2.0
C#
0f2f363f5f1316d83ebf5d9f4a3d9b2248ed991b
Prepare new release.
AlegriGroup/FeatureSwitcher.VstsConfiguration
src/FeatureSwitcher.VstsConfiguration/Properties/AssemblyInfo.cs
src/FeatureSwitcher.VstsConfiguration/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("FeatureSwitcher.VstsConfiguration")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Alegri International Service GmbH")] [assembly: AssemblyProduct("FeatureSwitcher.VstsConfiguration")] [assembly: AssemblyCopyright("Copyright © Alegri International Service GmbH 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ba9392fc-fb58-45ca-9142-bd77bb26f21c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.0.0")] #pragma warning disable CS7035 // The specified version string does not conform to the recommended format - major.minor.build.revision [assembly: AssemblyFileVersion("1.2.0.0")] #pragma warning restore CS7035 // The specified version string does not conform to the recommended format - major.minor.build.revision [assembly: InternalsVisibleTo("FeatureSwitcher.VstsConfiguration.Tests")]
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("FeatureSwitcher.VstsConfiguration")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Alegri International Service GmbH")] [assembly: AssemblyProduct("FeatureSwitcher.VstsConfiguration")] [assembly: AssemblyCopyright("Copyright © Alegri International Service GmbH 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ba9392fc-fb58-45ca-9142-bd77bb26f21c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.0")] #pragma warning disable CS7035 // The specified version string does not conform to the recommended format - major.minor.build.revision [assembly: AssemblyFileVersion("1.1.0.0")] #pragma warning restore CS7035 // The specified version string does not conform to the recommended format - major.minor.build.revision [assembly: InternalsVisibleTo("FeatureSwitcher.VstsConfiguration.Tests")]
mit
C#
05ec31dbcb21a70b9595a8ee979df99c8e6c8bf3
make sync
shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,tmat/roslyn,KevinRansom/roslyn,wvdd007/roslyn,physhi/roslyn,bartdesmet/roslyn,panopticoncentral/roslyn,KevinRansom/roslyn,tannergooding/roslyn,diryboy/roslyn,panopticoncentral/roslyn,tannergooding/roslyn,dotnet/roslyn,diryboy/roslyn,dotnet/roslyn,sharwell/roslyn,mavasani/roslyn,AlekseyTs/roslyn,panopticoncentral/roslyn,ErikSchierboom/roslyn,weltkante/roslyn,KevinRansom/roslyn,mavasani/roslyn,AmadeusW/roslyn,physhi/roslyn,AmadeusW/roslyn,mgoertz-msft/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,eriawan/roslyn,wvdd007/roslyn,ErikSchierboom/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,ErikSchierboom/roslyn,wvdd007/roslyn,tmat/roslyn,sharwell/roslyn,AlekseyTs/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,tmat/roslyn,jasonmalinowski/roslyn,diryboy/roslyn,eriawan/roslyn,physhi/roslyn,mgoertz-msft/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,tannergooding/roslyn,mgoertz-msft/roslyn,AmadeusW/roslyn,sharwell/roslyn,bartdesmet/roslyn,AlekseyTs/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,bartdesmet/roslyn,weltkante/roslyn
src/Features/Core/Portable/Diagnostics/IDiagnosticModeService.cs
src/Features/Core/Portable/Diagnostics/IDiagnosticModeService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Service exposed to determine what diagnostic mode a workspace is in. Exposed in this fashion so that individual /// workspaces can override that value based on other factors. /// </summary> internal interface IDiagnosticModeService : IWorkspaceService { DiagnosticMode GetDiagnosticMode(Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken); } [ExportWorkspaceService(typeof(IDiagnosticModeService)), Shared] internal class DefaultDiagnosticModeServiceFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultDiagnosticModeServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new DefaultDiagnosticModeService(workspaceServices.Workspace); private class DefaultDiagnosticModeService : IDiagnosticModeService { private readonly Workspace _workspace; public DefaultDiagnosticModeService(Workspace workspace) => _workspace = workspace; public DiagnosticMode GetDiagnosticMode(Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) => _workspace.Options.GetOption(diagnosticMode); } } internal static class DiagnosticModeExtensions { public static DiagnosticMode GetDiagnosticMode(this Workspace workspace, Option2<DiagnosticMode> option, CancellationToken cancellationToken) { var service = workspace.Services.GetRequiredService<IDiagnosticModeService>(); return service.GetDiagnosticMode(option, cancellationToken); } public static bool IsPullDiagnostics(this Workspace workspace, Option2<DiagnosticMode> option, CancellationToken cancellationToken) { var mode = GetDiagnosticMode(workspace, option, cancellationToken); return mode == DiagnosticMode.Pull; } public static bool IsPushDiagnostics(this Workspace workspace, Option2<DiagnosticMode> option, CancellationToken cancellationToken) { var mode = GetDiagnosticMode(workspace, option, cancellationToken); return mode == DiagnosticMode.Push; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Service exposed to determine what diagnostic mode a workspace is in. Exposed in this fashion so that individual /// workspaces can override that value based on other factors. /// </summary> internal interface IDiagnosticModeService : IWorkspaceService { Task<DiagnosticMode> GetDiagnosticModeAsync(Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken); } [ExportWorkspaceService(typeof(IDiagnosticModeService)), Shared] internal class DefaultDiagnosticModeServiceFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultDiagnosticModeServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new DefaultDiagnosticModeService(workspaceServices.Workspace); private class DefaultDiagnosticModeService : IDiagnosticModeService { private readonly Workspace _workspace; public DefaultDiagnosticModeService(Workspace workspace) => _workspace = workspace; public Task<DiagnosticMode> GetDiagnosticModeAsync(Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) => Task.FromResult(_workspace.Options.GetOption(diagnosticMode)); } } internal static class DiagnosticModeExtensions { public static Task<DiagnosticMode> GetDiagnosticModeAsync(this Workspace workspace, Option2<DiagnosticMode> option, CancellationToken cancellationToken) { var service = workspace.Services.GetRequiredService<IDiagnosticModeService>(); return service.GetDiagnosticModeAsync(option, cancellationToken); } public static async Task<bool> IsPullDiagnosticsAsync(this Workspace workspace, Option2<DiagnosticMode> option, CancellationToken cancellationToken) { var mode = await GetDiagnosticModeAsync(workspace, option, cancellationToken).ConfigureAwait(false); return mode == DiagnosticMode.Pull; } public static async Task<bool> IsPushDiagnosticsAsync(this Workspace workspace, Option2<DiagnosticMode> option, CancellationToken cancellationToken) { var mode = await GetDiagnosticModeAsync(workspace, option, cancellationToken).ConfigureAwait(false); return mode == DiagnosticMode.Push; } } }
mit
C#
130c344125945423a30d3265825ea2a2b9f0a0b2
add sensePastWalls field for choosing whether the sensor detects objects across walls
billtowin/mega-epic-super-tankz,billtowin/mega-epic-super-tankz
modules/myModule/scripts/behaviors/misc/ProximitySensor.cs
modules/myModule/scripts/behaviors/misc/ProximitySensor.cs
if (!isObject(ProximitySensorBehavior)) { %template = new BehaviorTemplate(ProximitySensorBehavior); %template.friendlyName = "Proximity Sensor Behavior"; %template.behaviorType = "Misc"; %template.description = "Smart Mine AI whichs renders the owner invisible when Tank /or/ Vehicle is near and reveals itself when they are"; %template.addBehaviorField(scanUpdateTime, "Scan for targets update time", int, 100); %template.addBehaviorField(rangeRadius, "Range at which to turn visible", int, 12); %template.addBehaviorField(detectTypes, "Types of the SceneObjects to detect", string, "Vehicle"); %template.addBehaviorField(sensePastWalls, "Should the sensor detect objects across walls?", bool, false); //TODO: Currently Sensor calls its update functions every 100ms. // should add an option to only call the functions when the proximity sensor's status changes } function ProximitySensorBehavior::onBehaviorAdd(%this) { %this.scanSchedule = %this.schedule(%this.scanUpdateTime, scanForTargets); } function ProximitySensorBehavior::onBehaviorRemove(%this) { } function ProximitySensorBehavior::isDetectionTarget(%this, %obj) { for(%i=0; %i < getWordCount(%this.detectTypes); %i++) { %type = getWord(%this.detectTypes, %i); if(%type $= %obj.type) { return true; } } return false; } function ProximitySensorBehavior::scanForTargets(%this) { %picked = %this.owner.getScene().pickCircle(%this.owner.Position,%this.rangeRadius, -1, -1, "collision"); %isDetectionTargetNear = false; for(%i = 0; %i < getWordCount(%picked) ; %i++) { %obj = getWord(%picked,%i); %isValidTarget = %this.isDetectionTarget(%obj); if(%isValidTarget) { %isDetectionTargetNear = true; //Check if there is a wall blocking the path %rayPicked = %this.owner.getScene().pickRay(%this.owner.Position, %obj.Position, -1, -1); %isWallBlockingPath = false; if(!%this.sensePastWalls) { for(%j = 0; %j < getWordCount(%rayPicked) ; %j++) { %possibleWall = getWord(%rayPicked,%j); if(%possibleWall.type $= Wall) { %isWallBlockingPath = true; break; } } } } } if(%isDetectionTargetNear && !%isWallBlockingPath) { %this.owner.onProximitySensorOn(); } else { %this.owner.onProximitySensorOff(); } %this.scanSchedule = %this.schedule(%this.scanUpdateTime, scanForTargets); }
if (!isObject(ProximitySensorBehavior)) { %template = new BehaviorTemplate(ProximitySensorBehavior); %template.friendlyName = "Proximity Sensor Behavior"; %template.behaviorType = "Misc"; %template.description = "Smart Mine AI whichs renders the owner invisible when Tank /or/ Vehicle is near and reveals itself when they are"; %template.addBehaviorField(scanUpdateTime, "Scan for targets update time", int, 100); %template.addBehaviorField(rangeRadius, "Range at which to turn visible", int, 12); %template.addBehaviorField(detectTypes, "Types of the SceneObjects to detect", string, "Vehicle"); } function ProximitySensorBehavior::onBehaviorAdd(%this) { %this.scanSchedule = %this.schedule(%this.scanUpdateTime, scanForTargets); } function ProximitySensorBehavior::onBehaviorRemove(%this) { } function ProximitySensorBehavior::isDetectionTarget(%this, %obj) { for(%i=0; %i < getWordCount(%this.detectTypes); %i++) { %type = getWord(%this.detectTypes, %i); if(%type $= %obj.type) { return true; } } return false; } function ProximitySensorBehavior::scanForTargets(%this) { %picked = %this.owner.getScene().pickCircle(%this.owner.Position,%this.rangeRadius, -1, -1, "collision"); %isDetectionTargetNear = false; for(%i = 0; %i < getWordCount(%picked) ; %i++) { %obj = getWord(%picked,%i); %isValidTarget = %this.isDetectionTarget(%obj); if(%isValidTarget) { %isDetectionTargetNear = true; //Check if there is a wall blocking the path %rayPicked = %this.owner.getScene().pickRay(%this.owner.Position, %obj.Position, -1, -1); %isWallBlockingPath = false; for(%j = 0; %j < getWordCount(%rayPicked) ; %j++) { %possibleWall = getWord(%rayPicked,%j); if(%possibleWall.type $= Wall) { %isWallBlockingPath = true; break; } } } } if(%isDetectionTargetNear && !%isWallBlockingPath) { %this.owner.onProximitySensorOn(); } else { %this.owner.onProximitySensorOff(); } %this.scanSchedule = %this.schedule(%this.scanUpdateTime, scanForTargets); }
mit
C#
1567befb2ce4f0891cf08440046ea9714dc4cd4d
Add overload to the default Host to accept any configuration
noobot/noobot,Workshop2/noobot
src/Noobot.Runner/NoobotHost.cs
src/Noobot.Runner/NoobotHost.cs
using System; using Common.Logging; using Noobot.Core; using Noobot.Core.Configuration; using Noobot.Core.DependencyResolution; namespace Noobot.Runner { /// <summary> /// NoobotHost is required due to TopShelf. /// </summary> public class NoobotHost { private readonly IConfigReader _configReader; private readonly ILog _logger; private INoobotCore _noobotCore; /// <summary> /// Default constructor will use the default ConfigReader from Core.Configuration /// and look for the configuration file at .\configuration\config.json /// </summary> public NoobotHost() : this(new ConfigReader()) { } public NoobotHost(IConfigReader configReader) { _configReader = configReader; _logger = LogManager.GetLogger(GetType()); } public void Start() { IContainerFactory containerFactory = new ContainerFactory(new ConfigurationBase(), _configReader, _logger); INoobotContainer container = containerFactory.CreateContainer(); _noobotCore = container.GetNoobotCore(); Console.WriteLine("Connecting..."); _noobotCore .Connect() .ContinueWith(task => { if (!task.IsCompleted || task.IsFaulted) { Console.WriteLine($"Error connecting to Slack: {task.Exception}"); } }); } public void Stop() { Console.WriteLine("Disconnecting..."); _noobotCore.Disconnect(); } } }
using System; using Common.Logging; using Noobot.Core; using Noobot.Core.Configuration; using Noobot.Core.DependencyResolution; namespace Noobot.Runner { /// <summary> /// NoobotHost is required due to TopShelf. /// </summary> public class NoobotHost { private readonly IConfigReader _configReader; private readonly ILog _logger; private INoobotCore _noobotCore; public NoobotHost(IConfigReader configReader) { _configReader = configReader; _logger = LogManager.GetLogger(GetType()); } public void Start() { IContainerFactory containerFactory = new ContainerFactory(new ConfigurationBase(), _configReader, _logger); INoobotContainer container = containerFactory.CreateContainer(); _noobotCore = container.GetNoobotCore(); Console.WriteLine("Connecting..."); _noobotCore .Connect() .ContinueWith(task => { if (!task.IsCompleted || task.IsFaulted) { Console.WriteLine($"Error connecting to Slack: {task.Exception}"); } }); } public void Stop() { Console.WriteLine("Disconnecting..."); _noobotCore.Disconnect(); } } }
mit
C#
4e9ec329dddbc7866fa168ad90e0738ddf3c546d
Set log level to INFO
boumenot/Grobid.NET
test/Grobid.Test/GrobidTest.cs
test/Grobid.Test/GrobidTest.cs
using System; using System.IO; using ApprovalTests; using ApprovalTests.Reporters; using FluentAssertions; using Xunit; using Grobid.NET; using org.apache.log4j; using org.grobid.core; namespace Grobid.Test { [UseReporter(typeof(DiffReporter))] public class GrobidTest { static GrobidTest() { BasicConfigurator.configure(); org.apache.log4j.Logger.getRootLogger().setLevel(Level.INFO); } [Fact] [Trait("Test", "EndToEnd")] public void ExtractTest() { var binPath = Environment.GetEnvironmentVariable("PDFTOXMLEXE"); var factory = new GrobidFactory( "grobid.zip", binPath, Directory.GetCurrentDirectory()); var grobid = factory.Create(); var result = grobid.Extract(@"essence-linq.pdf"); result.Should().NotBeEmpty(); Approvals.Verify(result); } [Fact] public void Test() { var x = GrobidModels.NAMES_HEADER; x.name().Should().Be("NAMES_HEADER"); x.toString().Should().Be("name/header"); } } }
using System; using System.IO; using ApprovalTests; using ApprovalTests.Reporters; using FluentAssertions; using Xunit; using Grobid.NET; using org.apache.log4j; using org.grobid.core; namespace Grobid.Test { [UseReporter(typeof(DiffReporter))] public class GrobidTest { static GrobidTest() { BasicConfigurator.configure(); org.apache.log4j.Logger.getRootLogger().setLevel(Level.ERROR); } [Fact] [Trait("Test", "EndToEnd")] public void ExtractTest() { var binPath = Environment.GetEnvironmentVariable("PDFTOXMLEXE"); var factory = new GrobidFactory( "grobid.zip", binPath, Directory.GetCurrentDirectory()); var grobid = factory.Create(); var result = grobid.Extract(@"essence-linq.pdf"); result.Should().NotBeEmpty(); Approvals.Verify(result); } [Fact] public void Test() { var x = GrobidModels.NAMES_HEADER; x.name().Should().Be("NAMES_HEADER"); x.toString().Should().Be("name/header"); } } }
apache-2.0
C#
13a08c002e9a14c6781bcc198479f556230d52f3
Make PlayerInputBehavior always occupy movement
futurechris/zombai
Assets/Scripts/Models/Behaviors/PlayerControlBehavior.cs
Assets/Scripts/Models/Behaviors/PlayerControlBehavior.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; public class PlayerControlBehavior : AgentBehavior { // Get keyboard/touch input and convert it into a "plan" public override bool updatePlan(List<AgentPercept> percepts, int allottedWorkUnits) { if(_myself.MoveInUse) { return false; } Action newMoveAction = null; Action newLookAction = null; // unlike other behaviors, for responsiveness, this should always clear immediately this.currentPlans.Clear(); Vector2 lookVector = Vector2.zero; Vector2 moveVector = Vector2.zero; if(!_myself.LookInUse) { float hLookAxis = Input.GetAxis("LookHorizontal"); float vLookAxis = Input.GetAxis("LookVertical"); if(hLookAxis != 0 || vLookAxis != 0) { lookVector = new Vector2(hLookAxis, vLookAxis); } } if(!_myself.MoveInUse) { float hAxis = Input.GetAxis("Horizontal"); float vAxis = Input.GetAxis("Vertical"); if(hAxis != 0 || vAxis != 0) { moveVector = new Vector2(hAxis/2.0f, vAxis/2.0f); } } if(moveVector != Vector2.zero) { newMoveAction = new Action(Action.ActionType.MOVE_TOWARDS); newMoveAction.TargetPoint = (_myself.Location + moveVector); this.currentPlans.Add(newMoveAction); } else { newMoveAction = new Action(Action.ActionType.STAY); this.currentPlans.Add(newMoveAction); } if(lookVector != Vector2.zero) { newLookAction = new Action(Action.ActionType.TURN_TO_DEGREES); Vector2 netVector = lookVector; float angle = 90.0f - Mathf.Rad2Deg * Mathf.Atan2(netVector.x, netVector.y); newLookAction.Direction = (angle); this.currentPlans.Add(newLookAction); } else if(moveVector != Vector2.zero) { // if no specific look input, turn in the direction we're moving newLookAction = new Action(Action.ActionType.TURN_TOWARDS); newLookAction.TargetPoint = (_myself.Location + moveVector); this.currentPlans.Add(newLookAction); } return (currentPlans.Count > 0); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class PlayerControlBehavior : AgentBehavior { // Get keyboard/touch input and convert it into a "plan" public override bool updatePlan(List<AgentPercept> percepts, int allottedWorkUnits) { if(_myself.MoveInUse) { return false; } Action newMoveAction = null; Action newLookAction = null; // unlike other behaviors, for responsiveness, this should always clear immediately this.currentPlans.Clear(); Vector2 lookVector = Vector2.zero; Vector2 moveVector = Vector2.zero; if(!_myself.LookInUse) { float hLookAxis = Input.GetAxis("LookHorizontal"); float vLookAxis = Input.GetAxis("LookVertical"); if(hLookAxis != 0 || vLookAxis != 0) { lookVector = new Vector2(hLookAxis, vLookAxis); } } if(!_myself.MoveInUse) { float hAxis = Input.GetAxis("Horizontal"); float vAxis = Input.GetAxis("Vertical"); if(hAxis != 0 || vAxis != 0) { moveVector = new Vector2(hAxis/2.0f, vAxis/2.0f); } } if(moveVector != Vector2.zero) { newMoveAction = new Action(Action.ActionType.MOVE_TOWARDS); newMoveAction.TargetPoint = (_myself.Location + moveVector); this.currentPlans.Add(newMoveAction); } if(lookVector != Vector2.zero) { newLookAction = new Action(Action.ActionType.TURN_TO_DEGREES); Vector2 netVector = lookVector; float angle = 90.0f - Mathf.Rad2Deg * Mathf.Atan2(netVector.x, netVector.y); newLookAction.Direction = (angle); this.currentPlans.Add(newLookAction); } else if(moveVector != Vector2.zero) { // if no specific look input, turn in the direction we're moving newLookAction = new Action(Action.ActionType.TURN_TOWARDS); newLookAction.TargetPoint = (_myself.Location + moveVector); this.currentPlans.Add(newLookAction); } return (currentPlans.Count > 0); } }
mit
C#
b7f6edd65540e131452c144819711982484bfcd9
change tree
pixel-stuff/ld_dare_32
Unity/ludum-dare-32-PixelStuff/Assets/Scripts/Tree/tree.cs
Unity/ludum-dare-32-PixelStuff/Assets/Scripts/Tree/tree.cs
using UnityEngine; using System.Collections; public class tree : MonoBehaviour { enum TreeState{ UP, CHOPED, FALLEN, PICKED }; public GameObject rightChop; public GameObject leftChop; public GameObject trunk; public GameObject stump; public float SecondeAnimation; // Use this for initialization private TreeState state; private Transform fallenTransform; private float remaningSeconde; private float RotationZIteration; void Start () { state = TreeState.UP; } // Update is called once per frame void Update () { updatePosition (); //test if (this.gameObject.transform.position.x < 0) { chopLeft(); chopRight(); } //!test if ( state == TreeState.UP && isChoped()) { state = TreeState.CHOPED; calculFallPosition(); remaningSeconde = SecondeAnimation; } if (state == TreeState.CHOPED && remaningSeconde > 0) { remaningSeconde -= Time.deltaTime; fall (); } if (remaningSeconde < 0) { state = TreeState.FALLEN; } } void updatePosition(){ if (this.gameObject.transform.position.x > 0) { this.gameObject.transform.position = new Vector3 (this.gameObject.transform.position.x - 0.1f, this.gameObject.transform.position.y, 0); } } bool isChoped(){ return rightChop.GetComponent<ChopOnTree> ().isCompletlyChop() && leftChop.GetComponent<ChopOnTree> ().isCompletlyChop(); //return true; } void chopLeft(){ leftChop.GetComponent<ChopOnTree> ().triggerChop (); } void chopRight(){ rightChop.GetComponent<ChopOnTree> ().triggerChop (); } void calculFallPosition(){ RotationZIteration = (-90f) / SecondeAnimation; } void fall(){ //trunk.transform.position = new Vector3 (trunk.transform.position.x + PositionXIteration * Time.deltaTime, trunk.transform.position.y + PositionYIteration * Time.deltaTime, 0); trunk.transform.RotateAround (stump.transform.position, new Vector3 (0, 0, 1), RotationZIteration * Time.deltaTime); } public bool isFallen(){ return state == TreeState.FALLEN; } }
using UnityEngine; using System.Collections; public class tree : MonoBehaviour { enum TreeState{ UP, CHOPED, FALLEN, PICKED }; public GameObject rightChop; public GameObject leftChop; public GameObject trunk; public GameObject stump; public float SecondeAnimation; // Use this for initialization private TreeState state; private Transform fallenTransform; private float remaningSeconde; private float RotationZIteration; void Start () { state = TreeState.UP; } // Update is called once per frame void Update () { updatePosition (); //test if (this.gameObject.transform.position.x < 0) { chopLeft(); chopRight(); } //!test if ( state == TreeState.UP && isChoped()) { state = TreeState.CHOPED; calculFallPosition(); remaningSeconde = SecondeAnimation; } if (state == TreeState.CHOPED && remaningSeconde > 0) { remaningSeconde -= Time.deltaTime; fall (); } if (remaningSeconde < 0) { state = TreeState.FALLEN; } } void updatePosition(){ if (this.gameObject.transform.position.x > 0) { this.gameObject.transform.position = new Vector3 (this.gameObject.transform.position.x - 0.1f, 0, 0); } } bool isChoped(){ return rightChop.GetComponent<ChopOnTree> ().isCompletlyChop() && leftChop.GetComponent<ChopOnTree> ().isCompletlyChop(); //return true; } void chopLeft(){ leftChop.GetComponent<ChopOnTree> ().triggerChop (); } void chopRight(){ rightChop.GetComponent<ChopOnTree> ().triggerChop (); } void calculFallPosition(){ RotationZIteration = (-90f) / SecondeAnimation; } void fall(){ //trunk.transform.position = new Vector3 (trunk.transform.position.x + PositionXIteration * Time.deltaTime, trunk.transform.position.y + PositionYIteration * Time.deltaTime, 0); trunk.transform.RotateAround (stump.transform.position, new Vector3 (0, 0, 1), RotationZIteration * Time.deltaTime); } public bool isFallen(){ return state == TreeState.FALLEN; } }
mit
C#
42bdfdfa10f3759bcd1c688e705f3b2a923b32a7
Make class generatng code clearer (?)
TeamnetGroup/schema2fm
src/ConsoleApp/Table.cs
src/ConsoleApp/Table.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace ConsoleApp { public class Table { private readonly string tableName; private readonly IEnumerable<Column> columns; public Table(string tableName, IEnumerable<Column> columns) { this.tableName = tableName; this.columns = columns; } public void OutputMigrationCode(TextWriter writer) { writer.Write(@"namespace Cucu { [Migration("); writer.Write(DateTime.Now.ToString("yyyyMMddHHmmss")); writer.WriteLine(@")] public class Vaca : Migration { public override void Up() {"); writer.Write($" Create.Table(\"{tableName}\")"); columns.ToList().ForEach(c => { writer.WriteLine(); writer.Write(c.FluentMigratorCode()); }); writer.WriteLine(@"; } public override void Down() {"); writer.Write($" Delete.Table(\"{tableName}\");"); writer.WriteLine(@" } } }"); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace ConsoleApp { public class Table { private readonly string tableName; private readonly IEnumerable<Column> columns; public Table(string tableName, IEnumerable<Column> columns) { this.tableName = tableName; this.columns = columns; } public void OutputMigrationCode(TextWriter writer) { writer.Write(@"namespace Cucu { [Migration("); writer.Write(DateTime.Now.ToString("yyyyMMddHHmmss")); writer.Write(@")] public class Vaca : Migration { public override void Up() { Create.Table("""); writer.Write(tableName); writer.Write(@""")"); columns.ToList().ForEach(c => { writer.WriteLine(); writer.Write(c.FluentMigratorCode()); }); writer.Write(@"; } public override void Down() { Delete.Table("""); writer.Write(tableName); writer.WriteLine(@"""); } } }"); } } }
mit
C#
26f2f88c67ae54cacb211d48827a74f7700d07ab
Add documentation attribute default value (#6095)
QuantConnect/Lean,jameschch/Lean,QuantConnect/Lean,QuantConnect/Lean,jameschch/Lean,JKarathiya/Lean,AlexCatarino/Lean,JKarathiya/Lean,JKarathiya/Lean,jameschch/Lean,jameschch/Lean,AlexCatarino/Lean,AlexCatarino/Lean,QuantConnect/Lean,jameschch/Lean,AlexCatarino/Lean,JKarathiya/Lean
Common/DocumentationAttribute.cs
Common/DocumentationAttribute.cs
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Newtonsoft.Json; namespace QuantConnect { /// <summary> /// Custom attribute used for documentation /// </summary> [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public sealed class DocumentationAttribute : Attribute { /// <summary> /// The documentation tag /// </summary> [JsonProperty(PropertyName = "tag")] public string Tag { get; } /// <summary> /// The associated weight of this attribute and tag /// </summary> [JsonProperty(PropertyName = "weight")] public int Weight { get; } /// <summary> /// The attributes type id, we override it to ignore it when serializing /// </summary> [JsonIgnore] public override object TypeId => base.TypeId; /// <summary> /// Creates a new instance /// </summary> public DocumentationAttribute(string tag, int weight = 0) { Tag = tag; Weight = weight; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Newtonsoft.Json; namespace QuantConnect { /// <summary> /// Custom attribute used for documentation /// </summary> [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public sealed class DocumentationAttribute : Attribute { /// <summary> /// The documentation tag /// </summary> [JsonProperty(PropertyName = "tag")] public string Tag { get; } /// <summary> /// The associated weight of this attribute and tag /// </summary> [JsonProperty(PropertyName = "weight")] public int Weight { get; } /// <summary> /// The attributes type id, we override it to ignore it when serializing /// </summary> [JsonIgnore] public override object TypeId => base.TypeId; /// <summary> /// Creates a new instance /// </summary> public DocumentationAttribute(string tag, int weight) { Tag = tag; Weight = weight; } } }
apache-2.0
C#
8284b9518dd52e453dad94b982d6cf7672d5d830
Update to fix small error in code.
awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples
dotnet3.5/S3/ListObjectsExample/ListObjects/ListObjects.cs
dotnet3.5/S3/ListObjectsExample/ListObjects/ListObjects.cs
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX - License - Identifier: Apache - 2.0 // snippet-start:[S3.dotnet35.ListObjects] using Amazon; using Amazon.S3; using Amazon.S3.Model; using System; using System.Threading.Tasks; namespace ListObjects { // The following example lists objects in an Amazon Simple Storage // Service (Amazon S3) bucket. It was created using AWS SDK for .NET 3.5 // and .NET 5.0. public class ListObjects { // Specify your AWS Region (an example Region is shown). private static readonly RegionEndpoint BUCKET_REGION = RegionEndpoint.USWest2; private static IAmazonS3 _s3Client; private const string BUCKET_NAME = "doc-example-bucket"; static async Task Main() { _s3Client = new AmazonS3Client(BUCKET_REGION); Console.WriteLine($"Listing the objects contained in {BUCKET_NAME}:\n"); await ListingObjectsAsync(_s3Client, BUCKET_NAME); } /// <summary> /// This method uses a paginator to retrieve the list of objects in an /// an Amazon S3 bucket. /// </summary> /// <param name="client">An Amazon S3 client object.</param> /// <param name="bucketName">The name of the S3 bucket whose objects /// you want to list.</param> static async Task ListingObjectsAsync(IAmazonS3 client, string bucketName) { var listObjectsV2Paginator = client.Paginators.ListObjectsV2(new ListObjectsV2Request { BucketName = bucketName }); await foreach(var entry in listObjectsV2Paginator.S3Objects) { Console.WriteLine($"key = {entry.Key} size = {entry.Size}"); } } } } // snippet-end:[S3.dotnet35.ListObjects]
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX - License - Identifier: Apache - 2.0 // snippet-start:[S3.dotnet35.ListObjects] using Amazon; using Amazon.S3; using Amazon.S3.Model; using System; using System.Threading.Tasks; namespace ListObjects { // The following example lists objects in an Amazon Simple Storage // Service (Amazon S3) bucket. It was created using AWS SDK for .NET 3.5 // and .NET 5.0. public class ListObjects { // Specify your AWS Region (an example Region is shown). private static readonly RegionEndpoint BUCKET_REGION = RegionEndpoint.USEast2; //RegionEndpoint.USWest2; private static IAmazonS3 _s3Client; private const string BUCKET_NAME = "igsmiths3photos"; // "doc-example-bucket"; static async Task Main() { _s3Client = new AmazonS3Client(BUCKET_REGION); Console.WriteLine($"Listing the objects contained in {BUCKET_NAME}:\n"); await ListingObjectsAsync(_s3Client, BUCKET_NAME); } static async Task ListingObjectsAsync(IAmazonS3 client, string bucketName) { var listObjectsV2Paginator = client.Paginators.ListObjectsV2(new ListObjectsV2Request { BucketName = bucketName }); await foreach(var entry in listObjectsV2Paginator.S3Objects) { Console.WriteLine($"key = {entry.Key} size = {entry.Size}"); } } } } // snippet-end:[S3.dotnet35.ListObjects]
apache-2.0
C#
67db9b7a61b64ab11345efef546fe69c54099ea4
Add methods to buy stuff
bastuijnman/ludum-dare-36
Assets/Scripts/Player.cs
Assets/Scripts/Player.cs
using UnityEngine; using System.Collections; public class Player : MonoBehaviour { private int money = 500; public int GetMoney () { return money; } public bool Buy (int price) { if (price > money) { return false; } money -= price; return true; } // Update is called once per frame void Update () { if (Input.GetMouseButtonDown(0)) { // TODO: place tower } } }
using UnityEngine; using System.Collections; public class Player : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetMouseButtonDown(0)) { // TODO: place tower } } }
mit
C#
c7c8dff05accc9703bc681ab7bbd0edc83a5f41e
Save Ian (#5759)
space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
Content.Server/Spawners/Components/ConditionalSpawnerComponent.cs
Content.Server/Spawners/Components/ConditionalSpawnerComponent.cs
using System.Collections.Generic; using Content.Server.GameTicking; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Random; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; namespace Content.Server.Spawners.Components { [RegisterComponent] public class ConditionalSpawnerComponent : Component, IMapInit { [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IRobustRandom _robustRandom = default!; public override string Name => "ConditionalSpawner"; [ViewVariables(VVAccess.ReadWrite)] [DataField("prototypes")] public List<string> Prototypes { get; set; } = new(); [ViewVariables(VVAccess.ReadWrite)] [DataField("gameRules")] private readonly List<string> _gameRules = new(); [ViewVariables(VVAccess.ReadWrite)] [DataField("chance")] public float Chance { get; set; } = 1.0f; public void RuleAdded(GameRuleAddedEvent obj) { if(_gameRules.Contains(obj.Rule.GetType().Name)) Spawn(); } private void TrySpawn() { if (_gameRules.Count == 0) { Spawn(); return; } foreach (var rule in _gameRules) { if (!EntitySystem.Get<GameTicker>().HasGameRule(rule)) continue; Spawn(); return; } } public virtual void Spawn() { if (Chance != 1.0f && !_robustRandom.Prob(Chance)) return; if (Prototypes.Count == 0) { Logger.Warning($"Prototype list in ConditionalSpawnComponent is empty! Entity: {Owner}"); return; } if(!_entMan.Deleted(Owner)) _entMan.SpawnEntity(_robustRandom.Pick(Prototypes), _entMan.GetComponent<TransformComponent>(Owner).Coordinates); } public virtual void MapInit() { TrySpawn(); } } }
using System.Collections.Generic; using Content.Server.GameTicking; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Random; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; namespace Content.Server.Spawners.Components { [RegisterComponent] public class ConditionalSpawnerComponent : Component, IMapInit { [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IRobustRandom _robustRandom = default!; public override string Name => "ConditionalSpawner"; [ViewVariables(VVAccess.ReadWrite)] [DataField("prototypes")] public List<string> Prototypes { get; set; } = new(); [ViewVariables(VVAccess.ReadWrite)] [DataField("gameRules")] private readonly List<string> _gameRules = new(); [ViewVariables(VVAccess.ReadWrite)] [DataField("chance")] public float Chance { get; set; } = 1.0f; public void RuleAdded(GameRuleAddedEvent obj) { if(_gameRules.Contains(obj.Rule.GetType().Name)) Spawn(); } private void TrySpawn() { if (_gameRules.Count == 0) { Spawn(); return; } foreach (var rule in _gameRules) { if (!EntitySystem.Get<GameTicker>().HasGameRule(rule)) continue; Spawn(); return; } } public virtual void Spawn() { if (Chance != 1.0f && !_robustRandom.Prob(Chance)) return; if (Prototypes.Count == 0) { Logger.Warning($"Prototype list in ConditionalSpawnComponent is empty! Entity: {Owner}"); return; } if(_entMan.Deleted(Owner)) _entMan.SpawnEntity(_robustRandom.Pick(Prototypes), _entMan.GetComponent<TransformComponent>(Owner).Coordinates); } public virtual void MapInit() { TrySpawn(); } } }
mit
C#
a7a1956a32a67a2f668701be1863bab596c78c85
Add method to get path segment representing parent element
arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5
src/Arkivverket.Arkade/Core/Noark5/ReadElementEventArgs.cs
src/Arkivverket.Arkade/Core/Noark5/ReadElementEventArgs.cs
using System; using System.Collections.Generic; using System.Linq; namespace Arkivverket.Arkade.Core.Noark5 { public class ReadElementEventArgs : EventArgs { public string Name { get; set; } public string Value { get; set; } public ElementPath Path { get; set; } public ReadElementEventArgs(string name, string value, ElementPath path) { Name = name; Value = value; Path = path; } public bool NameEquals(string inputName) { return StringEquals(Name, inputName); } private bool StringEquals(string input1, string input2) { return string.Equals(input1, input2, StringComparison.CurrentCultureIgnoreCase); } } public class ElementPath { private readonly List<string> _path; public ElementPath(List<string> path) { _path = path; } public bool Matches(params string[] elementNames) { if (!_path.Any()) return false; var matches = true; for (var i = 0; i < elementNames.Length; i++) { matches = matches && string.Equals(elementNames[i], _path[i], StringComparison.CurrentCultureIgnoreCase); } return matches; } public string GetParent() { return _path.Count > 1 ? _path[1] : null; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Arkivverket.Arkade.Core.Noark5 { public class ReadElementEventArgs : EventArgs { public string Name { get; set; } public string Value { get; set; } public ElementPath Path { get; set; } public ReadElementEventArgs(string name, string value, ElementPath path) { Name = name; Value = value; Path = path; } public bool NameEquals(string inputName) { return StringEquals(Name, inputName); } private bool StringEquals(string input1, string input2) { return string.Equals(input1, input2, StringComparison.CurrentCultureIgnoreCase); } } public class ElementPath { private readonly List<string> _path; public ElementPath(List<string> path) { _path = path; } public bool Matches(params string[] elementNames) { if (!_path.Any()) return false; var matches = true; for (var i = 0; i < elementNames.Length; i++) { matches = matches && string.Equals(elementNames[i], _path[i], StringComparison.CurrentCultureIgnoreCase); } return matches; } } }
agpl-3.0
C#
d079f08745b07492f8c0427089d84e6ace9d0695
Fix 'overriding view manager' sample
canton7/Stylet,canton7/Stylet
Samples/Stylet.Samples.OverridingViewManager/CustomViewManager.cs
Samples/Stylet.Samples.OverridingViewManager/CustomViewManager.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Windows; namespace Stylet.Samples.OverridingViewManager { [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] sealed class ViewModelAttribute : Attribute { readonly Type viewModel; public ViewModelAttribute(Type viewModel) { this.viewModel = viewModel; } public Type ViewModel { get { return viewModel; } } } public class CustomViewManager : ViewManager { // Dictionary of ViewModel type -> View type private readonly Dictionary<Type, Type> viewModelToViewMapping; public CustomViewManager(Func<Type, object> viewFactory, List<Assembly> viewAssemblies) : base(viewFactory, viewAssemblies) { var mappings = from type in this.ViewAssemblies.SelectMany(x => x.GetExportedTypes()) let attribute = type.GetCustomAttribute<ViewModelAttribute>() where attribute != null && typeof(UIElement).IsAssignableFrom(type) select new { View = type, ViewModel = attribute.ViewModel }; this.viewModelToViewMapping = mappings.ToDictionary(x => x.ViewModel, x => x.View); } protected override Type LocateViewForModel(Type modelType) { Type viewType; if (!this.viewModelToViewMapping.TryGetValue(modelType, out viewType)) throw new Exception(String.Format("Could not find View for ViewModel {0}", modelType.Name)); return viewType; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Windows; namespace Stylet.Samples.OverridingViewManager { [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] sealed class ViewModelAttribute : Attribute { readonly Type viewModel; public ViewModelAttribute(Type viewModel) { this.viewModel = viewModel; } public Type ViewModel { get { return viewModel; } } } public class CustomViewManager : ViewManager { // Dictionary of ViewModel type -> View type private readonly Dictionary<Type, Type> viewModelToViewMapping; public CustomViewManager(ViewManagerConfig config) : base(config) { var mappings = from type in this.ViewsAssembly.GetExportedTypes() let attribute = type.GetCustomAttribute<ViewModelAttribute>() where attribute != null && typeof(UIElement).IsAssignableFrom(type) select new { View = type, ViewModel = attribute.ViewModel }; this.viewModelToViewMapping = mappings.ToDictionary(x => x.ViewModel, x => x.View); } protected override Type LocateViewForModel(Type modelType) { Type viewType; if (!this.viewModelToViewMapping.TryGetValue(modelType, out viewType)) throw new Exception(String.Format("Could not find View for ViewModel {0}", modelType.Name)); return viewType; } } }
mit
C#
9b252de849a11985c7d1cf15ad91cbef11f0a847
Add IComparable interface to AnalyzeRequest
mjrousos/dotnet-apiport-old,conniey/dotnet-apiport,conniey/dotnet-apiport,Microsoft/dotnet-apiport,conniey/dotnet-apiport,twsouthwick/dotnet-apiport,mjrousos/dotnet-apiport,Microsoft/dotnet-apiport,JJVertical/dotnet-apiport,Microsoft/dotnet-apiport,twsouthwick/dotnet-apiport,JJVertical/dotnet-apiport,mjrousos/dotnet-apiport
src/Microsoft.Fx.Portability/ObjectModel/AnalyzeRequest.cs
src/Microsoft.Fx.Portability/ObjectModel/AnalyzeRequest.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Newtonsoft.Json; using System; using System.Collections.Generic; namespace Microsoft.Fx.Portability.ObjectModel { public sealed class AnalyzeRequest : IComparable { public const byte CurrentVersion = 2; public AnalyzeRequestFlags RequestFlags { get; set; } public IDictionary<MemberInfo, ICollection<AssemblyInfo>> Dependencies { get; set; } public ICollection<string> UnresolvedAssemblies { get; set; } [JsonIgnore] public IDictionary<string, ICollection<string>> UnresolvedAssembliesDictionary { get; set; } public ICollection<AssemblyInfo> UserAssemblies { get; set; } public ICollection<string> AssembliesWithErrors { get; set; } public ICollection<string> Targets { get; set; } public string ApplicationName { get; set; } public byte Version { get; set; } public int CompareTo(object obj) { var analyzeObject = obj as AnalyzeRequest; return ApplicationName.CompareTo(analyzeObject.ApplicationName); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Newtonsoft.Json; using System.Collections.Generic; namespace Microsoft.Fx.Portability.ObjectModel { public sealed class AnalyzeRequest { public const byte CurrentVersion = 2; public AnalyzeRequestFlags RequestFlags { get; set; } public IDictionary<MemberInfo, ICollection<AssemblyInfo>> Dependencies { get; set; } public ICollection<string> UnresolvedAssemblies { get; set; } [JsonIgnore] public IDictionary<string, ICollection<string>> UnresolvedAssembliesDictionary { get; set; } public ICollection<AssemblyInfo> UserAssemblies { get; set; } public ICollection<string> AssembliesWithErrors { get; set; } public ICollection<string> Targets { get; set; } public string ApplicationName { get; set; } public byte Version { get; set; } } }
mit
C#
c311f38ef8e63684ac53bcdb4bbfc207ffd465e4
Update WalletWasabi/Microservices/ProcessStartInfoFactory.cs
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Microservices/ProcessStartInfoFactory.cs
WalletWasabi/Microservices/ProcessStartInfoFactory.cs
using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace WalletWasabi.Microservices { /// <summary> /// Factory for <see cref="ProcessStartInfo"/> with pre-defined properties as needed in Wasabi Wallet. /// </summary> public class ProcessStartInfoFactory { /// <summary> /// Creates new <see cref="ProcessStartInfo"/> instance. /// </summary> /// <param name="processPath">Path to process.</param> /// <param name="arguments">Process arguments.</param> /// <param name="openConsole">Open console window. Only for Windows platform.</param> /// <returns><see cref="ProcessStartInfo"/> instance.</returns> public static ProcessStartInfo Make(string processPath, string arguments, bool openConsole = false) { ProcessWindowStyle windowStyle; if (openConsole) { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { throw new PlatformNotSupportedException($"{RuntimeInformation.OSDescription} is not supported."); } windowStyle = ProcessWindowStyle.Normal; } else { windowStyle = ProcessWindowStyle.Hidden; } var p = new ProcessStartInfo(fileName: processPath, arguments) { FileName = processPath, Arguments = arguments, RedirectStandardOutput = !openConsole, UseShellExecute = openConsole, CreateNoWindow = !openConsole, WindowStyle = windowStyle }; return p; } } }
using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace WalletWasabi.Microservices { /// <summary> /// Factory for <see cref="ProcessStartInfo"/> with pre-defined properties as needed in Wasabi Wallet. /// </summary> public class ProcessStartInfoFactory { /// <summary> /// Creates new <see cref="ProcessStartInfo"/> instance. /// </summary> /// <param name="processPath">Path to process.</param> /// <param name="arguments">Process arguments.</param> /// <param name="openConsole">Open console window. Only for Windows platform.</param> /// <returns><see cref="ProcessStartInfo"/> instance.</returns> public static ProcessStartInfo Make(string processPath, string arguments, bool openConsole = false) { ProcessWindowStyle windowStyle; if (openConsole) { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { throw new PlatformNotSupportedException($"{RuntimeInformation.OSDescription} is not supported."); } windowStyle = ProcessWindowStyle.Normal; } else { windowStyle = ProcessWindowStyle.Hidden; } var p = new ProcessStartInfo(fileName: processPath, arguments); p.FileName = processPath; p.Arguments = arguments; p.RedirectStandardOutput = !openConsole; p.UseShellExecute = openConsole; p.CreateNoWindow = !openConsole; p.WindowStyle = windowStyle; return p; } } }
mit
C#
85c5cf87fc533a7ecc5abce5a8e83a3de4557f29
Add panel1 object
60071jimmy/UartOscilloscope,60071jimmy/UartOscilloscope
QueueDataGraphic/QueueDataGraphic/Form1.Designer.cs
QueueDataGraphic/QueueDataGraphic/Form1.Designer.cs
namespace QueueDataGraphic { partial class Form1 { /// <summary> /// 設計工具所需的變數。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清除任何使用中的資源。 /// </summary> /// <param name="disposing">如果應該處置 Managed 資源則為 true,否則為 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form 設計工具產生的程式碼 /// <summary> /// 此為設計工具支援所需的方法 - 請勿使用程式碼編輯器修改 /// 這個方法的內容。 /// </summary> private void InitializeComponent() { this.panel1 = new System.Windows.Forms.Panel(); this.SuspendLayout(); // // panel1 // this.panel1.Location = new System.Drawing.Point(12, 12); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(808, 386); this.panel1.TabIndex = 0; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(832, 410); this.Controls.Add(this.panel1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel panel1; } }
namespace QueueDataGraphic { partial class Form1 { /// <summary> /// 設計工具所需的變數。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清除任何使用中的資源。 /// </summary> /// <param name="disposing">如果應該處置 Managed 資源則為 true,否則為 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form 設計工具產生的程式碼 /// <summary> /// 此為設計工具支援所需的方法 - 請勿使用程式碼編輯器修改 /// 這個方法的內容。 /// </summary> private void InitializeComponent() { this.SuspendLayout(); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(832, 410); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); } #endregion } }
apache-2.0
C#
39e96b3201fe5e5973b43cad3b10c01d9d9e9fdf
Update CommonTelemetryOptions.cs
tiksn/TIKSN-Framework
TIKSN.Core/Analytics/Telemetry/CommonTelemetryOptions.cs
TIKSN.Core/Analytics/Telemetry/CommonTelemetryOptions.cs
namespace TIKSN.Analytics.Telemetry { public class CommonTelemetryOptions { public CommonTelemetryOptions() { this.IsEventTrackingEnabled = true; this.IsExceptionTrackingEnabled = true; this.IsMetricTrackingEnabled = true; this.IsTraceTrackingEnabled = true; } public bool IsEventTrackingEnabled { get; set; } public bool IsExceptionTrackingEnabled { get; set; } public bool IsMetricTrackingEnabled { get; set; } public bool IsTraceTrackingEnabled { get; set; } } }
namespace TIKSN.Analytics.Telemetry { public class CommonTelemetryOptions { public CommonTelemetryOptions() { IsEventTrackingEnabled = true; IsExceptionTrackingEnabled = true; IsMetricTrackingEnabled = true; IsTraceTrackingEnabled = true; } public bool IsEventTrackingEnabled { get; set; } public bool IsExceptionTrackingEnabled { get; set; } public bool IsMetricTrackingEnabled { get; set; } public bool IsTraceTrackingEnabled { get; set; } } }
mit
C#
fae4e956e1ec969fe059d0b4ecffc8e349b879fb
Fix tests
Flepper/flepper,Flepper/flepper
Flepper.Tests.Unit/QueryBuilder/Commands/DeleteCommandTests.cs
Flepper.Tests.Unit/QueryBuilder/Commands/DeleteCommandTests.cs
using Flepper.Core.QueryBuilder; using FluentAssertions; using Xunit; namespace Flepper.Tests.Unit.QueryBuilder.Commands { [Collection("CommandTests")] public class DeleteCommandTests { [Fact] public void ShouldCreateDeleteStatement() { FlepperQueryBuilder.Delete().From("Test"); FlepperQueryBuilder.Query .Trim() .Should() .Be("DELETE FROM [Test]"); } [Fact] public void ShouldCreateDeleteStatementWithWhere() { FlepperQueryBuilder.Delete() .From("Test") .Where("Id") .EqualTo(2); FlepperQueryBuilder.Query .Trim() .Should() .Be("DELETE FROM [Test] WHERE [Id] = 2"); } } }
using Flepper.Core.QueryBuilder; using FluentAssertions; using Xunit; namespace Flepper.Tests.Unit.QueryBuilder.Commands { [Collection("CommandTests")] public class DeleteCommandTests { [Fact] public void ShouldCreateDeleteStatement() { FlepperQueryBuilder.Delete().From("Test"); FlepperQueryBuilder.Query .Trim() .Should() .Be("DELETE FROM [Test]"); } [Fact] public void ShouldCreateDeleteStatementWithWhere() { FlepperQueryBuilder.Delete() .From("Test") .Where("Id") .EqualTo(2); FlepperQueryBuilder.Query .Trim() .Should() .Be("DELETE FROM [Test] WHERE [Id] = 2"); } } }
mit
C#
1617bf6442ab68c2b495acc9c712895480d9f58a
Update Arsenal.cs (#55)
BosslandGmbH/BuddyWing.DefaultCombat
trunk/DefaultCombat/Routines/Advanced/Mercenary/Arsenal.cs
trunk/DefaultCombat/Routines/Advanced/Mercenary/Arsenal.cs
// Copyright (C) 2011-2016 Bossland GmbH // See the file LICENSE for the source code's detailed license using Buddy.BehaviorTree; using DefaultCombat.Core; using DefaultCombat.Helpers; namespace DefaultCombat.Routines { public class Arsenal : RotationBase { public override string Name { get { return "Mercenary Arsenal"; } } public override Composite Buffs { get { return new PrioritySelector( Spell.Buff("Hunter's Boon") ); } } public override Composite Cooldowns { get { return new PrioritySelector( Spell.Buff("Determination", ret => Me.IsStunned), Spell.Buff("Vent Heat", ret => Me.ResourcePercent() >= 50), Spell.Buff("Supercharged Gas", ret => Me.BuffCount("Supercharge") == 10), Spell.Buff("Energy Shield", ret => Me.HealthPercent <= 70), Spell.Buff("Kolto Overload", ret => Me.HealthPercent <= 30), Spell.Buff("Responsive Safeguards", ret => Me.HealthPercent <= 50) ); } } public override Composite SingleTarget { get { return new PrioritySelector( //Movement CombatMovement.CloseDistance(Distance.Ranged), //Rotation Spell.Cast("Rapid Shots", ret => Me.ResourcePercent() > 40), Spell.Cast("Blazing Bolts", ret => Me.HasBuff("Barrage") && Me.Level >= 57), Spell.Cast("Unload", ret => Me.Level < 57), Spell.Cast("Heatseeker Missiles", ret => Me.CurrentTarget.HasDebuff("Heat Signature")), Spell.Cast("Rail Shot", ret => Me.BuffCount("Tracer Lock") == 5), Spell.Cast("Electro Net"), Spell.Cast("Priming Shot"), Spell.Cast("Tracer Missile"), Spell.Cast("Rapid Shots") ); } } public override Composite AreaOfEffect { get { return new Decorator(ret => Targeting.ShouldAoe, new PrioritySelector( Spell.Buff("Thermal Sensor Override"), Spell.Buff("Power Surge"), Spell.CastOnGround("Death from Above"), Spell.Cast("Fusion Missile", ret => Me.ResourcePercent() <= 10 && Me.HasBuff("Power Surge")), Spell.CastOnGround("Sweeping Blasters", ret => Me.ResourcePercent() <= 10)) ); } } } }
// Copyright (C) 2011-2016 Bossland GmbH // See the file LICENSE for the source code's detailed license using Buddy.BehaviorTree; using DefaultCombat.Core; using DefaultCombat.Helpers; namespace DefaultCombat.Routines { public class Arsenal : RotationBase { public override string Name { get { return "Mercenary Arsenal"; } } public override Composite Buffs { get { return new PrioritySelector( Spell.Buff("High Velocity Gas Cylinder"), Spell.Buff("Hunter's Boon") ); } } public override Composite Cooldowns { get { return new PrioritySelector( Spell.Buff("Determination", ret => Me.IsStunned), Spell.Buff("Vent Heat", ret => Me.ResourcePercent() >= 50), Spell.Buff("Supercharged Gas", ret => Me.BuffCount("Supercharge") == 10), Spell.Buff("Energy Shield", ret => Me.HealthPercent <= 70), Spell.Buff("Kolto Overload", ret => Me.HealthPercent <= 30) ); } } public override Composite SingleTarget { get { return new PrioritySelector( //Movement CombatMovement.CloseDistance(Distance.Ranged), //Rotation Spell.Cast("Rapid Shots", ret => Me.ResourcePercent() > 40), Spell.Cast("Blazing Bolts", ret => Me.HasBuff("Barrage") && Me.Level >= 57), Spell.Cast("Unload", ret => Me.Level < 57), Spell.Cast("Heatseeker Missiles", ret => Me.CurrentTarget.HasDebuff("Heat Signature")), Spell.Cast("Rail Shot", ret => Me.BuffCount("Tracer Lock") == 5), Spell.Cast("Electro Net"), Spell.Cast("Priming Shot"), Spell.Cast("Tracer Missile"), Spell.Cast("Rapid Shots") ); } } public override Composite AreaOfEffect { get { return new Decorator(ret => Targeting.ShouldAoe, new PrioritySelector( Spell.Buff("Thermal Sensor Override"), Spell.Buff("Power Surge"), Spell.CastOnGround("Death from Above"), Spell.Cast("Fusion Missile", ret => Me.ResourcePercent() <= 10 && Me.HasBuff("Power Surge")), Spell.Cast("Flame Thrower", ret => Me.CurrentTarget.Distance <= 1f), Spell.CastOnGround("Sweeping Blasters", ret => Me.ResourcePercent() <= 10)) ); } } } }
apache-2.0
C#
f9a4f796db967ab04291810c3d1997303e1246c2
Add Show toggle for GridDebugger
yanyiyun/LockstepFramework,SnpM/Lockstep-Framework,erebuswolf/LockstepFramework
Integration/Test/GridDebugger.cs
Integration/Test/GridDebugger.cs
using UnityEngine; using System.Collections; namespace Lockstep { public class GridDebugger : MonoBehaviour { public bool Show; public GridType LeGridType; public float LeHeight; [Range (.1f,.9f)] public float NodeSize = .4f; void OnDrawGizmos () { if (Show) { nodeScale = new Vector3(NodeSize,NodeSize,NodeSize); switch (this.LeGridType) { case GridType.Pathfinding: DrawPathfinding(); break; } } } private Vector3 nodeScale; void DrawPathfinding() { for (int i = 0; i < GridManager.NodeCount; i++) { for (int j = 0; j < GridManager.NodeCount; j++) { GridNode node = GridManager.GetNode(i,j); if (node.Unwalkable) Gizmos.color = Color.red; else Gizmos.color = Color.gray; Gizmos.DrawCube(node.WorldPos.ToVector3(LeHeight),nodeScale); } } } public enum GridType { Pathfinding } } }
using UnityEngine; using System.Collections; namespace Lockstep { public class GridDebugger : MonoBehaviour { public GridType LeGridType; public float LeHeight; [Range (.1f,.9f)] public float NodeSize = .4f; void OnDrawGizmos () { nodeScale = new Vector3(NodeSize,NodeSize,NodeSize); switch (this.LeGridType) { case GridType.Pathfinding: DrawPathfinding(); break; } } private Vector3 nodeScale; void DrawPathfinding() { for (int i = 0; i < GridManager.NodeCount; i++) { for (int j = 0; j < GridManager.NodeCount; j++) { GridNode node = GridManager.GetNode(i,j); if (node.Unwalkable) Gizmos.color = Color.red; else Gizmos.color = Color.gray; Gizmos.DrawCube(node.WorldPos.ToVector3(LeHeight),nodeScale); } } } public enum GridType { Pathfinding } } }
mit
C#
654f5dfbfac729ad232b8fbc16dd43925d48e2a6
fix xml doc
NebulousConcept/b2-csharp-client
b2-csharp-client/B2.Client/Rest/AuthenticatedB2Client.cs
b2-csharp-client/B2.Client/Rest/AuthenticatedB2Client.cs
using System.Net; using System.Threading.Tasks; using B2.Client.Rest.Api; using B2.Client.Rest.Request; using B2.Client.Rest.Response; namespace B2.Client.Rest { /// <summary> /// A B2 REST client that can make authenticated API calls. /// </summary> public sealed class AuthenticatedB2Client : RestClient { private readonly IAuthenticationToken token; /// <summary> /// Create a new <see cref="AuthenticatedB2Client"/>. /// </summary> /// <param name="token">The authentication/authorization token.</param> /// <param name="webProxy">The optional proxy to use.</param> public AuthenticatedB2Client(IAuthenticationToken token, IWebProxy webProxy = null) : base(token.Endpoint, webProxy) { this.token = token; } /// <summary> /// Perform a request to an API and get a response back. /// </summary> /// <param name="api">The API to call.</param> /// <param name="request">The request to pass to the API.</param> /// <typeparam name="TReq">The API request type.</typeparam> /// <typeparam name="TRes">The API response type.</typeparam> /// <returns>A deserialized API response.</returns> public async Task<TRes> PerformApiRequestAsync<TReq, TRes>(IAuthenticatedApi<TReq, TRes> api, TReq request) where TReq : IRestRequest where TRes : IResponse { var client = GetHttpClient(); var req = request.ToHttpRequestMessage(api.ResourceUrl); foreach (var header in token.Headers) { req.Headers.Add(header.Name, header.Value); } var response = await client.SendAsync(req); return await HandleResponseAsync<TRes>(response); } } }
using System.Net; using System.Threading.Tasks; using B2.Client.Rest.Api; using B2.Client.Rest.Request; using B2.Client.Rest.Response; namespace B2.Client.Rest { /// <summary> /// A B2 REST client that can make authenticated API calls. /// </summary> public sealed class AuthenticatedB2Client : RestClient { private readonly IAuthenticationToken token; /// <summary> /// Create a new <see cref="AuthenticatedB2Client"/>. /// </summary> /// <param name="token">The authentication/authorization token.</param> /// <param name="endpoint">The endpoint of the client.</param> /// <param name="webProxy">The optional proxy to use.</param> public AuthenticatedB2Client(IAuthenticationToken token, IWebProxy webProxy = null) : base(token.Endpoint, webProxy) { this.token = token; } /// <summary> /// Perform a request to an authentication API and get an authentication response back. /// </summary> /// <param name="authApi">The authentication API to call.</param> /// <param name="request">The request to pass to the API.</param> /// <typeparam name="TReq">The API request type.</typeparam> /// <typeparam name="TRes">The API response type.</typeparam> /// <returns>A deserialized API response.</returns> public async Task<TRes> PerformApiRequestAsync<TReq, TRes>(IAuthenticatedApi<TReq, TRes> api, TReq request) where TReq : IRestRequest where TRes : IResponse { var client = GetHttpClient(); var req = request.ToHttpRequestMessage(api.ResourceUrl); foreach (var header in token.Headers) { req.Headers.Add(header.Name, header.Value); } var response = await client.SendAsync(req); return await HandleResponseAsync<TRes>(response); } } }
mit
C#
526f4e551d2e8c8de668714f3128d532e5eaa87c
Add create for purchase method for Address
goshippo/shippo-csharp-client
Shippo/Address.cs
Shippo/Address.cs
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace Shippo { [JsonObject (MemberSerialization.OptIn)] public class Address : ShippoId { [JsonProperty (PropertyName = "object_state")] public string ObjectState; [JsonProperty (PropertyName = "object_purpose")] public string ObjectPurpose; [JsonProperty (PropertyName = "object_source")] public string ObjectSource; [JsonProperty (PropertyName = "object_created")] public DateTime? ObjectCreated; [JsonProperty (PropertyName = "object_updated")] public DateTime? ObjectUpdated; [JsonProperty (PropertyName = "object_owner")] public string ObjectOwner; [JsonProperty (PropertyName = "name")] public string Name; [JsonProperty (PropertyName = "company")] public string Company; [JsonProperty (PropertyName = "street1")] public string Street1; [JsonProperty (PropertyName = "street_no")] public string StreetNo; [JsonProperty (PropertyName = "street2")] public string Street2; [JsonProperty (PropertyName = "street3")] public string Street3; [JsonProperty (PropertyName = "city")] public string City; [JsonProperty (PropertyName = "state")] public string State; [JsonProperty (PropertyName = "zip")] public string Zip; [JsonProperty (PropertyName = "country")] public string Country; [JsonProperty (PropertyName = "phone")] public string Phone; [JsonProperty (PropertyName = "email")] public string Email; [JsonProperty (PropertyName = "is_residential")] public bool? IsResidential; [JsonProperty (PropertyName = "validate")] public bool? Validate; [JsonProperty (PropertyName = "metadata")] public string Metadata; [JsonProperty (PropertyName = "test")] public bool Test; [JsonProperty (PropertyName = "messages")] public List<string> Messages; public static Address createForPurchase (String purpose, String name, String street1, String street2, String city, String state, String zip, String country, String phone, String email) { Address a = new Address (); a.ObjectPurpose = purpose; a.Name = name; a.Street1 = street1; a.Street2 = street2; a.City = city; a.State = state; a.Zip = zip; a.Country = country; a.Phone = phone; a.Email = email; return a; } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace Shippo { [JsonObject (MemberSerialization.OptIn)] public class Address : ShippoId { [JsonProperty (PropertyName = "object_state")] public string ObjectState; [JsonProperty (PropertyName = "object_purpose")] public string ObjectPurpose; [JsonProperty (PropertyName = "object_source")] public string ObjectSource; [JsonProperty (PropertyName = "object_created")] public DateTime? ObjectCreated; [JsonProperty (PropertyName = "object_updated")] public DateTime? ObjectUpdated; [JsonProperty (PropertyName = "object_owner")] public string ObjectOwner; [JsonProperty (PropertyName = "name")] public string Name; [JsonProperty (PropertyName = "company")] public string Company; [JsonProperty (PropertyName = "street1")] public string Street1; [JsonProperty (PropertyName = "street_no")] public string StreetNo; [JsonProperty (PropertyName = "street2")] public string Street2; [JsonProperty (PropertyName = "street3")] public string Street3; [JsonProperty (PropertyName = "city")] public string City; [JsonProperty (PropertyName = "state")] public string State; [JsonProperty (PropertyName = "zip")] public string Zip; [JsonProperty (PropertyName = "country")] public string Country; [JsonProperty (PropertyName = "phone")] public string Phone; [JsonProperty (PropertyName = "email")] public string Email; [JsonProperty (PropertyName = "is_residential")] public bool? IsResidential; [JsonProperty (PropertyName = "validate")] public bool? Validate; [JsonProperty (PropertyName = "metadata")] public string Metadata; [JsonProperty (PropertyName = "test")] public bool Test; [JsonProperty (PropertyName = "messages")] public List<string> Messages; } }
apache-2.0
C#
465492ba0a8aefb704106983895149deed372e3f
add new branhc
toannvqo/dnn_publish
Components/ProductController.cs
Components/ProductController.cs
using DotNetNuke.Data; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Christoc.Modules.DNNModule1.Components { public class ProductController { public Product GetProduct(int productId) { Product p; using (IDataContext ctx = DataContext.Instance()) { Console.WriteLine("new branch"); Console.WriteLine("shshshshshs"); var rep = ctx.GetRepository<Product>(); p = rep.GetById(productId); } return p; } public IEnumerable<Product> getAll() { IEnumerable<Product> p; using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); p = rep.Get(); } return p; } public void CreateProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Insert(p); } } public void DeleteProduct(int productId) { var p = GetProduct(productId); DeleteProduct(p); } public void DeleteProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Delete(p); } } public void UpdateProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Update(p); } } } }
using DotNetNuke.Data; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Christoc.Modules.DNNModule1.Components { public class ProductController { public Product GetProduct(int productId) { Product p; using (IDataContext ctx = DataContext.Instance()) { Console.WriteLine("hello world"); Console.WriteLine("shshshshshs"); var rep = ctx.GetRepository<Product>(); p = rep.GetById(productId); } return p; } public IEnumerable<Product> getAll() { IEnumerable<Product> p; using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); p = rep.Get(); } return p; } public void CreateProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Insert(p); } } public void DeleteProduct(int productId) { var p = GetProduct(productId); DeleteProduct(p); } public void DeleteProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Delete(p); } } public void UpdateProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Update(p); } } } }
mit
C#
c2b98bd41c7935342fd8a0290bb12269ee660c06
Add IEnumerable<KeyValuePair<>>.ConcatKVP convenience function
orbitalgames/collections-extensions
IEnumerableExtensions.cs
IEnumerableExtensions.cs
/* The MIT License (MIT) Copyright (c) 2015 Orbital Games, LLC. 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.Collections.Generic; using System.Linq; using System; namespace OrbitalGames.Collections { /// <summary> /// Extension methods for System.IEnumerable /// </summary> public static class IEnumerableExtensions { /// <summary> /// Joins the string representations of each element of the given IEnumerable using a given separator string. /// </summary> /// <param name="source">IEnumerable to join</param> /// <param name="separator">String to use as a separator</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="source" /> is null</exception> /// <returns>Joined string</returns> public static string StringJoin<TSource>(this IEnumerable<TSource> source, string separator) { if (source == null) { throw new ArgumentNullException("source"); } return string.Join(separator, source.Select<TSource, string>(x => x.ToString()).ToArray()); } /// <summary> /// Returns the cartesian product of a sequence of sequences. /// </summary> /// <param name="source">Sequence of sequences on which to operate</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="source" /> is null</exception> /// <returns>Cartesian product of source</returns> /// <remarks> /// Inspired by Eric Lippert: http://ericlippert.com/2010/06/28/computing-a-cartesian-product-with-linq/ /// </remarks> public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> source) { if (source == null) { throw new ArgumentNullException("source"); } IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return source.Aggregate(emptyProduct, (accumulator, sequence) => accumulator.SelectMany(accseq => sequence.Select(item => accseq.Concat(new[] { item })))); } /// <summary> /// Concatenates a single key/value pair to a sequence of <see cref="KeyValuePair{TKey, TValue}" /> elements. /// </summary> /// <param name="source">Sequence to which the new key/value pair will be concatenated</param> /// <param name="key">Key</param> /// <param name="value">Value</param> /// <returns>Concatenation of the original sequence and the given key/value pair</returns> public static IEnumerable<KeyValuePair<TKey, TValue>> ConcatKVP<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source, TKey key, TValue value) { return source.Concat(new[] { new KeyValuePair<TKey, TValue>(key, value) }); } } }
/* The MIT License (MIT) Copyright (c) 2015 Orbital Games, LLC. 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.Collections.Generic; using System.Linq; using System; namespace OrbitalGames.Collections { /// <summary> /// Extension methods for System.IEnumerable /// </summary> public static class IEnumerableExtensions { /// <summary> /// Joins the string representations of each element of the given IEnumerable using a given separator string. /// </summary> /// <param name="source">IEnumerable to join</param> /// <param name="separator">String to use as a separator</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="source" /> is null</exception> /// <returns>Joined string</returns> public static string StringJoin<TSource>(this IEnumerable<TSource> source, string separator) { if (source == null) { throw new ArgumentNullException("source"); } return string.Join(separator, source.Select<TSource, string>(x => x.ToString()).ToArray()); } /// <summary> /// Returns the cartesian product of a sequence of sequences. /// </summary> /// <param name="source">Sequence of sequences on which to operate</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="source" /> is null</exception> /// <returns>Cartesian product of source</returns> /// <remarks> /// Inspired by Eric Lippert: http://ericlippert.com/2010/06/28/computing-a-cartesian-product-with-linq/ /// </remarks> public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> source) { if (source == null) { throw new ArgumentNullException("source"); } IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return source.Aggregate(emptyProduct, (accumulator, sequence) => accumulator.SelectMany(accseq => sequence.Select(item => accseq.Concat(new[] { item })))); } } }
mit
C#
b7595a1e770b928bddc1a4bd4751532e63531893
Fix indentation homecontroller
erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner
Zk/Controllers/HomeController.cs
Zk/Controllers/HomeController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using Zk.Helpers; using Zk.ViewModels; namespace Zk.Controllers { [Authorize] public class HomeController : Controller { public ActionResult Index() { // Months are used for the CSS classes // to add to the squares and for displayal within the square. var months = MonthHelper.GetAllMonths() .Select(m => m.ToString().ToLower()) .ToList(); var viewModel = new MainViewModel { // Seasons in Dutch (singular: "seizoen"; plural: "seizoenen") used for displayal in top row. SeizoenenForDisplay = new[] { "herfst", "winter", "lente", "zomer" }, // Seasons used for the CSS classes which refer to the different images. SeasonsCssClasses = new[] { "autumn", "winter", "spring", "summer" }, MonthsOrdered = new Stack<string>(new[] { months[7], months[4], months[1], months[10], months[6], months[3], months[0], months[9], months[5], months[2], months[11], months[8] }) }; return View(viewModel); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using Zk.Helpers; using Zk.ViewModels; namespace Zk.Controllers { [Authorize] public class HomeController : Controller { public ActionResult Index() { // Months are used for the CSS classes // to add to the squares and for displayal within the square. var months = MonthHelper.GetAllMonths() .Select(m => m.ToString().ToLower()) .ToList(); var viewModel = new MainViewModel { // Seasons in Dutch (singular: "seizoen"; plural: "seizoenen") used for displayal in top row. SeizoenenForDisplay = new[] { "herfst", "winter", "lente", "zomer" }, // Seasons used for the CSS classes which refer to the different images. SeasonsCssClasses = new[] { "autumn", "winter", "spring", "summer" }, MonthsOrdered = new Stack<string>(new[] { months[7], months[4], months[1], months[10], months[6], months[3], months[0], months[9], months[5], months[2], months[11], months[8] }) }; return View(viewModel); } } }
mit
C#
bd518ebab5dfbbd432ad46b471843d144981cc97
Update Reporter to detect OpenTK version.
eylvisaker/AgateLib
Drivers/AgateOTK/Otk_Reporter.cs
Drivers/AgateOTK/Otk_Reporter.cs
// The contents of this file are subject to the Mozilla Public License // Version 1.1 (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.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the // License for the specific language governing rights and limitations // under the License. // // The Original Code is AgateLib. // // The Initial Developer of the Original Code is Erik Ylvisaker. // Portions created by Erik Ylvisaker are Copyright (C) 2006. // All Rights Reserved. // // Contributor(s): Erik Ylvisaker // using System; using System.Collections.Generic; using System.Reflection; using System.Text; using AgateLib.Drivers; namespace AgateOTK { class Otk_Reporter : AgateDriverReporter { public override IEnumerable<AgateDriverInfo> ReportDrivers() { string opentk_version = "0.9.5"; opentk_version = GetOpenTKVersion(opentk_version); yield return new AgateDriverInfo( DisplayTypeID.OpenGL, typeof(GL_Display), "OpenGL through OpenTK" + opentk_version, 1120); if (ReportOpenAL()) { yield return new AgateDriverInfo( AudioTypeID.OpenAL, typeof(AL_Audio), "OpenAL through OpenTK" + opentk_version, 100); } } private static string GetOpenTKVersion(string opentk_version) { Assembly otkass = Assembly.GetAssembly(typeof(OpenTK.Graphics.GL)); object[] attribs = otkass.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false); AssemblyFileVersionAttribute version = attribs[0] as AssemblyFileVersionAttribute; if (version != null) opentk_version = " " + version.Version; return opentk_version; } bool ReportOpenAL() { try { // test for the presence of working OpenAL. new OpenTK.Audio.AudioContext().Dispose(); return true; } catch (Exception) { return false; } } } }
// The contents of this file are subject to the Mozilla Public License // Version 1.1 (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.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the // License for the specific language governing rights and limitations // under the License. // // The Original Code is AgateLib. // // The Initial Developer of the Original Code is Erik Ylvisaker. // Portions created by Erik Ylvisaker are Copyright (C) 2006. // All Rights Reserved. // // Contributor(s): Erik Ylvisaker // using System; using System.Collections.Generic; using System.Text; using AgateLib.Drivers; namespace AgateOTK { class Otk_Reporter : AgateDriverReporter { public override IEnumerable<AgateDriverInfo> ReportDrivers() { yield return new AgateDriverInfo( DisplayTypeID.OpenGL, typeof(GL_Display), "OpenGL through OpenTK 0.9.5", 1120); if (ReportOpenAL()) { yield return new AgateDriverInfo( AudioTypeID.OpenAL, typeof(AL_Audio), "OpenAL through OpenTK 0.9.5", 100); } } bool ReportOpenAL() { try { // test for the presence of working OpenAL. new OpenTK.Audio.AudioContext().Dispose(); return true; } catch (Exception) { return false; } } } }
mit
C#
c0f0bbf7991cb0b69238ce2a93efc83dcf054c9c
adjust test code for algorithm
myxini/block-program
block-program/RecognitionTest/ClassifierTest.cs
block-program/RecognitionTest/ClassifierTest.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Myxini.Recognition; using Myxini.Recognition.Image; using Myxini.Recognition.Properties; using System.Drawing; namespace RecognitionTest { [TestClass] public class ClassifierTest { [TestMethod] public void ClusteringTest() { var classifier = new Classifier(); var algorithm = new SADAlgorithm(); Clustering(classifier, algorithm, Resources.PatternLED0, Command.LED, 0); Clustering(classifier, algorithm, Resources.PatternLED1, Command.LED, 1); Clustering(classifier, algorithm, Resources.PatternMoveBackward1, Command.Move, -1); Clustering(classifier, algorithm, Resources.PatternMoveForward1, Command.Move, 1); Clustering(classifier, algorithm, Resources.PatternRotateCCW, Command.Rotate, -1); Clustering(classifier, algorithm, Resources.PatternRotateCW, Command.Rotate, 1); Clustering(classifier, algorithm, Resources.PatternMicroSwitch, Command.MicroSwitch, null); Clustering(classifier, algorithm, Resources.PatternPSD, Command.PSD, null); Clustering(classifier, algorithm, Resources.PatternStart, Command.Start, null); Clustering(classifier, algorithm, Resources.PatternEnd, Command.End, null); } private void Clustering( Classifier classifier, IPatternMatchingAlgorithm algorithm, Bitmap pattern, Command command, int? parameter0 ) { IImage image = new BitmapImage(pattern); IBlock block = classifier.Clustering(image, algorithm); Assert.AreEqual(command, block.CommandIdentification); if (block.Parameter.ValueLength() == 1) { Assert.AreEqual(block.Parameter.Value(0), parameter0); } } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Myxini.Recognition; using Myxini.Recognition.Image; using Myxini.Recognition.Properties; using System.Drawing; namespace RecognitionTest { [TestClass] public class ClassifierTest { [TestMethod] public void ClusteringTest() { var classifier = new Classifier(); Clustering(classifier, Resources.PatternLED0, Command.LED, 0); Clustering(classifier, Resources.PatternLED1, Command.LED, 1); Clustering(classifier, Resources.PatternMoveBackward1, Command.Move, -1); Clustering(classifier, Resources.PatternMoveForward1, Command.Move, 1); Clustering(classifier, Resources.PatternRotateCCW, Command.Rotate, -1); Clustering(classifier, Resources.PatternRotateCW, Command.Rotate, 1); Clustering(classifier, Resources.PatternMicroSwitch, Command.MicroSwitch, null); Clustering(classifier, Resources.PatternPSD, Command.PSD, null); Clustering(classifier, Resources.PatternStart, Command.Start, null); Clustering(classifier, Resources.PatternEnd, Command.End, null); } private void Clustering(Classifier classifier, Bitmap pattern, Command command, int? parameter0) { IImage image = new BitmapImage(pattern); IBlock block = classifier.Clustering(image); Assert.AreEqual(command, block.CommandIdentification); if (block.Parameter.ValueLength() == 1) { Assert.AreEqual(block.Parameter.Value(0), parameter0); } } } }
mit
C#
6d498d43cf25fc3739f1b3efa8b62fb2b6e09cd0
Update PanoramaGroupHeaderConverter.cs
Danghor/MahApps.Metro,Evangelink/MahApps.Metro,xxMUROxx/MahApps.Metro,pfattisc/MahApps.Metro,p76984275/MahApps.Metro,batzen/MahApps.Metro,ye4241/MahApps.Metro,jumulr/MahApps.Metro,chuuddo/MahApps.Metro,MahApps/MahApps.Metro,Jack109/MahApps.Metro,psinl/MahApps.Metro
MahApps.Metro/Converters/PanoramaGroupHeaderConverter.cs
MahApps.Metro/Converters/PanoramaGroupHeaderConverter.cs
using MahApps.Metro.Controls; using System; using System.Globalization; using System.Windows; using System.Windows.Controls; using System.Windows.Data; namespace MahApps.Metro.Converters { public class PanoramaGroupHeaderConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var result = new Thickness(10, 0, 0, 20); var panorama_group_header = (Label)values[0]; var panorama_left_edge = panorama_group_header.TryFindParent<ScrollViewer>().Margin.Left; var panorama_group = panorama_group_header.TryFindParent<DockPanel>(); var panorama_group_left_edge = panorama_group.TranslatePoint(new Point(0, 0), null).X; var panorama_group_header_max_left = (panorama_group.ActualWidth - panorama_group_header.ActualWidth) - 20; var proposed_left_margin = Math.Abs(panorama_group_left_edge - panorama_left_edge) + 10; // Return (left = 0) if group left margin is beyond panorama left margin if (panorama_group_left_edge < panorama_left_edge) // Calculate to group header receive how much content is scrolled ... // ... except if new position is beyond group width result.Left = proposed_left_margin < panorama_group_header_max_left ? proposed_left_margin : panorama_group_header_max_left; return result; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
using MahApps.Metro.Controls; using System; using System.Globalization; using System.Windows; using System.Windows.Controls; using System.Windows.Data; namespace MahApps.Metro.Converters { public class PanoramaGroupHeaderConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var result = new Thickness(10, 0, 20, 0); var panorama_group_header = (Label)values[0]; var panorama_left_edge = panorama_group_header.TryFindParent<ScrollViewer>().Margin.Left; var panorama_group = panorama_group_header.TryFindParent<DockPanel>(); var panorama_group_left_edge = panorama_group.TranslatePoint(new Point(0, 0), null).X; var panorama_group_header_max_left = (panorama_group.ActualWidth - panorama_group_header.ActualWidth) - 20; var proposed_left_margin = Math.Abs(panorama_group_left_edge - panorama_left_edge) + 10; // Return (left = 0) if group left margin is beyond panorama left margin if (panorama_group_left_edge < panorama_left_edge) // Calculate to group header receive how much content is scrolled ... // ... except if new position is beyond group width result.Left = proposed_left_margin < panorama_group_header_max_left ? proposed_left_margin : panorama_group_header_max_left; return result; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
mit
C#
e26bab1d86d47aa561f59f2d49e747cec21bf880
Revert LowLatencyTaskFactory to the default.
rubyu/CreviceApp,rubyu/CreviceApp
CreviceApp/GM.GestureMachine.cs
CreviceApp/GM.GestureMachine.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Crevice.GestureMachine { using System.Threading; using System.Drawing; using Crevice.Core.FSM; using Crevice.Core.Events; using Crevice.Threading; public class NullGestureMachine : GestureMachine { public NullGestureMachine() : base(new GestureMachineConfig(), new CallbackManager()) { } } public class GestureMachine : GestureMachine<GestureMachineConfig, ContextManager, EvaluationContext, ExecutionContext> { public GestureMachine( GestureMachineConfig gestureMachineConfig, CallbackManager callbackManager) : base(gestureMachineConfig, callbackManager, new ContextManager()) { } private readonly TaskFactory _strokeWatcherTaskFactory = LowLatencyScheduler.CreateTaskFactory( "StrokeWatcherTaskScheduler", ThreadPriority.Highest, 1); protected override TaskFactory StrokeWatcherTaskFactory => _strokeWatcherTaskFactory; public override bool Input(IPhysicalEvent evnt, Point? point) { lock (lockObject) { if (point.HasValue) { ContextManager.CursorPosition = point.Value; } return base.Input(evnt, point); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Crevice.GestureMachine { using System.Threading; using System.Drawing; using Crevice.Core.FSM; using Crevice.Core.Events; using Crevice.Threading; public class NullGestureMachine : GestureMachine { public NullGestureMachine() : base(new GestureMachineConfig(), new CallbackManager()) { } } public class GestureMachine : GestureMachine<GestureMachineConfig, ContextManager, EvaluationContext, ExecutionContext> { public GestureMachine( GestureMachineConfig gestureMachineConfig, CallbackManager callbackManager) : base(gestureMachineConfig, callbackManager, new ContextManager()) { } private readonly TaskFactory _strokeWatcherTaskFactory = LowLatencyScheduler.CreateTaskFactory( "StrokeWatcherTaskScheduler", ThreadPriority.Highest, 1); protected override TaskFactory StrokeWatcherTaskFactory => _strokeWatcherTaskFactory; private readonly TaskFactory _lowPriorityTaskFactory = LowLatencyScheduler.CreateTaskFactory( "LowPriorityTaskScheduler", ThreadPriority.Lowest, 1); protected override TaskFactory LowPriorityTaskFactory => _lowPriorityTaskFactory; public override bool Input(IPhysicalEvent evnt, Point? point) { lock (lockObject) { if (point.HasValue) { ContextManager.CursorPosition = point.Value; } return base.Input(evnt, point); } } } }
mit
C#
66f636045e54ad0e96a4c001f09b01bb665ac3f1
Add instantiation of context on app start.
miracle-as/kitos,miracle-as/kitos,os2kitos/kitos,os2kitos/kitos,miracle-as/kitos,miracle-as/kitos,os2kitos/kitos,os2kitos/kitos
Presentation.Web/Global.asax.cs
Presentation.Web/Global.asax.cs
using System.Data.Entity; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Infrastructure.DataAccess; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Presentation.Web { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); // Turns off self reference looping when serializing models in API controlllers GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // Support polymorphism in web api JSON output GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto; // Set JSON serialization in WEB API to use camelCase (javascript) instead of PascalCase (C#) GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // Convert all dates to UTC GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; // Create and seed database var context = new KitosContext(); context.Database.Initialize(false); } } }
using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Presentation.Web { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); // Turns off self reference looping when serializing models in API controlllers GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // Support polymorphism in web api JSON output GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto; // Set JSON serialization in WEB API to use camelCase (javascript) instead of PascalCase (C#) GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // Convert all dates to UTC GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; } } }
mpl-2.0
C#
101c99ecca9bd77238a88d06c1219d881aa71913
change JWK content type to application/json
MienDev/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4
src/IdentityServer4/src/Endpoints/Results/JsonWebKeysResult.cs
src/IdentityServer4/src/Endpoints/Results/JsonWebKeysResult.cs
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityServer4.Extensions; using IdentityServer4.Hosting; using IdentityServer4.Models; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace IdentityServer4.Endpoints.Results { /// <summary> /// Result for the jwks document /// </summary> /// <seealso cref="IdentityServer4.Hosting.IEndpointResult" /> public class JsonWebKeysResult : IEndpointResult { /// <summary> /// Gets the web keys. /// </summary> /// <value> /// The web keys. /// </value> public IEnumerable<JsonWebKey> WebKeys { get; } /// <summary> /// Gets the maximum age. /// </summary> /// <value> /// The maximum age. /// </value> public int? MaxAge { get; } /// <summary> /// Initializes a new instance of the <see cref="JsonWebKeysResult" /> class. /// </summary> /// <param name="webKeys">The web keys.</param> /// <param name="maxAge">The maximum age.</param> public JsonWebKeysResult(IEnumerable<JsonWebKey> webKeys, int? maxAge) { WebKeys = webKeys ?? throw new ArgumentNullException(nameof(webKeys)); MaxAge = maxAge; } /// <summary> /// Executes the result. /// </summary> /// <param name="context">The HTTP context.</param> /// <returns></returns> public Task ExecuteAsync(HttpContext context) { if (MaxAge.HasValue && MaxAge.Value >= 0) { context.Response.SetCache(MaxAge.Value, "Origin"); } return context.Response.WriteJsonAsync(new { keys = WebKeys }, "application/json; charset=UTF-8"); } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityServer4.Extensions; using IdentityServer4.Hosting; using IdentityServer4.Models; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace IdentityServer4.Endpoints.Results { /// <summary> /// Result for the jwks document /// </summary> /// <seealso cref="IdentityServer4.Hosting.IEndpointResult" /> public class JsonWebKeysResult : IEndpointResult { /// <summary> /// Gets the web keys. /// </summary> /// <value> /// The web keys. /// </value> public IEnumerable<JsonWebKey> WebKeys { get; } /// <summary> /// Gets the maximum age. /// </summary> /// <value> /// The maximum age. /// </value> public int? MaxAge { get; } /// <summary> /// Initializes a new instance of the <see cref="JsonWebKeysResult" /> class. /// </summary> /// <param name="webKeys">The web keys.</param> /// <param name="maxAge">The maximum age.</param> public JsonWebKeysResult(IEnumerable<JsonWebKey> webKeys, int? maxAge) { WebKeys = webKeys ?? throw new ArgumentNullException(nameof(webKeys)); MaxAge = maxAge; } /// <summary> /// Executes the result. /// </summary> /// <param name="context">The HTTP context.</param> /// <returns></returns> public Task ExecuteAsync(HttpContext context) { if (MaxAge.HasValue && MaxAge.Value >= 0) { context.Response.SetCache(MaxAge.Value, "Origin"); } return context.Response.WriteJsonAsync(new { keys = WebKeys }, "application/jwk-set+json; charset=UTF-8"); } } }
apache-2.0
C#
a528b9d5f47b02e44e4748e8c4ba2a98ee9f3366
Allow .map files as default browsable file extensions from the App_Plugins static file handler.
robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS
src/Umbraco.Core/Configuration/Models/UmbracoPluginSettings.cs
src/Umbraco.Core/Configuration/Models/UmbracoPluginSettings.cs
// Copyright (c) Umbraco. // See LICENSE for more details. using System.Collections.Generic; namespace Umbraco.Cms.Core.Configuration.Models { /// <summary> /// Typed configuration options for the plugins. /// </summary> [UmbracoOptions(Constants.Configuration.ConfigPlugins)] public class UmbracoPluginSettings { /// <summary> /// Gets or sets the allowed file extensions (including the period ".") that should be accessible from the browser. /// </summary> /// WB-TODO public ISet<string> BrowsableFileExtensions { get; set; } = new HashSet<string>(new[] { ".html", // markup ".css", // styles ".js", // scripts ".jpg", ".jpeg", ".gif", ".png", ".svg", // images ".eot", ".ttf", ".woff", // fonts ".xml", ".json", ".config", // configurations ".lic", // license ".map" // js map files }); } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System.Collections.Generic; namespace Umbraco.Cms.Core.Configuration.Models { /// <summary> /// Typed configuration options for the plugins. /// </summary> [UmbracoOptions(Constants.Configuration.ConfigPlugins)] public class UmbracoPluginSettings { /// <summary> /// Gets or sets the allowed file extensions (including the period ".") that should be accessible from the browser. /// </summary> /// WB-TODO public ISet<string> BrowsableFileExtensions { get; set; } = new HashSet<string>(new[] { ".html", // markup ".css", // styles ".js", // scripts ".jpg", ".jpeg", ".gif", ".png", ".svg", // images ".eot", ".ttf", ".woff", // fonts ".xml", ".json", ".config", // configurations ".lic" // license }); } }
mit
C#
02fd2a4487590a8d2f375aa6ee52b52fd718f349
remove using
northwoodspd/UIA.Extensions,northwoodspd/UIA.Extensions
src/UIA.Extensions.Units/AutomationProviders/ValueProviderTest.cs
src/UIA.Extensions.Units/AutomationProviders/ValueProviderTest.cs
using System.Windows.Automation; using System.Windows.Forms; using NUnit.Framework; using Should.Fluent; namespace UIA.Extensions.AutomationProviders { [TestFixture] public class ValueProviderTest { private ValueControlStub _valueControl; private ValueProvider _valueProvider; [SetUp] public void SetUp() { _valueControl = new ValueControlStub(new Control()); _valueProvider = new ValueProvider(_valueControl); } [Test] public void ItHasTheCorrectPattern() { _valueProvider.GetPatternProvider(ValuePatternIdentifiers.Pattern.Id) .Should().Be.SameAs(_valueProvider); } [Test] public void ValuesCanBeRetrieved() { _valueControl.Value = "Expected Value"; _valueProvider.Value.Should().Equal("Expected Value"); } [Test] public void ValuesCanBeSet() { _valueProvider.SetValue("The expected value to be set"); _valueControl.Value.Should().Equal("The expected value to be set"); } class ValueControlStub : ValueControl { public ValueControlStub(Control control) : base(control) { } public override string Value { get; set; } } } }
using System; using System.Windows.Automation; using System.Windows.Forms; using NUnit.Framework; using Should.Fluent; namespace UIA.Extensions.AutomationProviders { [TestFixture] public class ValueProviderTest { private ValueControlStub _valueControl; private ValueProvider _valueProvider; [SetUp] public void SetUp() { _valueControl = new ValueControlStub(new Control()); _valueProvider = new ValueProvider(_valueControl); } [Test] public void ItHasTheCorrectPattern() { _valueProvider.GetPatternProvider(ValuePatternIdentifiers.Pattern.Id) .Should().Be.SameAs(_valueProvider); } [Test] public void ValuesCanBeRetrieved() { _valueControl.Value = "Expected Value"; _valueProvider.Value.Should().Equal("Expected Value"); } [Test] public void ValuesCanBeSet() { _valueProvider.SetValue("The expected value to be set"); _valueControl.Value.Should().Equal("The expected value to be set"); } class ValueControlStub : ValueControl { public ValueControlStub(Control control) : base(control) { } public override string Value { get; set; } } } }
mit
C#
f39dc8f5ff1aef8d9948f7ae60efefc1fe30114e
Return review URL in response to auto API review create request (#1292)
tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools
src/dotnet/APIView/APIViewWeb/Controllers/AutoReviewController.cs
src/dotnet/APIView/APIViewWeb/Controllers/AutoReviewController.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using APIViewWeb.Filters; using APIViewWeb.Respositories; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.Linq; using System.Threading.Tasks; namespace APIViewWeb.Controllers { [TypeFilter(typeof(ApiKeyAuthorizeAsyncFilter))] public class AutoReviewController : Controller { private readonly ReviewManager _reviewManager; public AutoReviewController(ReviewManager reviewManager) { _reviewManager = reviewManager; } [HttpPost] public async Task<ActionResult> UploadAutoReview([FromForm] IFormFile file, string label) { if (file != null) { using (var openReadStream = file.OpenReadStream()) { var review = await _reviewManager.CreateMasterReviewAsync(User, file.FileName, label, openReadStream, false); if(review != null) { var reviewUrl = $"{this.Request.Scheme}://{this.Request.Host}/Assemblies/Review/{review.ReviewId}"; //Return 200 OK if last revision is approved and 201 if revision is not yet approved. var result = review.Revisions.Last().Approvers.Count > 0 ? Ok(reviewUrl) : StatusCode(statusCode: StatusCodes.Status201Created, reviewUrl); return result; } } } // Return internal server error for any unknown error return StatusCode(statusCode: StatusCodes.Status500InternalServerError); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using APIViewWeb.Filters; using APIViewWeb.Respositories; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.Linq; using System.Threading.Tasks; namespace APIViewWeb.Controllers { [TypeFilter(typeof(ApiKeyAuthorizeAsyncFilter))] public class AutoReviewController : Controller { private readonly ReviewManager _reviewManager; public AutoReviewController(ReviewManager reviewManager) { _reviewManager = reviewManager; } [HttpPost] public async Task<ActionResult> UploadAutoReview([FromForm] IFormFile file, string label) { if (file != null) { using (var openReadStream = file.OpenReadStream()) { var review = await _reviewManager.CreateMasterReviewAsync(User, file.FileName, label, openReadStream, false); if(review != null) { //Return 200 OK if last revision is approved and 201 if revision is not yet approved. var result = review.Revisions.Last().Approvers.Count > 0 ? Ok() : StatusCode(statusCode: StatusCodes.Status201Created); return result; } } } // Return internal server error for any unknown error return StatusCode(statusCode: StatusCodes.Status500InternalServerError); } } }
mit
C#
c2ea3bdd447f470bcea261a336ed32afba567b88
Improve ManualResetEventSlim creation and disposal
EVAST9919/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework
osu.Framework.Tests/IO/BackgroundGameHeadlessGameHost.cs
osu.Framework.Tests/IO/BackgroundGameHeadlessGameHost.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.Threading; using System.Threading.Tasks; using osu.Framework.Platform; namespace osu.Framework.Tests.IO { /// <summary> /// Ad headless host for testing purposes. Contains an arbitrary game that is running after construction. /// </summary> public class BackgroundGameHeadlessGameHost : HeadlessGameHost { private TestGame testGame; public BackgroundGameHeadlessGameHost(string gameName = @"", bool bindIPC = false, bool realtime = true, bool portableInstallation = false) : base(gameName, bindIPC, realtime, portableInstallation) { using (var gameCreated = new ManualResetEventSlim(false)) { Task.Run(() => { try { testGame = new TestGame(); // ReSharper disable once AccessToDisposedClosure gameCreated.Set(); Run(testGame); } catch { // may throw an unobserved exception if we don't handle here. } }); gameCreated.Wait(); testGame.HasProcessed.Wait(); } } private class TestGame : Game { internal readonly ManualResetEventSlim HasProcessed = new ManualResetEventSlim(false); protected override void Update() { base.Update(); HasProcessed.Set(); } protected override void Dispose(bool isDisposing) { HasProcessed.Dispose(); base.Dispose(isDisposing); } } protected override void Dispose(bool isDisposing) { if (ExecutionState != ExecutionState.Stopped) Exit(); base.Dispose(isDisposing); } } }
// 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.Threading; using System.Threading.Tasks; using osu.Framework.Platform; namespace osu.Framework.Tests.IO { /// <summary> /// Ad headless host for testing purposes. Contains an arbitrary game that is running after construction. /// </summary> public class BackgroundGameHeadlessGameHost : HeadlessGameHost { private TestGame testGame; public BackgroundGameHeadlessGameHost(string gameName = @"", bool bindIPC = false, bool realtime = true, bool portableInstallation = false) : base(gameName, bindIPC, realtime, portableInstallation) { var gameCreated = new ManualResetEventSlim(false); Task.Run(() => { try { testGame = new TestGame(); gameCreated.Set(); Run(testGame); } catch { // may throw an unobserved exception if we don't handle here. } }); using (gameCreated) gameCreated.Wait(); using (testGame.HasProcessed) testGame.HasProcessed.Wait(); } private class TestGame : Game { public readonly ManualResetEventSlim HasProcessed = new ManualResetEventSlim(false); protected override void Update() { base.Update(); HasProcessed.Set(); } } protected override void Dispose(bool isDisposing) { if (ExecutionState != ExecutionState.Stopped) Exit(); base.Dispose(isDisposing); } } }
mit
C#
0adf819830028c3f984163237205c8e7c5c2efe5
Use https for Sparkle updates and change log access
cixonline/cixreader,cixonline/cixreader,cixonline/cixreader,cixonline/cixreader
CIXReader/Utilities/Constants_Windows.cs
CIXReader/Utilities/Constants_Windows.cs
// ***************************************************** // CIXReader // Constants_Windows.cs // // Author: Steve Palmer (spalmer@cix) // // Created: 21/06/2015 11:02 // // Copyright (C) 2013-2015 CIX Online Ltd. All Rights Reserved. // ***************************************************** namespace CIXReader.Utilities { /// <summary> /// Constants specific to the Windows version. /// </summary> public static partial class Constants { /// <summary> /// URL to the appcast link. /// </summary> public const string AppCastURL = "https://cixreader.cixhosting.co.uk/cixreader/windows/release/appcast.xml"; /// <summary> /// URL to the beta appcast link. /// </summary> public const string BetaAppCastURL = "https://cixreader.cixhosting.co.uk/cixreader/windows/beta/appcast.xml"; /// <summary> /// Change log file link. /// </summary> public const string ChangeLogURL = "https://cixreader.cixhosting.co.uk/cixreader/windows/{0}/changes.html"; /// <summary> /// Support forum for this version of CIXReader /// </summary> public const string SupportForum = "cix.support/cixreader"; /// <summary> /// Beta forum for this version of CIXReader /// </summary> public const string BetaForum = "cix.beta/cixreader"; } }
// ***************************************************** // CIXReader // Constants_Windows.cs // // Author: Steve Palmer (spalmer@cix) // // Created: 21/06/2015 11:02 // // Copyright (C) 2013-2015 CIX Online Ltd. All Rights Reserved. // ***************************************************** namespace CIXReader.Utilities { /// <summary> /// Constants specific to the Windows version. /// </summary> public static partial class Constants { /// <summary> /// URL to the appcast link. /// </summary> public const string AppCastURL = "http://cixreader.cixhosting.co.uk/cixreader/windows/release/appcast.xml"; /// <summary> /// URL to the beta appcast link. /// </summary> public const string BetaAppCastURL = "http://cixreader.cixhosting.co.uk/cixreader/windows/beta/appcast.xml"; /// <summary> /// Change log file link. /// </summary> public const string ChangeLogURL = "http://cixreader.cixhosting.co.uk/cixreader/windows/{0}/changes.html"; /// <summary> /// Support forum for this version of CIXReader /// </summary> public const string SupportForum = "cix.support/cixreader"; /// <summary> /// Beta forum for this version of CIXReader /// </summary> public const string BetaForum = "cix.beta/cixreader"; } }
apache-2.0
C#
ff6d1a814f5f622fdaa423f28158f9cae82f101a
Fix issue where SECDataConverter would fatally fail
jameschch/Lean,StefanoRaggi/Lean,QuantConnect/Lean,AlexCatarino/Lean,StefanoRaggi/Lean,JKarathiya/Lean,JKarathiya/Lean,jameschch/Lean,jameschch/Lean,StefanoRaggi/Lean,QuantConnect/Lean,StefanoRaggi/Lean,jameschch/Lean,QuantConnect/Lean,JKarathiya/Lean,QuantConnect/Lean,jameschch/Lean,JKarathiya/Lean,AlexCatarino/Lean,AlexCatarino/Lean,AlexCatarino/Lean,StefanoRaggi/Lean
Common/Data/Custom/SEC/SECReportFiler.cs
Common/Data/Custom/SEC/SECReportFiler.cs
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Newtonsoft.Json; using System.Collections.Generic; using QuantConnect.Util; namespace QuantConnect.Data.Custom.SEC { public class SECReportFiler { /// <summary> /// SEC data containing company data such as company name, cik, etc. /// </summary> [JsonProperty("COMPANY-DATA")] public SECReportCompanyData CompanyData; /// <summary> /// Information regarding the filing itself /// </summary> [JsonProperty("FILING-VALUES"), JsonConverter(typeof(SingleValueListConverter<SECReportFilingValues>))] public List<SECReportFilingValues> Values; /// <summary> /// Information related to the business' address /// </summary> [JsonProperty("BUSINESS-ADDRESS"), JsonConverter(typeof(SingleValueListConverter<SECReportBusinessAddress>))] public List<SECReportBusinessAddress> BusinessAddress; /// <summary> /// Company mailing address information /// </summary> [JsonProperty("MAIL-ADDRESS"), JsonConverter(typeof(SingleValueListConverter<SECReportMailAddress>))] public List<SECReportMailAddress> MailingAddress; /// <summary> /// Former company names /// </summary> [JsonProperty("FORMER-COMPANY"), JsonConverter(typeof(SingleValueListConverter<SECReportFormerCompany>))] public List<SECReportFormerCompany> FormerCompanies; } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Newtonsoft.Json; using System.Collections.Generic; using QuantConnect.Util; namespace QuantConnect.Data.Custom.SEC { public class SECReportFiler { /// <summary> /// SEC data containing company data such as company name, cik, etc. /// </summary> [JsonProperty("COMPANY-DATA")] public SECReportCompanyData CompanyData; /// <summary> /// Information regarding the filing itself /// </summary> [JsonProperty("FILING-VALUES")] public SECReportFilingValues Values; /// <summary> /// Information related to the business' address /// </summary> [JsonProperty("BUSINESS-ADDRESS"), JsonConverter(typeof(SingleValueListConverter<SECReportBusinessAddress>))] public List<SECReportBusinessAddress> BusinessAddress; /// <summary> /// Company mailing address information /// </summary> [JsonProperty("MAIL-ADDRESS"), JsonConverter(typeof(SingleValueListConverter<SECReportMailAddress>))] public List<SECReportMailAddress> MailingAddress; /// <summary> /// Former company names /// </summary> [JsonProperty("FORMER-COMPANY"), JsonConverter(typeof(SingleValueListConverter<SECReportFormerCompany>))] public List<SECReportFormerCompany> FormerCompanies; } }
apache-2.0
C#
68e3d217c0411bfef5e2a2e1dd3a06db79396f12
Fix race in DotnetUnderTest.FullPath on Windows.
johnbeisner/cli,johnbeisner/cli,livarcocc/cli-1,johnbeisner/cli,livarcocc/cli-1,livarcocc/cli-1
test/Microsoft.DotNet.Tools.Tests.Utilities/DotnetUnderTest.cs
test/Microsoft.DotNet.Tools.Tests.Utilities/DotnetUnderTest.cs
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Globalization; using System.Runtime.InteropServices; using Microsoft.DotNet.Cli.Utils; namespace Microsoft.DotNet.Tools.Test.Utilities { public static class DotnetUnderTest { static string _pathToDotnetUnderTest; public static string FullName { get { // This will hurt us when we try to publish and run tests // separately. Filled an issue against arcade to change // the CLI used to run the tests, at which point we can // revert this code to what it was before. // Issue: https://github.com/dotnet/arcade/issues/1207 if (_pathToDotnetUnderTest == null) { _pathToDotnetUnderTest = Path.Combine( new RepoDirectoriesProvider().DotnetRoot, $"dotnet{Constants.ExeSuffix}"); } return _pathToDotnetUnderTest; } } public static bool IsLocalized() { for (var culture = CultureInfo.CurrentUICulture; !culture.Equals(CultureInfo.InvariantCulture); culture = culture.Parent) { if (culture.Name == "en") { return false; } } return true; } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Globalization; using System.Runtime.InteropServices; using Microsoft.DotNet.Cli.Utils; namespace Microsoft.DotNet.Tools.Test.Utilities { public static class DotnetUnderTest { static string _pathToDotnetUnderTest; public static string FullName { get { // This will hurt us when we try to publish and run tests // separately. Filled an issue against arcade to change // the CLI used to run the tests, at which point we can // revert this code to what it was before. // Issue: https://github.com/dotnet/arcade/issues/1207 if (_pathToDotnetUnderTest == null) { _pathToDotnetUnderTest = Path.Combine( new RepoDirectoriesProvider().DotnetRoot, "dotnet"); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { _pathToDotnetUnderTest = $"{_pathToDotnetUnderTest}.exe"; } } return _pathToDotnetUnderTest; } } public static bool IsLocalized() { for (var culture = CultureInfo.CurrentUICulture; !culture.Equals(CultureInfo.InvariantCulture); culture = culture.Parent) { if (culture.Name == "en") { return false; } } return true; } } }
mit
C#
8ad9e0958fe01e917894447e7d38252f9aa9d88f
Create Contact method added to Contact Controller
ADukeLabs/DEX,ADukeLabs/DEX,ADukeLabs/DEX
DEX/DEX/Controllers/ContactController.cs
DEX/DEX/Controllers/ContactController.cs
using DEX.Models; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace DEX.Controllers { public class ContactController : Controller { private ApplicationDbContext db = new ApplicationDbContext(); //// GET: Contact/Create //public ActionResult Create() //{ // return View(); //} // POST: Contact/Create [HttpPost] public ActionResult Create([Bind(Include = "Id,Name,Title,Email,PhoneNumber")]Contact contact, int? id) { contact.Company = db.Companies.Find(id); if (ModelState.IsValid) db.Contacts.Add(contact); db.SaveChanges(); return RedirectToAction("Menu", "Home"); } protected override void Dispose(bool disposing) { if (disposing) db.Dispose(); base.Dispose(disposing); } } }
using DEX.Models; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace DEX.Controllers { public class ContactController : Controller { private ApplicationDbContext db = new ApplicationDbContext(); } }
apache-2.0
C#
c35c900f43234ae76092c7e1d4014287ea361c57
Add "equal to" and "not equal to" deserialization values to TriggerCondition
lordmilko/PrtgAPI,lordmilko/PrtgAPI
src/PrtgAPI/Enums/Deserialization/Triggers/TriggerCondition.cs
src/PrtgAPI/Enums/Deserialization/Triggers/TriggerCondition.cs
using System.Xml.Serialization; using PrtgAPI.Attributes; namespace PrtgAPI { /// <summary> /// Specifies threshold conditions to be used in notification triggers. /// </summary> public enum TriggerCondition { /// <summary> /// Trigger when sensor's value is above the threshold. /// </summary> [XmlEnum("0")] [XmlEnumAlternateName("above")] Above, /// <summary> /// Trigger when the sensor's value is below the threshold. /// </summary> [XmlEnum("1")] [XmlEnumAlternateName("below")] Below, /// <summary> /// Trigger when the sensor's value is equal to the threshold. /// </summary> [XmlEnum("2")] [XmlEnumAlternateName("equal to")] [XmlEnumAlternateName("Equal to")] Equals, /// <summary> /// Trigger when the sensor's value is not equal to the threshold. /// </summary> [XmlEnum("3")] [XmlEnumAlternateName("not equal to")] [XmlEnumAlternateName("Not Equal to")] NotEquals, /// <summary> /// Trigger whenever the sensor's value changes. For use in <see cref="TriggerType.Change"/> triggers only. /// </summary> [XmlEnum("change")] Change } }
using System.Xml.Serialization; using PrtgAPI.Attributes; namespace PrtgAPI { /// <summary> /// Specifies threshold conditions to be used in notification triggers. /// </summary> public enum TriggerCondition { /// <summary> /// Trigger when sensor's value is above the threshold. /// </summary> [XmlEnum("0")] [XmlEnumAlternateName("above")] Above, /// <summary> /// Trigger when the sensor's value is below the threshold. /// </summary> [XmlEnum("1")] [XmlEnumAlternateName("below")] Below, /// <summary> /// Trigger when the sensor's value is equal to the threshold. /// </summary> [XmlEnum("2")] [XmlEnumAlternateName("Equal to")] Equals, /// <summary> /// Trigger when the sensor's value is not equal to the threshold. /// </summary> [XmlEnum("3")] [XmlEnumAlternateName("Not Equal to")] NotEquals, /// <summary> /// Trigger whenever the sensor's value changes. For use in <see cref="TriggerType.Change"/> triggers only. /// </summary> [XmlEnum("change")] Change } }
mit
C#
f7db1475ca6a4dfb75b12f7f499ee043ab95ab60
fix typo
shabtaisharon/ds3_net_sdk,shabtaisharon/ds3_net_sdk,SpectraLogic/ds3_net_sdk,rpmoore/ds3_net_sdk,shabtaisharon/ds3_net_sdk,rpmoore/ds3_net_sdk,RachelTucker/ds3_net_sdk,rpmoore/ds3_net_sdk,RachelTucker/ds3_net_sdk,SpectraLogic/ds3_net_sdk,RachelTucker/ds3_net_sdk,SpectraLogic/ds3_net_sdk
Ds3/Helpers/Strategies/ReadRandomAccessHelperStrategy.cs
Ds3/Helpers/Strategies/ReadRandomAccessHelperStrategy.cs
/* * ****************************************************************************** * Copyright 2014 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ using Ds3.Helpers.Strategies.ChunkStrategies; using Ds3.Helpers.Strategies.StreamFactory; using System; namespace Ds3.Helpers.Strategies { /// <summary> /// The ReadRandomAccessHelperStrategy bundle ReadRandomAccessChunkStrategy with ReadRandomAccessStreamFactory /// </summary> /// <typeparam name="TItem"></typeparam> public class ReadRandomAccessHelperStrategy<TItem> : IHelperStrategy<TItem> where TItem : IComparable<TItem> { private readonly IChunkStrategy _readRandomAccessChunkStrategy; private readonly IStreamFactory<TItem> _readRandomAccessStreamFactory; public ReadRandomAccessHelperStrategy(int retryAfter = -1) { this._readRandomAccessChunkStrategy = new ReadRandomAccessChunkStrategy(retryAfter); this._readRandomAccessStreamFactory = new ReadRandomAccessStreamFactory<TItem>(); } public IChunkStrategy GetChunkStrategy() { return this._readRandomAccessChunkStrategy; } public IStreamFactory<TItem> GetStreamFactory() { return this._readRandomAccessStreamFactory; } } }
/* * ****************************************************************************** * Copyright 2014 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ using Ds3.Helpers.Strategies.ChunkStrategies; using Ds3.Helpers.Strategies.StreamFactory; using System; namespace Ds3.Helpers.Strategies { /// <summary> /// The ReadRandomAccessHelperStrategy bundle ReadRandomAccessChunkStrategy with ReadRandomAccessStreamFactory /// </summary> /// <typeparam name="TItem"></typeparam> public class ReadRandomAccessHelperStrategy<TItem> : IHelperStrategy<TItem> where TItem : IComparable<TItem> { private readonly IChunkStrategy _readRandomAccessChunkStrategy; private readonly IStreamFactory<TItem> _readRandomAccessStreamFactory; public ReadRandomAccessHelperStrategy(int retyrAfter = -1) { this._readRandomAccessChunkStrategy = new ReadRandomAccessChunkStrategy(retyrAfter); this._readRandomAccessStreamFactory = new ReadRandomAccessStreamFactory<TItem>(); } public IChunkStrategy GetChunkStrategy() { return this._readRandomAccessChunkStrategy; } public IStreamFactory<TItem> GetStreamFactory() { return this._readRandomAccessStreamFactory; } } }
apache-2.0
C#
fdef0a7f0d885223d2dfe1a9f6b8bfc81ffc8659
还原ILContext代码。
winddyhe/knight
Assets/Plugins/ILRuntime/ILRuntime/Runtime/Enviorment/ILContext.cs
Assets/Plugins/ILRuntime/ILRuntime/Runtime/Enviorment/ILContext.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.CLR.Method; namespace ILRuntime.Runtime.Enviorment { public unsafe struct ILContext { public AppDomain AppDomain { get; private set; } public StackObject* ESP { get; private set; } public List<object> ManagedStack { get; private set; } public IMethod Method { get; private set; } public ILIntepreter Interpreter { get; private set; } internal ILContext(AppDomain domain, ILIntepreter intpreter, StackObject* esp, List<object> mStack, IMethod method) { AppDomain = domain; ESP = esp; ManagedStack = mStack; Method = method; Interpreter = intpreter; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.CLR.Method; namespace ILRuntime.Runtime.Enviorment { public unsafe struct ILContext { public AppDomain AppDomain { get; private set; } public StackObject* ESP { get; private set; } public List<object> ManagedStack { get; private set; } public IMethod Method { get; private set; } public ILIntepreter Interpreter { get; private set; } //internal ILContext(AppDomain domain,ILIntepreter intpreter, StackObject* esp, List<object> mStack, IMethod method) //{ // AppDomain = domain; // ESP = esp; // ManagedStack = mStack; // Method = method; // Interpreter = intpreter; //} } }
mit
C#
573b3456bbc6e5e3c1c4bb414678ccd9a233aa02
Fix converting default colors
praeclarum/Ooui,praeclarum/Ooui,praeclarum/Ooui
Ooui.Forms/Extensions/ColorExtensions.cs
Ooui.Forms/Extensions/ColorExtensions.cs
using System; namespace Ooui.Forms.Extensions { public static class ColorExtensions { public static Color ToOouiColor (this Xamarin.Forms.Color color) { const byte defaultRed = 0; const byte defaultGreen = 0; const byte defaultBlue = 0; const byte defaultAlpha = 255; byte r = color.R < 0 ? defaultRed : (byte)(color.R * 255.0 + 0.5); byte g = color.G < 0 ? defaultGreen : (byte)(color.G * 255.0 + 0.5); byte b = color.B < 0 ? defaultBlue : (byte)(color.B * 255.0 + 0.5); byte a = color.A < 0 ? defaultAlpha : (byte)(color.A * 255.0 + 0.5); return new Color (r, g, b, a); } public static Color ToOouiColor (this Xamarin.Forms.Color color, Xamarin.Forms.Color defaultColor) { if (color == Xamarin.Forms.Color.Default) return defaultColor.ToOouiColor (); return color.ToOouiColor (); } } }
using System; namespace Ooui.Forms.Extensions { public static class ColorExtensions { public static Color ToOouiColor (this Xamarin.Forms.Color color) { return new Color ((byte)(color.R * 255.0 + 0.5), (byte)(color.G * 255.0 + 0.5), (byte)(color.B * 255.0 + 0.5), (byte)(color.A * 255.0 + 0.5)); } public static Color ToOouiColor (this Xamarin.Forms.Color color, Xamarin.Forms.Color defaultColor) { if (color == Xamarin.Forms.Color.Default) return defaultColor.ToOouiColor (); return color.ToOouiColor (); } } }
mit
C#
bac3108aea03fb72b9ccc146b6cfb7353cf8f63a
Remove unnecessary keywords
peppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu,ppy/osu
osu.Game/Overlays/Settings/Sections/Gameplay/HUDSettings.cs
osu.Game/Overlays/Settings/Sections/Gameplay/HUDSettings.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. #nullable disable using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Localisation; using osu.Game.Configuration; using osu.Game.Localisation; namespace osu.Game.Overlays.Settings.Sections.Gameplay { public class HUDSettings : SettingsSubsection { protected override LocalisableString Header => GameplaySettingsStrings.HUDHeader; [BackgroundDependencyLoader] private void load(OsuConfigManager config) { Children = new Drawable[] { new SettingsEnumDropdown<HUDVisibilityMode> { LabelText = GameplaySettingsStrings.HUDVisibilityMode, Current = config.GetBindable<HUDVisibilityMode>(OsuSetting.HUDVisibilityMode) }, new SettingsCheckbox { ClassicDefault = false, LabelText = GameplaySettingsStrings.ShowHealthDisplayWhenCantFail, Current = config.GetBindable<bool>(OsuSetting.ShowHealthDisplayWhenCantFail), Keywords = new[] { "hp", "bar" } }, new SettingsCheckbox { LabelText = GameplaySettingsStrings.AlwaysShowKeyOverlay, Current = config.GetBindable<bool>(OsuSetting.KeyOverlay), Keywords = new[] { "counter" }, }, new SettingsCheckbox { LabelText = GameplaySettingsStrings.AlwaysShowGameplayLeaderboard, Current = config.GetBindable<bool>(OsuSetting.GameplayLeaderboard), }, }; } } }
// 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. #nullable disable using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Localisation; using osu.Game.Configuration; using osu.Game.Localisation; namespace osu.Game.Overlays.Settings.Sections.Gameplay { public class HUDSettings : SettingsSubsection { protected override LocalisableString Header => GameplaySettingsStrings.HUDHeader; [BackgroundDependencyLoader] private void load(OsuConfigManager config) { Children = new Drawable[] { new SettingsEnumDropdown<HUDVisibilityMode> { LabelText = GameplaySettingsStrings.HUDVisibilityMode, Current = config.GetBindable<HUDVisibilityMode>(OsuSetting.HUDVisibilityMode) }, new SettingsCheckbox { ClassicDefault = false, LabelText = GameplaySettingsStrings.ShowHealthDisplayWhenCantFail, Current = config.GetBindable<bool>(OsuSetting.ShowHealthDisplayWhenCantFail), Keywords = new[] { "hp", "bar" } }, new SettingsCheckbox { LabelText = GameplaySettingsStrings.AlwaysShowKeyOverlay, Current = config.GetBindable<bool>(OsuSetting.KeyOverlay), Keywords = new[] { "counter" }, }, new SettingsCheckbox { LabelText = GameplaySettingsStrings.AlwaysShowGameplayLeaderboard, Current = config.GetBindable<bool>(OsuSetting.GameplayLeaderboard), Keywords = new[] { "leaderboard", "score" }, }, }; } } }
mit
C#
1437cfe1672993cc82767aca0f257592b7bd729d
Make SentryLogger thread safe (ContextData was being modified while it was being serialized)
Piotrekol/StreamCompanion,Piotrekol/StreamCompanion
osu!StreamCompanion/Code/Core/Loggers/SentryLogger.cs
osu!StreamCompanion/Code/Core/Loggers/SentryLogger.cs
using System; using System.Collections.Generic; using osu_StreamCompanion.Code.Helpers; using SharpRaven; using SharpRaven.Data; using StreamCompanionTypes.Enums; using StreamCompanionTypes.Interfaces.Services; namespace osu_StreamCompanion.Code.Core.Loggers { public class SentryLogger : IContextAwareLogger { public static string RavenDsn = "https://2a3c77450ec84295b6a6d426b2fdd9b5@sentry.io/107853"; public static RavenClient RavenClient { get; } = new RavenClient(RavenDsn); public static Dictionary<string, string> ContextData { get; } = new Dictionary<string, string>(); private object _lockingObject = new object(); public SentryLogger() { RavenClient.Release = Program.ScVersion; } public void Log(object logMessage, LogLevel loglvevel, params string[] vals) { if (loglvevel == LogLevel.Error) { SentryEvent sentryEvent; if (logMessage is Exception) { if (logMessage is NonLoggableException) return; sentryEvent = new SentryEvent((Exception)logMessage); } else sentryEvent = new SentryEvent(string.Format(logMessage.ToString(), vals)); lock (_lockingObject) { sentryEvent.Extra = ContextData; RavenClient.Capture(sentryEvent); } } } public void SetContextData(string key, string value) { lock (_lockingObject) ContextData[key] = value; } } }
using System; using System.Collections.Generic; using osu_StreamCompanion.Code.Helpers; using SharpRaven; using SharpRaven.Data; using StreamCompanionTypes.Enums; using StreamCompanionTypes.Interfaces.Services; namespace osu_StreamCompanion.Code.Core.Loggers { public class SentryLogger : IContextAwareLogger { public static string RavenDsn = "https://2a3c77450ec84295b6a6d426b2fdd9b5@sentry.io/107853"; public static RavenClient RavenClient { get; } = new RavenClient(RavenDsn); public static Dictionary<string,string> ContextData { get; } = new Dictionary<string, string>(); public SentryLogger() { RavenClient.Release = Program.ScVersion; } public void Log(object logMessage, LogLevel loglvevel, params string[] vals) { if (loglvevel == LogLevel.Error) { SentryEvent sentryEvent; if (logMessage is Exception) { if (logMessage is NonLoggableException) return; sentryEvent = new SentryEvent((Exception)logMessage); } else sentryEvent = new SentryEvent(string.Format(logMessage.ToString(), vals)); sentryEvent.Extra = ContextData; RavenClient.Capture(sentryEvent); } } public void SetContextData(string key, string value) { ContextData[key] = value; } } }
mit
C#
b06128ffa5f4845bd0c9ae6dabe11120336b5cf4
Rename "Final PP" to "Achieved PP"
peppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,ppy/osu
osu.Game/Rulesets/Difficulty/PerformanceAttributes.cs
osu.Game/Rulesets/Difficulty/PerformanceAttributes.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 Newtonsoft.Json; namespace osu.Game.Rulesets.Difficulty { public class PerformanceAttributes { /// <summary> /// Calculated score performance points. /// </summary> [JsonProperty("pp")] public double Total { get; set; } /// <summary> /// Return a <see cref="PerformanceDisplayAttribute"/> for each attribute so that a performance breakdown can be displayed. /// Some attributes may be omitted if they are not meant for display. /// </summary> /// <returns></returns> public virtual IEnumerable<PerformanceDisplayAttribute> GetAttributesForDisplay() { yield return new PerformanceDisplayAttribute(nameof(Total), "Achieved PP", Total); } } }
// 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 Newtonsoft.Json; namespace osu.Game.Rulesets.Difficulty { public class PerformanceAttributes { /// <summary> /// Calculated score performance points. /// </summary> [JsonProperty("pp")] public double Total { get; set; } /// <summary> /// Return a <see cref="PerformanceDisplayAttribute"/> for each attribute so that a performance breakdown can be displayed. /// Some attributes may be omitted if they are not meant for display. /// </summary> /// <returns></returns> public virtual IEnumerable<PerformanceDisplayAttribute> GetAttributesForDisplay() { yield return new PerformanceDisplayAttribute(nameof(Total), "Final PP", Total); } } }
mit
C#
f41fd69129ddced6c0f70f5ae844f035fb68a6ac
delete spaces
sunkaixuan/SqlSugar
Src/Asp.Net/SqlSugar/Enum/ProperyType.cs
Src/Asp.Net/SqlSugar/Enum/ProperyType.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SqlSugar { public enum CSharpDataType { @int, @bool, @string, @DateTime, @decimal, @double, @Guid, @byte, @enum, @short, @long, @object, @other, @byteArray, @float, @time, @DateTimeOffset, @Single, @TimeSpan } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SqlSugar { public enum CSharpDataType { @int, @bool, @string, @DateTime, @decimal, @double, @Guid, @byte, @enum, @short, @long, @object, @other, @byteArray, @float, @time, @DateTimeOffset, @Single, @TimeSpan } }
apache-2.0
C#
d985b8ab2aafd86c9f4d24fdcd39634de8a0b10c
Increase beatmapset download timeout
peppy/osu-new,smoogipoo/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,ppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,smoogipooo/osu,UselessToucan/osu,smoogipoo/osu
osu.Game/Online/API/Requests/DownloadBeatmapSetRequest.cs
osu.Game/Online/API/Requests/DownloadBeatmapSetRequest.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.IO.Network; using osu.Game.Beatmaps; namespace osu.Game.Online.API.Requests { public class DownloadBeatmapSetRequest : ArchiveDownloadRequest<BeatmapSetInfo> { private readonly bool noVideo; public DownloadBeatmapSetRequest(BeatmapSetInfo set, bool noVideo) : base(set) { this.noVideo = noVideo; } protected override WebRequest CreateWebRequest() { var req = base.CreateWebRequest(); req.Timeout = 60000; return req; } protected override string Target => $@"beatmapsets/{Model.OnlineBeatmapSetID}/download{(noVideo ? "?noVideo=1" : "")}"; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Beatmaps; namespace osu.Game.Online.API.Requests { public class DownloadBeatmapSetRequest : ArchiveDownloadRequest<BeatmapSetInfo> { private readonly bool noVideo; public DownloadBeatmapSetRequest(BeatmapSetInfo set, bool noVideo) : base(set) { this.noVideo = noVideo; } protected override string Target => $@"beatmapsets/{Model.OnlineBeatmapSetID}/download{(noVideo ? "?noVideo=1" : "")}"; } }
mit
C#
4f91e949b5b30ebab073c321dcf5088109b34e2c
Revert the addition of SQL code for deleting DuplicateCuratedPackages. This will move over to a SQL script in NuGetOperations.
KuduApps/NuGetGallery,grenade/NuGetGallery_download-count-patch,skbkontur/NuGetGallery,mtian/SiteExtensionGallery,projectkudu/SiteExtensionGallery,mtian/SiteExtensionGallery,KuduApps/NuGetGallery,JetBrains/ReSharperGallery,KuduApps/NuGetGallery,mtian/SiteExtensionGallery,JetBrains/ReSharperGallery,JetBrains/ReSharperGallery,KuduApps/NuGetGallery,ScottShingler/NuGetGallery,KuduApps/NuGetGallery,grenade/NuGetGallery_download-count-patch,skbkontur/NuGetGallery,projectkudu/SiteExtensionGallery,grenade/NuGetGallery_download-count-patch,ScottShingler/NuGetGallery,skbkontur/NuGetGallery,ScottShingler/NuGetGallery,projectkudu/SiteExtensionGallery
Website/Migrations/201304030226233_CuratedFeedPackageUniqueness.cs
Website/Migrations/201304030226233_CuratedFeedPackageUniqueness.cs
namespace NuGetGallery.Migrations { using System.Data.Entity.Migrations; public partial class CuratedFeedPackageUniqueness : DbMigration { public override void Up() { // ADD uniqueness constraint - as an Index, since it seems reasonable to look up curated package entries by their feed + registration CreateIndex("CuratedPackages", new[] { "CuratedFeedKey", "PackageRegistrationKey" }, unique: true, name: "IX_CuratedFeed_PackageRegistration"); } public override void Down() { // REMOVE uniqueness constraint DropIndex("CuratedPackages", "IX_CuratedPackage_CuratedFeedAndPackageRegistration"); } } }
namespace NuGetGallery.Migrations { using System.Data.Entity.Migrations; public partial class CuratedFeedPackageUniqueness : DbMigration { public override void Up() { // DELETE duplicate CuratedPackages from the database // Trying to prefer keeping duplicated entries that were manually added, or were added with notes Sql(@"WITH NumberedRows AS ( SELECT Row_number() OVER (PARTITION BY CuratedFeedKey, PackageRegistrationKey ORDER BY CuratedFeedKey, PackageRegistrationKey, AutomaticallyCurated, Notes DESC) RowId, * from CuratedPackages ) DELETE FROM NumberedRows WHERE RowId > 1"); // ADD uniqueness constraint - as an Index, since it seems like a reasonable way to look up curated packages CreateIndex("CuratedPackages", new[] { "CuratedFeedKey", "PackageRegistrationKey" }, unique: true, name: "IX_CuratedFeed_PackageRegistration"); } public override void Down() { // REMOVE uniqueness constraint DropIndex("CuratedPackages", "IX_CuratedPackage_CuratedFeedAndPackageRegistration"); } } }
apache-2.0
C#
2b9044ba1ab00f91a9d9d96268bba534f6f522a3
Handle code execution synchronously
appharbor/ConsolR,appharbor/ConsolR
Web/EndPoints/ExecuteEndPoint.cs
Web/EndPoints/ExecuteEndPoint.cs
using System; using System.Configuration; using System.Threading.Tasks; using System.Web.Mvc; using Compilify.Models; using Compilify.Web.Services; using Newtonsoft.Json; using SignalR; using SignalR.Hosting; using Compilify.Services; namespace Compilify.Web.EndPoints { public class ExecuteEndPoint : PersistentConnection { static ExecuteEndPoint() { int timeout; if (!int.TryParse(ConfigurationManager.AppSettings["Compilify.ExecutionTimeout"], out timeout)) { timeout = DefaultExecutionTimeout; } ExecutionTimeout = TimeSpan.FromSeconds(timeout); } private const int DefaultExecutionTimeout = 30; private static readonly TimeSpan ExecutionTimeout; private static readonly CSharpExecutor Executer = new CSharpExecutor(); /// <summary> /// Handle messages sent by the client.</summary> protected override Task OnReceivedAsync(IRequest request, string connectionId, string data) { var post = JsonConvert.DeserializeObject<Post>(data); var result = Executer.Execute(post); return Connection.Send(connectionId, new { status = "ok", data = result.Result }); } } }
using System; using System.Configuration; using System.Threading.Tasks; using System.Web.Mvc; using Compilify.Models; using Compilify.Web.Services; using Newtonsoft.Json; using SignalR; using SignalR.Hosting; namespace Compilify.Web.EndPoints { public class ExecuteEndPoint : PersistentConnection { static ExecuteEndPoint() { int timeout; if (!int.TryParse(ConfigurationManager.AppSettings["Compilify.ExecutionTimeout"], out timeout)) { timeout = DefaultExecutionTimeout; } ExecutionTimeout = TimeSpan.FromSeconds(timeout); } private const int DefaultExecutionTimeout = 30; private static readonly TimeSpan ExecutionTimeout; /// <summary> /// Handle messages sent by the client.</summary> protected override Task OnReceivedAsync(IRequest request, string connectionId, string data) { var post = JsonConvert.DeserializeObject<Post>(data); var command = new ExecuteCommand { ClientId = connectionId, Code = post.Content, Classes = post.Classes, Submitted = DateTime.UtcNow, TimeoutPeriod = ExecutionTimeout }; var message = command.GetBytes(); var gateway = DependencyResolver.Current.GetService<RedisConnectionGateway>(); var redis = gateway.GetConnection(); return redis.Lists.AddLast(0, "queue:execute", message) .ContinueWith(t => { if (t.IsFaulted) { return Connection.Send(connectionId, new { status = "error", message = t.Exception != null ? t.Exception.Message : null }); } return Connection.Send(connectionId, new { status = "ok" }); }); } } }
mit
C#
3ce66812c1b5b4156e955f916da9114daa55f50b
Revert "add comment"
toannvqo/dnn_publish
Components/ProductController.cs
Components/ProductController.cs
using DotNetNuke.Data; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Christoc.Modules.DNNModule1.Components { public class ProductController { public Product GetProduct(int productId) { Product p; using (IDataContext ctx = DataContext.Instance()) { Console.WriteLine("new branch"); Console.WriteLine("shshshshshs"); var rep = ctx.GetRepository<Product>(); p = rep.GetById(productId); } return p; } public IEnumerable<Product> getAll() { IEnumerable<Product> p; using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); p = rep.Get(); } return p; } public void CreateProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Insert(p); } } public void DeleteProduct(int productId) { var p = GetProduct(productId); DeleteProduct(p); } public void DeleteProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Delete(p); } } public void UpdateProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Update(p); } } } }
using DotNetNuke.Data; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Christoc.Modules.DNNModule1.Components { public class ProductController { public Product GetProduct(int productId) { Product p; using (IDataContext ctx = DataContext.Instance()) { Console.WriteLine("new branch"); Console.WriteLine("shshshshshs"); // fasdfasfd var rep = ctx.GetRepository<Product>(); p = rep.GetById(productId); } return p; } public IEnumerable<Product> getAll() { IEnumerable<Product> p; using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); p = rep.Get(); } return p; } public void CreateProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Insert(p); } } public void DeleteProduct(int productId) { var p = GetProduct(productId); DeleteProduct(p); } public void DeleteProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Delete(p); } } public void UpdateProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Update(p); } } } }
mit
C#
5ef0badaf1919f2f637c350865bb13b887840927
Fix casing inconsistency
cake-contrib/Cake.Recipe,cake-contrib/Cake.Recipe
Cake.Recipe/Content/addins.cake
Cake.Recipe/Content/addins.cake
/////////////////////////////////////////////////////////////////////////////// // ADDINS /////////////////////////////////////////////////////////////////////////////// #addin nuget:?package=Cake.Codecov&version=0.3.0 #addin nuget:?package=Cake.Coveralls&version=0.7.0 #addin nuget:?package=Cake.Figlet&version=1.0.0 #addin nuget:?package=Cake.Git&version=0.16.1 #addin nuget:?package=Cake.Gitter&version=0.7.0 #addin nuget:?package=Cake.Graph&version=0.4.0 #addin nuget:?package=Cake.Incubator&version=1.7.2 #addin nuget:?package=Cake.Kudu&version=0.6.0 #addin nuget:?package=Cake.MicrosoftTeams&version=0.6.0 #addin nuget:?package=Cake.ReSharperReports&version=0.8.0 #addin nuget:?package=Cake.Slack&version=0.10.0 #addin nuget:?package=Cake.Transifex&version=0.4.0 #addin nuget:?package=Cake.Twitter&version=0.6.0 #addin nuget:?package=Cake.Wyam&version=1.2.0 Action<string, IDictionary<string, string>> RequireAddin = (code, envVars) => { var script = MakeAbsolute(File(string.Format("./{0}.cake", Guid.NewGuid()))); try { System.IO.File.WriteAllText(script.FullPath, code); var arguments = new Dictionary<string, string>(); if(BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient") != null) { arguments.Add("nuget_useinprocessclient", BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient")); } if(BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification") != null) { arguments.Add("settings_skipverification", BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification")); } CakeExecuteScript(script, new CakeSettings { EnvironmentVariables = envVars, Arguments = arguments }); } finally { if (FileExists(script)) { DeleteFile(script); } } };
/////////////////////////////////////////////////////////////////////////////// // ADDINS /////////////////////////////////////////////////////////////////////////////// #addin nuget:?package=Cake.Codecov&version=0.3.0 #addin nuget:?package=Cake.Coveralls&version=0.7.0 #addin nuget:?package=Cake.Figlet&version=1.0.0 #addin nuget:?package=Cake.Git&version=0.16.1 #addin nuget:?package=Cake.Gitter&version=0.7.0 #addin nuget:?package=Cake.Graph&version=0.4.0 #addin nuget:?package=Cake.Incubator&version=1.7.2 #addin nuget:?package=Cake.Kudu&version=0.6.0 #addin nuget:?package=Cake.MicrosoftTeams&version=0.6.0 #addin nuget:?package=Cake.ReSharperReports&version=0.8.0 #addin nuget:?package=Cake.Slack&version=0.10.0 #addin nuget:?package=Cake.Transifex&Version=0.4.0 #addin nuget:?package=Cake.Twitter&version=0.6.0 #addin nuget:?package=Cake.Wyam&version=1.2.0 Action<string, IDictionary<string, string>> RequireAddin = (code, envVars) => { var script = MakeAbsolute(File(string.Format("./{0}.cake", Guid.NewGuid()))); try { System.IO.File.WriteAllText(script.FullPath, code); var arguments = new Dictionary<string, string>(); if(BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient") != null) { arguments.Add("nuget_useinprocessclient", BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient")); } if(BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification") != null) { arguments.Add("settings_skipverification", BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification")); } CakeExecuteScript(script, new CakeSettings { EnvironmentVariables = envVars, Arguments = arguments }); } finally { if (FileExists(script)) { DeleteFile(script); } } };
mit
C#
ffe33fa804e0cf09deece6081c321915f3d77198
use string interpolation
isse-augsburg/ssharp,isse-augsburg/ssharp,maul-esel/ssharp,maul-esel/ssharp,isse-augsburg/ssharp,isse-augsburg/ssharp,maul-esel/ssharp,maul-esel/ssharp,isse-augsburg/ssharp
models/SelfOrganizingPillProduction/ParticulateDispenser.cs
models/SelfOrganizingPillProduction/ParticulateDispenser.cs
using System; using System.Collections.Generic; using System.Linq; namespace SelfOrganizingPillProduction { /// <summary> /// A production station that adds ingredients to the containers. /// </summary> class ParticulateDispenser : Station { private readonly Dictionary<IngredientType, uint> availableIngredients = new Dictionary<IngredientType, uint>(); public override Capability[] AvailableCapabilities { get { return availableIngredients.Select(kv => new Ingredient(type: kv.Key, amount: kv.Value)).ToArray(); } } protected override void ExecuteRole(Role role) { foreach (var capability in role.CapabilitiesToApply) { var ingredient = capability as Ingredient; if (ingredient == null) throw new InvalidOperationException($"Invalid capability in ParticulateDispenser: {capability}"); if (!availableIngredients.ContainsKey(ingredient.Type) || availableIngredients[ingredient.Type] < ingredient.Amount) throw new InvalidOperationException($"Insufficient amount available of ingredient {ingredient.Type}"); availableIngredients[ingredient.Type] -= ingredient.Amount; Container.AddIngredient(ingredient); } } } }
using System; using System.Collections.Generic; using System.Linq; namespace SelfOrganizingPillProduction { /// <summary> /// A production station that adds ingredients to the containers. /// </summary> class ParticulateDispenser : Station { private readonly Dictionary<IngredientType, uint> availableIngredients = new Dictionary<IngredientType, uint>(); public override Capability[] AvailableCapabilities { get { return availableIngredients.Select(kv => new Ingredient(type: kv.Key, amount: kv.Value)).ToArray(); } } protected override void ExecuteRole(Role role) { foreach (var capability in role.CapabilitiesToApply) { var ingredient = capability as Ingredient; if (ingredient == null) throw new InvalidOperationException("Invalid capability in ParticulateDispenser: " + capability); if (!availableIngredients.ContainsKey(ingredient.Type) || availableIngredients[ingredient.Type] < ingredient.Amount) throw new InvalidOperationException("Insufficient amount available of ingredient " + ingredient.Type); availableIngredients[ingredient.Type] -= ingredient.Amount; Container.AddIngredient(ingredient); } } } }
mit
C#
c089240eb6f766111ed66ce6d6d101dce3bd41ff
Convert members to properties
justincolangelo/EdgeInstallerTest,justincolangelo/EdgeInstallerTest,codevlabs/DirigoEdge,justincolangelo/EdgeInstallerTest,justincolangelo/EdgeInstallerTest,codevlabs/DirigoEdge,codevlabs/DirigoEdge,justincolangelo/EdgeInstallerTest,codevlabs/DirigoEdge,codevlabs/DirigoEdge
DirigoEdge/Areas/Admin/Models/ViewModels/EditModuleViewModel.cs
DirigoEdge/Areas/Admin/Models/ViewModels/EditModuleViewModel.cs
using System; using System.Collections.Generic; using System.Linq; using DirigoEdgeCore.Data.Entities; using DirigoEdgeCore.Models.ViewModels; namespace DirigoEdge.Areas.Admin.Models.ViewModels { public class EditModuleViewModel : DraftableModel { public ContentModule TheModule { get; set; } public List<Schema> Schemas { get; set; } public List<RevisionViewModel> Revisions { get; set; } public override int? ParentId() { return TheModule.ParentContentModuleId; } public EditModuleViewModel(int id) { Heading = "Edit Module"; EditURL = "editmodule"; TheModule = Context.ContentModules.FirstOrDefault(x => x.ContentModuleId == id); if (TheModule == null) { return; } BookmarkTitle = TheModule.ModuleName; // Set Unparsed Html on Legacy Modules if (String.IsNullOrEmpty(TheModule.HTMLUnparsed) && !String.IsNullOrEmpty(TheModule.HTMLContent)) { TheModule.HTMLUnparsed = TheModule.HTMLContent; } var newerVersion = Context.ContentModules.Where(x => (x.ParentContentModuleId == id || x.ContentModuleId == id) && x.CreateDate > TheModule.CreateDate && x.ContentModuleId != TheModule.ContentModuleId).OrderByDescending(x => x.CreateDate).FirstOrDefault(); if (newerVersion != null) { NewerVersionId = newerVersion.ContentModuleId; } var parentId = TheModule.ParentContentModuleId ?? TheModule.ContentModuleId; Revisions = Context.ContentModules.Where(x => x.ParentContentModuleId == parentId || x.ContentModuleId == parentId).OrderByDescending(x => x.CreateDate).ToList().Select(rev => new RevisionViewModel { Date = rev.CreateDate, ContentId = rev.ContentModuleId, AuthorName = rev.DraftAuthorName, WasPublished = rev.WasPublished }).ToList(); Schemas = Context.Schemas.ToList(); } } }
using System; using System.Collections.Generic; using System.Linq; using DirigoEdgeCore.Data.Entities; using DirigoEdgeCore.Models.ViewModels; namespace DirigoEdge.Areas.Admin.Models.ViewModels { public class EditModuleViewModel : DraftableModel { public ContentModule TheModule; public List<Schema> Schemas; public List<RevisionViewModel> Revisions; public override int? ParentId() { return TheModule.ParentContentModuleId; } public EditModuleViewModel(int id) { Heading = "Edit Module"; EditURL = "editmodule"; TheModule = Context.ContentModules.FirstOrDefault(x => x.ContentModuleId == id); if (TheModule == null) { return; } BookmarkTitle = TheModule.ModuleName; // Set Unparsed Html on Legacy Modules if (String.IsNullOrEmpty(TheModule.HTMLUnparsed) && !String.IsNullOrEmpty(TheModule.HTMLContent)) { TheModule.HTMLUnparsed = TheModule.HTMLContent; } var newerVersion = Context.ContentModules.Where(x => (x.ParentContentModuleId == id || x.ContentModuleId == id) && x.CreateDate > TheModule.CreateDate && x.ContentModuleId != TheModule.ContentModuleId).OrderByDescending(x => x.CreateDate).FirstOrDefault(); if (newerVersion != null) { NewerVersionId = newerVersion.ContentModuleId; } var parentId = TheModule.ParentContentModuleId ?? TheModule.ContentModuleId; Revisions = Context.ContentModules.Where(x => x.ParentContentModuleId == parentId || x.ContentModuleId == parentId).OrderByDescending(x => x.CreateDate).ToList().Select(rev => new RevisionViewModel { Date = rev.CreateDate, ContentId = rev.ContentModuleId, AuthorName = rev.DraftAuthorName, WasPublished = rev.WasPublished }).ToList(); Schemas = Context.Schemas.ToList(); } } }
mit
C#
f1449a9ecd3808577ba1b869303548d49fc68cb1
Replace String with string.
Zakkgard/Moonfire
Moonfire/Core/Moonfire.CoreTests/Collections/ObjectPoolTests.cs
Moonfire/Core/Moonfire.CoreTests/Collections/ObjectPoolTests.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moonfire.Core.Collections; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Moonfire.Core.Collections.Tests { [TestClass()] public class ObjectPoolTests { private ObjectPool<string> sut; [TestInitialize] public void Setup() { sut = new ObjectPool<string>(() => ""); } [TestMethod] public void ShouldReturnEmptyStringIfNothingWasIn() { string result = sut.GetObject(); Assert.AreEqual("", result); } [TestMethod] public void ShouldReturnEmptyStringWhenAskedTwice() { Assert.AreEqual("", sut.GetObject()); Assert.AreEqual("", sut.GetObject()); } [TestMethod] public void ShouldReturnObjectThatWasAlreadyPutInThePull() { sut.PutObject("1"); Assert.AreEqual("1", sut.GetObject()); } [TestMethod] public void ShouldReturnObjectsInReveresedOrderOfTheOneTheyWarePutIn() { sut.PutObject("1"); sut.PutObject("2"); Assert.AreEqual("2", sut.GetObject()); Assert.AreEqual("1", sut.GetObject()); } [TestMethod] public void ShouldReturnEmptyStringIfAllOjbectedThatInThePullArePulledOut() { sut.PutObject("1"); sut.PutObject("2"); sut.GetObject(); sut.GetObject(); Assert.AreEqual("", sut.GetObject()); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moonfire.Core.Collections; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Moonfire.Core.Collections.Tests { [TestClass()] public class ObjectPoolTests { private ObjectPool<String> sut; [TestInitialize] public void Setup() { sut = new ObjectPool<String>(() => ""); } [TestMethod] public void ShouldReturnEmptyStringIfNothingWasIn() { String result = sut.GetObject(); Assert.AreEqual("", result); } [TestMethod] public void ShouldReturnEmptyStringWhenAskedTwice() { Assert.AreEqual("", sut.GetObject()); Assert.AreEqual("", sut.GetObject()); } [TestMethod] public void ShouldReturnObjectThatWasAlreadyPutInThePull() { sut.PutObject("1"); Assert.AreEqual("1", sut.GetObject()); } [TestMethod] public void ShouldReturnObjectsInReveresedOrderOfTheOneTheyWarePutIn() { sut.PutObject("1"); sut.PutObject("2"); Assert.AreEqual("2", sut.GetObject()); Assert.AreEqual("1", sut.GetObject()); } [TestMethod] public void ShouldReturnEmptyStringIfAllOjbectedThatInThePullArePulledOut() { sut.PutObject("1"); sut.PutObject("2"); sut.GetObject(); sut.GetObject(); Assert.AreEqual("", sut.GetObject()); } } }
mit
C#
f84b0f665254090035ced9fbf98599d2cfe7c895
Add support for nullable sources
plainerman/TicTacTube
TicTacTubeCore/Pipelines/DataPipeline.cs
TicTacTubeCore/Pipelines/DataPipeline.cs
using System; using System.Collections.Generic; using System.Linq; using log4net; using TicTacTubeCore.Processors.Definitions; using TicTacTubeCore.Sources.Files; namespace TicTacTubeCore.Pipelines { /// <inheritdoc /> /// <summary> /// A pipeline that stores multiple processors that process / modify / ... some sort of data. /// </summary> public class DataPipeline : IDataPipeline { private static readonly ILog Log = LogManager.GetLogger(typeof(DataPipeline)); /// <summary> /// The collection of data processor that are the actual pipeline processors. /// </summary> protected readonly ICollection<IDataProcessor> DataProcessors; /// <summary> /// Create a <see cref="DataPipeline" /> with a given collection of dataProcessors. /// </summary> /// <param name="dataProcessors"> /// The collection of data processors that are the actual pipeline processors. May not be /// <c>null</c>. /// </param> public DataPipeline(ICollection<IDataProcessor> dataProcessors) { DataProcessors = dataProcessors ?? throw new ArgumentNullException(nameof(dataProcessors)); } /// <summary> /// Create a <see cref="DataPipeline" /> with a given collection of dataProcessorsOrBuilders. /// </summary> /// <param name="dataProcessorsOrBuilder"> /// The collection of data processors (or builders) that are the actual pipeline /// processors. May not be <c>null</c>. /// </param> public DataPipeline(IEnumerable<IDataProcessorOrBuilder> dataProcessorsOrBuilder) { DataProcessors = dataProcessorsOrBuilder?.Select(d => d.Build()).ToList() ?? throw new ArgumentNullException(nameof(dataProcessorsOrBuilder)); } /// <inheritdoc /> public void Execute(IFileSource fileSource) { Log.Info($"Executing pipeline with fileSource {fileSource.GetType().Name}"); IFileSource prev = null; DataProcessors.Aggregate(fileSource, (current, processor) => { if (current != prev) { current?.Init(); prev = current; } current?.BeginExecute(); var newSource = processor.Execute(current); current?.EndExecute(); return newSource; }); } /// <summary> /// Check whether the object is a builder or not. (Hint: it is never a builder). /// </summary> public bool IsBuilder => false; /// <inheritdoc /> public IDataPipeline Build() => this; } }
using System; using System.Collections.Generic; using System.Linq; using log4net; using TicTacTubeCore.Processors.Definitions; using TicTacTubeCore.Sources.Files; namespace TicTacTubeCore.Pipelines { /// <inheritdoc /> /// <summary> /// A pipeline that stores multiple processors that process / modify / ... some sort of data. /// </summary> public class DataPipeline : IDataPipeline { private static readonly ILog Log = LogManager.GetLogger(typeof(DataPipeline)); /// <summary> /// The collection of data processor that are the actual pipeline processors. /// </summary> protected readonly ICollection<IDataProcessor> DataProcessors; /// <summary> /// Create a <see cref="DataPipeline" /> with a given collection of dataProcessors. /// </summary> /// <param name="dataProcessors"> /// The collection of data processors that are the actual pipeline processors. May not be /// <c>null</c>. /// </param> public DataPipeline(ICollection<IDataProcessor> dataProcessors) { DataProcessors = dataProcessors ?? throw new ArgumentNullException(nameof(dataProcessors)); } /// <summary> /// Create a <see cref="DataPipeline" /> with a given collection of dataProcessorsOrBuilders. /// </summary> /// <param name="dataProcessorsOrBuilder"> /// The collection of data processors (or builders) that are the actual pipeline /// processors. May not be <c>null</c>. /// </param> public DataPipeline(IEnumerable<IDataProcessorOrBuilder> dataProcessorsOrBuilder) { DataProcessors = dataProcessorsOrBuilder?.Select(d => d.Build()).ToList() ?? throw new ArgumentNullException(nameof(dataProcessorsOrBuilder)); } /// <inheritdoc /> public void Execute(IFileSource fileSource) { Log.Info($"Executing pipeline with fileSource {fileSource.GetType().Name}"); IFileSource prev = null; DataProcessors.Aggregate(fileSource, (current, processor) => { if (current != prev) { current.Init(); prev = current; } current.BeginExecute(); var newSource = processor.Execute(current); current.EndExecute(); return newSource; }); } /// <summary> /// Check whether the object is a builder or not. (Hint: it is never a builder). /// </summary> public bool IsBuilder => false; /// <inheritdoc /> public IDataPipeline Build() => this; } }
mit
C#
630b4f1bb5d9ed15399869a046493164f34c8726
fix table html
codingoutloud/matechtax,codingoutloud/matechtax
MATechTaxWebSite/MATechTaxWebSite/Views/Home/Index.cshtml
MATechTaxWebSite/MATechTaxWebSite/Views/Home/Index.cshtml
@{ @model IEnumerable<MATechTaxWebSite.Models.BlobSnapshot> ViewBag.Title = "Interested in the MA Tech Tax on Software Services?"; ViewBag.FaqUrl = System.Configuration.ConfigurationManager.AppSettings["DorFaqUrl"]; } @section featured { <section class="featured"> <div class="content-wrapper"> <hgroup class="title"> <h1>@ViewBag.Title.</h1> <h2>@ViewBag.Message</h2> </hgroup> <p> </p> </div> </section> } <h2>DOR FAQ</h2> <a href="@ViewBag.FaqUrl">LATEST Sofware Service Sales Tax FAQ</a> <h3>DOR FAQ HISTORY (Partial)</h3> <table border="1"> <tr> <th>Thumbprint</th><th>URL</th><th>Last Update (Approx)</th><th>Date Captured</th><th>Comment</th> </tr> @foreach (var snap in Model) { <tr> <td>@snap.Thumbprint</td><td><a href="@snap.Url">@snap.Url</a></td><td>@snap.LastModified</td><td>@snap.WhenCaptured</td><td><small>@snap.Comment</small></td> </tr> } </table> <section class="contact"> <header> <h3>Email</h3> </header> <p> <span><a href="mailto:matechtax@gmail.com">matechtax@gmail.com</a></span> </p> </section>
@{ @model IEnumerable<MATechTaxWebSite.Models.BlobSnapshot> ViewBag.Title = "Interested in the MA Tech Tax on Software Services?"; ViewBag.FaqUrl = System.Configuration.ConfigurationManager.AppSettings["DorFaqUrl"]; } @section featured { <section class="featured"> <div class="content-wrapper"> <hgroup class="title"> <h1>@ViewBag.Title.</h1> <h2>@ViewBag.Message</h2> </hgroup> <p> </p> </div> </section> } <h2>DOR FAQ</h2> <a href="@ViewBag.FaqUrl">LATEST Sofware Service Sales Tax FAQ</a> <h3>DOR FAQ HISTORY (Partial)</h3> <ol class="round"> @foreach (var snap in Model) { <table> <tr> <th>Thumbprint</th><th>URL</th><th>Last Update (Approx)</th><th>Date Captured</th><th>Comment</th> </tr> <tr> <td>@snap.Thumbprint</td><td><a href="@snap.Url">@snap.Url</a></td><td>@snap.LastModified</td><td>@snap.WhenCaptured</td><td><small>@snap.Comment</small></td> </tr> </table> } </ol> <section class="contact"> <header> <h3>Email</h3> </header> <p> <span><a href="mailto:matechtax@gmail.com">matechtax@gmail.com</a></span> </p> </section>
mit
C#
79d9fbb998f4bdb48e6ef13cee5a9e50fa754704
Add comments to the notification interface
mattgwagner/CertiPay.Common
CertiPay.Common.Notifications/Notifications/Notification.cs
CertiPay.Common.Notifications/Notifications/Notification.cs
using System; using System.Collections.Generic; namespace CertiPay.Common.Notifications { /// <summary> /// Describes the base notification content required to send /// </summary> public class Notification { /// <summary> /// The content of the message /// </summary> public virtual String Content { get; set; } = String.Empty; /// <summary> /// A list of recipients for the notification, whether emails, phone numbers, or device identifiers /// </summary> public virtual ICollection<String> Recipients { get; set; } = new List<String>(); } }
using System; using System.Collections.Generic; namespace CertiPay.Common.Notifications { public class Notification { public String Content { get; set; } public ICollection<String> Recipients { get; set; } public Notification() { this.Recipients = new List<String>(); } } }
mit
C#
d64f07b00c0694fba9293e9b7948b792dd06eef9
Remove unused positional constructor arg
PietroProperties/holms.platformclient.net
csharp/HOLMS.Platform/HOLMS.Platform/Types/Extensions/Booking/CancellationPolicy.cs
csharp/HOLMS.Platform/HOLMS.Platform/Types/Extensions/Booking/CancellationPolicy.cs
using HOLMS.Types.Booking.Indicators; using HOLMS.Types.Extensions; using HOLMS.Types.Primitive; namespace HOLMS.Types.Booking { public partial class CancellationPolicy : EntityDTO<CancellationPolicyIndicator> { public CancellationPolicy(CancellationPolicyIndicator id, string description, int noPenaltyDays, CancellationFeeCategory c, decimal cancellationFeeAmount, decimal cancellationFeeRate, string policyText) { EntityId = id; Description = description; NoPenaltyDays = noPenaltyDays; FeeCategory = c; CancellationFeeAmount = new MonetaryAmount(cancellationFeeAmount); CancellationFeeRate = new FixedPointRatio(cancellationFeeRate); CancellationPolicyText = policyText; } public override CancellationPolicyIndicator GetIndicator() { return EntityId; } } }
using HOLMS.Types.Booking.Indicators; using HOLMS.Types.Extensions; using HOLMS.Types.Primitive; namespace HOLMS.Types.Booking { public partial class CancellationPolicy : EntityDTO<CancellationPolicyIndicator> { public CancellationPolicy(CancellationPolicyIndicator id, string description, int noPenaltyDays, int forfeitDepositDays, CancellationFeeCategory c, decimal cancellationFeeAmount, decimal cancellationFeeRate, string policyText) { EntityId = id; Description = description; NoPenaltyDays = noPenaltyDays; FeeCategory = c; CancellationFeeAmount = new MonetaryAmount(cancellationFeeAmount); CancellationFeeRate = new FixedPointRatio(cancellationFeeRate); CancellationPolicyText = policyText; } public override CancellationPolicyIndicator GetIndicator() { return EntityId; } } }
mit
C#
b966c386f091c7bf27815284f68376a56a2d8592
Fix method name
RichardHowells/Dnn.Platform,dnnsoftware/Dnn.AdminExperience.Library,mitchelsellers/Dnn.Platform,valadas/Dnn.Platform,dnnsoftware/Dnn.Platform,dnnsoftware/Dnn.Platform,valadas/Dnn.Platform,mitchelsellers/Dnn.Platform,mitchelsellers/Dnn.Platform,EPTamminga/Dnn.Platform,valadas/Dnn.Platform,RichardHowells/Dnn.Platform,RichardHowells/Dnn.Platform,mitchelsellers/Dnn.Platform,bdukes/Dnn.Platform,robsiera/Dnn.Platform,mitchelsellers/Dnn.Platform,dnnsoftware/Dnn.Platform,bdukes/Dnn.Platform,dnnsoftware/Dnn.Platform,EPTamminga/Dnn.Platform,nvisionative/Dnn.Platform,dnnsoftware/Dnn.AdminExperience.Library,robsiera/Dnn.Platform,bdukes/Dnn.Platform,valadas/Dnn.Platform,dnnsoftware/Dnn.Platform,valadas/Dnn.Platform,nvisionative/Dnn.Platform,RichardHowells/Dnn.Platform,EPTamminga/Dnn.Platform,bdukes/Dnn.Platform,nvisionative/Dnn.Platform,dnnsoftware/Dnn.AdminExperience.Library,robsiera/Dnn.Platform
src/Dnn.PersonaBar.Library/Prompt/Common/ControllerBase.cs
src/Dnn.PersonaBar.Library/Prompt/Common/ControllerBase.cs
using System.IO; using System.Net; using System.Net.Http; using Dnn.PersonaBar.Library.Prompt.Models; using Localization = DotNetNuke.Services.Localization.Localization; namespace Dnn.PersonaBar.Library.Prompt.Common { public abstract class ControllerBase : PersonaBarApiController { private static string LocalResourcesFile => Path.Combine("~/DesktopModules/admin/Dnn.PersonaBar/App_LocalResources/SharedResources.resx"); protected HttpResponseMessage OkResponse(string msg, object data = null) { return Request.CreateResponse(HttpStatusCode.OK, new ResponseModel(false, msg, data?.ToString() ?? "")); } protected HttpResponseMessage UnauthorizedResponse(string msg = "", object data = null) { if (string.IsNullOrEmpty(msg)) { msg = Localization.GetString("Prompt_NotAuthorized", LocalResourcesFile, true); } else { msg += " " + Localization.GetString("Prompt_SessionTimedOut", LocalResourcesFile, true); } return Request.CreateResponse(HttpStatusCode.Unauthorized, new ResponseModel(true, msg, data?.ToString() ?? "")); } protected HttpResponseMessage BadRequestResponse(string msg = "", object data = null) { if (string.IsNullOrEmpty(msg)) { msg = Localization.GetString("Prompt_InvalidData", LocalResourcesFile, true); } return Request.CreateResponse(HttpStatusCode.BadRequest, new ResponseModel(true, msg, data?.ToString() ?? "")); } protected HttpResponseMessage ServerErrorResponse(string msg = "", object data = null) { if (string.IsNullOrEmpty(msg)) { msg = Localization.GetString("Prompt_ServerError", LocalResourcesFile, true); } return Request.CreateResponse(HttpStatusCode.InternalServerError, new ResponseModel(true, msg, data?.ToString() ?? "")); } protected HttpResponseMessage NotImplementedResponse(string msg = "", object data = null) { if (string.IsNullOrEmpty(msg)) { msg = Localization.GetString("Prompt_NotImplemented", LocalResourcesFile, true); } return Request.CreateResponse(HttpStatusCode.NotImplemented, new ResponseModel(true, msg, data?.ToString() ?? "")); } } }
using System.IO; using System.Net; using System.Net.Http; using Dnn.PersonaBar.Library.Prompt.Models; using Localization = DotNetNuke.Services.Localization.Localization; namespace Dnn.PersonaBar.Library.Prompt.Common { public abstract class ControllerBase : PersonaBarApiController { private static string LocalResourcesFile => Path.Combine("~/DesktopModules/admin/Dnn.PersonaBar/App_LocalResources/SharedResources.resx"); protected HttpResponseMessage OkResponse(string msg, object data = null) { return Request.CreateResponse(HttpStatusCode.OK, new ResponseModel(false, msg, data?.ToString() ?? "")); } protected HttpResponseMessage UnauthorizedResponse(string msg = "", object data = null) { if (string.IsNullOrEmpty(msg)) { msg = Localization.GetString("Prompt_NotAuthorized", LocalResourcesFile, true); } else { msg += " " + Localization.GetString("Prompt_SessionTimedOut", LocalResourcesFile, true); } return Request.CreateResponse(HttpStatusCode.Unauthorized, new ResponseModel(true, msg, data?.ToString() ?? "")); } protected HttpResponseMessage BadRequestResponse(string msg = "", object data = null) { if (string.IsNullOrEmpty(msg)) { msg = Localization.GetString("Prompt_InvalidData", LocalResourcesFile, true); } return Request.CreateResponse(HttpStatusCode.BadRequest, new ResponseModel(true, msg, data?.ToString() ?? "")); } protected HttpResponseMessage ServerErrorResponse(string msg = "", object data = null) { if (string.IsNullOrEmpty(msg)) { msg = Localization.GetString("Prompt_ServerError", LocalResourcesFile, true); } return Request.CreateResponse(HttpStatusCode.InternalServerError, new ResponseModel(true, msg, data?.ToString() ?? "")); } protected HttpResponseMessage NotImplementedrResponse(string msg = "", object data = null) { if (string.IsNullOrEmpty(msg)) { msg = Localization.GetString("Prompt_NotImplemented", LocalResourcesFile, true); } return Request.CreateResponse(HttpStatusCode.NotImplemented, new ResponseModel(true, msg, data?.ToString() ?? "")); } } }
mit
C#
6a69283358dd0a9a0e18d53b971480551a278bdd
Fix MessageHistoryResource after merge conflict
mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype
src/Glimpse.Server.Web/Resources/MessageHistoryResource.cs
src/Glimpse.Server.Web/Resources/MessageHistoryResource.cs
using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNet.Http; using Microsoft.Net.Http.Headers; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Glimpse.Server.Web { public class MessageHistoryResource : IResource { private readonly InMemoryStorage _store; private readonly JsonSerializer _jsonSerializer; public MessageHistoryResource(IStorage storage, JsonSerializer jsonSerializer) { // TODO: This hack is needed to get around signalr problem jsonSerializer.ContractResolver = new CamelCasePropertyNamesContractResolver(); // TODO: Really shouldn't be here _store = (InMemoryStorage)storage; _jsonSerializer = jsonSerializer; } public async Task Invoke(HttpContext context, IDictionary<string, string> parameters) { var response = context.Response; response.Headers[HeaderNames.ContentType] = "application/json"; var list = _store.Query(null); var output = _jsonSerializer.Serialize(list); await response.WriteAsync(output); } public string Name => "MessageHistory"; public ResourceParameters Parameters => null; } }
using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNet.Http; using Microsoft.Net.Http.Headers; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Glimpse.Server.Web { public class MessageHistoryResource : IResource { private readonly InMemoryStorage _store; private readonly JsonSerializer _jsonSerializer; public MessageHistoryResource(IStorage storage, JsonSerializer jsonSerializer) { // TODO: This hack is needed to get around signalr problem jsonSerializer.ContractResolver = new CamelCasePropertyNamesContractResolver(); // TODO: Really shouldn't be here _store = (InMemoryStorage)storage; _jsonSerializer = jsonSerializer; } public async Task Invoke(HttpContext context, IDictionary<string, string> parameters) { var response = context.Response; response.Headers[HeaderNames.ContentType] = "application/json"; var list = _store.AllMessages; var output = _jsonSerializer.Serialize(list); await response.WriteAsync(output); } public string Name => "MessageHistory"; public ResourceParameters Parameters => null; } }
mit
C#
c8eaf8130f6136140531c0e9168bc75a51c931db
Remove redundant
nikeee/HolzShots
src/HolzShots.Core.Tests/FileStringContentDataAttribute.cs
src/HolzShots.Core.Tests/FileStringContentDataAttribute.cs
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Xunit.Sdk; namespace HolzShots { [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)] public sealed class FileStringContentDataAttribute : DataAttribute { public string FileName { get; } public FileStringContentDataAttribute(string fileName) => FileName = fileName; public override IEnumerable<object[]> GetData(MethodInfo testMethod) { if (testMethod == null) throw new ArgumentNullException(nameof(testMethod)); yield return new [] { File.ReadAllText(GetFullFilename(FileName)) }; } private static string GetFullFilename(string filename) { var executable = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath; return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(executable), filename)); } } }
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Xunit.Sdk; namespace HolzShots.Core.Tests { [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)] public sealed class FileStringContentDataAttribute : DataAttribute { public string FileName { get; } public FileStringContentDataAttribute(string fileName) => FileName = fileName; public override IEnumerable<object[]> GetData(MethodInfo testMethod) { if (testMethod == null) throw new ArgumentNullException(nameof(testMethod)); yield return new Object[] { File.ReadAllText(GetFullFilename(FileName)) }; } private static string GetFullFilename(string filename) { var executable = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath; return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(executable), filename)); } } }
agpl-3.0
C#
854b4592be76a765fa32b68e5e67032d1389826b
update wording
ForNeVeR/fornever.me,ForNeVeR/fornever.me,ForNeVeR/fornever.me
ForneverMind/views/Index.cshtml
ForneverMind/views/Index.cshtml
@using RazorEngine.Templating @inherits TemplateBase<ForneverMind.Models.PostArchiveModel> @{ Layout = "_Layout.cshtml"; ViewBag.Title = "int 20h"; } <p>Привет!</p> <p> Меня зовут <a class="secret-link" href="http://scpfoundation.ru/scp-579"> [ДАННЫЕ УДАЛЕНЫ] </a>, в интернете я известен под псевдонимом “Фридрих фон Нёвер”. </p> <p> В основном здесь, на сайте, публикуются различные технические заметки, так или иначе связанные с моей основной деятельностью — программированием. </p> <h2>Последние посты</h2> <ul> @foreach (var post in Model.Posts) { <li> <a href=".@post.Url">@post.Title</a> — @post.Date.ToString("yyyy.MM.dd") </li> } </ul> <p>Список всех постов можно найти в разделе <a href="./archive.html">Архив</a>.</p>
@using RazorEngine.Templating @inherits TemplateBase<ForneverMind.Models.PostArchiveModel> @{ Layout = "_Layout.cshtml"; ViewBag.Title = "int 20h"; } <p>Привет!</p> <p>Меня зовут <a class="secret-link" href="http://scpfoundation.ru/scp-579">[ДАННЫЕ УДАЛЕНЫ]</a>, в интернете я известен под псевдонимом “Фридрих фон Нёвер”.</p> <p>Это мой сайт, совмещённый с блогом. В основном здесь публикуются различные технические заметки, так или иначе связанные с моей основной деятельностью — программированием.</p> <h2>Последние посты</h2> <ul> @foreach (var post in Model.Posts) { <li> <a href=".@post.Url">@post.Title</a> — @post.Date.ToString("yyyy.MM.dd") </li> } </ul> <p>Список всех постов можно найти в разделе <a href="./archive.html">Архив</a>.</p>
mit
C#
4af885f6b1b4a28b91c6fa115e8f1718b2041c97
Adjust default mania speed to match stable
UselessToucan/osu,DrabWeb/osu,smoogipoo/osu,johnneijzen/osu,smoogipoo/osu,DrabWeb/osu,peppy/osu,smoogipooo/osu,johnneijzen/osu,peppy/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,ZLima12/osu,DrabWeb/osu,NeoAdonis/osu,ZLima12/osu,EVAST9919/osu,naoey/osu,peppy/osu-new,2yangk23/osu,ppy/osu,EVAST9919/osu,UselessToucan/osu,2yangk23/osu,naoey/osu,naoey/osu,ppy/osu,smoogipoo/osu
osu.Game.Rulesets.Mania/Configuration/ManiaConfigManager.cs
osu.Game.Rulesets.Mania/Configuration/ManiaConfigManager.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Configuration.Tracking; using osu.Game.Configuration; using osu.Game.Rulesets.Configuration; using osu.Game.Rulesets.Mania.UI; namespace osu.Game.Rulesets.Mania.Configuration { public class ManiaConfigManager : RulesetConfigManager<ManiaSetting> { public ManiaConfigManager(SettingsStore settings, RulesetInfo ruleset, int? variant = null) : base(settings, ruleset, variant) { } protected override void InitialiseDefaults() { base.InitialiseDefaults(); Set(ManiaSetting.ScrollTime, 2250.0, 50.0, 10000.0, 50.0); Set(ManiaSetting.ScrollDirection, ManiaScrollingDirection.Down); } public override TrackedSettings CreateTrackedSettings() => new TrackedSettings { new TrackedSetting<double>(ManiaSetting.ScrollTime, v => new SettingDescription(v, "Scroll Time", $"{v}ms")) }; } public enum ManiaSetting { ScrollTime, ScrollDirection } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Configuration.Tracking; using osu.Game.Configuration; using osu.Game.Rulesets.Configuration; using osu.Game.Rulesets.Mania.UI; namespace osu.Game.Rulesets.Mania.Configuration { public class ManiaConfigManager : RulesetConfigManager<ManiaSetting> { public ManiaConfigManager(SettingsStore settings, RulesetInfo ruleset, int? variant = null) : base(settings, ruleset, variant) { } protected override void InitialiseDefaults() { base.InitialiseDefaults(); Set(ManiaSetting.ScrollTime, 1500.0, 50.0, 10000.0, 50.0); Set(ManiaSetting.ScrollDirection, ManiaScrollingDirection.Down); } public override TrackedSettings CreateTrackedSettings() => new TrackedSettings { new TrackedSetting<double>(ManiaSetting.ScrollTime, v => new SettingDescription(v, "Scroll Time", $"{v}ms")) }; } public enum ManiaSetting { ScrollTime, ScrollDirection } }
mit
C#
5f43299d3779ffbde32d3bd2f735592f30fad820
Fix tests failing due to base logic firing
peppy/osu,NeoAdonis/osu,peppy/osu-new,NeoAdonis/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,ppy/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu
osu.Game/Overlays/Changelog/ChangelogUpdateStreamControl.cs
osu.Game/Overlays/Changelog/ChangelogUpdateStreamControl.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Overlays.Changelog { public class ChangelogUpdateStreamControl : OverlayStreamControl<APIUpdateStream> { protected override OverlayStreamItem<APIUpdateStream> CreateStreamItem(APIUpdateStream value) => new ChangelogUpdateStreamItem(value); protected override void LoadComplete() { // suppress base logic of immediately selecting first item if one exists // (we always want to start with no stream selected). } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Overlays.Changelog { public class ChangelogUpdateStreamControl : OverlayStreamControl<APIUpdateStream> { protected override OverlayStreamItem<APIUpdateStream> CreateStreamItem(APIUpdateStream value) => new ChangelogUpdateStreamItem(value); } }
mit
C#
eda4f3c165acd66395c18051e7cdf026ef74bccf
Remove ConcurrentQueue wrapper around input enumerable and just iterate it directly in the Run method
HeadspringLabs/bulk-writer
src/BulkWriter/Pipeline/Internal/StartEtlPipelineStep.cs
src/BulkWriter/Pipeline/Internal/StartEtlPipelineStep.cs
using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; namespace BulkWriter.Pipeline.Internal { internal class StartEtlPipelineStep<TIn> : EtlPipelineStep<TIn, TIn> { private readonly IEnumerable<TIn> _inputEnumerable; public StartEtlPipelineStep(EtlPipelineContext pipelineContext, IEnumerable<TIn> inputEnumerable) : base(pipelineContext, new BlockingCollection<TIn>()) { _inputEnumerable = inputEnumerable; } public override void Run(CancellationToken cancellationToken) { RunSafely(() => { foreach (var item in _inputEnumerable) { OutputCollection.Add(item, cancellationToken); } }); } } }
using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; namespace BulkWriter.Pipeline.Internal { internal class StartEtlPipelineStep<TIn> : EtlPipelineStep<TIn, TIn> { public StartEtlPipelineStep(EtlPipelineContext pipelineContext, IEnumerable<TIn> enumerable) : base(pipelineContext, new BlockingCollection<TIn>(new ConcurrentQueue<TIn>(enumerable))) { } public override void Run(CancellationToken cancellationToken) { var enumerable = InputCollection.GetConsumingEnumerable(cancellationToken); RunSafely(() => { foreach (var item in enumerable) { OutputCollection.Add(item, cancellationToken); } }); } } }
apache-2.0
C#
e7aab02adb1794ee14055ce922d56943a4ed7de3
Fix broken test
gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork
src/BloomTests/TeamCollection/FolderTeamCollectionTests2.cs
src/BloomTests/TeamCollection/FolderTeamCollectionTests2.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Bloom.TeamCollection; using BloomTemp; using NUnit.Framework; using SIL.IO; namespace BloomTests.TeamCollection { /// <summary> /// The main FolderTeamCollectionTests class is mostly made up of tests that benefit from a OneTimeSetup /// function that creates a collection already connected to local and TeamCollection folders that /// already have some content created in the OneTimeSetup. This class is for tests /// where that setup gets in the way. /// </summary> public class FolderTeamCollectionTests2 { [Test] public void ConnectToTeamCollection_SetsUpRequiredFiles() { using (var collectionFolder = new TemporaryFolder("FolderTeamCollectionTests2_Collection")) { using (var sharedFolder = new TemporaryFolder("FolderTeamCollectionTests2_Shared")) { SyncAtStartupTests.MakeFakeBook(collectionFolder.FolderPath, "Some book", "Something"); var settingsFileName = Path.ChangeExtension(Path.GetFileName(collectionFolder.FolderPath), "bloomCollection"); var settingsPath = Path.Combine(collectionFolder.FolderPath, settingsFileName); // As an aside, this is a convenient place to check that a TC manager created when TC settings does not exist // functions and does not have a current collection. var tcManager = new TeamCollectionManager(settingsPath, null); Assert.That(tcManager.CurrentCollection, Is.Null); RobustFile.WriteAllText(settingsPath, "This is a fake settings file"); FolderTeamCollection.CreateTeamCollectionSettingsFile(collectionFolder.FolderPath, sharedFolder.FolderPath); var nonBookFolder = Path.Combine(collectionFolder.FolderPath, "Some other folder"); Directory.CreateDirectory(nonBookFolder); tcManager = new TeamCollectionManager(settingsPath, null); var collection = tcManager.CurrentCollection; // sut (collection as FolderTeamCollection)?.ConnectToTeamCollection(sharedFolder.FolderPath); Assert.That(collection, Is.Not.Null); var joinCollectioPath = Path.Combine(sharedFolder.FolderPath, "Join this Team Collection.JoinBloomTC"); Assert.That(File.Exists(joinCollectioPath)); var teamCollectionSettingsPath = Path.Combine(collectionFolder.FolderPath, TeamCollectionManager.TeamCollectionSettingsFileName); Assert.That(File.Exists(teamCollectionSettingsPath)); Assert.That(RobustFile.ReadAllText(teamCollectionSettingsPath), Contains.Substring("<TeamCollectionFolder>" + sharedFolder.FolderPath+"</TeamCollectionFolder>")); var sharedSettingsPath = Path.Combine(collectionFolder.FolderPath, settingsFileName); Assert.That(RobustFile.ReadAllText(sharedSettingsPath), Is.EqualTo("This is a fake settings file")); var bookPath = Path.Combine(sharedFolder.FolderPath, "Books", "Some book.bloom"); Assert.That(File.Exists(bookPath)); } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Bloom.TeamCollection; using BloomTemp; using NUnit.Framework; using SIL.IO; namespace BloomTests.TeamCollection { /// <summary> /// The main FolderTeamCollectionTests class is mostly made up of tests that benefit from a OneTimeSetup /// function that creates a collection already connected to local and TeamCollection folders that /// already have some content created in the OneTimeSetup. This class is for tests /// where that setup gets in the way. /// </summary> public class FolderTeamCollectionTests2 { [Test] public void ConnectToTeamCollection_SetsUpRequiredFiles() { using (var collectionFolder = new TemporaryFolder("FolderTeamCollectionTests2_Collection")) { using (var sharedFolder = new TemporaryFolder("FolderTeamCollectionTests2_Shared")) { SyncAtStartupTests.MakeFakeBook(collectionFolder.FolderPath, "Some book", "Something"); var settingsFileName = Path.ChangeExtension(Path.GetFileName(collectionFolder.FolderPath), "bloomCollection"); var settingsPath = Path.Combine(collectionFolder.FolderPath, settingsFileName); // As an aside, this is a convenient place to check that a TC manager created when TC settings does not exist // functions and does not have a current collection. var tcManager = new TeamCollectionManager(settingsPath, null); Assert.That(tcManager.CurrentCollection, Is.Null); RobustFile.WriteAllText(settingsPath, "This is a fake settings file"); FolderTeamCollection.CreateTeamCollectionSettingsFile(collectionFolder.FolderPath, sharedFolder.FolderPath); var nonBookFolder = Path.Combine(collectionFolder.FolderPath, "Some other folder"); Directory.CreateDirectory(nonBookFolder); tcManager = new TeamCollectionManager(settingsPath, null); var collection = tcManager.CurrentCollection; // sut (collection as FolderTeamCollection)?.ConnectToTeamCollection(sharedFolder.FolderPath); Assert.That(collection, Is.Not.Null); var joinCollectioPath = Path.Combine(sharedFolder.FolderPath, "Join this Team Collection.JoinBloomTC"); Assert.That(File.Exists(joinCollectioPath)); var teamCollectionSettingsPath = Path.Combine(collectionFolder.FolderPath, TeamCollectionManager.TeamCollectionSettingsFileName); Assert.That(File.Exists(teamCollectionSettingsPath)); Assert.That(RobustFile.ReadAllText(teamCollectionSettingsPath), Contains.Substring("<TeamCollectionFolder>" + sharedFolder.FolderPath+"</TeamCollectionFolder>")); var sharedSettingsPath = Path.Combine(collectionFolder.FolderPath, settingsFileName); Assert.That(RobustFile.ReadAllText(sharedSettingsPath), Is.EqualTo("This is a fake settings file")); var bookPath = Path.Combine(sharedFolder.FolderPath, "Some book.bloom"); Assert.That(File.Exists(bookPath)); } } } } }
mit
C#
a78b4761875ca06649d8884ea71ab046e9cd7020
Use minute instead of month in logger timestamp.
krishachetan89/Winium.StoreApps,NetlifeBackupSolutions/Winium.StoreApps,krishachetan89/Winium.StoreApps,2gis/Winium.StoreApps,2gis/Winium.StoreApps,NetlifeBackupSolutions/Winium.StoreApps
Winium/Winium.StoreApps.Driver/Logger.cs
Winium/Winium.StoreApps.Driver/Logger.cs
namespace Winium.StoreApps.Driver { #region using System.ComponentModel; using NLog; using NLog.Targets; #endregion internal static class Logger { #region Constants private const string LayoutFormat = "${date:format=HH\\:mm\\:ss} [${level:uppercase=true}] ${message}"; #endregion #region Static Fields private static readonly NLog.Logger Log = LogManager.GetLogger("outerdriver"); #endregion #region Public Methods and Operators public static void Debug([Localizable(false)] string message, params object[] args) { Log.Debug(message, args); } public static void Error([Localizable(false)] string message, params object[] args) { Log.Error(message, args); } public static void Fatal([Localizable(false)] string message, params object[] args) { Log.Fatal(message, args); } public static void Info([Localizable(false)] string message, params object[] args) { Log.Info(message, args); } public static void TargetConsole(bool verbose) { var target = new ConsoleTarget { Layout = LayoutFormat }; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, verbose ? LogLevel.Debug : LogLevel.Fatal); LogManager.ReconfigExistingLoggers(); } public static void TargetFile(string fileName, bool verbose) { var target = new FileTarget { Layout = LayoutFormat, FileName = fileName }; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, verbose ? LogLevel.Debug : LogLevel.Info); LogManager.ReconfigExistingLoggers(); } public static void Trace([Localizable(false)] string message, params object[] args) { Log.Trace(message, args); } public static void Warn([Localizable(false)] string message, params object[] args) { Log.Warn(message, args); } #endregion } }
namespace Winium.StoreApps.Driver { #region using System.ComponentModel; using NLog; using NLog.Targets; #endregion internal static class Logger { #region Constants private const string LayoutFormat = "${date:format=HH\\:MM\\:ss} [${level:uppercase=true}] ${message}"; #endregion #region Static Fields private static readonly NLog.Logger Log = LogManager.GetLogger("outerdriver"); #endregion #region Public Methods and Operators public static void Debug([Localizable(false)] string message, params object[] args) { Log.Debug(message, args); } public static void Error([Localizable(false)] string message, params object[] args) { Log.Error(message, args); } public static void Fatal([Localizable(false)] string message, params object[] args) { Log.Fatal(message, args); } public static void Info([Localizable(false)] string message, params object[] args) { Log.Info(message, args); } public static void TargetConsole(bool verbose) { var target = new ConsoleTarget { Layout = LayoutFormat }; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, verbose ? LogLevel.Debug : LogLevel.Fatal); LogManager.ReconfigExistingLoggers(); } public static void TargetFile(string fileName, bool verbose) { var target = new FileTarget { Layout = LayoutFormat, FileName = fileName }; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, verbose ? LogLevel.Debug : LogLevel.Info); LogManager.ReconfigExistingLoggers(); } public static void Trace([Localizable(false)] string message, params object[] args) { Log.Trace(message, args); } public static void Warn([Localizable(false)] string message, params object[] args) { Log.Warn(message, args); } #endregion } }
mpl-2.0
C#
4de11793b1f5401203ef8bb3e077092e993236d9
Speed up dotnet restore by * not executing _commandRunner to check for existence of dotnet (dotnet-script is already running as a dotnet tool) * computing a project hash so we only have to run dotnet restore once per project configuration. If runtime or nuget package dependencies change, it will run dotnet restore, otherwise it will be skipped.
filipw/dotnet-script,filipw/dotnet-script
src/Dotnet.Script.DependencyModel/Context/DotnetRestorer.cs
src/Dotnet.Script.DependencyModel/Context/DotnetRestorer.cs
using Dotnet.Script.DependencyModel.Environment; using Dotnet.Script.DependencyModel.Logging; using Dotnet.Script.DependencyModel.Process; using System; using System.IO; using System.Linq; using System.Security.Cryptography; namespace Dotnet.Script.DependencyModel.Context { public class DotnetRestorer : IRestorer { private readonly CommandRunner _commandRunner; private readonly Logger _logger; private readonly ScriptEnvironment _scriptEnvironment; public DotnetRestorer(CommandRunner commandRunner, LogFactory logFactory) { _commandRunner = commandRunner; _logger = logFactory.CreateLogger<DotnetRestorer>(); _scriptEnvironment = ScriptEnvironment.Default; } public void Restore(string pathToProjectFile, string[] packageSources) { var packageSourcesArgument = CreatePackageSourcesArguments(); var runtimeIdentifier = _scriptEnvironment.RuntimeIdentifier; // compute hash of project to see if it is different, such as new nuget packages added or removed string projectHash; using (var sha256 = SHA256.Create()) { projectHash = Convert.ToBase64String(sha256.ComputeHash(File.ReadAllBytes(pathToProjectFile))); } // get old hash code string hashFile = pathToProjectFile + ".hash"; if (File.Exists(hashFile) && (File.ReadAllText(hashFile) == projectHash)) { // if the same no need to do dotnet restore, package is identical return; } _logger.Debug($"Restoring {pathToProjectFile} using the dotnet cli. RuntimeIdentifier : {runtimeIdentifier}"); var exitcode = _commandRunner.Execute("dotnet", $"restore \"{pathToProjectFile}\" -r {runtimeIdentifier} {packageSourcesArgument}"); if (exitcode != 0) { // We must throw here, otherwise we may incorrectly run with the old 'project.assets.json' throw new Exception($"Unable to restore packages from '{pathToProjectFile}'. Make sure that all script files contains valid NuGet references"); } // save projectHash for next time File.WriteAllText(hashFile, projectHash); string CreatePackageSourcesArguments() { return packageSources.Length == 0 ? string.Empty : packageSources.Select(s => $"-s {s}") .Aggregate((current, next) => $"{current} {next}"); } } public bool CanRestore => true; } }
using System; using System.Linq; using Dotnet.Script.DependencyModel.Environment; using Dotnet.Script.DependencyModel.Logging; using Dotnet.Script.DependencyModel.Process; namespace Dotnet.Script.DependencyModel.Context { public class DotnetRestorer : IRestorer { private readonly CommandRunner _commandRunner; private readonly Logger _logger; private readonly ScriptEnvironment _scriptEnvironment; public DotnetRestorer(CommandRunner commandRunner, LogFactory logFactory) { _commandRunner = commandRunner; _logger = logFactory.CreateLogger<DotnetRestorer>(); _scriptEnvironment = ScriptEnvironment.Default; } public void Restore(string pathToProjectFile, string[] packageSources) { var packageSourcesArgument = CreatePackageSourcesArguments(); var runtimeIdentifier = _scriptEnvironment.RuntimeIdentifier; _logger.Debug($"Restoring {pathToProjectFile} using the dotnet cli. RuntimeIdentifier : {runtimeIdentifier}"); var exitcode = _commandRunner.Execute("dotnet", $"restore \"{pathToProjectFile}\" -r {runtimeIdentifier} {packageSourcesArgument}"); if (exitcode != 0) { // We must throw here, otherwise we may incorrectly run with the old 'project.assets.json' throw new Exception($"Unable to restore packages from '{pathToProjectFile}'. Make sure that all script files contains valid NuGet references"); } string CreatePackageSourcesArguments() { return packageSources.Length == 0 ? string.Empty : packageSources.Select(s => $"-s {s}") .Aggregate((current, next) => $"{current} {next}"); } } public bool CanRestore => _commandRunner.Execute("dotnet", "--version") == 0; } }
mit
C#
bc24ded0f0905cd085b048ae2a390e0f021a15ef
Add Requester ID
mattnis/ZendeskApi_v2,CKCobra/ZendeskApi_v2,mwarger/ZendeskApi_v2,dcrowe/ZendeskApi_v2
ZendeskApi_v2/Models/Requests/Request.cs
ZendeskApi_v2/Models/Requests/Request.cs
// JSON C# Class Generator // http://at-my-window.blogspot.com/?page=json-class-generator using System; using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using ZendeskApi_v2.Models.Shared; using ZendeskApi_v2.Models.Tickets; namespace ZendeskApi_v2.Models.Requests { public class Request { [JsonProperty("url")] public string Url { get; set; } [JsonProperty("id")] public long? Id { get; set; } [JsonProperty("status")] public string Status { get; set; } [JsonProperty("subject")] public string Subject { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("organization_id")] public long? OrganizationId { get; set; } [JsonProperty("via")] public Via Via { get; set; } [JsonProperty("custom_fields")] public IList<CustomField> CustomFields { get; set; } [JsonProperty("created_at")] public string CreatedAt { get; set; } [JsonProperty("updated_at")] public string UpdatedAt { get; set; } [JsonProperty("requester_id")] public long? RequesterId { get; set; } /// <summary> /// This is used for updates only /// </summary> [JsonProperty("comment")] public Comment Comment { get; set; } } }
// JSON C# Class Generator // http://at-my-window.blogspot.com/?page=json-class-generator using System; using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using ZendeskApi_v2.Models.Shared; using ZendeskApi_v2.Models.Tickets; namespace ZendeskApi_v2.Models.Requests { public class Request { [JsonProperty("url")] public string Url { get; set; } [JsonProperty("id")] public long? Id { get; set; } [JsonProperty("status")] public string Status { get; set; } [JsonProperty("subject")] public string Subject { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("organization_id")] public long? OrganizationId { get; set; } [JsonProperty("via")] public Via Via { get; set; } [JsonProperty("custom_fields")] public IList<CustomField> CustomFields { get; set; } [JsonProperty("created_at")] public string CreatedAt { get; set; } [JsonProperty("updated_at")] public string UpdatedAt { get; set; } /// <summary> /// This is used for updates only /// </summary> [JsonProperty("comment")] public Comment Comment { get; set; } } }
apache-2.0
C#
180521a2bd542d33f19b0fec2f2b217e4c77c762
Add simple Anmeldung email template caching via static ConcurrentDictionary
christophwille/myhaflinger.com,christophwille/myhaflinger.com,christophwille/myhaflinger.com
src/MyHaflinger.Treffen/Services/AnmeldungMailService.cs
src/MyHaflinger.Treffen/Services/AnmeldungMailService.cs
using System; using System.Collections.Concurrent; using System.IO; using System.Threading.Tasks; using MyHaflinger.Common.Services; using MyHaflinger.Treffen.Db; using RazorLight; namespace MyHaflinger.Treffen.Services { public class AnmeldungMailService { private static readonly ConcurrentDictionary<string,string> Templates = new ConcurrentDictionary<string, string>(); private readonly ISmtpMailService _smtpMailService; private readonly string _sender; public AnmeldungMailService(ISmtpMailService smtpMailService, string sender) { _smtpMailService = smtpMailService; _sender = sender; } private RazorLightEngine GetEngine() { return new RazorLightEngineBuilder() .UseMemoryCachingProvider() .Build(); } private string GetTemplate(string templateKey) { string key = "MyHaflinger.Treffen.Templates." + templateKey + ".cshtml"; if (!Templates.TryGetValue(key, out string templateValue)) { using (var stream = GetType().Assembly.GetManifestResourceStream(key)) { using (var reader = new StreamReader(stream)) { templateValue = reader.ReadToEnd(); } } Templates.TryAdd(key, templateValue); } return templateValue; } public async Task<bool> SendStep1Mail(string urlForContinuation, string to) { string template = GetTemplate("Anmeldung_Step1_Email"); string msgToSend = await GetEngine().CompileRenderAsync("Anmeldung_Step1_Email", template, new { LinkToForm = urlForContinuation }); return await _smtpMailService.SendMailAsync(to, "Emailadresse validiert, Haflingertreffen Salzkammergut", msgToSend, true, _sender); } public async Task<bool> SendRegCompleteMailToParticipant(Registration reg) { string template = GetTemplate("Anmeldung_FinalStep"); string msgToSend = await GetEngine().CompileRenderAsync("Anmeldung_FinalStep", template, reg); return await _smtpMailService.SendMailAsync(reg.EmailAddress, "Anmeldebestätigung", msgToSend, true, _sender); } public async Task<bool> SendNewRegInfoToRegDesk(string to, Registration reg) { string template = GetTemplate("Anmeldung_New_2RegDesk"); string msgToSend = await GetEngine().CompileRenderAsync("Anmeldung_New_2RegDesk", template, reg); return await _smtpMailService.SendMailAsync(to, "Neue Anmeldung", msgToSend, true, _sender); } } }
using System; using System.IO; using System.Threading.Tasks; using MyHaflinger.Common.Services; using MyHaflinger.Treffen.Db; using RazorLight; namespace MyHaflinger.Treffen.Services { public class AnmeldungMailService { private readonly ISmtpMailService _smtpMailService; private readonly string _sender; public AnmeldungMailService(ISmtpMailService smtpMailService, string sender) { _smtpMailService = smtpMailService; _sender = sender; } private RazorLightEngine GetEngine() { return new RazorLightEngineBuilder() .UseMemoryCachingProvider() .Build(); } private string GetTemplate(string templateKey) { string key = "MyHaflinger.Treffen.Templates." + templateKey + ".cshtml"; using (var stream = GetType().Assembly.GetManifestResourceStream(key)) { using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } public async Task<bool> SendStep1Mail(string urlForContinuation, string to) { string template = GetTemplate("Anmeldung_Step1_Email"); string msgToSend = await GetEngine().CompileRenderAsync("Anmeldung_Step1_Email", template, new { LinkToForm = urlForContinuation }); return await _smtpMailService.SendMailAsync(to, "Emailadresse validiert, Haflingertreffen Salzkammergut", msgToSend, true, _sender); } public async Task<bool> SendRegCompleteMailToParticipant(Registration reg) { string template = GetTemplate("Anmeldung_FinalStep"); string msgToSend = await GetEngine().CompileRenderAsync("Anmeldung_FinalStep", template, reg); return await _smtpMailService.SendMailAsync(reg.EmailAddress, "Anmeldebestätigung", msgToSend, true, _sender); } public async Task<bool> SendNewRegInfoToRegDesk(string to, Registration reg) { string template = GetTemplate("Anmeldung_New_2RegDesk"); string msgToSend = await GetEngine().CompileRenderAsync("Anmeldung_New_2RegDesk", template, reg); return await _smtpMailService.SendMailAsync(to, "Neue Anmeldung", msgToSend, true, _sender); } } }
mit
C#
d0b45512defe712c4f5d0d8e533520346607455c
revert constructor
SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers
src/SFA.DAS.EmployerUsers.Api.Types/ChangedByUserInfo.cs
src/SFA.DAS.EmployerUsers.Api.Types/ChangedByUserInfo.cs
namespace SFA.DAS.EmployerUsers.Api.Types { public class ChangedByUserInfo { public string UserId { get; set; } public string Email { get; set; } public ChangedByUserInfo(string userId, string email) { UserId = userId; Email = email; } } }
namespace SFA.DAS.EmployerUsers.Api.Types { public class ChangedByUserInfo { public string UserId { get; set; } public string Email { get; set; } } }
mit
C#
ed072d8cc3445b2de54947c4045bd92ae2190ad9
Allow click-through of toolbar items.
bbqchickenrobot/Eto-1,PowerOfCode/Eto,bbqchickenrobot/Eto-1,l8s/Eto,PowerOfCode/Eto,l8s/Eto,bbqchickenrobot/Eto-1,l8s/Eto,PowerOfCode/Eto
Source/Eto.Platform.Windows/Forms/ToolBar/ToolBarHandler.cs
Source/Eto.Platform.Windows/Forms/ToolBar/ToolBarHandler.cs
using SD = System.Drawing; using SWF = System.Windows.Forms; using Eto.Forms; using System; namespace Eto.Platform.Windows { public class ToolBarHandler : WidgetHandler<ToolStripEx, ToolBar>, IToolBar { ToolBarDock dock = ToolBarDock.Top; public ToolBarHandler() { Control = new ToolStripEx(); Control.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.StackWithOverflow; Control.AutoSize = true; } public ToolBarDock Dock { get { return dock; } set { dock = value; } } public void AddButton(ToolItem item) { ((IToolBarItemHandler)item.Handler).CreateControl(this); } public void RemoveButton(ToolItem item) { Control.Items.Remove((SWF.ToolStripItem)item.ControlObject); } public ToolBarTextAlign TextAlign { get { /*switch (control.TextAlign) { case SWF.ToolBarTextAlign.Right: return ToolBarTextAlign.Right; default: case SWF.ToolBarTextAlign.Underneath: return ToolBarTextAlign.Underneath; } */ return ToolBarTextAlign.Underneath; } set { switch (value) { case ToolBarTextAlign.Right: //control.TextAlign = SWF.ToolBarTextAlign.Right; break; case ToolBarTextAlign.Underneath: //control.TextAlign = SWF.ToolBarTextAlign.Underneath; break; default: throw new NotSupportedException(); } } } public void Clear() { Control.Items.Clear(); } } /// <summary> /// This class adds on to the functionality provided in System.Windows.Forms.ToolStrip. /// <see cref="http://blogs.msdn.com/b/rickbrew/archive/2006/01/09/511003.aspx"/> /// </summary> public class ToolStripEx : SWF.ToolStrip { /// <summary> /// Gets or sets whether the ToolStripEx honors item clicks when its containing form does /// not have input focus. /// </summary> /// <remarks> /// Default value is false, which is the same behavior provided by the base ToolStrip class. /// </remarks> public bool ClickThrough { get; set; } protected override void WndProc(ref SWF.Message m) { base.WndProc(ref m); if (this.ClickThrough && m.Msg == NativeConstants.WM_MOUSEACTIVATE && m.Result == (IntPtr)NativeConstants.MA_ACTIVATEANDEAT) m.Result = (IntPtr)NativeConstants.MA_ACTIVATE; } } internal sealed class NativeConstants { private NativeConstants() { } internal const uint WM_MOUSEACTIVATE = 0x21; internal const uint MA_ACTIVATE = 1; internal const uint MA_ACTIVATEANDEAT = 2; internal const uint MA_NOACTIVATE = 3; internal const uint MA_NOACTIVATEANDEAT = 4; } }
using SD = System.Drawing; using SWF = System.Windows.Forms; using Eto.Forms; using System; namespace Eto.Platform.Windows { public class ToolBarHandler : WidgetHandler<SWF.ToolStrip, ToolBar>, IToolBar { ToolBarDock dock = ToolBarDock.Top; public ToolBarHandler() { Control = new SWF.ToolStrip(); Control.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.StackWithOverflow; Control.AutoSize = true; } public ToolBarDock Dock { get { return dock; } set { dock = value; } } public void AddButton(ToolItem item) { ((IToolBarItemHandler)item.Handler).CreateControl(this); } public void RemoveButton(ToolItem item) { Control.Items.Remove((SWF.ToolStripItem)item.ControlObject); } public ToolBarTextAlign TextAlign { get { /*switch (control.TextAlign) { case SWF.ToolBarTextAlign.Right: return ToolBarTextAlign.Right; default: case SWF.ToolBarTextAlign.Underneath: return ToolBarTextAlign.Underneath; } */ return ToolBarTextAlign.Underneath; } set { switch (value) { case ToolBarTextAlign.Right: //control.TextAlign = SWF.ToolBarTextAlign.Right; break; case ToolBarTextAlign.Underneath: //control.TextAlign = SWF.ToolBarTextAlign.Underneath; break; default: throw new NotSupportedException(); } } } public void Clear() { Control.Items.Clear(); } } }
bsd-3-clause
C#
eafe2b145241d786c8ec384639f844c89eebb3ea
Improve NicknameHistoryRepository.
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
src/MitternachtBot/Services/Database/Repositories/Impl/NicknameHistoryRepository.cs
src/MitternachtBot/Services/Database/Repositories/Impl/NicknameHistoryRepository.cs
using System; using System.Linq; using Microsoft.EntityFrameworkCore; using Mitternacht.Services.Database.Models; namespace Mitternacht.Services.Database.Repositories.Impl { public class NicknameHistoryRepository : Repository<NicknameHistoryModel>, INicknameHistoryRepository { public NicknameHistoryRepository(DbContext context) : base(context) { } public IQueryable<NicknameHistoryModel> GetGuildUserNames(ulong guildId, ulong userId) => _set.AsQueryable().Where(n => n.GuildId == guildId && n.UserId == userId); public IQueryable<NicknameHistoryModel> GetUserNames(ulong userId) => _set.AsQueryable().Where(n => n.UserId == userId); public bool AddUsername(ulong guildId, ulong userId, string nickname, ushort discriminator) { nickname = nickname?.Trim() ?? ""; var current = GetGuildUserNames(guildId, userId).OrderByDescending(u => u.DateSet).FirstOrDefault(); if(current != null || !string.IsNullOrWhiteSpace(nickname)) { var now = DateTime.UtcNow; if(current != null) { if(string.IsNullOrWhiteSpace(nickname)) { if(!current.DateReplaced.HasValue) { current.DateReplaced = now; return true; } else { return false; } } else { if(!string.Equals(current.Name, nickname, StringComparison.Ordinal) || current.DiscordDiscriminator != discriminator || current.DateReplaced.HasValue) { if(!current.DateReplaced.HasValue) { current.DateReplaced = now; } } else { return false; } } } else { _set.Add(new NicknameHistoryModel { UserId = userId, GuildId = guildId, Name = nickname, DiscordDiscriminator = discriminator, DateSet = now, }); } return true; } else { return false; } } public bool CloseNickname(ulong guildId, ulong userId) { var current = GetUserNames(userId).OrderByDescending(u => u.DateSet).FirstOrDefault(); if(current != null && !current.DateReplaced.HasValue) { current.DateReplaced = DateTime.UtcNow; return true; } else { return false; } } } }
using System; using System.Linq; using Microsoft.EntityFrameworkCore; using Mitternacht.Services.Database.Models; namespace Mitternacht.Services.Database.Repositories.Impl { public class NicknameHistoryRepository : Repository<NicknameHistoryModel>, INicknameHistoryRepository { public NicknameHistoryRepository(DbContext context) : base(context) { } public IQueryable<NicknameHistoryModel> GetGuildUserNames(ulong guildId, ulong userId) => _set.AsQueryable().Where(n => n.GuildId == guildId && n.UserId == userId); public IQueryable<NicknameHistoryModel> GetUserNames(ulong userId) => _set.AsQueryable().Where(n => n.UserId == userId); public bool AddUsername(ulong guildId, ulong userId, string nickname, ushort discriminator) { nickname = nickname?.Trim() ?? ""; var current = GetGuildUserNames(guildId, userId).OrderByDescending(u => u.DateSet).FirstOrDefault(); if(current != null || !string.IsNullOrWhiteSpace(nickname)) { var now = DateTime.UtcNow; if(current != null) { if(string.IsNullOrWhiteSpace(nickname)) { if(!current.DateReplaced.HasValue) { current.DateReplaced = now; _set.Update(current); return true; } else { return false; } } else { if(!string.Equals(current.Name, nickname, StringComparison.Ordinal) || current.DiscordDiscriminator != discriminator || current.DateReplaced.HasValue) { if(!current.DateReplaced.HasValue) { current.DateReplaced = now; _set.Update(current); } } else { return false; } } } else { _set.Add(new NicknameHistoryModel { UserId = userId, GuildId = guildId, Name = nickname, DiscordDiscriminator = discriminator, DateSet = now, }); } return true; } else { return false; } } public bool CloseNickname(ulong guildId, ulong userId) { var current = GetUserNames(userId).OrderByDescending(u => u.DateSet).FirstOrDefault(); var now = DateTime.UtcNow; if(current != null && !current.DateReplaced.HasValue) { current.DateReplaced = now; _set.Update(current); return true; } else { return false; } } } }
mit
C#
1dbbbc0b38776f29885fe0707c2fe0678373b2d0
Add all opcodes to the enum
joshpeterson/mos,joshpeterson/mos,joshpeterson/mos
Mos6510/Instructions/Opcodes.cs
Mos6510/Instructions/Opcodes.cs
namespace Mos6510.Instructions { public enum Opcode { Adc, // Add Memory to Accumulator with Carry And, // "AND" Memory with Accumulator Asl, // Shift Left One Bit (Memory or Accumulator) Bcc, // Branch on Carry Clear Bcs, // Branch on Carry Set Beq, // Branch on Result Zero Bit, // Test Bits in Memory with Accumulator Bmi, // Branch on Result Minus Bne, // Branch on Result not Zero Bpl, // Branch on Result Plus Brk, // Force Break Bvc, // Branch on Overflow Clear Bvs, // Branch on Overflow Set Clc, // Clear Carry Flag Cld, // Clear Decimal Mode Cli, // Clear interrupt Disable Bit Clv, // Clear Overflow Flag Cmp, // Compare Memory and Accumulator Cpx, // Compare Memory and Index X Cpy, // Compare Memory and Index Y Dec, // Decrement Memory by One Dex, // Decrement Index X by One Dey, // Decrement Index Y by One Eor, // "Exclusive-Or" Memory with Accumulator Inc, // Increment Memory by One Inx, // Increment Index X by One Iny, // Increment Index Y by One Jmp, // Jump to New Location Jsr, // Jump to New Location Saving Return Address Lda, // Load Accumulator with Memory Ldx, // Load Index X with Memory Ldy, // Load Index Y with Memory Lsr, // Shift Right One Bit (Memory or Accumulator) Nop, // No Operation Ora, // "OR" Memory with Accumulator Pha, // Push Accumulator on Stack Php, // Push Processor Status on Stack Pla, // Pull Accumulator from Stack Plp, // Pull Processor Status from Stack Rol, // Rotate One Bit Left (Memory or Accumulator) Ror, // Rotate One Bit Right (Memory or Accumulator) Rti, // Return from Interrupt Rts, // Return from Subroutine Sbc, // Subtract Memory from Accumulator with Borrow Sec, // Set Carry Flag Sed, // Set Decimal Mode Sei, // Set Interrupt Disable Status Sta, // Store Accumulator in Memory Stx, // Store Index X in Memory Sty, // Store Index Y in Memory Tax, // Transfer Accumulator to Index X Tay, // Transfer Accumulator to Index Y Tsx, // Transfer Stack Pointer to Index X Txa, // Transfer Index X to Accumulator Txs, // Transfer Index X to Stack Pointer Tya, // Transfer Index Y to Accumulator } }
namespace Mos6510.Instructions { public enum Opcode { Inx, Iny, Nop, And, Ora, Eor, Adc, Clc, Lda, Sbc, Sta, Ldx, Ldy, } }
mit
C#
5e1a387369b958138e2a98c285f57e34de52b5b1
Fix wrong json key of WeekdayOfMonth property.
omise/omise-dotnet
Omise/Models/ScheduleRequest.cs
Omise/Models/ScheduleRequest.cs
using System; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Omise.Models { public class ScheduleOnRequest : Request { [JsonProperty("weekdays")] public Weekdays[] Weekdays { get; set; } [JsonProperty("days_of_month")] public int[] DaysOfMonth { get; set; } [JsonProperty("weekday_of_month")] public String WeekdayOfMonth { get; set; } } public class CreateScheduleRequest : Request { public int Every { get; set; } public SchedulePeriod Period { get; set; } public ScheduleOnRequest On { get; set; } [JsonProperty("start_date")] public DateTime? StartDate { get; set; } [JsonProperty("end_date")] public DateTime? EndDate { get; set; } public ChargeScheduling Charge { get; set; } public TransferScheduling Transfer { get; set; } public CreateScheduleRequest() { On = new ScheduleOnRequest(); } } }
using System; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Omise.Models { public class ScheduleOnRequest : Request { [JsonProperty("weekdays")] public Weekdays[] Weekdays { get; set; } [JsonProperty("days_of_month")] public int[] DaysOfMonth { get; set; } [JsonProperty("weekdays_of_month")] public String WeekdayOfMonth { get; set; } } public class CreateScheduleRequest : Request { public int Every { get; set; } public SchedulePeriod Period { get; set; } public ScheduleOnRequest On { get; set; } [JsonProperty("start_date")] public DateTime? StartDate { get; set; } [JsonProperty("end_date")] public DateTime? EndDate { get; set; } public ChargeScheduling Charge { get; set; } public TransferScheduling Transfer { get; set; } public CreateScheduleRequest() { On = new ScheduleOnRequest(); } } }
mit
C#
ea16a83f2371dd485a70289c9fd1dbf211e91827
Improve test by adding zero and error check
aloisdg/RandomStringUtils
RandomStringUtils.Test/Tests.cs
RandomStringUtils.Test/Tests.cs
using System; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework; using Assert = NUnit.Framework.Assert; namespace RandomStringUtils.Test { [TestFixture] public class Tests { private const int Count = 126; [Test] public void TestRandom() { Assert.AreEqual(Count, RandomStringUtils.Random(Count).Length); } [Test] public void TestRandomZero() { Assert.AreEqual(0, RandomStringUtils.Random(0).Length); } [Test] public void TestRandomError() { Assert.Throws<ArgumentException>(() => RandomStringUtils.Random(-1)); } [Test] public void TestRandomAlphabetic() { var result = RandomStringUtils.RandomAlphabetic(Count); Assert.IsTrue(Count == result.Length && result.All<Char>(Char.IsLetter)); } [Test] public void TestRandomAlphanumeric() { var result = RandomStringUtils.RandomAlphanumeric(Count); Assert.IsTrue(Count == result.Length && result.All<Char>(Char.IsLetterOrDigit)); } /// <summary> /// Check if RandomNumeric return a correct string made with digit. /// </summary> [Test] public void TestRandomNumeric() { var result = RandomStringUtils.RandomNumeric(Count); Assert.IsTrue(Count == result.Length && result.All<Char>(Char.IsDigit)); } [Test] public void TestRandomAscii() { var result = RandomStringUtils.RandomAscii(Count); Assert.IsTrue(Count == result.Length && result.All<Char>(c => c >= 32 && c <= 126)); } } }
using System; using System.Diagnostics; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework; using Assert = NUnit.Framework.Assert; namespace RandomStringUtils.Test { [TestFixture] public class Tests { private const int Count = 126; [Test] public void TestRandom() { Assert.AreEqual(Count, RandomStringUtils.Random(Count).Length); } [Test] public void TestRandomAlphabetic() { var result = RandomStringUtils.RandomAlphabetic(Count); Assert.IsTrue(Count == result.Length && result.All<Char>(Char.IsLetter)); } [Test] public void TestRandomAlphanumeric() { var result = RandomStringUtils.RandomAlphanumeric(Count); Assert.IsTrue(Count == result.Length && result.All<Char>(Char.IsLetterOrDigit)); } [Test] public void TestRandomNumeric() { var result = RandomStringUtils.RandomNumeric(Count); Assert.IsTrue(Count == result.Length && result.All<Char>(Char.IsDigit)); } [Test] public void TestRandomAscii() { var result = RandomStringUtils.RandomAscii(Count); Assert.IsTrue(Count == result.Length && result.All<Char>(c => c >= 32 && c <= 126)); } } }
apache-2.0
C#
2b6ffe651a372d2adf21fa0acdbaa571f940d394
Move it to other GetMapExpression method 2
gentledepp/AutoMapper,BlaiseD/AutoMapper,lbargaoanu/AutoMapper,AutoMapper/AutoMapper,mjalil/AutoMapper,AutoMapper/AutoMapper
src/AutoMapper/QueryableExtensions/ExpressionRequest.cs
src/AutoMapper/QueryableExtensions/ExpressionRequest.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; namespace AutoMapper.QueryableExtensions { [DebuggerDisplay("{SourceType.Name}, {DestinationType.Name}")] public class ExpressionRequest : IEquatable<ExpressionRequest> { public Type SourceType { get; } public Type DestinationType { get; } public MemberInfo[] MembersToExpand { get; } internal ICollection<ExpressionRequest> PreviousRequests { get; } internal IEnumerable<ExpressionRequest> GetPreviousRequestsAndSelf() => PreviousRequests.Concat(new[] { this }); internal bool AlreadyExists => PreviousRequests.Contains(this); public ExpressionRequest(Type sourceType, Type destinationType, MemberInfo[] membersToExpand, ExpressionRequest parentRequest) { SourceType = sourceType; DestinationType = destinationType; MembersToExpand = membersToExpand.OrderBy(p => p.Name).ToArray(); PreviousRequests = parentRequest == null ? new HashSet<ExpressionRequest>() : new HashSet<ExpressionRequest>(parentRequest.GetPreviousRequestsAndSelf()); } public bool Equals(ExpressionRequest other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return MembersToExpand.SequenceEqual(other.MembersToExpand) && SourceType == other.SourceType && DestinationType == other.DestinationType; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((ExpressionRequest) obj); } public override int GetHashCode() { var hashCode = HashCodeCombiner.Combine(SourceType, DestinationType); foreach(var member in MembersToExpand) { hashCode = HashCodeCombiner.CombineCodes(hashCode, member.GetHashCode()); } return hashCode; } public static bool operator ==(ExpressionRequest left, ExpressionRequest right) => Equals(left, right); public static bool operator !=(ExpressionRequest left, ExpressionRequest right) => !Equals(left, right); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; namespace AutoMapper.QueryableExtensions { [DebuggerDisplay("{SourceType.Name}, {DestinationType.Name}")] public class ExpressionRequest : IEquatable<ExpressionRequest> { public Type SourceType { get; } public Type DestinationType { get; } public MemberInfo[] MembersToExpand { get; } internal ICollection<ExpressionRequest> PreviousRequests { get; } internal IEnumerable<ExpressionRequest> GetPreviousRequestsAndSelf() => PreviousRequests.Concat(new[] { this }); internal bool AlreadyExists => PreviousRequests.Contains(this); public ExpressionRequest(Type sourceType, Type destinationType, MemberInfo[] membersToExpand, ExpressionRequest parentRequest) { SourceType = sourceType; DestinationType = destinationType; MembersToExpand = membersToExpand?.OrderBy(p => p.Name).ToArray(); PreviousRequests = parentRequest == null ? new HashSet<ExpressionRequest>() : new HashSet<ExpressionRequest>(parentRequest.GetPreviousRequestsAndSelf()); } public bool Equals(ExpressionRequest other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return MembersToExpand.SequenceEqual(other.MembersToExpand) && SourceType == other.SourceType && DestinationType == other.DestinationType; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((ExpressionRequest) obj); } public override int GetHashCode() { var hashCode = HashCodeCombiner.Combine(SourceType, DestinationType); foreach(var member in MembersToExpand) { hashCode = HashCodeCombiner.CombineCodes(hashCode, member.GetHashCode()); } return hashCode; } public static bool operator ==(ExpressionRequest left, ExpressionRequest right) => Equals(left, right); public static bool operator !=(ExpressionRequest left, ExpressionRequest right) => !Equals(left, right); } }
mit
C#
09f82213107996d824fa0e29bf104d74057abcd2
Fix problem with multivalues (#1363)
leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net
src/Joinrpg.AspNetCore.Helpers/FormCollectionHelpers.cs
src/Joinrpg.AspNetCore.Helpers/FormCollectionHelpers.cs
using System; using System.Collections.Generic; using System.Linq; using JoinRpg.Helpers; using Microsoft.AspNetCore.Http; namespace Joinrpg.AspNetCore.Helpers { public static class FormCollectionHelpers { private static Dictionary<string, string?> ToDictionary(this IFormCollection collection) => collection.Keys.ToDictionary(key => key, key => TransformToString(collection, key)); private static string? TransformToString(IFormCollection collection, string key) { Microsoft.Extensions.Primitives.StringValues value = collection[key]; return value.ToString(); } public static IReadOnlyDictionary<int, string?> GetDynamicValuesFromPost(this HttpRequest request, string prefix) { var post = request.Form.ToDictionary(); return post.Keys.UnprefixNumbers(prefix) .ToDictionary(fieldClientId => fieldClientId, fieldClientId => post[prefix + fieldClientId]); } } }
using System; using System.Collections.Generic; using System.Linq; using JoinRpg.Helpers; using Microsoft.AspNetCore.Http; namespace Joinrpg.AspNetCore.Helpers { public static class FormCollectionHelpers { private static Dictionary<string, string?> ToDictionary(this IFormCollection collection) => collection.Keys.ToDictionary(key => key, key => (string?)collection[key].First()); public static IReadOnlyDictionary<int, string?> GetDynamicValuesFromPost(this HttpRequest request, string prefix) { var post = request.Form.ToDictionary(); return post.Keys.UnprefixNumbers(prefix) .ToDictionary(fieldClientId => fieldClientId, fieldClientId => post[prefix + fieldClientId]); } } }
mit
C#
71c680388c0e83ec5a3b5a3a4c7bf914bc844eb4
Make ExcludeFromCodeCoverage compatibility stub internal
lunet-io/markdig
src/Markdig/Helpers/ExcludeFromCodeCoverageAttribute.cs
src/Markdig/Helpers/ExcludeFromCodeCoverageAttribute.cs
#if NET35 || UAP using System; namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)] internal class ExcludeFromCodeCoverageAttribute : Attribute { } } #endif
#if NET35 || UAP using System; namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)] public class ExcludeFromCodeCoverageAttribute : Attribute { } } #endif
bsd-2-clause
C#
63e95f0f55e1b4ab494341e7bc63c8ee23fdbdd8
check for keys already existing
bitwarden/core,bitwarden/core,bitwarden/core,bitwarden/core
src/Core/Models/Api/Request/Accounts/KeysRequestModel.cs
src/Core/Models/Api/Request/Accounts/KeysRequestModel.cs
using Bit.Core.Models.Table; using System.ComponentModel.DataAnnotations; namespace Bit.Core.Models.Api { public class KeysRequestModel { public string PublicKey { get; set; } [Required] public string EncryptedPrivateKey { get; set; } public User ToUser(User existingUser) { if(string.IsNullOrWhiteSpace(existingUser.PublicKey) && !string.IsNullOrWhiteSpace(PublicKey)) { existingUser.PublicKey = PublicKey; } if(string.IsNullOrWhiteSpace(existingUser.PrivateKey)) { existingUser.PrivateKey = EncryptedPrivateKey; } return existingUser; } } }
using Bit.Core.Models.Table; using System.ComponentModel.DataAnnotations; namespace Bit.Core.Models.Api { public class KeysRequestModel { public string PublicKey { get; set; } [Required] public string EncryptedPrivateKey { get; set; } public User ToUser(User existingUser) { if(!string.IsNullOrWhiteSpace(PublicKey)) { existingUser.PublicKey = PublicKey; } existingUser.PrivateKey = EncryptedPrivateKey; return existingUser; } } }
agpl-3.0
C#
35a3edaa743d43e6c4b88949bd5c10c4f3b38e48
Reformat comment
wangkanai/Detection
src/DependencyInjection/DetectionCollectionExtensions.cs
src/DependencyInjection/DetectionCollectionExtensions.cs
// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved. // The Apache v2. See License.txt in the project root for license information. using System; using Wangkanai.Detection.DependencyInjection.Options; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Contains extension method to <see cref="IServiceCollection" /> for configuring client services. /// </summary> public static class DetectionCollectionExtensions { /// <summary> /// Add Detection Service to the services container. /// </summary> /// <param name="services">The services available in the application.</param> /// <param name="setAction">An <see cref="Action{DetectionOptions}"/> to configure the provided <see cref="DetectionOptions"/>.</param> /// <returns>An <see cref="IServiceCollection" /> so that additional calls can be chained.</returns> public static IDetectionBuilder AddDetection(this IServiceCollection services, Action<DetectionOptions> setAction) => services.Configure(setAction) .AddDetection(); /// <summary> /// Add Detection Service to the services container. /// </summary> /// <param name="services">The services available in the application.</param> /// <returns>An <see cref="IServiceCollection" /> so that additional calls can be chained.</returns> public static IDetectionBuilder AddDetection(this IServiceCollection services) => services.AddDetectionBuilder() // Detection .AddRequiredPlatformServices() .AddCoreServices() // Responsive .AddSessionServices() .AddResponsiveService() // Validation .AddMarkerService(); internal static IDetectionBuilder AddDetectionBuilder(this IServiceCollection services) => new DetectionBuilder(services); } }
// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved. // The Apache v2. See License.txt in the project root for license information. using System; using Wangkanai.Detection.DependencyInjection.Options; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Contains extension method to <see cref="IServiceCollection" /> for configuring client services. /// </summary> public static class DetectionCollectionExtensions { /// <summary> /// Add Detection Service to the services container. /// </summary> /// <param name="services">The services available in the application.</param> /// <param name="setAction">An <see cref="Action{DetectionOptions}"/> to configure the provided <see cref="DetectionOptions"/>.</param> /// <returns>An <see cref="IServiceCollection" /> so that additional calls can be chained.</returns> public static IDetectionBuilder AddDetection(this IServiceCollection services, Action<DetectionOptions> setAction) => services.Configure(setAction) .AddDetection(); /// <summary> /// Add Detection Service to the services container. /// </summary> /// <param name="services">The services available in the application.</param> /// <returns>An <see cref="IServiceCollection" /> so that additional calls can be chained.</returns> public static IDetectionBuilder AddDetection(this IServiceCollection services) => services.AddDetectionBuilder() // Detection .AddRequiredPlatformServices() .AddCoreServices() // Responsive .AddSessionServices() .AddResponsiveService() // Validation .AddMarkerService(); internal static IDetectionBuilder AddDetectionBuilder(this IServiceCollection services) => new DetectionBuilder(services); } }
apache-2.0
C#
638cf4e3d8ad2f1f41aaec1f4158b904e1eddf79
Fix for editing bug
funnelweblog/FunnelWeb,funnelweblog/FunnelWeb,funnelweblog/FunnelWeb
src/FunnelWeb.Web/Application/Mvc/Binders/ArrayBinder.cs
src/FunnelWeb.Web/Application/Mvc/Binders/ArrayBinder.cs
using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using System.Web.Helpers; namespace FunnelWeb.Web.Application.Mvc.Binders { /// <summary> /// Lets us take an array of values (comma seperated) or duplicate values of the same name from HTTP input /// and convert it to an array of integers. For example, foo=1,2,3 or foo=1&foo=2&foo=3. Used for things like /// checkbox lists. /// </summary> public class ArrayBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var selectedIdentities = new List<int>(); var formValues = controllerContext.HttpContext.Request.Unvalidated().Form; foreach (var parameter in formValues) { var key = (string) parameter; if (!key.StartsWith(bindingContext.ModelName)) continue; var value = formValues[key] ?? string.Empty; var values = value.Split(',').Select(x => x.Trim()); foreach (var item in values) { var id = 0; if (int.TryParse(item, out id)) { selectedIdentities.Add(id); } } } return selectedIdentities.ToArray(); } } }
using System.Collections.Generic; using System.Linq; using System.Web.Mvc; namespace FunnelWeb.Web.Application.Mvc.Binders { /// <summary> /// Lets us take an array of values (comma seperated) or duplicate values of the same name from HTTP input /// and convert it to an array of integers. For example, foo=1,2,3 or foo=1&foo=2&foo=3. Used for things like /// checkbox lists. /// </summary> public class ArrayBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var selectedIdentities = new List<int>(); var formValues = controllerContext.HttpContext.Request.Form; foreach (var parameter in formValues) { var key = (string) parameter; if (!key.StartsWith(bindingContext.ModelName)) continue; var value = formValues[key] ?? string.Empty; var values = value.Split(',').Select(x => x.Trim()); foreach (var item in values) { var id = 0; if (int.TryParse(item, out id)) { selectedIdentities.Add(id); } } } return selectedIdentities.ToArray(); } } }
bsd-3-clause
C#
627913a4af48dc16541d29e9376f2569c49bf282
fix shlemiel-method of retrieving information
wislon/xamarin-android-use-removable-sd-card
src/TestExternalSd/StorageClasses/ExternalSdCardInfo.cs
src/TestExternalSd/StorageClasses/ExternalSdCardInfo.cs
namespace TestExternalSd.StorageClasses { public static class ExternalSdCardInfo { private static string _path = null; private static bool? _isWriteable; private static FileSystemBlockInfo _fileSystemBlockInfo = null; /// <summary> /// Quick property you can check after initialising /// </summary> public static bool ExternalSdCardExists { get { return !string.IsNullOrWhiteSpace(Path); } } /// <summary> /// Returns the path to External SD card (if there is one), /// otherwise empty string if there isn't /// </summary> public static string Path { get { return _path ?? GetExternalSdCardPath(); } } /// <summary> /// Returns whether the external SD card is writeable. The first /// call to this is an expensive one, because it actually tries to /// write a test file to the external disk /// </summary> public static bool IsWriteable { get { return _isWriteable ?? IsExternalCardWriteable(); } } /// <summary> /// The values in the <see cref="FileSystemBlockInfo"/> object may have /// changed depending on what's going on in the file system, so it repopulates relatively /// expensively every time you read this property /// </summary> public static FileSystemBlockInfo FileSystemBlockInfo { get { return GetFileSystemBlockInfo(); } } private static FileSystemBlockInfo GetFileSystemBlockInfo() { if (!string.IsNullOrWhiteSpace(Path)) { _fileSystemBlockInfo = ExternalSdStorageHelper.GetFileSystemBlockInfo(_path); return _fileSystemBlockInfo; } return null; } private static bool IsExternalCardWriteable() { if (string.IsNullOrWhiteSpace(Path)) { return false; } _isWriteable = ExternalSdStorageHelper.IsWriteable(_path); return _isWriteable.Value; } private static string GetExternalSdCardPath() { _path = ExternalSdStorageHelper.GetExternalSdCardPath(); return _path; } } }
namespace TestExternalSd.StorageClasses { public static class ExternalSdCardInfo { private static string _path = null; private static bool? _isWriteable; private static FileSystemBlockInfo _fileSystemBlockInfo = null; /// <summary> /// Quick property you can check after initialising /// </summary> public static bool ExternalSdCardExists { get { return !string.IsNullOrWhiteSpace(GetExternalSdCardPath()); } } /// <summary> /// Returns the path to External SD card (if there is one), /// otherwise empty string if there isn't /// </summary> public static string Path { get { return _path ?? GetExternalSdCardPath(); } } /// <summary> /// Returns whether the external SD card is writeable. The first /// call to this is an expensive one, because it actually tries to /// write a test file to the external disk /// </summary> public static bool IsWriteable { get { return _isWriteable ?? IsExternalCardWriteable(); } } /// <summary> /// The values in the <see cref="FileSystemBlockInfo"/> object may have /// changed depending on what's going on in the file system, so it repopulates relatively /// expensively every time you read this property /// </summary> public static FileSystemBlockInfo FileSystemBlockInfo { get { return GetFileSystemBlockInfo(); } } private static FileSystemBlockInfo GetFileSystemBlockInfo() { if (!string.IsNullOrWhiteSpace(GetExternalSdCardPath())) { _fileSystemBlockInfo = ExternalSdStorageHelper.GetFileSystemBlockInfo(_path); return _fileSystemBlockInfo; } return null; } private static bool IsExternalCardWriteable() { if (string.IsNullOrWhiteSpace(GetExternalSdCardPath())) { return false; } _isWriteable = ExternalSdStorageHelper.IsWriteable(_path); return _isWriteable.Value; } private static string GetExternalSdCardPath() { _path = ExternalSdStorageHelper.GetExternalSdCardPath(); return _path; } } }
mit
C#
299ed6228f43f01d1fc1c8c12f0de3c79398ff5a
add entropy at RandomUtils initialization
you21979/NBitcoin,thepunctuatedhorizon/BrickCoinAlpha.0.0.1,lontivero/NBitcoin,stratisproject/NStratis,MetacoSA/NBitcoin,MetacoSA/NBitcoin,dangershony/NStratis,NicolasDorier/NBitcoin,bitcoinbrisbane/NBitcoin,HermanSchoenfeld/NBitcoin
NBitcoin/RandomUtils.partial.cs
NBitcoin/RandomUtils.partial.cs
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace NBitcoin { public class RNGCryptoServiceProviderRandom : IRandom { readonly RNGCryptoServiceProvider _Instance; public RNGCryptoServiceProviderRandom() { _Instance = new RNGCryptoServiceProvider(); } #region IRandom Members public void GetBytes(byte[] output) { _Instance.GetBytes(output); } #endregion } public partial class RandomUtils { static RandomUtils() { //Thread safe http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider(v=vs.110).aspx Random = new RNGCryptoServiceProviderRandom(); AddEntropy(Guid.NewGuid().ToByteArray()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace NBitcoin { public class RNGCryptoServiceProviderRandom : IRandom { readonly RNGCryptoServiceProvider _Instance; public RNGCryptoServiceProviderRandom() { _Instance = new RNGCryptoServiceProvider(); } #region IRandom Members public void GetBytes(byte[] output) { _Instance.GetBytes(output); } #endregion } public partial class RandomUtils { static RandomUtils() { //Thread safe http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider(v=vs.110).aspx Random = new RNGCryptoServiceProviderRandom(); } } }
mit
C#
61a878fbd74cef12939dcdfb001fee353fe71531
fix bad merge
agrc/Crash-web,agrc/Crash-web,agrc/Crash-web,agrc/Crash-web
api/chart-function/Models/Row.cs
api/chart-function/Models/Row.cs
namespace crash_statistics.Models { public class Row { public Row() { } public Row(int occurrences, object label, string type) { Occurrences = occurrences; Label = label; Type = type; } public int Occurrences { get; set; } public object Label { get; set; } = string.Empty; public string Type { get; set; } = string.Empty; } }
namespace crash_statistics.Models { public class Row { public Row() { } public Row(int occurrences, object label, string type) { Occurrences = occurrences; Label = label; Type = type; } public int Occurrences { get; set; } public object Label { get; set; } public string Type { get; set; } } }
mit
C#
2fdc815802eb7478e6e3931de2771e4100274831
Change of query for API get all account balances
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EAS.Api/Orchestrators/AccountsOrchestrator.cs
src/SFA.DAS.EAS.Api/Orchestrators/AccountsOrchestrator.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.UI; using MediatR; using NLog; using SFA.DAS.EAS.Api.Models; using SFA.DAS.EAS.Application.Queries.AccountTransactions.GetAccountBalances; using SFA.DAS.EAS.Application.Queries.GetBatchEmployerAccountTransactions; using SFA.DAS.EAS.Application.Queries.GetPagedEmployerAccounts; namespace SFA.DAS.EAS.Api.Orchestrators { public class AccountsOrchestrator { private readonly IMediator _mediator; private readonly ILogger _logger; public AccountsOrchestrator(IMediator mediator, ILogger logger ) { if (mediator == null) throw new ArgumentNullException(nameof(mediator)); _mediator = mediator; _logger = logger; } public async Task<OrchestratorResponse<PagedApiResponseViewModel<AccountWithBalanceViewModel>>> GetAllAccountsWithBalances(string toDate, int pageSize, int pageNumber) { toDate = toDate ?? DateTime.MaxValue.ToString("yyyyMMddHHmmss"); var accountsResult = await _mediator.SendAsync(new GetPagedEmployerAccountsQuery() {ToDate = toDate, PageSize = pageSize, PageNumber = pageNumber}); var transactionResult = await _mediator.SendAsync(new GetAccountBalancesRequest { AccountIds = accountsResult.Accounts.Select(account => account.Id).ToList() }); var data = new List<AccountWithBalanceViewModel>(); accountsResult.Accounts.ForEach(account => { var accountBalance = transactionResult.Accounts.SingleOrDefault(c=>c.AccountId==account.Id); data.Add(new AccountWithBalanceViewModel() { AccountId = account.Id, AccountName = account.Name, AccountHashId = account.HashedId, Balance = accountBalance?.Balance ?? 0 }); }); return new OrchestratorResponse<PagedApiResponseViewModel<AccountWithBalanceViewModel>>() {Data = new PagedApiResponseViewModel<AccountWithBalanceViewModel>() {Data = data, Page = pageNumber, TotalPages = (accountsResult.AccountsCount / pageSize) + 1} }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.UI; using MediatR; using NLog; using SFA.DAS.EAS.Api.Models; using SFA.DAS.EAS.Application.Queries.AccountTransactions.GetAccountBalances; using SFA.DAS.EAS.Application.Queries.GetBatchEmployerAccountTransactions; using SFA.DAS.EAS.Application.Queries.GetEmployerAccounts; namespace SFA.DAS.EAS.Api.Orchestrators { public class AccountsOrchestrator { private readonly IMediator _mediator; private readonly ILogger _logger; public AccountsOrchestrator(IMediator mediator, ILogger logger ) { if (mediator == null) throw new ArgumentNullException(nameof(mediator)); _mediator = mediator; _logger = logger; } public async Task<OrchestratorResponse<PagedApiResponseViewModel<AccountWithBalanceViewModel>>> GetAllAccountsWithBalances(string toDate, int pageSize, int pageNumber) { toDate = toDate ?? DateTime.MaxValue.ToString("yyyyMMddHHmmss"); var accountsResult = await _mediator.SendAsync(new GetEmployerAccountsQuery() {ToDate = toDate, PageSize = pageSize, PageNumber = pageNumber}); var transactionResult = await _mediator.SendAsync(new GetAccountBalancesRequest { AccountIds = accountsResult.Accounts.Select(account => account.Id).ToList() }); var data = new List<AccountWithBalanceViewModel>(); accountsResult.Accounts.ForEach(account => { var accountBalance = transactionResult.Accounts.SingleOrDefault(c=>c.AccountId==account.Id); data.Add(new AccountWithBalanceViewModel() { AccountId = account.Id, AccountName = account.Name, AccountHashId = account.HashedId, Balance = accountBalance?.Balance ?? 0 }); }); return new OrchestratorResponse<PagedApiResponseViewModel<AccountWithBalanceViewModel>>() {Data = new PagedApiResponseViewModel<AccountWithBalanceViewModel>() {Data = data, Page = pageNumber, TotalPages = (accountsResult.AccountsCount / pageSize) + 1} }; } } }
mit
C#
d4c465334123dc2bb533f26fc57382f97f016390
Add skip lines
zzzprojects/Z.ExtensionMethods
src/Z.IO/System.IO.StreamReader/StreamReader.SkipLines.cs
src/Z.IO/System.IO.StreamReader/StreamReader.SkipLines.cs
// Description: C# Extension Methods Library to enhances the .NET Framework by adding hundreds of new methods. It drastically increases developers productivity and code readability. Support C# and VB.NET // Website & Documentation: https://github.com/zzzprojects/Z.ExtensionMethods // Forum: https://github.com/zzzprojects/Z.ExtensionMethods/issues // License: https://github.com/zzzprojects/Z.ExtensionMethods/blob/master/LICENSE // More projects: http://www.zzzprojects.com/ // Copyright © ZZZ Projects Inc. 2014 - 2016. All rights reserved. using System.IO; public static partial class Extensions { /// <summary> /// Skips the specified number of lines in a stream reader based on its current position. /// </summary> /// <param name="this">The stream reader.</param> /// <param name="skipCount">The number of lines to skip.</param> public static void SkipLines(this StreamReader @this, int skipCount) { for (var i = 0; i < skipCount && !@this.EndOfStream; i++) { @this.ReadLine(); } } }
// Description: C# Extension Methods Library to enhances the .NET Framework by adding hundreds of new methods. It drastically increases developers productivity and code readability. Support C# and VB.NET // Website & Documentation: https://github.com/zzzprojects/Z.ExtensionMethods // Forum: https://github.com/zzzprojects/Z.ExtensionMethods/issues // License: https://github.com/zzzprojects/Z.ExtensionMethods/blob/master/LICENSE // More projects: http://www.zzzprojects.com/ // Copyright © ZZZ Projects Inc. 2014 - 2016. All rights reserved. using System.IO; using System.Linq; public static partial class Extensions { /// <summary> /// Skips the specified number of lines in a stream reader based on its current position. /// </summary> /// <param name="this">The stream reader.</param> /// <param name="skipCount">The number of lines to skip.</param> public static void SkipLines(this StreamReader @this, int skipCount) { for (var i = 0; i < skipCount && !@this.EndOfStream; i++) { @this.ReadLine(); } } }
mit
C#
581334ab8184701e9440fd95046d63fc4fe7913b
fix adding tabs to TabControl after it is loaded on a form
bbqchickenrobot/Eto-1,PowerOfCode/Eto,l8s/Eto,PowerOfCode/Eto,l8s/Eto,l8s/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1
Source/Eto.Platform.Gtk/Forms/Controls/TabControlHandler.cs
Source/Eto.Platform.Gtk/Forms/Controls/TabControlHandler.cs
using System; using System.Collections; using Eto.Forms; namespace Eto.Platform.GtkSharp { public class TabControlHandler : GtkControl<Gtk.Notebook, TabControl>, ITabControl { public TabControlHandler() { Control = new Gtk.Notebook(); Control.SwitchPage += delegate { Widget.OnSelectedIndexChanged (EventArgs.Empty); if (SelectedIndex >= 0) Widget.TabPages[SelectedIndex].OnClick (EventArgs.Empty); }; } public int SelectedIndex { get { return Control.CurrentPage; } set { Control.CurrentPage = value; } } public void InsertTab (int index, TabPage page) { var pageHandler = (TabPageHandler)page.Handler; if (Widget.Loaded) { pageHandler.Control.ShowAll (); pageHandler.LabelControl.ShowAll (); } if (index == -1) Control.AppendPage(pageHandler.Control, pageHandler.LabelControl); else Control.InsertPage(pageHandler.Control, pageHandler.LabelControl, index); } public void ClearTabs () { while (Control.NPages > 0) Control.RemovePage (0); } public void RemoveTab (int index, TabPage page) { Control.RemovePage (index); } } }
using System; using System.Collections; using Eto.Forms; namespace Eto.Platform.GtkSharp { public class TabControlHandler : GtkControl<Gtk.Notebook, TabControl>, ITabControl { public TabControlHandler() { Control = new Gtk.Notebook(); Control.SwitchPage += delegate { Widget.OnSelectedIndexChanged (EventArgs.Empty); if (SelectedIndex >= 0) Widget.TabPages[SelectedIndex].OnClick (EventArgs.Empty); }; } public int SelectedIndex { get { return Control.CurrentPage; } set { Control.CurrentPage = value; } } public void InsertTab (int index, TabPage page) { var pageHandler = (TabPageHandler)page.Handler; if (index == -1) Control.AppendPage(pageHandler.Control, pageHandler.LabelControl); else Control.InsertPage(pageHandler.Control, pageHandler.LabelControl, index); } public void ClearTabs () { while (Control.NPages > 0) Control.RemovePage (0); } public void RemoveTab (int index, TabPage page) { Control.RemovePage (index); } } }
bsd-3-clause
C#
4485a50d1ea1d7656ba6d90a76eba3cfe3fcaac4
Update ApplicationInsightsHelper.cs
tiksn/TIKSN-Framework
TIKSN.Core/Analytics/Telemetry/ApplicationInsightsHelper.cs
TIKSN.Core/Analytics/Telemetry/ApplicationInsightsHelper.cs
using System; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.DataContracts; namespace TIKSN.Analytics.Telemetry { internal static class ApplicationInsightsHelper { internal static SeverityLevel? ConvertSeverityLevel(TelemetrySeverityLevel? severityLevel) { if (severityLevel.HasValue) { return severityLevel.Value switch { TelemetrySeverityLevel.Verbose => SeverityLevel.Verbose, TelemetrySeverityLevel.Information => SeverityLevel.Information, TelemetrySeverityLevel.Warning => SeverityLevel.Warning, TelemetrySeverityLevel.Error => SeverityLevel.Error, TelemetrySeverityLevel.Critical => SeverityLevel.Critical, _ => throw new NotSupportedException(), }; } return null; } [Obsolete] internal static void TrackEvent(EventTelemetry telemetry) { var client = new TelemetryClient(); client.TrackEvent(telemetry); } [Obsolete] internal static void TrackException(ExceptionTelemetry telemetry) { var client = new TelemetryClient(); client.TrackException(telemetry); } [Obsolete] internal static void TrackMetric(MetricTelemetry telemetry) { var client = new TelemetryClient(); client.TrackMetric(telemetry); } [Obsolete] internal static void TrackTrace(TraceTelemetry telemetry) { var client = new TelemetryClient(); client.TrackTrace(telemetry); } } }
using System; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.DataContracts; namespace TIKSN.Analytics.Telemetry { internal static class ApplicationInsightsHelper { internal static SeverityLevel? ConvertSeverityLevel(TelemetrySeverityLevel? severityLevel) { if (severityLevel.HasValue) { switch (severityLevel.Value) { case TelemetrySeverityLevel.Verbose: return SeverityLevel.Verbose; case TelemetrySeverityLevel.Information: return SeverityLevel.Information; case TelemetrySeverityLevel.Warning: return SeverityLevel.Warning; case TelemetrySeverityLevel.Error: return SeverityLevel.Error; case TelemetrySeverityLevel.Critical: return SeverityLevel.Critical; default: throw new NotSupportedException(); } } return null; } internal static void TrackEvent(EventTelemetry telemetry) { var client = new TelemetryClient(); client.TrackEvent(telemetry); } internal static void TrackException(ExceptionTelemetry telemetry) { var client = new TelemetryClient(); client.TrackException(telemetry); } internal static void TrackMetric(MetricTelemetry telemetry) { var client = new TelemetryClient(); client.TrackMetric(telemetry); } internal static void TrackTrace(TraceTelemetry telemetry) { var client = new TelemetryClient(); client.TrackTrace(telemetry); } } }
mit
C#
3f9168c21ec937f32dbae75cfaba878c9632e2b9
Disable EF Core transaction test.
ilyhacker/aspnetboilerplate,carldai0106/aspnetboilerplate,carldai0106/aspnetboilerplate,AlexGeller/aspnetboilerplate,ryancyq/aspnetboilerplate,lvjunlei/aspnetboilerplate,verdentk/aspnetboilerplate,fengyeju/aspnetboilerplate,verdentk/aspnetboilerplate,jaq316/aspnetboilerplate,virtualcca/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,virtualcca/aspnetboilerplate,ZhaoRd/aspnetboilerplate,4nonym0us/aspnetboilerplate,4nonym0us/aspnetboilerplate,ShiningRush/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,luchaoshuai/aspnetboilerplate,carldai0106/aspnetboilerplate,andmattia/aspnetboilerplate,AlexGeller/aspnetboilerplate,zquans/aspnetboilerplate,ZhaoRd/aspnetboilerplate,ryancyq/aspnetboilerplate,ilyhacker/aspnetboilerplate,Nongzhsh/aspnetboilerplate,zclmoon/aspnetboilerplate,ryancyq/aspnetboilerplate,luchaoshuai/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,ilyhacker/aspnetboilerplate,s-takatsu/aspnetboilerplate,carldai0106/aspnetboilerplate,virtualcca/aspnetboilerplate,beratcarsi/aspnetboilerplate,yuzukwok/aspnetboilerplate,andmattia/aspnetboilerplate,zquans/aspnetboilerplate,AlexGeller/aspnetboilerplate,zclmoon/aspnetboilerplate,lvjunlei/aspnetboilerplate,ShiningRush/aspnetboilerplate,jaq316/aspnetboilerplate,berdankoca/aspnetboilerplate,s-takatsu/aspnetboilerplate,4nonym0us/aspnetboilerplate,zclmoon/aspnetboilerplate,jaq316/aspnetboilerplate,yuzukwok/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,andmattia/aspnetboilerplate,zquans/aspnetboilerplate,yuzukwok/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,verdentk/aspnetboilerplate,690486439/aspnetboilerplate,oceanho/aspnetboilerplate,berdankoca/aspnetboilerplate,ShiningRush/aspnetboilerplate,beratcarsi/aspnetboilerplate,oceanho/aspnetboilerplate,fengyeju/aspnetboilerplate,690486439/aspnetboilerplate,beratcarsi/aspnetboilerplate,ryancyq/aspnetboilerplate,ZhaoRd/aspnetboilerplate,690486439/aspnetboilerplate,Nongzhsh/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,Nongzhsh/aspnetboilerplate,lvjunlei/aspnetboilerplate,s-takatsu/aspnetboilerplate,oceanho/aspnetboilerplate,berdankoca/aspnetboilerplate,fengyeju/aspnetboilerplate
test/Abp.EntityFrameworkCore.Tests/Transaction_Tests.cs
test/Abp.EntityFrameworkCore.Tests/Transaction_Tests.cs
using System; using System.Threading.Tasks; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.EntityFrameworkCore.Tests.Domain; using Microsoft.EntityFrameworkCore; using Shouldly; namespace Abp.EntityFrameworkCore.Tests { //WE CAN NOT TEST TRANSACTIONS SINCE INMEMORY DB DOES NOT SUPPORT IT! TODO: Use SQLite public class Transaction_Tests : EntityFrameworkCoreModuleTestBase { private readonly IUnitOfWorkManager _uowManager; private readonly IRepository<Blog> _blogRepository; public Transaction_Tests() { _uowManager = Resolve<IUnitOfWorkManager>(); _blogRepository = Resolve<IRepository<Blog>>(); } //[Fact] public async Task Should_Rollback_Transaction_On_Failure() { const string exceptionMessage = "This is a test exception!"; var blogName = Guid.NewGuid().ToString("N"); try { using (_uowManager.Begin()) { await _blogRepository.InsertAsync( new Blog(blogName, $"http://{blogName}.com/") ); throw new ApplicationException(exceptionMessage); } } catch (ApplicationException ex) when (ex.Message == exceptionMessage) { } await UsingDbContextAsync(async context => { var blog = await context.Blogs.FirstOrDefaultAsync(b => b.Name == blogName); blog.ShouldNotBeNull(); }); } } }
using System; using System.Threading.Tasks; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.EntityFrameworkCore.Tests.Domain; using Microsoft.EntityFrameworkCore; using Shouldly; using Xunit; namespace Abp.EntityFrameworkCore.Tests { public class Transaction_Tests : EntityFrameworkCoreModuleTestBase { private readonly IUnitOfWorkManager _uowManager; private readonly IRepository<Blog> _blogRepository; public Transaction_Tests() { _uowManager = Resolve<IUnitOfWorkManager>(); _blogRepository = Resolve<IRepository<Blog>>(); } [Fact] public async Task Should_Rollback_Transaction_On_Failure() { const string exceptionMessage = "This is a test exception!"; var blogName = Guid.NewGuid().ToString("N"); try { using (_uowManager.Begin()) { await _blogRepository.InsertAsync( new Blog(blogName, $"http://{blogName}.com/") ); throw new ApplicationException(exceptionMessage); } } catch (ApplicationException ex) when (ex.Message == exceptionMessage) { } await UsingDbContextAsync(async context => { var blog = await context.Blogs.FirstOrDefaultAsync(b => b.Name == blogName); blog.ShouldNotBeNull(); }); } } }
mit
C#
e28e51beb5f552bfe3ddf16c82712df6123cf0a0
Create CreateHostBuilder method.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Backend/Program.cs
WalletWasabi.Backend/Program.cs
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using System; using System.Threading.Tasks; using WalletWasabi.Logging; namespace WalletWasabi.Backend { public static class Program { #pragma warning disable IDE1006 // Naming Styles public static async Task Main(string[] args) #pragma warning restore IDE1006 // Naming Styles { try { using var host = CreateHostBuilder(args).Build(); await host.RunWithTasksAsync(); } catch (Exception ex) { Logger.LogCritical(ex); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>()); } }
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using System; using System.Threading.Tasks; using WalletWasabi.Logging; namespace WalletWasabi.Backend { public static class Program { #pragma warning disable IDE1006 // Naming Styles public static async Task Main(string[] args) #pragma warning restore IDE1006 // Naming Styles { try { using var host = Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => webBuilder .UseStartup<Startup>()) .Build(); await host.RunWithTasksAsync(); } catch (Exception ex) { Logger.LogCritical(ex); } } } }
mit
C#
291250b4c2e239b8cb7bb733c7384b2b0a36e686
Fix typo
tom-englert/Wax
Wax.Model/Wix/WixProductNode.cs
Wax.Model/Wix/WixProductNode.cs
namespace tomenglertde.Wax.Model.Wix { using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Xml.Linq; using JetBrains.Annotations; using tomenglertde.Wax.Model.Tools; public class WixProductNode : WixNode { public WixProductNode([NotNull] WixSourceFile sourceFile, [NotNull] XElement node) : base(sourceFile, node) { Contract.Requires(sourceFile != null); Contract.Requires(node != null); } [NotNull] public IEnumerable<WixPropertyNode> PropertyNodes { get { Contract.Ensures(Contract.Result<IEnumerable<WixPropertyNode>>() != null); return Node.Descendants(WixNames.PropertyNode).Select(node => new WixPropertyNode(SourceFile, node)); } } [NotNull] public IEnumerable<string> EnumerateCustomActionRefs() { Contract.Ensures(Contract.Result<IEnumerable<string>>() != null); return Node.Descendants(WixNames.CustomActionRefNode).Select(node => node.Attribute("Id").Value); } public WixPropertyNode AddProperty([NotNull] WixProperty property) { Contract.Requires(property != null); var newNode = new XElement(WixNames.PropertyNode, new XAttribute("Id", property.Name), new XAttribute("Value", property.Value)); Node.AddWithFormatting(newNode); SourceFile.Save(); return new WixPropertyNode(SourceFile, newNode); } public void AddCustomActionRef(string id) { Contract.Requires(!string.IsNullOrWhiteSpace(id)); var newNode = new XElement(WixNames.CustomActionRefNode, new XAttribute("Id", id)); Node.AddWithFormatting(newNode); SourceFile.Save(); } } }
namespace tomenglertde.Wax.Model.Wix { using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Xml.Linq; using JetBrains.Annotations; using tomenglertde.Wax.Model.Tools; public class WixProductNode : WixNode { public WixProductNode([NotNull] WixSourceFile sourceFile, [NotNull] XElement node) : base(sourceFile, node) { Contract.Requires(sourceFile != null); Contract.Requires(node != null); } [NotNull] public IEnumerable<WixPropertyNode> PropertyNodes { get { Contract.Ensures(Contract.Result<IEnumerable<WixPropertyNode>>() != null); return Node.Descendants(WixNames.PropertyNode).Select(node => new WixPropertyNode(SourceFile, node)); } } [NotNull] public IEnumerable<string> EnumerateCustomActionRefs() { Contract.Ensures(Contract.Result<IEnumerable<WixPropertyNode>>() != null); return Node.Descendants(WixNames.CustomActionRefNode).Select(node => node.Attribute("Id").Value); } public WixPropertyNode AddProperty([NotNull] WixProperty property) { Contract.Requires(property != null); var newNode = new XElement(WixNames.PropertyNode, new XAttribute("Id", property.Name), new XAttribute("Value", property.Value)); Node.AddWithFormatting(newNode); SourceFile.Save(); return new WixPropertyNode(SourceFile, newNode); } public void AddCustomActionRef(string id) { Contract.Requires(!string.IsNullOrWhiteSpace(id)); var newNode = new XElement(WixNames.CustomActionRefNode, new XAttribute("Id", id)); Node.AddWithFormatting(newNode); SourceFile.Save(); } } }
mit
C#
1e76c830908f21f8b25ddcbb2f93aa2a99106b0e
clean up whitespace
mgutekunst/ace-jump,jsturtevant/ace-jump
AceJump/LetterReference.xaml.cs
AceJump/LetterReference.xaml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace AceJump { /// <summary> /// Interaction logic for LetterReference.xaml /// </summary> public partial class LetterReference : UserControl { public const int PADDING = 5; public LetterReference(string referenceLetter, Rect bounds) { InitializeComponent(); this.Content = referenceLetter.ToUpper(); this.Background = Brushes.GreenYellow; // give font some room this.Width = bounds.Width + (PADDING * 2); this.Height = bounds.Height + (PADDING * 2); this.Padding = new Thickness(PADDING); // make it stand out this.FontWeight = FontWeights.ExtraBold; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace AceJump { /// <summary> /// Interaction logic for LetterReference.xaml /// </summary> public partial class LetterReference : UserControl { public const int PADDING = 5; public LetterReference(string referenceLetter, Rect bounds) { InitializeComponent(); this.Content = referenceLetter.ToUpper(); this.Background = Brushes.GreenYellow; // give font some room this.Width = bounds.Width + (PADDING * 2); this.Height = bounds.Height + (PADDING * 2); this.Padding = new Thickness(PADDING); // make it stand out this.FontWeight = FontWeights.ExtraBold; } } }
mit
C#
30dca2a094ce63eeede1278835cb4f63f7640468
Make card image types optional
timheuer/alexa-skills-dotnet,stoiveyp/alexa-skills-dotnet
Alexa.NET/Response/CardImage.cs
Alexa.NET/Response/CardImage.cs
using Newtonsoft.Json; namespace Alexa.NET.Response { public class CardImage { [JsonProperty("smallImageUrl",NullValueHandling = NullValueHandling.Ignore)] public string SmallImageUrl { get; set; } [JsonProperty("largeImageUrl", NullValueHandling = NullValueHandling.Ignore)] public string LargeImageUrl { get; set; } } }
using Newtonsoft.Json; namespace Alexa.NET.Response { public class CardImage { [JsonProperty("smallImageUrl")] [JsonRequired] public string SmallImageUrl { get; set; } [JsonProperty("largeImageUrl")] [JsonRequired] public string LargeImageUrl { get; set; } } }
mit
C#
be2295dbca8af09cc44f8d62457e035358f1a325
Update assembly to version 1.1.2
Brightspace/valence-sdk-dotnet-restsharp
lib/D2L.Extensibility.AuthSdk.Restsharp/Properties/AssemblyInfo.cs
lib/D2L.Extensibility.AuthSdk.Restsharp/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("D2L.Extensibility.AuthSdk.Restsharp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Desire2Learn")] [assembly: AssemblyProduct("D2L.Extensibility.AuthSdk.Restsharp")] [assembly: AssemblyCopyright("Copyright © Desire2Learn 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("be777b05-e524-4e94-9e59-b50300593ba5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.2.0")] [assembly: AssemblyFileVersion("1.1.2.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("D2L.Extensibility.AuthSdk.Restsharp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Desire2Learn")] [assembly: AssemblyProduct("D2L.Extensibility.AuthSdk.Restsharp")] [assembly: AssemblyCopyright("Copyright © Desire2Learn 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("be777b05-e524-4e94-9e59-b50300593ba5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
28e8327699a8267c08a5ff04e613c5afeed4a4d8
Make RoslynCodeGlobals State property generic
Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D
Dependencies/ScriptEngine.Roslyn/Roslyn/RoslynCodeGlobals.cs
Dependencies/ScriptEngine.Roslyn/Roslyn/RoslynCodeGlobals.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Test2d; namespace Test2d { /// <summary> /// /// </summary> public class RoslynCodeGlobals<T> { /// <summary> /// /// </summary> public EditorContext Context; /// <summary> /// /// </summary> public BaseShape[] Shapes; /// <summary> /// /// </summary> public T State; } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Test2d; namespace Test2d { /// <summary> /// /// </summary> public class RoslynCodeGlobals { /// <summary> /// /// </summary> public EditorContext Context; /// <summary> /// /// </summary> public BaseShape[] Shapes; /// <summary> /// /// </summary> public object State; } }
mit
C#