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 |
|---|---|---|---|---|---|---|---|---|
63941afa19556b0f21ac9d23cadf0be4c7b264c3
|
Remove unnecessary brackets
|
lukedrury/super-market-kata
|
supermarketkata/engine/rules/PercentageDiscount.cs
|
supermarketkata/engine/rules/PercentageDiscount.cs
|
using System;
using engine.core;
namespace engine.rules
{
public class PercentageDiscount : Rule
{
private readonly string m_ApplicableItemName;
private readonly double m_Percentage;
public PercentageDiscount(string applicableItemName, int percentage)
{
m_ApplicableItemName = applicableItemName;
m_Percentage = percentage;
}
public override Basket Apply(Basket basket)
{
var discountedBasket = new Basket();
foreach (var item in basket)
{
discountedBasket.Add(item);
if (item.Name.Equals(m_ApplicableItemName) && !item.UsedInOffer)
{
var discountToApply = -(int) Math.Ceiling(item.Price * m_Percentage / 100);
discountedBasket.Add(string.Format("{0}:{1}% discount", m_ApplicableItemName, m_Percentage), discountToApply);
}
}
return discountedBasket;
}
}
}
|
using System;
using engine.core;
namespace engine.rules
{
public class PercentageDiscount : Rule
{
private readonly string m_ApplicableItemName;
private readonly double m_Percentage;
public PercentageDiscount(string applicableItemName, int percentage)
{
m_ApplicableItemName = applicableItemName;
m_Percentage = percentage;
}
public override Basket Apply(Basket basket)
{
var discountedBasket = new Basket();
foreach (var item in basket)
{
discountedBasket.Add(item);
if (item.Name.Equals(m_ApplicableItemName) && !item.UsedInOffer)
{
var discountToApply = -(int) Math.Ceiling(item.Price * (m_Percentage / 100));
discountedBasket.Add(string.Format("{0}:{1}% discount", m_ApplicableItemName, m_Percentage), discountToApply);
}
}
return discountedBasket;
}
}
}
|
mit
|
C#
|
19c925517b59a9fd25b2f51eb5daaa676a1f5dbf
|
Copy Updates Other Copy elements of the Same Type on the Same Page When Saving
|
tommcclean/PortalCMS,tommcclean/PortalCMS,tommcclean/PortalCMS
|
Portal.CMS.Web/Areas/Admin/Views/Copy/_Copy.cshtml
|
Portal.CMS.Web/Areas/Admin/Views/Copy/_Copy.cshtml
|
@model Portal.CMS.Entities.Entities.Copy.Copy
@using Portal.CMS.Web.Areas.Admin.Helpers;
@{
Layout = "";
var isAdmin = UserHelper.IsAdmin;
}
<script type="text/javascript">
$(document).ready(function () {
tinymce.init({
selector: '.copy-@(Model.CopyId).admin', inline: true, plugins: ['advlist autolink lists link image charmap anchor searchreplace visualblocks code fullscreen media table contextmenu paste'],
toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
setup:function(ed) {
ed.on('change', function(e) {
var dataParams = { "copyId": @Model.CopyId, "copyName": "@Model.CopyName", "copyBody": ed.getContent() };
$.ajax({data: dataParams, type: 'POST', cache: false, url: '/Admin/Copy/Inline'});
$('.copy-@(Model.CopyId)').html(ed.getContent());
});
}
});
});
</script>
<div class="copy-wrapper">
@if (isAdmin) { <div class="box-title">@Model.CopyName</div> }
<div class="@(UserHelper.IsAdmin ? "admin" : "") copy-@Model.CopyId copy-block">
@Html.Raw(Model.CopyBody)
</div>
</div>
|
@model Portal.CMS.Entities.Entities.Copy.Copy
@using Portal.CMS.Web.Areas.Admin.Helpers;
@{
Layout = "";
var isAdmin = UserHelper.IsAdmin;
}
<script type="text/javascript">
$(document).ready(function () {
tinymce.init({
selector: '#copy-@(Model.CopyId).admin', inline: true, plugins: ['advlist autolink lists link image charmap anchor searchreplace visualblocks code fullscreen media table contextmenu paste'],
toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
setup:function(ed) {
ed.on('change', function(e) {
var dataParams = { "copyId": @Model.CopyId, "copyName": "@Model.CopyName", "copyBody": ed.getContent() };
$.ajax({data: dataParams, type: 'POST', cache: false, url: '/Admin/Copy/Inline'});
});
}
});
});
</script>
<div class="copy-wrapper">
@if (isAdmin) { <div class="box-title">@Model.CopyName</div> }
<div id="copy-@Model.CopyId" class="@(UserHelper.IsAdmin ? "admin" : "") copy-block">
@Html.Raw(Model.CopyBody)
</div>
</div>
|
mit
|
C#
|
6ddb98b19d38ca1bafab57a141e75c714bb54903
|
add GitVersion for incrementing version
|
nrjohnstone/AmbientContext
|
build.cake
|
build.cake
|
#addin "Newtonsoft.Json"
#tool "nuget:?package=GitVersion.CommandLine"
#tool "nuget:?package=xunit.runner.console"
//////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
//////////////////////////////////////////////////////////////////////
// PREPARATION
//////////////////////////////////////////////////////////////////////
// Define directories.
var solutionDir = Directory("./");
var solutionFile = solutionDir + File("AmbientContext.sln");
var buildDir = Directory("./src/AmbientContext/bin") + Directory(configuration);
//////////////////////////////////////////////////////////////////////
// TASKS
//////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() =>
{
CleanDirectory(buildDir);
});
Task("Restore-NuGet-Packages")
.Does(() =>
{
NuGetRestore(solutionFile);
});
Task("Build")
.Does(() =>
{
if(IsRunningOnWindows())
{
// Use MSBuild
MSBuild(solutionFile, settings =>
settings.SetConfiguration(configuration));
}
else
{
// Use XBuild
XBuild(solutionFile, settings =>
settings.SetConfiguration(configuration));
}
});
Task("Rebuild")
.IsDependentOn("Clean")
.IsDependentOn("Restore-NuGet-Packages")
.IsDependentOn("Build")
.IsDependentOn("Run-Unit-Tests")
.Does(() =>
{ });
Task("Run-Unit-Tests")
.Does(() =>
{
var testAssemblies = GetFiles(".\\test\\AmbientContext.Tests\\bin\\" + configuration + "\\net451\\*\\AmbientContext.Tests.dll");
Console.WriteLine(testAssemblies.Count());
XUnit2(testAssemblies);
});
Task("Get-DNV")
.ContinueOnError()
.Does(() =>
{
if (!FileExists("./tools/dnv.exe")) {
if (FileExists("./tools/updeps.exe"))
DeleteFile("./tools/updeps.exe");
DownloadFile("https://github.com/PhilipDaniels/dotnetversioning/raw/master/dnv.zip", "./tools/dnv.zip");
Unzip("./tools/dnv.zip", "./tools");
}
});
Task("Update-Version")
.Does(() =>
{
GitVersion(new GitVersionSettings {
UpdateAssemblyInfo = true});
});
//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("Build")
.IsDependentOn("Run-Unit-Tests");
//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////
RunTarget(target);
|
#addin "Newtonsoft.Json"
#tool "nuget:?package=xunit.runner.console"
//////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
//////////////////////////////////////////////////////////////////////
// PREPARATION
//////////////////////////////////////////////////////////////////////
// Define directories.
var solutionDir = Directory("./");
var solutionFile = solutionDir + File("AmbientContext.sln");
var buildDir = Directory("./src/AmbientContext/bin") + Directory(configuration);
//////////////////////////////////////////////////////////////////////
// TASKS
//////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() =>
{
CleanDirectory(buildDir);
});
Task("Restore-NuGet-Packages")
.Does(() =>
{
NuGetRestore(solutionFile);
});
Task("Build")
.Does(() =>
{
if(IsRunningOnWindows())
{
// Use MSBuild
MSBuild(solutionFile, settings =>
settings.SetConfiguration(configuration));
}
else
{
// Use XBuild
XBuild(solutionFile, settings =>
settings.SetConfiguration(configuration));
}
});
Task("Rebuild")
.IsDependentOn("Clean")
.IsDependentOn("Restore-NuGet-Packages")
.IsDependentOn("Build")
.IsDependentOn("Run-Unit-Tests")
.Does(() =>
{ });
Task("Run-Unit-Tests")
.Does(() =>
{
var testAssemblies = GetFiles(".\\test\\AmbientContext.Tests\\bin\\" + configuration + "\\net451\\*\\AmbientContext.Tests.dll");
Console.WriteLine(testAssemblies.Count());
XUnit2(testAssemblies);
});
Task("Get-DNV")
.ContinueOnError()
.Does(() =>
{
if (!FileExists("./tools/dnv.exe")) {
if (FileExists("./tools/updeps.exe"))
DeleteFile("./tools/updeps.exe");
DownloadFile("https://github.com/PhilipDaniels/dotnetversioning/raw/master/dnv.zip", "./tools/dnv.zip");
Unzip("./tools/dnv.zip", "./tools");
}
});
//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("Build")
.IsDependentOn("Run-Unit-Tests");
//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////
RunTarget(target);
|
mit
|
C#
|
0a5ffb934229fdbd71eddcd9a6371d473fa29e16
|
Fix output path for nuget package.
|
sqeezy/FibonacciHeap,sqeezy/FibonacciHeap
|
build.cake
|
build.cake
|
#tool "nuget:?package=xunit.runner.console"
var target = Argument("target", "Default");
var outputDir = "./bin";
Task("Default")
.IsDependentOn("Xunit")
.Does(() =>
{
});
Task("Xunit")
.IsDependentOn("Build")
.Does(()=>
{
DotNetCoreTest("./src/FibonacciHeap.Tests/FibonacciHeap.Tests.csproj");
});
Task("Build")
.IsDependentOn("NugetRestore")
.Does(()=>
{
DotNetCoreMSBuild("FibonacciHeap.sln");
});
Task("NugetRestore")
.IsDependentOn("Clean")
.Does(()=>
{
DotNetCoreRestore();
});
Task("NugetPack")
.IsDependentOn("Clean")
.Does(()=>
{
var settings = new DotNetCorePackSettings
{
Configuration = "Release",
OutputDirectory = "nupkgs"
};
DotNetCorePack("src/FibonacciHeap", settings);
});
Task("Clean")
.Does(()=>
{
CleanDirectories("**/bin/**");
CleanDirectories("**/obj/**");
CleanDirectories("nupkgs");
});
RunTarget(target);
|
#tool "nuget:?package=xunit.runner.console"
var target = Argument("target", "Default");
var outputDir = "./bin";
Task("Default")
.IsDependentOn("Xunit")
.Does(() =>
{
});
Task("Xunit")
.IsDependentOn("Build")
.Does(()=>
{
DotNetCoreTest("./src/FibonacciHeap.Tests/FibonacciHeap.Tests.csproj");
});
Task("Build")
.IsDependentOn("NugetRestore")
.Does(()=>
{
DotNetCoreMSBuild("FibonacciHeap.sln");
});
Task("NugetRestore")
.IsDependentOn("Clean")
.Does(()=>
{
DotNetCoreRestore();
});
Task("NugetPack")
.IsDependentOn("Build")
.Does(()=>
{
var settings = new DotNetCorePackSettings
{
Configuration = "Release",
OutputDirectory = "../../nupkgs"
};
DotNetCorePack("src/FibonacciHeap", settings);
});
Task("Clean")
.Does(()=>
{
CleanDirectories("**/bin/**");
CleanDirectories("**/obj/**");
CleanDirectories("nupkgs");
});
RunTarget(target);
|
mit
|
C#
|
aa331ae4e959c93e9c98ac56b7d0b7cdb3c4560b
|
Apply suggestions from code review
|
mjedrzejek/nunit,mjedrzejek/nunit,nunit/nunit,nunit/nunit
|
src/NUnitFramework/framework/Attributes/TypeGetMemberExtension.cs
|
src/NUnitFramework/framework/Attributes/TypeGetMemberExtension.cs
|
using System;
using System.Collections.Generic;
using System.Reflection;
namespace NUnit.Framework
{
internal static class TypeGetMemberExtension
{
/// <summary>
/// Searches for the specified members, using the specified binding constraints.
/// </summary>
/// <remarks>
/// Similar to <see cref="Type.GetMember(string, BindingFlags)"/> but also finds private static members from the base class.
/// </remarks>
/// <param name="type">The type to find the members from.</param>
/// <param name="name">The string containing the name of the members to get.</param>
/// <param name="flags">A bitwise combination of the enumeration values that specify how the search is conducted.</param>
/// <returns></returns>
public static MemberInfo[] GetMemberIncludingFromBase(this Type type, string name, BindingFlags flags)
{
var members = new List<MemberInfo>();
do
{
members.AddRange(type.GetMember(name, flags));
}
while ((type = type.BaseType) != null);
return members.ToArray();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Reflection;
namespace NUnit.Framework
{
internal static class TypeGetMemberExtension
{
/// <summary>
/// Searches for the specified members, using the specified binding constraints.
/// </summary>
/// <remarks>
/// Similar to <see cref="Type.GetMember(string, BindingFlags)"/> but also finds private static members from the base clas.
/// </remarks>
/// <param name="type">The type to find the member from.</param>
/// <param name="name">The string containing the name of the members to get.</param>
/// <param name="flags">A bitwise combination of the enumeration values that specify how the search is conducted.</param>
/// <returns></returns>
public static MemberInfo[] GetMemberIncludingFromBase(this Type type, string name, BindingFlags flags)
{
var members = new List<MemberInfo>();
do
{
members.AddRange(type.GetMember(name, flags));
}
while ((type = type.BaseType) != null);
return members.ToArray();
}
}
}
|
mit
|
C#
|
8ab062336d102b702d19abc38bcce81bbb2fe728
|
Update to Problem 2. Bonus Score
|
SimoPrG/CSharpPart1Homework
|
Conditional-Statements-Homework/BonusScore/BonusScore.cs
|
Conditional-Statements-Homework/BonusScore/BonusScore.cs
|
/*Problem 2. Bonus Score
Write a program that applies bonus score to given score in the range [1…9] by the following rules:
If the score is between 1 and 3, the program multiplies it by 10.
If the score is between 4 and 6, the program multiplies it by 100.
If the score is between 7 and 9, the program multiplies it by 1000.
If the score is 0 or more than 9, the program prints “invalid score”.
Examples:
score result
2 20
4 400
9 9000
-1 invalid score
10 invalid score
*/
using System;
class BonusScore
{
static void Main()
{
Console.Title = "Bonus Score"; //Changing the title of the console.
Console.WriteLine("Please, enter your score to get the bonus!");
Console.Write("score: ");
int score = int.Parse(Console.ReadLine());
int bonus;
switch (score)
{
case 1:
case 2:
case 3: bonus = score * 10; Console.WriteLine("\r\nresult\r\n" + bonus); break;
case 4:
case 5:
case 6: bonus = score * 100; Console.WriteLine("\r\nresult\r\n" + bonus); break;
case 7:
case 8:
case 9: bonus = score * 1000; Console.WriteLine("\r\nresult\r\n" + bonus); break;
default: Console.WriteLine("\r\nresult\r\ninvalid score"); break;
}
Console.ReadKey(); // Keeping the console opened.
}
}
|
/*Problem 2. Bonus Score
Write a program that applies bonus score to given score in the range [1…9] by the following rules:
If the score is between 1 and 3, the program multiplies it by 10.
If the score is between 4 and 6, the program multiplies it by 100.
If the score is between 7 and 9, the program multiplies it by 1000.
If the score is 0 or more than 9, the program prints “invalid score”.
Examples:
score result
2 20
4 400
9 9000
-1 invalid score
10 invalid score
*/
using System;
class BonusScore
{
static void Main()
{
Console.Title = "Bonus Score"; //Changing the title of the console.
Console.WriteLine("Please, enter your score to get the bonus!");
Console.Write("score: ");
int score = int.Parse(Console.ReadLine());
int bonus;
switch (score)
{
case 1:
case 2:
case 3: bonus = score * 10; Console.WriteLine("\nresult\n" + bonus); break;
case 4:
case 5:
case 6: bonus = score * 100; Console.WriteLine("\nresult\n" + bonus); break;
case 7:
case 8:
case 9: bonus = score * 1000; Console.WriteLine("\nresult\n" + bonus); break;
default: Console.WriteLine("\nresult\ninvalid score"); break;
}
Console.ReadKey(); // Keeping the console opened.
}
}
|
mit
|
C#
|
22661520effcc7a715a32da7c7f41cc49a70728f
|
Fix Paket classifier and allow syntax higlighting for groups
|
hmemcpy/Paket.VisualStudio,fsprojects/Paket.VisualStudio,mrinaldi/Paket.VisualStudio
|
src/Paket.VisualStudio/IntelliSense/Classifier/PaketClassifier.cs
|
src/Paket.VisualStudio/IntelliSense/Classifier/PaketClassifier.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.Language.StandardClassification;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
namespace Paket.VisualStudio.IntelliSense.Classifier
{
internal class PaketClassifier : IClassifier
{
private readonly IClassificationType keyword, comment;
private static readonly HashSet<string> validKeywords = new HashSet<string>
{
"source", "nuget", "github", "gist", "http",
"content", "reference", "redirects", "group"
};
public static IEnumerable<string> ValidKeywords
{
get { return validKeywords; }
}
internal PaketClassifier(IClassificationTypeRegistryService registry)
{
keyword = registry.GetClassificationType(PredefinedClassificationTypeNames.Keyword);
comment = registry.GetClassificationType(PredefinedClassificationTypeNames.Comment);
}
public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
{
IList<ClassificationSpan> spans = new List<ClassificationSpan>();
string text = span.GetText();
int index = text.IndexOf("#", StringComparison.Ordinal);
if (index > -1)
{
var result = new SnapshotSpan(span.Snapshot, span.Start + index, text.Length - index);
spans.Add(new ClassificationSpan(result, comment));
}
if (index == -1 || index > 0)
{
var trimmed = text.TrimStart();
var offset = text.Length - trimmed.Length;
string[] args = trimmed.Split(' ');
if (args.Length >= 2 && ValidKeywords.Contains(args[0].Trim().ToLowerInvariant()))
{
var result = new SnapshotSpan(span.Snapshot, span.Start + offset, args[0].Length);
spans.Add(new ClassificationSpan(result, keyword));
}
}
return spans;
}
public event EventHandler<ClassificationChangedEventArgs> ClassificationChanged = delegate { };
public void OnClassificationChanged(SnapshotSpan span)
{
ClassificationChanged(this, new ClassificationChangedEventArgs(span));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.Language.StandardClassification;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
namespace Paket.VisualStudio.IntelliSense.Classifier
{
internal class PaketClassifier : IClassifier
{
private readonly IClassificationType keyword, comment;
private static readonly HashSet<string> validKeywords = new HashSet<string>
{
"source", "nuget", "github", "gist", "http",
"content", "reference", "redirects"
};
public static IEnumerable<string> ValidKeywords
{
get { return validKeywords; }
}
internal PaketClassifier(IClassificationTypeRegistryService registry)
{
keyword = registry.GetClassificationType(PredefinedClassificationTypeNames.Keyword);
comment = registry.GetClassificationType(PredefinedClassificationTypeNames.Comment);
}
public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
{
IList<ClassificationSpan> spans = new List<ClassificationSpan>();
string text = span.GetText();
int index = text.IndexOf("#", StringComparison.Ordinal);
if (index > -1)
{
var result = new SnapshotSpan(span.Snapshot, span.Start + index, text.Length - index);
spans.Add(new ClassificationSpan(result, comment));
}
if (index == -1 || index > 0)
{
string[] args = text.Split(' ');
if (args.Length >= 2 && ValidKeywords.Contains(args[0].Trim().ToLowerInvariant()))
{
var result = new SnapshotSpan(span.Snapshot, span.Start, args[0].Length);
spans.Add(new ClassificationSpan(result, keyword));
}
}
return spans;
}
public event EventHandler<ClassificationChangedEventArgs> ClassificationChanged = delegate { };
public void OnClassificationChanged(SnapshotSpan span)
{
ClassificationChanged(this, new ClassificationChangedEventArgs(span));
}
}
}
|
mit
|
C#
|
7e47c72f4240c871c47e7fc9c09904d1e6fcee0a
|
Change extension method default parameters to use constants
|
whir1/serilog-sinks-graylog
|
src/Serilog.Sinks.Graylog/LoggerConfigurationGrayLogExtensions.cs
|
src/Serilog.Sinks.Graylog/LoggerConfigurationGrayLogExtensions.cs
|
using Serilog.Configuration;
using Serilog.Core;
using Serilog.Events;
using Serilog.Sinks.Graylog.Helpers;
using Serilog.Sinks.Graylog.Transport;
namespace Serilog.Sinks.Graylog
{
public static class LoggerConfigurationGrayLogExtensions
{
public static LoggerConfiguration Graylog(this LoggerSinkConfiguration loggerSinkConfiguration,
GraylogSinkOptions options)
{
var sink = (ILogEventSink) new GraylogSink(options);
return loggerSinkConfiguration.Sink(sink, options.MinimumLogEventLevel);
}
public static LoggerConfiguration Graylog(this LoggerSinkConfiguration loggerSinkConfiguration,
string hostnameOrAddress,
int port,
TransportType transportType,
LogEventLevel minimumLogEventLevel = LevelAlias.Minimum,
MessageIdGeneratortype messageIdGeneratorType = GraylogSinkOptions.DefaultMessageGeneratorType,
int shortMessageMaxLength = GraylogSinkOptions.DefaultShortMessageMaxLength,
int stackTraceDepth = GraylogSinkOptions.DefaultStackTraceDepth,
string facility = GraylogSinkOptions.DefaultFacility
)
{
var options = new GraylogSinkOptions
{
HostnameOrAdress = hostnameOrAddress,
Port = port,
TransportType = transportType,
MinimumLogEventLevel = minimumLogEventLevel,
MessageGeneratorType = messageIdGeneratorType,
ShortMessageMaxLength = shortMessageMaxLength,
StackTraceDepth = stackTraceDepth,
Facility = facility
};
return loggerSinkConfiguration.Graylog(options);
}
}
}
|
using Serilog.Configuration;
using Serilog.Core;
using Serilog.Events;
using Serilog.Sinks.Graylog.Helpers;
using Serilog.Sinks.Graylog.Transport;
namespace Serilog.Sinks.Graylog
{
public static class LoggerConfigurationGrayLogExtensions
{
public static LoggerConfiguration Graylog(this LoggerSinkConfiguration loggerSinkConfiguration,
GraylogSinkOptions options)
{
var sink = (ILogEventSink) new GraylogSink(options);
return loggerSinkConfiguration.Sink(sink, options.MinimumLogEventLevel);
}
public static LoggerConfiguration Graylog(this LoggerSinkConfiguration loggerSinkConfiguration,
string hostnameOrAddress,
int port,
TransportType transportType,
LogEventLevel minimumLogEventLevel = LevelAlias.Minimum,
MessageIdGeneratortype messageIdGeneratorType = GraylogSinkOptions.DefaultMessageGeneratorType,
int shortMessageMaxLength = 500,
int stackTraceDepth = 10,
string facility = GraylogSinkOptions.DefaultFacility
)
{
var options = new GraylogSinkOptions
{
HostnameOrAdress = hostnameOrAddress,
Port = port,
TransportType = transportType,
MinimumLogEventLevel = minimumLogEventLevel,
MessageGeneratorType = messageIdGeneratorType,
ShortMessageMaxLength = shortMessageMaxLength,
StackTraceDepth = stackTraceDepth,
Facility = facility
};
return loggerSinkConfiguration.Graylog(options);
}
}
}
|
mit
|
C#
|
16829b929c4ca3d98deb0ddc13a404c44774f40c
|
Optimize away empty string literals.
|
csainty/Veil,csainty/Veil
|
Src/Veil/Compiler/VeilTemplateCompiler.EmitWriteLiteral.cs
|
Src/Veil/Compiler/VeilTemplateCompiler.EmitWriteLiteral.cs
|
using Veil.Parser;
namespace Veil.Compiler
{
internal partial class VeilTemplateCompiler<T>
{
private void EmitWriteLiteral(SyntaxTreeNode.WriteLiteralNode node)
{
if (string.IsNullOrEmpty(node.LiteralContent)) return;
LoadWriterToStack();
emitter.LoadConstant(node.LiteralContent);
CallWriteFor(typeof(string));
}
}
}
|
using Veil.Parser;
namespace Veil.Compiler
{
internal partial class VeilTemplateCompiler<T>
{
private void EmitWriteLiteral(SyntaxTreeNode.WriteLiteralNode node)
{
LoadWriterToStack();
emitter.LoadConstant(node.LiteralContent);
CallWriteFor(typeof(string));
}
}
}
|
mit
|
C#
|
26271971172d2c6d20e5a0aadd89f40b5bcabdbd
|
Add ability to enter commands
|
StanislavUshakov/ArduinoWindowsRemoteControl
|
ArduinoWindowsRemoteControl/UI/EditCommandForm.cs
|
ArduinoWindowsRemoteControl/UI/EditCommandForm.cs
|
using ArduinoWindowsRemoteControl.Helpers;
using ArduinoWindowsRemoteControl.Interfaces;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ArduinoWindowsRemoteControl.UI
{
public partial class EditCommandForm : Form
{
private List<int> _pressedButtons = new List<int>();
private bool _isKeyStrokeEnabled = false;
public EditCommandForm()
{
InitializeComponent();
cbRemoteCommand.Items.AddRange(EnumHelpers.GetAvailableEnumValues<RemoteCommand>().ToArray());
}
private void btCancel_Click(object sender, EventArgs e)
{
Close();
}
private void tbCommand_KeyDown(object sender, KeyEventArgs e)
{
if (!_pressedButtons.Contains(e.KeyValue))
{
//key command ended, start new one
if (_pressedButtons.Count == 0)
{
_isKeyStrokeEnabled = false;
}
if (_isKeyStrokeEnabled)
{
tbCommand.Text += "-";
}
else
{
if (tbCommand.Text.Length > 0)
tbCommand.Text += ",";
}
tbCommand.Text += WinAPIHelpers.GetKeyStringForVirtualCode((byte)e.KeyValue);
tbCommand.SelectionStart = tbCommand.Text.Length;
_pressedButtons.Add(e.KeyValue);
}
else
{
if (_pressedButtons.Last() == e.KeyValue)
{
_isKeyStrokeEnabled = true;
}
}
e.Handled = true;
}
private void tbCommand_KeyUp(object sender, KeyEventArgs e)
{
_pressedButtons.Remove(e.KeyValue);
e.Handled = true;
}
private void tbCommand_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
}
}
|
using ArduinoWindowsRemoteControl.Helpers;
using ArduinoWindowsRemoteControl.Interfaces;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ArduinoWindowsRemoteControl.UI
{
public partial class EditCommandForm : Form
{
private List<int> _pressedButtons = new List<int>();
public EditCommandForm()
{
InitializeComponent();
cbRemoteCommand.Items.AddRange(EnumHelpers.GetAvailableEnumValues<RemoteCommand>().ToArray());
}
private void btCancel_Click(object sender, EventArgs e)
{
Close();
}
private void tbCommand_KeyDown(object sender, KeyEventArgs e)
{
if (!_pressedButtons.Contains(e.KeyValue))
{
tbCommand.Text += WinAPIHelpers.GetKeyStringForVirtualCode((byte)e.KeyValue);
_pressedButtons.Add(e.KeyValue);
}
e.Handled = true;
}
private void tbCommand_KeyUp(object sender, KeyEventArgs e)
{
_pressedButtons.Remove(e.KeyValue);
e.Handled = true;
}
private void tbCommand_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
}
}
|
mit
|
C#
|
74b3797b9f72722d406fe47307d2652ffe093814
|
Make one of two red tests green by implementing basic support for the Values-method with Id-Property.
|
ExRam/ExRam.Gremlinq
|
ExRam.Gremlinq/Gremlin/Steps/ValuesGremlinStep.cs
|
ExRam.Gremlinq/Gremlin/Steps/ValuesGremlinStep.cs
|
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Linq.Expressions;
namespace ExRam.Gremlinq
{
public sealed class ValuesGremlinStep<TSource, TTarget> : NonTerminalGremlinStep
{
private readonly Expression<Func<TSource, TTarget>>[] _projections;
public ValuesGremlinStep(Expression<Func<TSource, TTarget>>[] projections)
{
this._projections = projections;
}
public override IEnumerable<TerminalGremlinStep> Resolve(IGraphModel model)
{
var keys = this._projections
.Select(projection =>
{
if (projection.Body is MemberExpression memberExpression)
return model.GetIdentifier(memberExpression.Member.Name);
throw new NotSupportedException();
})
.ToArray();
var numberOfIdSteps = keys
.OfType<T>()
.Count(x => x == T.Id);
var propertyKeys = keys
.OfType<string>()
.Cast<object>()
.ToArray();
if (numberOfIdSteps > 1 || (numberOfIdSteps > 0 && propertyKeys.Length > 0))
throw new NotSupportedException();
if (numberOfIdSteps > 0)
yield return new TerminalGremlinStep("id");
else
{
yield return new TerminalGremlinStep(
"values",
propertyKeys
.ToImmutableList());
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Linq.Expressions;
namespace ExRam.Gremlinq
{
public sealed class ValuesGremlinStep<TSource, TTarget> : NonTerminalGremlinStep
{
private readonly Expression<Func<TSource, TTarget>>[] _projections;
public ValuesGremlinStep(Expression<Func<TSource, TTarget>>[] projections)
{
this._projections = projections;
}
public override IEnumerable<TerminalGremlinStep> Resolve(IGraphModel model)
{
yield return new TerminalGremlinStep(
"values",
this._projections
.Select(projection =>
{
if (projection.Body is MemberExpression memberExpression)
return model.GetIdentifier(memberExpression.Member.Name);
throw new NotSupportedException();
})
.ToImmutableList());
}
}
}
|
mit
|
C#
|
ecb7537dc978de646d3ff3ccb27b73ba18794c9f
|
Make it configurable if high or low throws.
|
GMJS/gmjs_ocs_dpt
|
IPOCS_Programmer/ObjectTypes/PointsMotor_Pulse.cs
|
IPOCS_Programmer/ObjectTypes/PointsMotor_Pulse.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IPOCS_Programmer.ObjectTypes
{
public class PointsMotor_Pulse : PointsMotor
{
public override byte motorTypeId { get { return 1; } }
public byte ThrowLeftOutput { get; set; }
public byte ThrowRightOutput { get; set; }
public byte positionPin { get; set; }
public bool reverseStatus { get; set; }
public bool lowToThrow { get; set; }
public override List<byte> Serialize()
{
var vector = new List<byte>();
vector.Add(motorTypeId);
vector.Add(this.ThrowLeftOutput);
vector.Add(this.ThrowRightOutput);
vector.Add(positionPin);
vector.Add((byte)(reverseStatus ? 1 : 0));
vector.Add((byte)(lowToThrow ? 1 : 0));
return vector;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IPOCS_Programmer.ObjectTypes
{
public class PointsMotor_Pulse : PointsMotor
{
public override byte motorTypeId { get { return 1; } }
public byte ThrowLeftOutput { get; set; }
public byte ThrowRightOutput { get; set; }
public byte positionPin { get; set; }
public bool reverseStatus { get; set; }
public override List<byte> Serialize()
{
var vector = new List<byte>();
vector.Add(motorTypeId);
vector.Add(this.ThrowLeftOutput);
vector.Add(this.ThrowRightOutput);
vector.Add(positionPin);
vector.Add((byte)(reverseStatus ? 1 : 0));
return vector;
}
}
}
|
mit
|
C#
|
be95b6e458013e0adc69de041794ab0c8928251f
|
fix Upgrade_20210829_TypeScript44
|
signumsoftware/framework,signumsoftware/framework
|
Signum.Upgrade/Upgrades/Upgrade_20210829_TypeScript44.cs
|
Signum.Upgrade/Upgrades/Upgrade_20210829_TypeScript44.cs
|
using Signum.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace Signum.Upgrade.Upgrades
{
class Upgrade_20210829_TypeScript44 : CodeUpgradeBase
{
public override string Description => "Update to TS 4.4";
public override void Execute(UpgradeContext uctx)
{
uctx.ChangeCodeFile(@"Southwind.React/package.json", file =>
{
file.UpdateNpmPackage("ts-loader", "9.2.5");
file.UpdateNpmPackage("typescript", "4.4.2");
});
uctx.ChangeCodeFile(@"Southwind.React/Southwind.React.csproj", file =>
{
file.UpdateNugetReference("Microsoft.TypeScript.MSBuild", "4.4.2");
});
}
}
}
|
using Signum.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace Signum.Upgrade.Upgrades
{
class Upgrade_20210829_TypeScript44 : CodeUpgradeBase
{
public override string Description => "Update to TS 4.4";
public override void Execute(UpgradeContext uctx)
{
uctx.ChangeCodeFile(@"Southwind.React/package.json", file =>
{
file.UpdateNpmPackage("ts-loader", "9.2.5");
file.UpdateNpmPackage("typescript", "4.4.2");
});
uctx.ChangeCodeFile(@"Southwind.React.csproj", file =>
{
file.UpdateNugetReference("Microsoft.TypeScript.MSBuild", "4.4.2");
});
}
}
}
|
mit
|
C#
|
a034849a1eb067c829d3c3c8fe89b644d807f580
|
Fix bug: allow anonymous users to see the amount of likes and users who like
|
erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner
|
Oogstplanner.Web/Controllers/FriendsController.cs
|
Oogstplanner.Web/Controllers/FriendsController.cs
|
using System;
using System.Linq;
using System.Web.Mvc;
using Newtonsoft.Json;
using Oogstplanner.Services;
using Oogstplanner.Web.Utilities.Helpers;
namespace Oogstplanner.Web.Controllers
{
[Authorize]
public sealed class FriendsController : Controller
{
readonly ICalendarLikingService calendarLikingService;
public FriendsController(ICalendarLikingService calendarLikingService)
{
if (calendarLikingService == null)
{
throw new ArgumentNullException("calendarLikingService");
}
this.calendarLikingService = calendarLikingService;
}
//
// POST /zaaikalender/like
[HttpPost]
public JsonResult Like(int calendarId)
{
try
{
bool wasUnlike;
calendarLikingService.Like(calendarId, out wasUnlike);
return Json(new { success = true, wasUnlike });
}
catch (Exception ex)
{
// TODO: Implement logging
return Json(new { success = false });
}
}
//
// GET /zaaikalender/{calendarId}/aantal-likes
[HttpGet]
[AllowAnonymous]
public ActionResult GetLikesCount(int calendarId)
{
int amountOfLikes = calendarLikingService.GetLikes(calendarId).Count();
return new JsonStringResult(amountOfLikes.ToString());
}
//
// GET /zaaikalender/{calendarId}/gebruikers-die-liken
[HttpGet]
[AllowAnonymous]
public ContentResult GetLikesUserNames(int calendarId)
{
var users = calendarLikingService.GetLikes(calendarId).Select(l => l.User.Name);
var usersJson = JsonConvert.SerializeObject(users);
return new JsonStringResult(usersJson);
}
}
}
|
using System;
using System.Linq;
using System.Web.Mvc;
using Newtonsoft.Json;
using Oogstplanner.Services;
using Oogstplanner.Web.Utilities.Helpers;
namespace Oogstplanner.Web.Controllers
{
[Authorize]
public sealed class FriendsController : Controller
{
readonly ICalendarLikingService calendarLikingService;
public FriendsController(ICalendarLikingService calendarLikingService)
{
if (calendarLikingService == null)
{
throw new ArgumentNullException("calendarLikingService");
}
this.calendarLikingService = calendarLikingService;
}
//
// POST /zaaikalender/like
[HttpPost]
public JsonResult Like(int calendarId)
{
try
{
bool wasUnlike;
calendarLikingService.Like(calendarId, out wasUnlike);
return Json(new { success = true, wasUnlike });
}
catch (Exception ex)
{
// TODO: Implement logging
return Json(new { success = false });
}
}
//
// GET /zaaikalender/aantallikes/{calendarId}
[HttpGet]
public ActionResult GetLikesCount(int calendarId)
{
int amountOfLikes = calendarLikingService.GetLikes(calendarId).Count();
return new JsonStringResult(amountOfLikes.ToString());
}
public ContentResult GetLikesUserNames(int calendarId)
{
var users = calendarLikingService.GetLikes(calendarId).Select(l => l.User.Name);
var usersJson = JsonConvert.SerializeObject(users);
return new JsonStringResult(usersJson);
}
}
}
|
mit
|
C#
|
73e011f780da92384a3f8a8039afb93b28a883ac
|
Update StringLocalizerMonitorOptions.cs
|
tiksn/TIKSN-Framework
|
TIKSN.Core/Localization/StringLocalizerMonitorOptions.cs
|
TIKSN.Core/Localization/StringLocalizerMonitorOptions.cs
|
using Microsoft.Extensions.Logging;
namespace TIKSN.Localization
{
public class StringLocalizerMonitorOptions
{
public LogLevel LogLevel { get; set; }
}
}
|
using Microsoft.Extensions.Logging;
namespace TIKSN.Localization
{
public class StringLocalizerMonitorOptions
{
public LogLevel LogLevel { get; set; }
}
}
|
mit
|
C#
|
d2d518e475d0f9147130b15b2eddc18fa3a28f2c
|
add parameters
|
AxelAndersen/quickpay-dotnet-client,QuickPay/quickpay-dotnet-client
|
QuickPay.IntegrationTests/RestClientSmokeTests.cs
|
QuickPay.IntegrationTests/RestClientSmokeTests.cs
|
using System;
using NUnit.Framework;
using Quickpay;
namespace QuickPay.IntegrationTests
{
[TestFixture]
public class RestClientSmokeTests
{
[Test]
public void CanPingGetApiWithCredentials()
{
var sut = new QuickPayRestClient(QpConfig.Username, QpConfig.Password);
var result = sut.Ping();
StringAssert.Contains("Pong", result.Msg);
}
/*
[Test]
public async void CanPingGetApiWithApiKey()
{
var sut = new QuickPayRestClient(QpConfig.ApiKey);
var result = await sut.PingAsync();
StringAssert.Contains("Pong", result.Msg);
}
*/
[Test]
public void CanGetAclResourcesAsync()
{
var sut = new QuickPayRestClient(QpConfig.Username, QpConfig.Password);
var result = sut.AclResources(AccountType.Merchant, 1, 90);
Assert.AreNotEqual(0, result.Count);
Assert.NotNull(result[0].Description);
}
}
}
|
using System;
using NUnit.Framework;
using Quickpay;
namespace QuickPay.IntegrationTests
{
[TestFixture]
public class RestClientSmokeTests
{
[Test]
public void CanPingGetApiWithCredentials()
{
var sut = new QuickPayRestClient(QpConfig.Username, QpConfig.Password);
var result = sut.Ping();
StringAssert.Contains("Pong", result.Msg);
}
/*
[Test]
public async void CanPingGetApiWithApiKey()
{
var sut = new QuickPayRestClient(QpConfig.ApiKey);
var result = await sut.PingAsync();
StringAssert.Contains("Pong", result.Msg);
}
*/
[Test]
public void CanGetAclResourcesAsync()
{
var sut = new QuickPayRestClient(QpConfig.Username, QpConfig.Password);
var result = sut.AclResources();
Assert.AreNotEqual(0, result.Count);
Assert.NotNull(result[0].Description);
}
}
}
|
mit
|
C#
|
e6751e288d54f4cd974ba6656008893ec73ae0f0
|
Fix build. More #ifdef insanity.
|
ajayanandgit/mbunit-v3,mterwoord/mbunit-v3,ajayanandgit/mbunit-v3,mterwoord/mbunit-v3,ajayanandgit/mbunit-v3,xJom/mbunit-v3,xJom/mbunit-v3,Gallio/mbunit-v3,ajayanandgit/mbunit-v3,mterwoord/mbunit-v3,mterwoord/mbunit-v3,Gallio/mbunit-v3,ajayanandgit/mbunit-v3,xJom/mbunit-v3,Gallio/mbunit-v3,mterwoord/mbunit-v3,xJom/mbunit-v3,Gallio/mbunit-v3,xJom/mbunit-v3,xJom/mbunit-v3,Gallio/mbunit-v3,Gallio/mbunit-v3,ajayanandgit/mbunit-v3,mterwoord/mbunit-v3,Gallio/mbunit-v3
|
src/Extensions/ReSharper/Gallio.ReSharperRunner/Provider/Daemons/AnnotationDaemonStage.cs
|
src/Extensions/ReSharper/Gallio.ReSharperRunner/Provider/Daemons/AnnotationDaemonStage.cs
|
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// 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 Gallio.Loader;
using JetBrains.Application.Settings;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Daemon;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.UnitTestExplorer;
namespace Gallio.ReSharperRunner.Provider.Daemons
{
/// <summary>
/// This daemon stage adds support for displaying annotations produced by
/// the test exploration process.
/// </summary>
[DaemonStage(StagesBefore=new [] { typeof(UnitTestDaemonStage)})]
public class AnnotationDaemonStage : IDaemonStage
{
static AnnotationDaemonStage()
{
LoaderManager.InitializeAndSetupRuntimeIfNeeded();
}
#if RESHARPER_31 || RESHARPER_40 || RESHARPER_41
public IDaemonStageProcess CreateProcess(IDaemonProcess process)
#elif RESHARPER_61
public IDaemonStageProcess CreateProcess(IDaemonProcess process, IContextBoundSettingsStore settings, DaemonProcessKind processKind)
#else
public IDaemonStageProcess CreateProcess(IDaemonProcess process, DaemonProcessKind processKind)
#endif
{
return new AnnotationDaemonStageProcess(process);
}
#if RESHARPER_60
public ErrorStripeRequest NeedsErrorStripe(IPsiSourceFile sourceFile)
{
return GetErrorStripe();
}
#endif
#if RESHARPER_61
public ErrorStripeRequest NeedsErrorStripe(IPsiSourceFile sourceFile, IContextBoundSettingsStore settingsStore)
{
return GetErrorStripe();
}
#endif
public ErrorStripeRequest NeedsErrorStripe(IProjectFile projectFile)
{
return GetErrorStripe();
}
private static ErrorStripeRequest GetErrorStripe()
{
return ErrorStripeRequest.STRIPE_AND_ERRORS;
}
}
}
|
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// 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 Gallio.Loader;
using JetBrains.Application.Settings;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Daemon;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.UnitTestExplorer;
namespace Gallio.ReSharperRunner.Provider.Daemons
{
/// <summary>
/// This daemon stage adds support for displaying annotations produced by
/// the test exploration process.
/// </summary>
[DaemonStage(StagesBefore=new [] { typeof(UnitTestDaemonStage)})]
public class AnnotationDaemonStage : IDaemonStage
{
static AnnotationDaemonStage()
{
LoaderManager.InitializeAndSetupRuntimeIfNeeded();
}
#if RESHARPER_31 || RESHARPER_40 || RESHARPER_41
public IDaemonStageProcess CreateProcess(IDaemonProcess process)
#elif RESHARPER_61
public IDaemonStageProcess CreateProcess(IDaemonProcess process, IContextBoundSettingsStore settings, DaemonProcessKind processKind)
#else
public IDaemonStageProcess CreateProcess(IDaemonProcess process, DaemonProcessKind processKind)
#endif
{
return new AnnotationDaemonStageProcess(process);
}
#if RESHARPER_60
public ErrorStripeRequest NeedsErrorStripe(IPsiSourceFile sourceFile)
#elif RESHARPER_61
public ErrorStripeRequest NeedsErrorStripe(IPsiSourceFile sourceFile, IContextBoundSettingsStore settingsStore)
#endif
{
return GetErrorStripe();
}
public ErrorStripeRequest NeedsErrorStripe(IProjectFile projectFile)
{
return GetErrorStripe();
}
private static ErrorStripeRequest GetErrorStripe()
{
return ErrorStripeRequest.STRIPE_AND_ERRORS;
}
}
}
|
apache-2.0
|
C#
|
e70c3be7b963085d661ae4d4dd0a0bbf4f19f355
|
Fix status text not updating upon reset
|
Curdflappers/UltimateTicTacToe
|
Assets/Resources/Scripts/game/view/StatusText.cs
|
Assets/Resources/Scripts/game/view/StatusText.cs
|
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Attach this to the status text game object
/// </summary>
public class StatusText : MonoBehaviour
{
Text text;
GlobalGame game;
public GlobalGame Game
{
get
{ return game; }
set
{
if (game != null)
{
game.WinnerChanged -= HandleGameStateChanged;
game.TurnChanged -= HandleGameStateChanged;
}
game = value;
if (game != null)
{
game.WinnerChanged += HandleGameStateChanged;
game.TurnChanged += HandleGameStateChanged;
}
UpdateState();
}
}
void UpdateState()
{
HandleGameStateChanged(game, null);
}
private void Start()
{
text = GetComponent<Text>();
UpdateState();
}
public void HandleGameStateChanged(object o, GameEventArgs e)
{
if (game == null)
{
text.text = "";
return;
}
if (game.GameOver())
{
if (game.Winner != null)
{
text.text = game.Winner.Name + " wins!";
return;
}
text.text = "Tie game";
return;
}
text.text = game.ActivePlayer().Name + "'s turn";
}
}
|
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Attach this to the status text game object
/// </summary>
public class StatusText : MonoBehaviour
{
Text text;
GlobalGame game;
public GlobalGame Game
{
get
{ return game; }
set
{
if (game != null)
{
game.WinnerChanged -= HandleGameStateChanged;
game.TurnChanged -= HandleGameStateChanged;
}
game = value;
game.WinnerChanged += HandleGameStateChanged;
game.TurnChanged += HandleGameStateChanged;
}
}
private void Start()
{
text = GetComponent<Text>();
if (game != null)
{
HandleGameStateChanged(null, null);
}
}
public void HandleGameStateChanged(object o, GameEventArgs e)
{
if (game.GameOver())
{
if (game.Winner != null)
{
text.text = game.Winner.Name + " wins!";
return;
}
text.text = "Tie game";
return;
}
text.text = game.ActivePlayer().Name + "'s turn";
}
}
|
mit
|
C#
|
7157f43938b6787ae9d63bf79f904d8e36da7b9c
|
Fix null error on status text initialization
|
Curdflappers/UltimateTicTacToe
|
Assets/Resources/Scripts/game/view/StatusText.cs
|
Assets/Resources/Scripts/game/view/StatusText.cs
|
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Attach this to the status text game object
/// </summary>
public class StatusText : MonoBehaviour
{
GlobalGame game;
public GlobalGame Game
{
get
{ return game; }
set
{
if (game != null)
{
game.WinnerChanged -= HandleGameStateChanged;
game.TurnChanged -= HandleGameStateChanged;
}
game = value;
if (game != null)
{
game.WinnerChanged += HandleGameStateChanged;
game.TurnChanged += HandleGameStateChanged;
}
UpdateState();
}
}
void UpdateState()
{
HandleGameStateChanged(game, null);
}
private void Awake()
{
UpdateState();
}
public void HandleGameStateChanged(object o, GameEventArgs e)
{
Text text = GetComponent<Text>();
if (game == null)
{
text.text = "";
return;
}
if (game.GameOver())
{
if (game.Winner != null)
{
text.text = game.Winner.Name + " wins!";
return;
}
text.text = "Tie game";
return;
}
text.text = game.ActivePlayer().Name + "'s turn";
}
}
|
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Attach this to the status text game object
/// </summary>
public class StatusText : MonoBehaviour
{
Text text;
GlobalGame game;
public GlobalGame Game
{
get
{ return game; }
set
{
if (game != null)
{
game.WinnerChanged -= HandleGameStateChanged;
game.TurnChanged -= HandleGameStateChanged;
}
game = value;
if (game != null)
{
game.WinnerChanged += HandleGameStateChanged;
game.TurnChanged += HandleGameStateChanged;
}
UpdateState();
}
}
void UpdateState()
{
HandleGameStateChanged(game, null);
}
private void Start()
{
text = GetComponent<Text>();
UpdateState();
}
public void HandleGameStateChanged(object o, GameEventArgs e)
{
if (game == null)
{
text.text = "";
return;
}
if (game.GameOver())
{
if (game.Winner != null)
{
text.text = game.Winner.Name + " wins!";
return;
}
text.text = "Tie game";
return;
}
text.text = game.ActivePlayer().Name + "'s turn";
}
}
|
mit
|
C#
|
f88c5e831eeda9d7f46354f7d246573649b1db9a
|
Bump assembly version to 1.0.19910.1700
|
atifaziz/Kons,atifaziz/Kons
|
AssemblyInfo.g.cs
|
AssemblyInfo.g.cs
|
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.
// Generated: Wed, 10 Aug 2016 17:00:19 GMT
using System.Reflection;
[assembly: AssemblyVersion("1.0.19910.0")]
[assembly: AssemblyFileVersion("1.0.19910.1700")]
|
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.
// Generated: Thu, 03 Dec 2015 09:03:32 GMT
using System.Reflection;
[assembly: AssemblyVersion("1.0.19103.0")]
[assembly: AssemblyFileVersion("1.0.19103.903")]
|
apache-2.0
|
C#
|
9493cd67e9da87a9b7ed4000d85a877049c486da
|
Remove internal delegate
|
vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary,vazgriz/CSharpGameLibrary
|
CSGL.Vulkan/ShaderModule.cs
|
CSGL.Vulkan/ShaderModule.cs
|
using System;
using System.Collections.Generic;
using System.IO;
namespace CSGL.Vulkan {
public class ShaderModuleCreateInfo {
public IList<byte> data;
}
public class ShaderModule : IDisposable, INative<Unmanaged.VkShaderModule> {
Unmanaged.VkShaderModule shaderModule;
bool disposed = false;
Device device;
public Unmanaged.VkShaderModule Native {
get {
return shaderModule;
}
}
public ShaderModule(Device device, ShaderModuleCreateInfo info) {
if (device == null) throw new ArgumentNullException(nameof(device));
if (info == null) throw new ArgumentNullException(nameof(info));
this.device = device;
CreateShader(info);
}
void CreateShader(ShaderModuleCreateInfo mInfo) {
if (mInfo.data == null) throw new ArgumentNullException(nameof(mInfo.data));
var info = new Unmanaged.VkShaderModuleCreateInfo();
info.sType = VkStructureType.ShaderModuleCreateInfo;
info.codeSize = (IntPtr)mInfo.data.Count;
var dataPinned = new NativeArray<byte>(mInfo.data);
info.pCode = dataPinned.Address;
using (dataPinned) {
var result = device.Commands.createShaderModule(device.Native, ref info, device.Instance.AllocationCallbacks, out shaderModule);
if (result != VkResult.Success) throw new ShaderModuleException(result, string.Format("Error creating shader module: {0}"));
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
void Dispose(bool disposing) {
if (disposed) return;
device.Commands.destroyShaderModule(device.Native, shaderModule, device.Instance.AllocationCallbacks);
disposed = true;
}
~ShaderModule() {
Dispose(false);
}
}
public class ShaderModuleException : VulkanException {
public ShaderModuleException(VkResult result, string message) : base(result, message) { }
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
namespace CSGL.Vulkan {
public class ShaderModuleCreateInfo {
public IList<byte> data;
}
public class ShaderModule : IDisposable, INative<Unmanaged.VkShaderModule> {
Unmanaged.VkShaderModule shaderModule;
bool disposed = false;
Device device;
Unmanaged.vkCreateShaderModuleDelegate createShaderModule;
Unmanaged.vkDestroyShaderModuleDelegate destroyShaderModule;
public Unmanaged.VkShaderModule Native {
get {
return shaderModule;
}
}
public ShaderModule(Device device, ShaderModuleCreateInfo info) {
if (device == null) throw new ArgumentNullException(nameof(device));
if (info == null) throw new ArgumentNullException(nameof(info));
this.device = device;
createShaderModule = device.Commands.createShaderModule;
destroyShaderModule = device.Commands.destroyShaderModule;
CreateShader(info);
}
void CreateShader(ShaderModuleCreateInfo mInfo) {
if (mInfo.data == null) throw new ArgumentNullException(nameof(mInfo.data));
var info = new Unmanaged.VkShaderModuleCreateInfo();
info.sType = VkStructureType.ShaderModuleCreateInfo;
info.codeSize = (IntPtr)mInfo.data.Count;
var dataPinned = new NativeArray<byte>(mInfo.data);
info.pCode = dataPinned.Address;
using (dataPinned) {
var result = createShaderModule(device.Native, ref info, device.Instance.AllocationCallbacks, out shaderModule);
if (result != VkResult.Success) throw new ShaderModuleException(result, string.Format("Error creating shader module: {0}"));
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
void Dispose(bool disposing) {
if (disposed) return;
destroyShaderModule(device.Native, shaderModule, device.Instance.AllocationCallbacks);
disposed = true;
}
~ShaderModule() {
Dispose(false);
}
}
public class ShaderModuleException : VulkanException {
public ShaderModuleException(VkResult result, string message) : base(result, message) { }
}
}
|
mit
|
C#
|
35f122845d83db909756d85e8c5038dee6650735
|
Change company house API request to use upper case to fix bug
|
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
|
src/SFA.DAS.EmployerApprenticeshipsService.Infrastructure/Services/CompaniesHouseEmployerVerificationService.cs
|
src/SFA.DAS.EmployerApprenticeshipsService.Infrastructure/Services/CompaniesHouseEmployerVerificationService.cs
|
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using NLog;
using SFA.DAS.EAS.Domain;
using SFA.DAS.EAS.Domain.Configuration;
using SFA.DAS.EAS.Domain.Interfaces;
namespace SFA.DAS.EAS.Infrastructure.Services
{
public class CompaniesHouseEmployerVerificationService : IEmployerVerificationService
{
private readonly EmployerApprenticeshipsServiceConfiguration _configuration;
private readonly ILogger _logger;
private readonly IManagedCompanyLookupService _managedCompanyLookupService;
public CompaniesHouseEmployerVerificationService(EmployerApprenticeshipsServiceConfiguration configuration, ILogger logger,IManagedCompanyLookupService managedCompanyLookupService)
{
_configuration = configuration;
_logger = logger;
_managedCompanyLookupService = managedCompanyLookupService;
}
public async Task<EmployerInformation> GetInformation(string id)
{
_logger.Info($"GetInformation({id})");
id = id.ToUpper();
if (_configuration.CompaniesHouse.UseManagedList)
{
var companies = _managedCompanyLookupService.GetCompanies();
var company = companies?.Data.SingleOrDefault(c => c.CompanyNumber.Equals(id, StringComparison.CurrentCultureIgnoreCase));
if (company != null)
{
_logger.Info($"Company {id} returned via managed lookup service.");
return company;
}
}
var webClient = new WebClient();
webClient.Headers.Add($"Authorization: Basic {_configuration.CompaniesHouse.ApiKey}");
try
{
var result = await webClient.DownloadStringTaskAsync($"https://api.companieshouse.gov.uk/company/{id}");
return JsonConvert.DeserializeObject<EmployerInformation>(result);
}
catch (WebException ex)
{
_logger.Error(ex, "There was a problem with the call to Companies House");
}
return null;
}
}
}
|
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using NLog;
using SFA.DAS.EAS.Domain;
using SFA.DAS.EAS.Domain.Configuration;
using SFA.DAS.EAS.Domain.Interfaces;
namespace SFA.DAS.EAS.Infrastructure.Services
{
public class CompaniesHouseEmployerVerificationService : IEmployerVerificationService
{
private readonly EmployerApprenticeshipsServiceConfiguration _configuration;
private readonly ILogger _logger;
private readonly IManagedCompanyLookupService _managedCompanyLookupService;
public CompaniesHouseEmployerVerificationService(EmployerApprenticeshipsServiceConfiguration configuration, ILogger logger,IManagedCompanyLookupService managedCompanyLookupService)
{
_configuration = configuration;
_logger = logger;
_managedCompanyLookupService = managedCompanyLookupService;
}
public async Task<EmployerInformation> GetInformation(string id)
{
_logger.Info($"GetInformation({id})");
if (_configuration.CompaniesHouse.UseManagedList)
{
var companies = _managedCompanyLookupService.GetCompanies();
var company = companies?.Data.SingleOrDefault(c => c.CompanyNumber.Equals(id, StringComparison.CurrentCultureIgnoreCase));
if (company != null)
{
_logger.Info($"Company {id} returned via managed lookup service.");
return company;
}
}
var webClient = new WebClient();
webClient.Headers.Add($"Authorization: Basic {_configuration.CompaniesHouse.ApiKey}");
try
{
var result = await webClient.DownloadStringTaskAsync($"https://api.companieshouse.gov.uk/company/{id}");
return JsonConvert.DeserializeObject<EmployerInformation>(result);
}
catch (WebException ex)
{
_logger.Error(ex, "There was a problem with the call to Companies House");
}
return null;
}
}
}
|
mit
|
C#
|
9e997769a4ae88a708b295eba81c31f9813b51fe
|
Fix issue when picking earnings for learners
|
SkillsFundingAgency/das-paymentsacceptancetesting
|
src/SFA.DAS.Payments.AcceptanceTests/Refactoring/Assertions/PaymentsAndEarningsRules/ProviderEarnedTotalRule.cs
|
src/SFA.DAS.Payments.AcceptanceTests/Refactoring/Assertions/PaymentsAndEarningsRules/ProviderEarnedTotalRule.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using SFA.DAS.Payments.AcceptanceTests.Refactoring.Contexts;
using SFA.DAS.Payments.AcceptanceTests.Refactoring.ReferenceDataModels;
using SFA.DAS.Payments.AcceptanceTests.Refactoring.ResultsDataModels;
namespace SFA.DAS.Payments.AcceptanceTests.Refactoring.Assertions.PaymentsAndEarningsRules
{
public class ProviderEarnedTotalRule : EarningsAndPaymentsRuleBase
{
public override void AssertBreakdown(EarningsAndPaymentsBreakdown breakdown, IEnumerable<LearnerResults> submissionResults, EmployerAccountContext employerAccountContext)
{
var allEarnings = GetEarningsForBreakdown(breakdown, submissionResults);
foreach (var period in breakdown.ProviderEarnedTotal)
{
AssertResultsForPeriod(period, allEarnings);
}
}
private LearnerEarningsResult[] GetEarningsForBreakdown(EarningsAndPaymentsBreakdown breakdown, IEnumerable<LearnerResults> submissionResults)
{
var filteredResults = submissionResults.Where(r => r.ProviderId.Equals(breakdown.ProviderId, StringComparison.CurrentCultureIgnoreCase));
if (breakdown is LearnerEarningsAndPaymentsBreakdown)
{
filteredResults = filteredResults.Where(r => r.LearnerId.Equals(((LearnerEarningsAndPaymentsBreakdown)breakdown).LearnerId, StringComparison.CurrentCultureIgnoreCase));
}
return filteredResults.Select(r => r.Earnings.Select(e => new LearnerEarningsResult
{
LearnerId = r.LearnerId,
DeliveryPeriod = e.DeliveryPeriod,
CalculationPeriod = e.CalculationPeriod,
Value = e.Value
})).SelectMany(e => e)
.OrderBy(e => e.DeliveryPeriod)
.ThenBy(e => e.LearnerId)
.ToArray();
}
private void AssertResultsForPeriod(PeriodValue period, LearnerEarningsResult[] allEarnings)
{
var earnedInPeriod = (from e in allEarnings
where e.DeliveryPeriod == period.PeriodName
group e by e.LearnerId into g
select g.First()).Sum(x => x.Value);
if (period.Value != earnedInPeriod)
{
throw new Exception($"Expected provider to earn {period.Value} in {period.PeriodName} but actually earned {earnedInPeriod}");
}
}
private class LearnerEarningsResult : EarningsResult
{
public string LearnerId { get; set; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using SFA.DAS.Payments.AcceptanceTests.Refactoring.Contexts;
using SFA.DAS.Payments.AcceptanceTests.Refactoring.ReferenceDataModels;
using SFA.DAS.Payments.AcceptanceTests.Refactoring.ResultsDataModels;
namespace SFA.DAS.Payments.AcceptanceTests.Refactoring.Assertions.PaymentsAndEarningsRules
{
public class ProviderEarnedTotalRule : EarningsAndPaymentsRuleBase
{
public override void AssertBreakdown(EarningsAndPaymentsBreakdown breakdown, IEnumerable<LearnerResults> submissionResults, EmployerAccountContext employerAccountContext)
{
var allEarnings = GetEarningsForBreakdown(breakdown, submissionResults);
foreach (var period in breakdown.ProviderEarnedTotal)
{
AssertResultsForPeriod(period, allEarnings);
}
}
private EarningsResult[] GetEarningsForBreakdown(EarningsAndPaymentsBreakdown breakdown, IEnumerable<LearnerResults> submissionResults)
{
var earnings = submissionResults.Where(r => r.ProviderId.Equals(breakdown.ProviderId, StringComparison.CurrentCultureIgnoreCase));
if (breakdown is LearnerEarningsAndPaymentsBreakdown)
{
earnings = earnings.Where(r => r.LearnerId.Equals(((LearnerEarningsAndPaymentsBreakdown)breakdown).LearnerId, StringComparison.CurrentCultureIgnoreCase));
}
return earnings.SelectMany(r => r.Earnings).ToArray();
}
private void AssertResultsForPeriod(PeriodValue period, EarningsResult[] allEarnings)
{
var earnedInPeriod = allEarnings.FirstOrDefault(r => r.DeliveryPeriod == period.PeriodName)?.Value;
if (period.Value != earnedInPeriod)
{
throw new Exception($"Expected provider to earn {period.Value} in {period.PeriodName} but actually earned {earnedInPeriod}");
}
}
}
}
|
mit
|
C#
|
3e7ebf2e40107db323fbacbbd544092ed5c874fa
|
Delete unused code from Player
|
ethanmoffat/EndlessClient
|
EndlessClient/Old/Player.cs
|
EndlessClient/Old/Player.cs
|
// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
namespace EndlessClient.Old
{
public class Player
{
public string AccountName { get; private set; }
public OldCharacter ActiveCharacter { get; private set; }
}
}
|
// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System.Linq;
using EOLib.Net.API;
namespace EndlessClient.Old
{
public class Player
{
private OldCharacter _activeCharacter;
public string AccountName { get; private set; }
public int PlayerID { get; private set; }
public CharRenderData[] CharData { get; private set; }
public OldCharacter ActiveCharacter
{
get
{
//This (theoretically) prevents a race condition in which a background thread calls "Logout"
// and sets _activeCharacter to null. By recreating a dummy character we are able to prevent
// the crashes that cause null reference exceptions (again, theoretically)
if (_activeCharacter == null)
{
return new OldCharacter();
}
return _activeCharacter;
}
private set { _activeCharacter = value; }
}
public Player()
{
Logout();
}
public void Logout()
{
if (OldWorld.Initialized && ActiveCharacter != null)
Logger.Log("Logging out MainPlayer. Setting ActiveCharacter = null.");
PlayerID = 0;
CharData = null;
ActiveCharacter = null;
}
public void SetAccountName(string acc)
{
AccountName = acc;
}
public void SetPlayerID(int newId)
{
PlayerID = newId;
}
public bool SetActiveCharacter(PacketAPI api, int id)
{
if (OldWorld.Initialized && ActiveCharacter != null)
Logger.Log("Setting Active Character to new ID {0}", id);
CharRenderData activeData = CharData.FirstOrDefault(d => d.id == id);
if (activeData == null)
return false;
ActiveCharacter = new OldCharacter(api, id, activeData);
return true;
}
public void ProcessCharacterData(CharacterLoginData[] dataArray)
{
CharData = new CharRenderData[dataArray.Length];
for (int i = 0; i < CharData.Length; ++i)
{
CharData[i] = new CharRenderData
{
name = dataArray[i].Name,
id = dataArray[i].ID,
level = dataArray[i].Level,
gender = dataArray[i].Gender,
hairstyle = dataArray[i].HairStyle,
haircolor = dataArray[i].HairColor,
race = dataArray[i].Race,
admin = (byte)dataArray[i].AdminLevel,
boots = dataArray[i].Boots,
armor = dataArray[i].Armor,
hat = dataArray[i].Hat,
shield = dataArray[i].Shield,
weapon = dataArray[i].Weapon
};
}
}
}
}
|
mit
|
C#
|
462348c0e92ac3a0be2b9d9bd3be95d165527355
|
improve nqueen output
|
lifebeyondfife/Decider
|
Examples/NQueens/Program.cs
|
Examples/NQueens/Program.cs
|
/*
Copyright © Iain McDonald 2010-2020
This file is part of Decider.
*/
using System;
using System.Globalization;
namespace Decider.Example.NQueens
{
public class Program
{
public static void Main(string[] args)
{
var nQueens = new NQueens((args.Length >= 1) ? Int32.Parse(args[0]) : 8);
nQueens.Search();
foreach (var solution in nQueens.Solutions)
{
for (var i = 0; i < nQueens.State.Variables.Count; ++i)
{
for (var j = 0; j < nQueens.State.Variables.Count; ++j)
Console.Write(solution[i.ToString(CultureInfo.CurrentCulture)].InstantiatedValue == j ? "Q " : ". ");
Console.WriteLine();
}
Console.WriteLine();
}
Console.WriteLine("Runtime:\t{0}", nQueens.State.Runtime);
Console.WriteLine("Backtracks:\t{0}", nQueens.State.Backtracks);
Console.WriteLine("Solutions:\t{0}", nQueens.State.NumberOfSolutions);
}
}
}
|
/*
Copyright © Iain McDonald 2010-2020
This file is part of Decider.
*/
using System;
using System.Globalization;
namespace Decider.Example.NQueens
{
public class Program
{
public static void Main(string[] args)
{
var nQueens = new NQueens((args.Length >= 1) ? Int32.Parse(args[0]) : 8);
nQueens.Search();
foreach (var solution in nQueens.Solutions)
{
for (var i = 0; i < nQueens.State.Variables.Count; ++i)
{
for (var j = 0; j < nQueens.State.Variables.Count; ++j)
Console.Write(solution[i.ToString(CultureInfo.CurrentCulture)].InstantiatedValue == j ? "Q" : ".");
Console.WriteLine();
}
Console.WriteLine();
}
Console.WriteLine("Runtime:\t{0}", nQueens.State.Runtime);
Console.WriteLine("Backtracks:\t{0}", nQueens.State.Backtracks);
Console.WriteLine("Solutions:\t{0}", nQueens.State.NumberOfSolutions);
}
}
}
|
mit
|
C#
|
e6f9e4e755dec97afdb81f3ac36e030982ec120b
|
Update Spacefolder.cs
|
KerbaeAdAstra/KerbalFuture
|
KerbalFuture/Spacefolder.cs
|
KerbalFuture/Spacefolder.cs
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using KSP;
namespace KerbalFuture
{
class SpacefolderData : MonoBehavior
{
public static string path()
{
return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
}
}
class FlightDrive : VesselModule
{
public st
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using KSP;
namespace SpaceFolderDrive
{
class SFDData : MonoBehavior
{
public static string path()
{
return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
}
}
class FlightDrive : VesselModule
{
public st
}
}
|
mit
|
C#
|
175a2325520cd5a95245e27ad06058b0af85e470
|
Update AppTester.
|
eylvisaker/AgateLib
|
Tests/Core/AppTester/App.cs
|
Tests/Core/AppTester/App.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using AgateLib;
namespace AppTester
{
class App : AgateApplication
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// These two lines are used by AgateLib tests to locate
// driver plugins and images.
AgateFileProvider.Assemblies.AddPath("../Drivers");
AgateFileProvider.Images.AddPath("Images");
new App().Run();
}
protected override AppInitParameters GetAppInitParameters()
{
var retval = base.GetAppInitParameters();
retval.AllowResize = true;
return retval;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using AgateLib;
namespace AppTester
{
class App : AgateApplication
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
new App().Run();
}
protected override AppInitParameters GetAppInitParameters()
{
var retval = base.GetAppInitParameters();
return retval;
}
}
}
|
mit
|
C#
|
7528b4e178e7028fdd8b301d3a4cb0f2df27fbe8
|
Add service alert for app update notice
|
RikkiGibson/Corvallis-Bus-Server,RikkiGibson/Corvallis-Bus-Server
|
CorvallisBus.Core/WebClients/ServiceAlertsClient.cs
|
CorvallisBus.Core/WebClients/ServiceAlertsClient.cs
|
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using CorvallisBus.Core.Models;
using HtmlAgilityPack;
namespace CorvallisBus.Core.WebClients
{
public static class ServiceAlertsClient
{
static readonly Uri FEED_URL = new Uri("https://www.corvallisoregon.gov/news?field_microsite_tid=581");
static readonly HttpClient httpClient = new HttpClient();
public static async Task<List<ServiceAlert>> GetServiceAlerts()
{
var responseStream = await httpClient.GetStreamAsync(FEED_URL);
var htmlDocument = new HtmlDocument();
htmlDocument.Load(responseStream);
var alerts = htmlDocument.DocumentNode.SelectNodes("//tbody/tr")
.Select(row => ParseRow(row))
.ToList();
alerts.Insert(0, new ServiceAlert(
title: "App Update for Upcoming CTS Schedule",
publishDate: "2019-09-09T00:00:00-07:00",
link: "https://rikkigibson.github.io/corvallisbus"));
return alerts;
}
private static ServiceAlert ParseRow(HtmlNode row)
{
var anchor = row.Descendants("a").First();
var relativeLink = anchor.Attributes["href"].Value;
var link = new Uri(FEED_URL, relativeLink).ToString();
var title = anchor.InnerText;
var publishDate = row.Descendants("span")
.First(node => node.HasClass("date-display-single"))
.Attributes["content"]
.Value;
return new ServiceAlert(title, publishDate, link);
}
}
}
|
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using CorvallisBus.Core.Models;
using HtmlAgilityPack;
namespace CorvallisBus.Core.WebClients
{
public static class ServiceAlertsClient
{
static readonly Uri FEED_URL = new Uri("https://www.corvallisoregon.gov/news?field_microsite_tid=581");
static readonly HttpClient httpClient = new HttpClient();
public static async Task<List<ServiceAlert>> GetServiceAlerts()
{
var responseStream = await httpClient.GetStreamAsync(FEED_URL);
var htmlDocument = new HtmlDocument();
htmlDocument.Load(responseStream);
var alerts = htmlDocument.DocumentNode.SelectNodes("//tbody/tr")
.Select(row => ParseRow(row))
.ToList();
return alerts;
}
private static ServiceAlert ParseRow(HtmlNode row)
{
var anchor = row.Descendants("a").First();
var relativeLink = anchor.Attributes["href"].Value;
var link = new Uri(FEED_URL, relativeLink).ToString();
var title = anchor.InnerText;
var publishDate = row.Descendants("span")
.First(node => node.HasClass("date-display-single"))
.Attributes["content"]
.Value;
return new ServiceAlert(title, publishDate, link);
}
}
}
|
mit
|
C#
|
e64e025014e9af000b3416eb7ff4bccdb821c920
|
Use GL_DEBUG instead of DEBUG.
|
luca-piccioni/OpenGL.Net,luca-piccioni/OpenGL.Net
|
OpenWF.Net/Wfd.cs
|
OpenWF.Net/Wfd.cs
|
// Copyright (C) 2015-2016 Luca Piccioni
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
// USA
using System.Diagnostics;
namespace OpenWF
{
/// <summary>
/// Modern OpenGL bindings: OpenWF, Display API.
/// </summary>
public partial class Wfd : KhronosApi
{
#region Constructors
/// <summary>
/// Static constructor.
/// </summary>
static Wfd()
{
// Load procedures
string platformLibrary = GetPlatformLibrary();
try {
LogComment("Querying OpenWF Display from {0}", platformLibrary);
BindAPI<Wfd>(platformLibrary, GetProcAddress.GetProcAddressOS);
LogComment("OpenWF Display availability: {0}", IsAvailable);
} catch (Exception exception) {
/* Fail-safe (it may fail due Egl access) */
LogComment("OpenWF Display not available:\n{0}", exception.ToString());
}
}
#endregion
#region API Binding
/// <summary>
/// Get whether EGL layer is avaialable.
/// </summary>
public static bool IsAvailable { get { return (Delegates.pwfdCreateDevice != null); } }
/// <summary>
/// Get the library name used for loading OpenGL functions.
/// </summary>
/// <returns>
/// It returns a <see cref="String"/> that specifies the library name to be used.
/// </returns>
private static string GetPlatformLibrary()
{
switch (Platform.CurrentPlatformId) {
case Platform.Id.Linux:
return ("libWFD.so");
default:
return (Library);
}
}
/// <summary>
/// Default import library.
/// </summary>
internal const string Library = "libWFD.dll";
#endregion
#region Error Handling
/// <summary>
/// OpenGL error checking.
/// </summary>
[Conditional("GL_DEBUG")]
private static void DebugCheckErrors(object returnValue)
{
}
#endregion
}
}
|
// Copyright (C) 2015-2016 Luca Piccioni
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
// USA
using System.Diagnostics;
namespace OpenWF
{
/// <summary>
/// Modern OpenGL bindings: OpenWF, Display API.
/// </summary>
public partial class Wfd : KhronosApi
{
#region Constructors
/// <summary>
/// Static constructor.
/// </summary>
static Wfd()
{
// Load procedures
string platformLibrary = GetPlatformLibrary();
try {
LogComment("Querying OpenWF Display from {0}", platformLibrary);
BindAPI<Wfd>(platformLibrary, GetProcAddress.GetProcAddressOS);
LogComment("OpenWF Display availability: {0}", IsAvailable);
} catch (Exception exception) {
/* Fail-safe (it may fail due Egl access) */
LogComment("OpenWF Display not available:\n{0}", exception.ToString());
}
}
#endregion
#region API Binding
/// <summary>
/// Get whether EGL layer is avaialable.
/// </summary>
public static bool IsAvailable { get { return (Delegates.pwfdCreateDevice != null); } }
/// <summary>
/// Get the library name used for loading OpenGL functions.
/// </summary>
/// <returns>
/// It returns a <see cref="String"/> that specifies the library name to be used.
/// </returns>
private static string GetPlatformLibrary()
{
switch (Platform.CurrentPlatformId) {
case Platform.Id.Linux:
return ("libWFD.so");
default:
return (Library);
}
}
/// <summary>
/// Default import library.
/// </summary>
internal const string Library = "libWFD.dll";
#endregion
#region Error Handling
/// <summary>
/// OpenGL error checking.
/// </summary>
[Conditional("DEBUG")]
private static void DebugCheckErrors(object returnValue)
{
}
#endregion
}
}
|
mit
|
C#
|
073cd56341f04f63d640ca0c4e10cb8d51f0ca4f
|
remove empty constructor
|
Notulp/Pluton,Notulp/Pluton
|
Pluton/plugins.cs
|
Pluton/plugins.cs
|
using System;
namespace Pluton
{
[ConsoleSystem.Factory("plugins")]
public class plugins : ConsoleSystem
{
[ConsoleSystem.Admin, ConsoleSystem.Help("Prints out plugin statistics!")]
public static void Loaded(ConsoleSystem.Arg args)
{
int count = PluginLoader.GetInstance().Plugins.Count;
string result = String.Format("Loaded plugins({0}):\r\n", count);
foreach (BasePlugin plugin in PluginLoader.GetInstance().Plugins.Values) {
result += String.Format(" {0, -22} [{1, -10}], timers: {2, 8}, parallel: {3, 8}\r\n", plugin.Name, plugin.Type, plugin.Timers.Count + plugin.ParallelTimers.Count, plugin.ParallelTimers.Count);
result += String.Format("Author: {0}, about: {1}, version: {2}\r\n\r\n", plugin.Author, plugin.About, plugin.Version);
}
args.ReplyWith(result);
}
}
}
|
using System;
namespace Pluton
{
[ConsoleSystem.Factory("plugins")]
public class plugins : ConsoleSystem
{
public plugins()
{
}
[ConsoleSystem.Admin, ConsoleSystem.Help("Prints out plugin statistics!")]
public static void Loaded(ConsoleSystem.Arg args)
{
int count = PluginLoader.GetInstance().Plugins.Count;
string result = String.Format("Loaded plugins({0}):\r\n", count);
foreach (BasePlugin plugin in PluginLoader.GetInstance().Plugins.Values) {
result += String.Format(" {0, -22} [{1, -10}], timers: {2, 8}, parallel: {3, 8}\r\n", plugin.Name, plugin.Type, plugin.Timers.Count + plugin.ParallelTimers.Count, plugin.ParallelTimers.Count);
result += String.Format("Author: {0}, about: {1}, version: {2}\r\n\r\n", plugin.Author, plugin.About, plugin.Version);
}
args.ReplyWith(result);
}
}
}
|
mit
|
C#
|
88222c01ef3718ed2096fb3324f548c21925dd3f
|
Add Connexion API
|
DiabHelp/DiabHelp-App-WP
|
Diabhelp/LoginScreen.xaml.cs
|
Diabhelp/LoginScreen.xaml.cs
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace Diabhelp
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class LoginScreen : Page
{
public LoginScreen()
{
this.InitializeComponent();
}
private async void connect_button_Click(object sender, RoutedEventArgs e)
{
Debug.WriteLine("login_clicked ok");
HttpClient client = new HttpClient();
try
{
TextBox login = (TextBox)login_input;
TextBox password = (TextBox)pass_input;
HttpResponseMessage response = await client.GetAsync("http://www.naquedounet.fr/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Debug.WriteLine(responseBody);
if (responseBody != "")
{
this.Frame.Navigate(typeof(ModulesScreen));
}
} catch(HttpRequestException ex)
{
Debug.WriteLine(ex.Message);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace Diabhelp
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class LoginScreen : Page
{
public LoginScreen()
{
this.InitializeComponent();
}
private void connect_button_Click(object sender, RoutedEventArgs e)
{
Debug.WriteLine("login_clicked ok");
this.Frame.Navigate(typeof(ModulesScreen));
}
}
}
|
mit
|
C#
|
c7874cc1582cff4f4229617c5e106e4678164b6c
|
add new line for better layout
|
SoftwareFans/AstroPhotoGallery,SoftwareFans/AstroPhotoGallery,SoftwareFans/AstroPhotoGallery
|
AstroPhotoGallery/AstroPhotoGallery/Views/Home/ListPictures.cshtml
|
AstroPhotoGallery/AstroPhotoGallery/Views/Home/ListPictures.cshtml
|
@model List<AstroPhotoGallery.Models.Picture>
@{
ViewBag.Title = "List";
}
<div class="container">
<div class="row">
@foreach (var picture in Model)
{
<div class="col-sm-6">
<article>
<header>
<h2>
@Html.ActionLink(@picture.PicTitle, "Details", "Picture", new { @id = picture.Id }, null)
</h2>
</header>
<div class="img-thumbnail">
<img src="@Url.Content(picture.ImagePath)" style="height:120px;width:220px"/>
</div>
<p>
<br />
@picture.PicDescription
</p>
<footer class="pull-right">
<small class="author">
Uploader: @picture.PicUploader.Email
</small>
</footer>
</article>
</div>
}
</div>
</div>
|
@model List<AstroPhotoGallery.Models.Picture>
@{
ViewBag.Title = "List";
}
<div class="container">
<div class="row">
@foreach (var picture in Model)
{
<div class="col-sm-6">
<article>
<header>
<h2>
@Html.ActionLink(@picture.PicTitle, "Details", "Picture", new { @id = picture.Id }, null)
</h2>
</header>
<div class="img-thumbnail">
<img src="@Url.Content(picture.ImagePath)" style="height:120px;width:220px"/>
</div>
<p>
@picture.PicDescription
</p>
<footer class="pull-right">
<small class="author">
Uploader: @picture.PicUploader.Email
</small>
</footer>
</article>
</div>
}
</div>
</div>
|
mit
|
C#
|
9e9b00372d84287465e4ced856b95ea4d5c85a75
|
Format code to use correct spacing
|
Microsoft/dotnet-apiweb,conniey/dotnet-apiweb,Microsoft/dotnet-apiweb,conniey/dotnet-apiweb
|
src/DotNetStatus/Startup.cs
|
src/DotNetStatus/Startup.cs
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Diagnostics;
using Microsoft.AspNet.Hosting;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Logging;
using Microsoft.Framework.Logging.Console;
using Microsoft.Fx.Portability;
using System;
namespace DotNetStatus.vNext
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
Configuration = new Configuration()
.AddJsonFile("config.json")
.AddEnvironmentVariables();
}
public IConfiguration Configuration { get; }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
// Add the following to the request pipeline only in development environment.
if (string.Equals(env.EnvironmentName, "Development", StringComparison.OrdinalIgnoreCase))
{
app.UseBrowserLink();
app.UseErrorPage(ErrorPageOptions.ShowAll);
}
else
{
// Add Error handling middleware which catches all application specific errors and
// send the request to the following path or controller action.
app.UseErrorHandler("/Home/Error");
}
// Add static files to the request pipeline
app.UseStaticFiles();
// Add MVC to the request pipeline (we use attribute routing)
app.UseMvc();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddInstance(new ProductInformation("DotNetStatus"));
services.AddSingleton<IApiPortService>(CreateService);
// Add MVC services to container
services.AddMvc();
}
private object CreateService(IServiceProvider arg)
{
string endpoint = null;
if (!Configuration.TryGet("ApiPortService", out endpoint))
{
throw new ArgumentNullException("ApiPortService", "Need to specify ApiPortService in config.json");
}
return new ApiPortService(endpoint, arg.GetRequiredService<ProductInformation>());
}
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Diagnostics;
using Microsoft.AspNet.Hosting;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Logging;
using Microsoft.Framework.Logging.Console;
using Microsoft.Fx.Portability;
using System;
namespace DotNetStatus.vNext
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
Configuration = new Configuration()
.AddJsonFile("config.json")
.AddEnvironmentVariables();
}
public IConfiguration Configuration { get; }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
// Add the following to the request pipeline only in development environment.
if (string.Equals(env.EnvironmentName, "Development", StringComparison.OrdinalIgnoreCase))
{
app.UseBrowserLink();
app.UseErrorPage(ErrorPageOptions.ShowAll);
}
else
{
// Add Error handling middleware which catches all application specific errors and
// send the request to the following path or controller action.
app.UseErrorHandler("/Home/Error");
}
// Add static files to the request pipeline
app.UseStaticFiles();
// Add MVC to the request pipeline (we use attribute routing)
app.UseMvc();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddInstance(new ProductInformation("DotNetStatus"));
services.AddSingleton<IApiPortService>(CreateService);
// Add MVC services to container
services.AddMvc();
}
private object CreateService(IServiceProvider arg)
{
string endpoint = null;
if(!Configuration.TryGet("ApiPortService", out endpoint))
{
throw new ArgumentNullException("ApiPortService", "Need to specify ApiPortService in config.json");
}
return new ApiPortService(endpoint, arg.GetRequiredService<ProductInformation>());
}
}
}
|
mit
|
C#
|
e0830e208a21c3060e507cad8be120591ff369cd
|
stop using DefaultBindingMetadataProvider
|
fluffynuts/PeanutButter,fluffynuts/PeanutButter,fluffynuts/PeanutButter
|
source/TestUtils/PeanutButter.TestUtils.AspNetCore/Builders/ViewDataDictionaryBuilder.cs
|
source/TestUtils/PeanutButter.TestUtils.AspNetCore/Builders/ViewDataDictionaryBuilder.cs
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Internal;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.Options;
using PeanutButter.TestUtils.AspNetCore.Fakes;
namespace PeanutButter.TestUtils.AspNetCore.Builders
{
/// <summary>
/// Build a ViewDataDictionary
/// </summary>
public class ViewDataDictionaryBuilder
: Builder<ViewDataDictionaryBuilder, ViewDataDictionary>
{
/// <inheritdoc />
public ViewDataDictionaryBuilder()
{
WithModel(new object());
}
/// <summary>
/// Set the model on the ViewDataDictionary
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ViewDataDictionaryBuilder WithModel(object model)
{
return With(o => o.Model = model);
}
/// <inheritdoc />
protected override ViewDataDictionary ConstructEntity()
{
return new ViewDataDictionary(
ModelMetadataBuilder.BuildDefault(),
new ModelStateDictionary()
);
}
/// <summary>
/// Implementation of IOptions<MvcOptions> to be used
/// for generating ViewDataDictionaries, or whatever else
/// you might like (:
/// </summary>
public class OptionsAccessor : IOptions<MvcOptions>
{
/// <inheritdoc />
public MvcOptions Value { get; } = new MvcOptions();
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Internal;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.Options;
namespace PeanutButter.TestUtils.AspNetCore.Builders
{
/// <summary>
/// Build a ViewDataDictionary
/// </summary>
public class ViewDataDictionaryBuilder
: Builder<ViewDataDictionaryBuilder, ViewDataDictionary>
{
/// <inheritdoc />
public ViewDataDictionaryBuilder()
{
WithModel(new object());
}
/// <summary>
/// Set the model on the ViewDataDictionary
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ViewDataDictionaryBuilder WithModel(object model)
{
return With(o => o.Model = model);
}
/// <inheritdoc />
protected override ViewDataDictionary ConstructEntity()
{
var compositeProvider = new DefaultCompositeMetadataDetailsProvider(
new[] { new DefaultBindingMetadataProvider() }
);
var optionsAccessor = new OptionsAccessor();
var provider = new DefaultModelMetadataProvider(
compositeProvider,
optionsAccessor
);
return new ViewDataDictionary(
provider,
new ModelStateDictionary()
);
}
/// <summary>
/// Implementation of IOptions<MvcOptions> to be used
/// for generating ViewDataDictionaries, or whatever else
/// you might like (:
/// </summary>
public class OptionsAccessor : IOptions<MvcOptions>
{
/// <inheritdoc />
public MvcOptions Value { get; } = new MvcOptions();
}
}
}
|
bsd-3-clause
|
C#
|
26f0b2a4fe65342757a52476367b6ae432b10b40
|
Remove bindable
|
ZLima12/osu,NeoAdonis/osu,ppy/osu,peppy/osu,peppy/osu,johnneijzen/osu,EVAST9919/osu,EVAST9919/osu,peppy/osu,ZLima12/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,2yangk23/osu,johnneijzen/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu,2yangk23/osu,ppy/osu,UselessToucan/osu,peppy/osu-new
|
osu.Game/Rulesets/Mods/ModHidden.cs
|
osu.Game/Rulesets/Mods/ModHidden.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.Configuration;
using osu.Game.Graphics;
using osu.Game.Rulesets.Objects.Drawables;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Sprites;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModHidden : Mod, IReadFromConfig, IApplicableToDrawableHitObjects, IApplicableToScoreProcessor
{
public override string Name => "Hidden";
public override string Acronym => "HD";
public override IconUsage Icon => OsuIcon.ModHidden;
public override ModType Type => ModType.DifficultyIncrease;
public override bool Ranked => true;
protected Bindable<bool> IncreaseFirstObjectVisibility = new Bindable<bool>();
public void ReadFromConfig(OsuConfigManager config)
{
IncreaseFirstObjectVisibility = config.GetBindable<bool>(OsuSetting.IncreaseFirstObjectVisibility);
}
public virtual void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
foreach (var d in drawables.Skip(IncreaseFirstObjectVisibility.Value ? 1 : 0))
d.ApplyCustomUpdateState += ApplyHiddenState;
}
public void ApplyToScoreProcessor(ScoreProcessor scoreProcessor)
{
scoreProcessor.AdjustRank = true;
}
protected virtual void ApplyHiddenState(DrawableHitObject hitObject, ArmedState state)
{
}
}
}
|
// 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.Configuration;
using osu.Game.Graphics;
using osu.Game.Rulesets.Objects.Drawables;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Sprites;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModHidden : Mod, IReadFromConfig, IApplicableToDrawableHitObjects, IApplicableToScoreProcessor
{
public override string Name => "Hidden";
public override string Acronym => "HD";
public override IconUsage Icon => OsuIcon.ModHidden;
public override ModType Type => ModType.DifficultyIncrease;
public override bool Ranked => true;
protected Bindable<bool> IncreaseFirstObjectVisibility = new Bindable<bool>();
public void ReadFromConfig(OsuConfigManager config)
{
IncreaseFirstObjectVisibility = config.GetBindable<bool>(OsuSetting.IncreaseFirstObjectVisibility);
}
public virtual void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
foreach (var d in drawables.Skip(IncreaseFirstObjectVisibility.Value ? 1 : 0))
d.ApplyCustomUpdateState += ApplyHiddenState;
}
public void ApplyToScoreProcessor(ScoreProcessor scoreProcessor)
{
scoreProcessor.AdjustRank.Value = true;
}
protected virtual void ApplyHiddenState(DrawableHitObject hitObject, ArmedState state)
{
}
}
}
|
mit
|
C#
|
60ebaac0094ea743b7f243e8e69ac103bd8c1164
|
update transaction model
|
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
|
src/SFA.DAS.EmployerApprenticeshipsService.Domain/Models/Payments/PaymentTransactionLine.cs
|
src/SFA.DAS.EmployerApprenticeshipsService.Domain/Models/Payments/PaymentTransactionLine.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using SFA.DAS.EAS.Domain.Models.Transaction;
namespace SFA.DAS.EAS.Domain.Models.Payments
{
public class PaymentTransactionLine : TransactionLine
{
public Guid? PaymentId { get; set; }
public long UkPrn { get; set; }
public string PeriodEnd { get; set; }
public string ProviderName { get; set; }
public decimal LineAmount { get; set; }
public string CourseName { get; set; }
public int? CourseLevel { get; set; }
public DateTime? CourseStartDate { get; set; }
public string ApprenticeName { get; set; }
public string ApprenticeNINumber { get; set; }
public decimal SfaCoInvestmentAmount { get; set; }
public decimal EmployerCoInvestmentAmount { get; set; }
public bool IsCoInvested => SfaCoInvestmentAmount + EmployerCoInvestmentAmount > 0;
public ICollection<PaymentTransactionLine> SubPayments =>
SubTransactions?.OfType<PaymentTransactionLine>().ToList() ??
new List<PaymentTransactionLine>();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using SFA.DAS.EAS.Domain.Models.Transaction;
namespace SFA.DAS.EAS.Domain.Models.Payments
{
public class PaymentTransactionLine : TransactionLine
{
public Guid? PaymentId { get; set; }
public long UkPrn { get; set; }
public string PeriodEnd { get; set; }
public string ProviderName { get; set; }
public decimal LineAmount { get; set; }
public string CourseName { get; set; }
public int? CourseLevel { get; set; }
public DateTime? CourseStartDate { get; set; }
public string ApprenticeName { get; set; }
public string ApprenticeNINumber { get; set; }
public ICollection<PaymentTransactionLine> SubPayments =>
SubTransactions?.OfType<PaymentTransactionLine>().ToList() ??
new List<PaymentTransactionLine>();
}
}
|
mit
|
C#
|
cde46b3f8d395a57825bf8ce26eb5ad01385e17a
|
Update C# mops to use 32bit values like the rest of the tests.
|
ashgti/parrot,ashgti/parrot,ashgti/parrot,ashgti/parrot,ashgti/parrot,ashgti/parrot,ashgti/parrot
|
examples/mops/mops.cs
|
examples/mops/mops.cs
|
// created on 03/03/2002 at 15:12
using System;
class App {
public static int Main(String[] args) {
int i1, i5;
// int i2 = 0;
int i3 = 1;
int i4 = 100000000;
DateTime start, end;
double n1, n2;
Console.WriteLine("Iterations: {0}", i4);
// IL_0038: ldloc.3
// IL_0039: ldloc.2
// IL_003a: sub
// IL_003b: stloc.3
// IL_003c: ldloc.3
// IL_003d: ldc.i4.0
// IL_003e: conv.i8
// IL_003f: bgt.s IL_0038
//
// Insane, isn't it?
i1 = 8;
i5 = i4 * i1;
Console.WriteLine("Estimated ops: {0}", i5);
start = DateTime.Now;
REDO:
i4 = i4 - i3;
if (i4 > 0)
goto REDO;
end = DateTime.Now;
n2 = (end-start).TotalMilliseconds;
n2 /= 1000; // Milliseconds to seconds
Console.WriteLine("Elapsed Time: {0}", n2);
n1 = i5;
n1 /= n2;
n2 = 1000000.0;
n1 /= n2;
Console.WriteLine("M op/s: {0}", n1);
return 0;
}
}
|
// created on 03/03/2002 at 15:12
using System;
class App {
public static int Main(String[] args) {
long i1, i5;
// int i2 = 0;
long i3 = 1;
long i4 = 100000000;
DateTime start, end;
double n1, n2;
Console.WriteLine("Iterations: {0}", i4);
// IL_0038: ldloc.3
// IL_0039: ldloc.2
// IL_003a: sub
// IL_003b: stloc.3
// IL_003c: ldloc.3
// IL_003d: ldc.i4.0
// IL_003e: conv.i8
// IL_003f: bgt.s IL_0038
//
// Insane, isn't it?
i1 = 8;
i5 = i4 * i1;
Console.WriteLine("Estimated ops: {0}", i5);
start = DateTime.Now;
REDO:
i4 = i4 - i3;
if (i4 > 0)
goto REDO;
end = DateTime.Now;
n2 = (end-start).TotalMilliseconds;
n2 /= 1000; // Milliseconds to seconds
Console.WriteLine("Elapsed Time: {0}", n2);
n1 = i5;
n1 /= n2;
n2 = 1000000.0;
n1 /= n2;
Console.WriteLine("M op/s: {0}", n1);
return 0;
}
}
|
artistic-2.0
|
C#
|
a8b255367b6cd3e60aa3ee553bd47f49aa220997
|
Implement FontsHandler.FontFamilyAvailable (missed this one)
|
l8s/Eto,l8s/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,l8s/Eto,bbqchickenrobot/Eto-1
|
Source/Eto.Platform.Windows/Drawing/FontsHandler.cs
|
Source/Eto.Platform.Windows/Drawing/FontsHandler.cs
|
using Eto.Drawing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using sd = System.Drawing;
namespace Eto.Platform.Windows.Drawing
{
public class FontsHandler : WidgetHandler<Widget>, IFonts
{
HashSet<string> availableFontFamilies;
public IEnumerable<FontFamily> AvailableFontFamilies
{
get {
return sd.FontFamily.Families.Select (r => new FontFamily(Generator, new FontFamilyHandler(r)));
}
}
public bool FontFamilyAvailable (string fontFamily)
{
if (availableFontFamilies == null) {
availableFontFamilies = new HashSet<string> (StringComparer.InvariantCultureIgnoreCase);
foreach (var family in sd.FontFamily.Families) {
availableFontFamilies.Add (family.Name);
}
}
return availableFontFamilies.Contains (fontFamily);
}
}
}
|
using Eto.Drawing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using sd = System.Drawing;
namespace Eto.Platform.Windows.Drawing
{
public class FontsHandler : WidgetHandler<Widget>, IFonts
{
public IEnumerable<FontFamily> AvailableFontFamilies
{
get {
return sd.FontFamily.Families.Select (r => new FontFamily(Generator, new FontFamilyHandler(r)));
}
}
}
}
|
bsd-3-clause
|
C#
|
c0ec71fac8f748175ea7d55f3fd47dac3774ff98
|
Add additonal tests GeneratorExtensionTests
|
inputfalken/Sharpy
|
Tests/Sharpy/Integration/GeneratorExtensionTests.cs
|
Tests/Sharpy/Integration/GeneratorExtensionTests.cs
|
using GeneratorAPI;
using NUnit.Framework;
using Sharpy;
using Sharpy.Enums;
using Sharpy.Implementation;
namespace Tests.Sharpy.Integration {
[TestFixture]
public class GeneratorExtensionTests {
[Test]
public void Username_Seed_Arg_Not_Null() {
var generator = Generator.Factory.Username(20);
Assert.IsNotNull(generator);
}
[Test]
public void Username_No_Arg_Not_Null() {
var generator = Generator.Factory.Username();
Assert.IsNotNull(generator);
}
[Test]
public void FirstName_No_Arg_Is_Not_Null() {
var generator = Generator.Factory.FirstName();
Assert.IsNotNull(generator);
}
[Test]
public void Username_Seed_Arg_Not_Generation_Is_Not_Null_Or_Whitespace() {
var username = Generator.Factory.Username(20);
Assert.IsFalse(string.IsNullOrWhiteSpace(username.Generate()));
}
[Test]
public void Username_No_Arg_Not_Generation_Is_Not_Null_Or_Whitespace() {
var username = Generator.Factory.Username();
Assert.IsFalse(string.IsNullOrWhiteSpace(username.Generate()));
}
[Test]
public void FirstName_No_Arg_Is_Not_Generation_Is_Not_Null_Or_Whitespace() {
var firstName = Generator.Factory.FirstName();
Assert.IsFalse(string.IsNullOrWhiteSpace(firstName.Generate()));
}
[Test]
public void FirstName_Gender_Arg_Is_Not_Generation_Is_Not_Null_Or_Whitespace() {
var firstName = Generator.Factory.FirstName(Gender.Female);
Assert.IsFalse(string.IsNullOrWhiteSpace(firstName.Generate()));
}
[Test]
public void FirstName_INameProvider_Arg_Is_Not_Generation_Is_Not_Null_Or_Whitespace() {
var firstName = Generator.Factory.FirstName(new NameByOrigin());
Assert.IsFalse(string.IsNullOrWhiteSpace(firstName.Generate()));
}
[Test]
public void FirstName_No_Arg_Is_Not_Null_() {
var generator = Generator.Factory.FirstName();
Assert.IsNotNull(generator);
}
[Test]
public void FirstName_Gender_Arg_Is_Not_Null_() {
var generator = Generator.Factory.FirstName(Gender.Female);
Assert.IsNotNull(generator);
}
[Test]
public void FirstName_INameProvider_Arg_Is_Not_Null() {
var generator = Generator.Factory.FirstName(new NameByOrigin());
Assert.IsNotNull(generator);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GeneratorAPI;
using NUnit.Framework.Internal;
using NUnit.Framework;
using Sharpy;
using Sharpy.Enums;
using Sharpy.Implementation;
namespace Tests.Sharpy.Integration
{
[TestFixture]
public class GeneratorExtensionTests
{
[Test]
public void FirstName_No_Arg_Is_Not_Null() {
var firstName = Generator.Factory.FirstName();
Assert.IsNotNull(firstName.Generate());
}
[Test]
public void FirstName_Gender_Arg_Is_Not_Null() {
var firstName = Generator.Factory.FirstName(Gender.Female);
Assert.IsNotNull(firstName.Generate());
}
[Test]
public void FirstName_INameProvider_Arg_Is_Not_Null() {
var firstName = Generator.Factory.FirstName(new NameByOrigin());
Assert.IsNotNull(firstName.Generate());
}
}
}
|
mit
|
C#
|
960c42569e5226f649a9128fefe5ea272897995d
|
Update minor version
|
Vtek/Bartender
|
Cheers.Cqrs/Properties/AssemblyInfo.cs
|
Cheers.Cqrs/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Cheers.Cqrs")]
[assembly: AssemblyDescription("Cheers CQRS contracts")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Valtech")]
[assembly: AssemblyProduct("Cheers")]
[assembly: AssemblyCopyright("© 2016 Valtech")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.1.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Cheers.Cqrs")]
[assembly: AssemblyDescription("Cheers CQRS contracts")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Valtech")]
[assembly: AssemblyProduct("Cheers")]
[assembly: AssemblyCopyright("© 2016 Valtech")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
|
mit
|
C#
|
1b57ecb7da8ba429ba467b6649ac766492ab3b82
|
add async processing
|
elyen3824/myfinanalysis-data
|
data-provider/run.csx
|
data-provider/run.csx
|
using System.Net;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
string symbol = await GetValueFromQuery(req, "symbol");
string start = await GetValueFromQuery(req, "start");
string end = await GetValueFromQuery(req, "end");
// Get request body
dynamic data = await req.Content.ReadAsAsync<object>();
// Set name to query string or body data
string[] symbols = data?.symbols;
HttpResponseMessage result = await GetResponse(req, symbol, symbols, start, end);
return result;
}
private static async Task<string> GetValueFromQuery(HttpRequestMessage req, string key)
{
return req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, key, true) == 0)
.Value;
}
private static async Task<HttpResponseMessage> GetResponse(HttpRequestMessage req, string symbol, string[] symbols, string start, string end)
{
if(symbol == null && symbols == null)
return req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body");
dynamic urls = await GetUrls(symbol, symbols, start, end);
return req.CreateResponse(HttpStatusCode.OK, urls);
}
private static async Task<dynamic> GetUrls(string symbol, string[] symbols, string start, string end)
{
if(symbol !=null)
return $"https://www.quandl.com/api/v3/datasets/WIKI/{symbol}/data.json?start_date={start}&end_date={end}&collapse=daily&transform=cumul";
return string.Empty;
}
|
using System.Net;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
string symbol = GetValueFromQuery(req, "symbol");
string start = GetValueFromQuery(req, "start");
string end = GetValueFromQuery(req, "end");
// Get request body
dynamic data = await req.Content.ReadAsAsync<object>();
// Set name to query string or body data
string[] symbols = data?.symbols;
HttpResponseMessage result = GetResponse(req, symbol, symbols, start, end);
return result;
}
private static string GetValueFromQuery(HttpRequestMessage req, string key)
{
return req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, key, true) == 0)
.Value;
}
private static HttpResponseMessage GetResponse(HttpRequestMessage req, string symbol, string[] symbols, string start, string end)
{
if(symbol == null && symbols == null)
return req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body");
dynamic urls = GetUrls(symbol, symbols, start, end);
return req.CreateResponse(HttpStatusCode.OK, urls);
}
private static dynamic GetUrls(string symbol, string[] symbols, string start, string end)
{
if(symbol !=null)
return $"https://www.quandl.com/api/v3/datasets/WIKI/{symbol}/data.json?start_date={start}&end_date={end}&collapse=daily&transform=cumul";
return string.Empty;
}
|
mit
|
C#
|
d577e7d388d8dd40ffd63b701654eef54089d04a
|
Fix NaN floating point comparison
|
danielchalmers/DesktopWidgets
|
DesktopWidgets/Helpers/DoubleHelper.cs
|
DesktopWidgets/Helpers/DoubleHelper.cs
|
using System;
using DesktopWidgets.Properties;
namespace DesktopWidgets.Helpers
{
public static class DoubleHelper
{
public static bool IsEqual(this double val1, double val2) =>
double.IsNaN(val1) || double.IsNaN(val2) ||
(Math.Abs(val1 - val2) > Settings.Default.DoubleComparisonTolerance);
}
}
|
using System;
using DesktopWidgets.Properties;
namespace DesktopWidgets.Helpers
{
public static class DoubleHelper
{
public static bool IsEqual(this double val1, double val2) =>
double.IsNaN(val1) || double.IsNaN(val1) ||
(Math.Abs(val1 - val2) > Settings.Default.DoubleComparisonTolerance);
}
}
|
apache-2.0
|
C#
|
4918d88e333f5545b1d7c241c93296f106da8e2f
|
Update jobpicker
|
bunashibu/kikan
|
Assets/Scripts/JobPicker.cs
|
Assets/Scripts/JobPicker.cs
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class JobPicker : MonoBehaviour {
public void PickManji() {
PickImpl(0, 30);
}
public void PickMagician() {
PickImpl(1, 2200);
}
public void PickWarrior() {
//PickImpl();
}
void PickImpl(int n, int life) {
_player = Instantiate(_player) as GameObject;
Instantiate(_jobs[n]).transform.parent = _player.transform;
HealthSystem hs = _player.GetComponentInChildren<HealthSystem>();
hs.Init(life, life, manager);
hs.Show();
DisableAllButtons();
DeleteCamera();
}
void DisableAllButtons() {
foreach (Button button in _buttons)
button.interactable = false;
}
void DeleteCamera() {
Destroy(_camera);
}
void Start() {
Destroy(gameObject, 10.0f);
}
[SerializeField] private GameObject _player;
[SerializeField] private GameObject _camera;
[SerializeField] private Button[] _buttons;
[SerializeField] private GameObject[] _jobs;
[SerializeField] private BattleSceneManager manager;
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class JobPicker : MonoBehaviour {
public void PickManji() {
PickImpl(0, 30);
}
public void PickMagician() {
PickImpl(1, 2200);
}
public void PickWarrior() {
//PickImpl();
}
void PickImpl(int n, int life) {
_player = Instantiate(_player) as GameObject;
Job job = Instantiate(_jobs[n]).GetComponent<Job>();
job.transform.parent = _player.transform;
HealthSystem hs = _player.GetComponentInChildren<HealthSystem>();
hs.Init(life, life, manager);
hs.Show();
DisableAllButtons();
DeleteCamera();
}
void DisableAllButtons() {
foreach (Button button in _buttons)
button.interactable = false;
}
void DeleteCamera() {
Destroy(_camera);
}
void Start() {
Destroy(gameObject, 10.0f);
}
[SerializeField] GameObject _player;
[SerializeField] GameObject _camera;
[SerializeField] Button[] _buttons;
[SerializeField] GameObject[] _jobs;
[SerializeField] public BattleSceneManager manager;
}
|
mit
|
C#
|
18f8d5b2690186c73caace681b32011917a75f5b
|
Tweak key format in analytics request
|
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
|
Core/Other/Analytics/AnalyticsReport.cs
|
Core/Other/Analytics/AnalyticsReport.cs
|
using System.Collections;
using System.Collections.Specialized;
using System.Text;
namespace TweetDuck.Core.Other.Analytics{
sealed class AnalyticsReport : IEnumerable{
private OrderedDictionary data = new OrderedDictionary(32);
private int separators;
public void Add(int ignored){ // adding separators to pretty print
data.Add((++separators).ToString(), null);
}
public void Add(string key, string value){
data.Add(key, value);
}
public AnalyticsReport FinalizeReport(){
if (!data.IsReadOnly){
data = data.AsReadOnly();
}
return this;
}
public IEnumerator GetEnumerator(){
return data.GetEnumerator();
}
public NameValueCollection ToNameValueCollection(){
NameValueCollection collection = new NameValueCollection();
foreach(DictionaryEntry entry in data){
if (entry.Value != null){
collection.Add(((string)entry.Key).ToLower().Replace(' ', '_'), (string)entry.Value);
}
}
return collection;
}
public override string ToString(){
StringBuilder build = new StringBuilder();
foreach(DictionaryEntry entry in data){
if (entry.Value == null){
build.AppendLine();
}
else{
build.AppendLine(entry.Key+": "+entry.Value);
}
}
return build.ToString();
}
}
}
|
using System.Collections;
using System.Collections.Specialized;
using System.Text;
namespace TweetDuck.Core.Other.Analytics{
sealed class AnalyticsReport : IEnumerable{
private OrderedDictionary data = new OrderedDictionary(32);
private int separators;
public void Add(int ignored){ // adding separators to pretty print
data.Add((++separators).ToString(), null);
}
public void Add(string key, string value){
data.Add(key, value);
}
public AnalyticsReport FinalizeReport(){
if (!data.IsReadOnly){
data = data.AsReadOnly();
}
return this;
}
public IEnumerator GetEnumerator(){
return data.GetEnumerator();
}
public NameValueCollection ToNameValueCollection(){
NameValueCollection collection = new NameValueCollection();
foreach(DictionaryEntry entry in data){
if (entry.Value != null){
collection.Add((string)entry.Key, (string)entry.Value);
}
}
return collection;
}
public override string ToString(){
StringBuilder build = new StringBuilder();
foreach(DictionaryEntry entry in data){
if (entry.Value == null){
build.AppendLine();
}
else{
build.AppendLine(entry.Key+": "+entry.Value);
}
}
return build.ToString();
}
}
}
|
mit
|
C#
|
52c8cea27dc8e0400fd125b80e262378b8a79153
|
Update spectator/multiplayer endpoint in line with new deployment
|
peppy/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu
|
osu.Game/Online/ProductionEndpointConfiguration.cs
|
osu.Game/Online/ProductionEndpointConfiguration.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Online
{
public class ProductionEndpointConfiguration : EndpointConfiguration
{
public ProductionEndpointConfiguration()
{
WebsiteRootUrl = APIEndpointUrl = @"https://osu.ppy.sh";
APIClientSecret = @"FGc9GAtyHzeQDshWP5Ah7dega8hJACAJpQtw6OXk";
APIClientID = "5";
SpectatorEndpointUrl = "https://spectator.ppy.sh/spectator";
MultiplayerEndpointUrl = "https://spectator.ppy.sh/multiplayer";
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Online
{
public class ProductionEndpointConfiguration : EndpointConfiguration
{
public ProductionEndpointConfiguration()
{
WebsiteRootUrl = APIEndpointUrl = @"https://osu.ppy.sh";
APIClientSecret = @"FGc9GAtyHzeQDshWP5Ah7dega8hJACAJpQtw6OXk";
APIClientID = "5";
SpectatorEndpointUrl = "https://spectator2.ppy.sh/spectator";
MultiplayerEndpointUrl = "https://spectator2.ppy.sh/multiplayer";
}
}
}
|
mit
|
C#
|
c4644c4b99f7f1e3e0147510b1b83cd4e29dca54
|
add successful login
|
Svetlin-Slavchev/Web-Forms-Teamwork,Svetlin-Slavchev/Web-Forms-Teamwork
|
EBooks/EBooks.Web/Account/Login.aspx.cs
|
EBooks/EBooks.Web/Account/Login.aspx.cs
|
using System;
using System.Web;
using System.Web.UI;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Owin;
using EBooks.Web.Models;
using System.Web.Security;
using System.Security.Principal;
namespace EBooks.Web.Account
{
public partial class Login : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LogIn(object sender, EventArgs e)
{
if (Membership.ValidateUser(UserName.Text, Password.Text))
{
HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(UserName.Text), null);
this.ErrorMessage.Visible = true;
this.FailureText.Text = Page.User.Identity.IsAuthenticated.ToString();
}
else
{
this.FailureText.Text = "Incorrect username or password";
this.ErrorMessage.Visible = true;
}
}
}
}
|
using System;
using System.Web;
using System.Web.UI;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Owin;
using EBooks.Web.Models;
using System.Web.Security;
namespace EBooks.Web.Account
{
public partial class Login : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LogIn(object sender, EventArgs e)
{
if (Membership.ValidateUser(this.UserName.Text, this.Password.Text))
{
if (this.RememberMe.Checked)
{
FormsAuthentication.RedirectFromLoginPage(this.UserName.Text, true);
}
else
{
FormsAuthentication.RedirectFromLoginPage(this.UserName.Text, false);
}
}
else
{
this.FailureText.Text = "Login Error";
}
}
}
}
|
mit
|
C#
|
09fc566e9536b98ee259f46a3af5ad0372f8777e
|
Hide character fields header if no fields
|
leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net
|
Joinrpg/Views/Character/Details.cshtml
|
Joinrpg/Views/Character/Details.cshtml
|
@using JoinRpg.Web.Models
@model CharacterDetailsViewModel
<div>
@Html.Partial("CharacterNavigation", Model.Navigation)
@* TODO: Жесточайше причесать эту страницу*@
<dl class="dl-horizontal">
<dt>Игрок</dt>
<dd>@Html.DisplayFor(model => model, "IPlayerCharacter")</dd>
<dt>@Html.DisplayNameFor(model => model.Description)</dt>
<dd>@Html.DisplayFor(model => model.Description)</dd>
<dt>@Html.DisplayNameFor(model => model.ParentGroups)</dt>
<dd>@Html.DisplayFor(model => model.ParentGroups)</dd>
</dl>
@if (Model.Fields.CharacterFields.Any())
{
<h4>Поля персонажа</h4>
<div class="form-horizontal">
@Html.Partial("_EditFieldsPartial", Model.Fields)
</div>
}
@Html.Partial("_PlotForCharacterPartial", Model.Plot)
</div>
|
@using JoinRpg.Web.Models
@model CharacterDetailsViewModel
<div>
@Html.Partial("CharacterNavigation", Model.Navigation)
@* TODO: Жесточайше причесать эту страницу*@
<dl class="dl-horizontal">
<dt>Игрок</dt>
<dd>@Html.DisplayFor(model => model, "IPlayerCharacter")</dd>
<dt>@Html.DisplayNameFor(model => model.Description)</dt>
<dd>@Html.DisplayFor(model => model.Description)</dd>
<dt>@Html.DisplayNameFor(model => model.ParentGroups)</dt>
<dd>@Html.DisplayFor(model => model.ParentGroups)</dd>
</dl>
<h4>Поля персонажа</h4>
<div class="form-horizontal">
@Html.Partial("_EditFieldsPartial", Model.Fields)
</div>
@Html.Partial("_PlotForCharacterPartial", Model.Plot)
</div>
|
mit
|
C#
|
46da86b9063c49149e2d9cf81f6431777e1f990f
|
Implement 100 prisoners problem
|
sakapon/Samples-2016,sakapon/Samples-2016
|
MathSample/PrisonersConsole/Program.cs
|
MathSample/PrisonersConsole/Program.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using Blaze.Randomization;
namespace PrisonersConsole
{
class Program
{
static void Main(string[] args)
{
var bulb = new Bulb();
var prisoners = Enumerable.Range(0, Prisoner.NumberOfPrisoners - 1)
.Select(i => new Prisoner())
.Concat(new[] { new CountingPrisoner() })
.ToArray();
var called = new HashSet<Prisoner>();
for (var i = 0; ; i++)
{
var prisoner = prisoners.GetRandomElement();
called.Add(prisoner);
var answer = prisoner.Call(bulb);
if (answer)
{
var isCorrect = called.Count == Prisoner.NumberOfPrisoners;
Console.WriteLine($"{i} calls");
Console.WriteLine(isCorrect ? "OK" : "NG");
break;
}
}
}
}
public class Bulb
{
public bool IsLighted { get; set; }
}
public class Prisoner
{
public const int NumberOfPrisoners = 100;
bool hasLighted;
public virtual bool Call(Bulb bulb)
{
if (bulb.IsLighted || hasLighted) return false;
bulb.IsLighted = true;
hasLighted = true;
return false;
}
}
public class CountingPrisoner : Prisoner
{
int count;
public override bool Call(Bulb bulb)
{
if (!bulb.IsLighted) return false;
bulb.IsLighted = false;
count++;
return count == NumberOfPrisoners - 1;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrisonersConsole
{
class Program
{
static void Main(string[] args)
{
}
}
}
|
mit
|
C#
|
b903960d7fd41da6997932ea40c05d66960388eb
|
Implement IEquatable
|
beardgame/utilities
|
src/Core/Maybe.cs
|
src/Core/Maybe.cs
|
using System;
using System.Collections.Generic;
namespace Bearded.Utilities
{
public struct Maybe<T> : IEquatable<Maybe<T>>
{
private readonly bool hasValue;
private readonly T value;
private Maybe(T value)
{
hasValue = true;
this.value = value;
}
public static Maybe<T> Nothing() => new Maybe<T>();
public static Maybe<T> Just(T value) => new Maybe<T>(value);
public T ValueOrDefault(T @default) => hasValue ? value : @default;
public Maybe<TOut> Select<TOut>(Func<T, TOut> map) => hasValue ? Maybe.Just(map(value)) : Maybe<TOut>.Nothing();
public Maybe<TOut> SelectMany<TOut>(Func<T, Maybe<TOut>> map) => hasValue ? map(value) : Maybe<TOut>.Nothing();
public void Match(Action<T> onValue, Action onNothing)
{
if (hasValue)
{
onValue(value);
}
else
{
onNothing();
}
}
public bool Equals(Maybe<T> other) =>
hasValue == other.hasValue && EqualityComparer<T>.Default.Equals(value, other.value);
public override bool Equals(object obj) => obj is Maybe<T> other && Equals(other);
public override int GetHashCode() => hasValue ? EqualityComparer<T>.Default.GetHashCode(value) : 0;
}
public static class Maybe
{
public static Maybe<T> FromNullable<T>(T value) where T : class =>
value == null ? Maybe<T>.Nothing() : Maybe<T>.Just(value);
public static Maybe<T> FromNullable<T>(T? value) where T : struct =>
value.HasValue ? Maybe<T>.Just(value.Value) : Maybe<T>.Nothing();
public static Maybe<T> Just<T>(T value) => Maybe<T>.Just(value);
}
}
|
using System;
namespace Bearded.Utilities
{
public struct Maybe<T>
{
private readonly bool hasValue;
private readonly T value;
private Maybe(T value)
{
hasValue = true;
this.value = value;
}
public static Maybe<T> Nothing() => new Maybe<T>();
public static Maybe<T> Just(T value) => new Maybe<T>(value);
public T ValueOrDefault(T @default) => hasValue ? value : @default;
public Maybe<TOut> Select<TOut>(Func<T, TOut> map) => hasValue ? Maybe.Just(map(value)) : Maybe<TOut>.Nothing();
public Maybe<TOut> SelectMany<TOut>(Func<T, Maybe<TOut>> map) => hasValue ? map(value) : Maybe<TOut>.Nothing();
public void Consume(Action<T> action)
{
Match(onValue: action, onNothing: () => { });
}
public void Match(Action<T> onValue, Action onNothing)
{
if (hasValue)
{
onValue(value);
}
else
{
onNothing();
}
}
}
public static class Maybe
{
public static Maybe<T> FromNullable<T>(T value) where T : class =>
value == null ? Maybe<T>.Nothing() : Maybe<T>.Just(value);
public static Maybe<T> FromNullable<T>(T? value) where T : struct =>
value.HasValue ? Maybe<T>.Just(value.Value) : Maybe<T>.Nothing();
public static Maybe<T> Just<T>(T value) => Maybe<T>.Just(value);
}
}
|
mit
|
C#
|
4d852a7a1c09133cfc65b9412cc4eb508017cc43
|
Add test cases attempting to send nulls
|
Tragetaschen/dbus-sharp,arfbtwn/dbus-sharp,openmedicus/dbus-sharp,mono/dbus-sharp,arfbtwn/dbus-sharp,mono/dbus-sharp,Tragetaschen/dbus-sharp,openmedicus/dbus-sharp
|
examples/TestExceptions.cs
|
examples/TestExceptions.cs
|
// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using NDesk.DBus;
using org.freedesktop.DBus;
public class ManagedDBusTestExceptions
{
public static void Main ()
{
Bus bus = Bus.Session;
string myNameReq = "org.ndesk.testexceptions";
ObjectPath myOpath = new ObjectPath ("/org/ndesk/testexceptions");
DemoObject demo;
if (bus.NameHasOwner (myNameReq)) {
demo = bus.GetObject<DemoObject> (myNameReq, myOpath);
} else {
demo = new DemoObject ();
bus.Register (myNameReq, myOpath, demo);
RequestNameReply nameReply = bus.RequestName (myNameReq, NameFlag.None);
Console.WriteLine ("RequestNameReply: " + nameReply);
while (true)
bus.Iterate ();
}
Console.WriteLine ();
//org.freedesktop.DBus.Error.InvalidArgs: Requested bus name "" is not valid
try {
bus.RequestName ("");
} catch (Exception e) {
Console.WriteLine (e);
}
//TODO: make this work as expected (what is expected?)
Console.WriteLine ();
try {
demo.ThrowSomeException ();
} catch (Exception e) {
Console.WriteLine (e);
}
Console.WriteLine ();
try {
demo.ThrowSomeExceptionNoRet ();
} catch (Exception e) {
Console.WriteLine (e);
}
//handle the thrown exception
//conn.Iterate ();
Console.WriteLine ();
try {
demo.HandleVariant (null);
} catch (Exception e) {
Console.WriteLine (e);
}
Console.WriteLine ();
try {
demo.HandleString (null);
} catch (Exception e) {
Console.WriteLine (e);
}
Console.WriteLine ();
try {
demo.HandleArray (null);
} catch (Exception e) {
Console.WriteLine (e);
}
}
}
[Interface ("org.ndesk.testexceptions")]
public class DemoObject : MarshalByRefObject
{
public int ThrowSomeException ()
{
Console.WriteLine ("Asked to throw some Exception");
throw new Exception ("Some Exception");
}
public void ThrowSomeExceptionNoRet ()
{
Console.WriteLine ("Asked to throw some Exception NoRet");
throw new Exception ("Some Exception NoRet");
}
public void HandleVariant (object o)
{
Console.WriteLine (o);
}
public void HandleString (string str)
{
Console.WriteLine (str);
}
public void HandleArray (byte[] arr)
{
Console.WriteLine (arr);
}
}
|
// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using NDesk.DBus;
using org.freedesktop.DBus;
public class ManagedDBusTestExceptions
{
public static void Main ()
{
Bus bus = Bus.Session;
string myNameReq = "org.ndesk.testexceptions";
ObjectPath myOpath = new ObjectPath ("/org/ndesk/testexceptions");
DemoObject demo;
if (bus.NameHasOwner (myNameReq)) {
demo = bus.GetObject<DemoObject> (myNameReq, myOpath);
} else {
demo = new DemoObject ();
bus.Register (myNameReq, myOpath, demo);
RequestNameReply nameReply = bus.RequestName (myNameReq, NameFlag.None);
Console.WriteLine ("RequestNameReply: " + nameReply);
while (true)
bus.Iterate ();
}
Console.WriteLine ();
//org.freedesktop.DBus.Error.InvalidArgs: Requested bus name "" is not valid
try {
bus.RequestName ("");
} catch (Exception e) {
Console.WriteLine (e);
}
//TODO: make this work as expected (what is expected?)
Console.WriteLine ();
try {
demo.ThrowSomeException ();
} catch (Exception e) {
Console.WriteLine (e);
}
Console.WriteLine ();
try {
demo.ThrowSomeExceptionNoRet ();
} catch (Exception e) {
Console.WriteLine (e);
}
//handle the thrown exception
//conn.Iterate ();
}
}
[Interface ("org.ndesk.testexceptions")]
public class DemoObject : MarshalByRefObject
{
public int ThrowSomeException ()
{
Console.WriteLine ("Asked to throw some Exception");
throw new Exception ("Some Exception");
}
public void ThrowSomeExceptionNoRet ()
{
Console.WriteLine ("Asked to throw some Exception NoRet");
throw new Exception ("Some Exception NoRet");
}
}
|
mit
|
C#
|
984e7b9c9d1e3f3d807be07278dcbc02a75abe7b
|
Make the assembly CLS compliant (#88)
|
maxwellb/Microsoft.IO.RecyclableMemoryStream,Microsoft/Microsoft.IO.RecyclableMemoryStream
|
src/Properties/AssemblyInfo.cs
|
src/Properties/AssemblyInfo.cs
|
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Microsoft.IO.RecyclableMemoryStream")]
[assembly: AssemblyDescription("Pooled memory allocator.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft.IO.RecyclableMemoryStream")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9ca0730b-3653-4fc4-b722-9e59fa70ea0b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.2.0")]
[assembly: AssemblyFileVersion("1.3.2.0")]
[assembly: CLSCompliant(true)]
#if !NOFRIENDASSEMBLY
[assembly: InternalsVisibleTo("Microsoft.IO.RecyclableMemoryStream.UnitTests")]
#endif
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Microsoft.IO.RecyclableMemoryStream")]
[assembly: AssemblyDescription("Pooled memory allocator.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft.IO.RecyclableMemoryStream")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9ca0730b-3653-4fc4-b722-9e59fa70ea0b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.2.0")]
[assembly: AssemblyFileVersion("1.3.2.0")]
#if !NOFRIENDASSEMBLY
[assembly: InternalsVisibleTo("Microsoft.IO.RecyclableMemoryStream.UnitTests")]
#endif
|
mit
|
C#
|
87542aea2d0a81a626736f49d5607ed3faafff25
|
Update Authorization.cs
|
giorgalis/skroutz.gr
|
skroutz.gr/Authorization/Authorization.cs
|
skroutz.gr/Authorization/Authorization.cs
|
using Newtonsoft.Json;
using skroutz.gr.ServiceBroker;
using System;
namespace skroutz.gr.Authorization
{
/// <summary>
/// Struct Credentials
/// </summary>
public struct Credentials
{
/// <summary>
/// The client Id you received from skroutz api team.
/// </summary>
[JsonProperty("client_id")]
public string ClientId { get; set; }
/// <summary>
/// The client secret you received from skroutz api team.
/// </summary>
[JsonProperty("client_secret")]
public string ClientSecret { get; set; }
}
/// <summary>
/// Class Authorization.
/// </summary>
internal class Authorization : Request
{
/// <summary>
/// Gets the AuthResponse.
/// </summary>
/// <value>The response.</value>
public AuthResponse AuthResponse { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="Authorization" /> class.
/// </summary>
/// <param name="credentials">The credentials.</param>
/// <param name="skroutzRequest">The SkroutzRequest</param>
/// <exception cref="ArgumentNullException">Thrown when <see cref="Credentials.ClientId"/> or <see cref="Credentials.ClientSecret"/> are null or empty.</exception>
public Authorization(SkroutzRequest skroutzRequest, Credentials credentials)
{
if (string.IsNullOrEmpty(credentials.ClientId))
throw new ArgumentNullException(nameof(credentials.ClientId));
if (string.IsNullOrEmpty(credentials.ClientSecret))
throw new ArgumentNullException(nameof(credentials.ClientSecret));
skroutzRequest.PostData = $"oauth2/token?client_id={credentials.ClientId}&client_secret={credentials.ClientSecret}&grant_type=client_credentials&scope=public";
skroutzRequest.Method = HttpMethod.POST;
this.AuthResponse = PostWebResultAsync(skroutzRequest).ContinueWith((t) =>
JsonConvert.DeserializeObject<AuthResponse>(t.Result.ToString())).Result;
}
}
}
|
using Newtonsoft.Json;
using skroutz.gr.ServiceBroker;
using System;
namespace skroutz.gr.Authorization
{
/// <summary>
/// Struct Credentials
/// </summary>
public struct Credentials
{
/// <summary>
/// The client Id you received from skroutz api team.
/// </summary>
[JsonProperty("client_id")]
public string ClientId { get; set; }
/// <summary>
/// The client secret you received from skroutz api team.
/// </summary>
[JsonProperty("client_secret")]
public string ClientSecret { get; set; }
}
/// <summary>
/// Class Authorization.
/// </summary>
internal class Authorization : Request
{
/// <summary>
/// Gets the AuthResponse.
/// </summary>
/// <value>The response.</value>
public AuthResponse AuthResponse { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="Authorization" /> class.
/// </summary>
/// <param name="credentials">The credentials.</param>
/// <param name="skroutzRequest">The SkroutzRequest</param>
/// <exception cref="ArgumentNullException">Thrown when <see cref="Credentials.ClientId"/> or <see cref="Credentials.ClientSecret"/> are null or empty.</exception>
public Authorization(SkroutzRequest skroutzRequest, Credentials credentials)
{
if (string.IsNullOrEmpty(credentials.ClientId)) throw new ArgumentNullException(nameof(credentials.ClientId));
if (string.IsNullOrEmpty(credentials.ClientSecret)) throw new ArgumentNullException(nameof(credentials.ClientSecret));
skroutzRequest.PostData = $"oauth2/token?client_id={credentials.ClientId}&client_secret={credentials.ClientSecret}&grant_type=client_credentials&scope=public";
skroutzRequest.Method = HttpMethod.POST;
this.AuthResponse = PostWebResultAsync(skroutzRequest).ContinueWith((t) =>
JsonConvert.DeserializeObject<AuthResponse>(t.Result.ToString())).Result;
}
}
}
|
mit
|
C#
|
2ce85fe1eb9b177d5b35f81e8dde29f2e21b862e
|
Increment version to v1.1.0.12
|
XeroAPI/XeroAPI.Net,TDaphneB/XeroAPI.Net,jcvandan/XeroAPI.Net,MatthewSteeples/XeroAPI.Net
|
source/XeroApi/Properties/AssemblyInfo.cs
|
source/XeroApi/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XeroApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xero")]
[assembly: AssemblyProduct("XeroApi")]
[assembly: AssemblyCopyright("Copyright © Xero 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")]
// 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.12")]
[assembly: AssemblyFileVersion("1.1.0.12")]
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XeroApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xero")]
[assembly: AssemblyProduct("XeroApi")]
[assembly: AssemblyCopyright("Copyright © Xero 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")]
// 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.11")]
[assembly: AssemblyFileVersion("1.1.0.11")]
|
mit
|
C#
|
d0567e4a196e54c95af02eeffd30e5d44a3e0061
|
add setters to Result.cs
|
ilovepi/Compiler,ilovepi/Compiler
|
compiler/frontend/Result.cs
|
compiler/frontend/Result.cs
|
namespace compiler.frontend
{
public enum Kind
{
Constant,
Variable,
Register,
Conditional
}
public struct Result
{
/// <summary>
/// Const, Variable, Register, Conditional
/// </summary>
public int Kind { get; set; }
/// <summary>
/// Numeric value
/// </summary>
public int Value { get; set; }
/// <summary>
/// UUID for an identifier
/// </summary>
public int Id { get; set; }
/// <summary>
/// Register number
/// </summary>
public int Regno { get; set; }
/// <summary>
/// Comparison Code ??? maybe I forgot what this was
/// </summary>
public int Cc { get; set; }
/// <summary>
/// True branch offset
/// </summary>
public int TrueValue { get; set; }
/// <summary>
/// False branch offset
/// </summary>
public int FalseValue { get; set; }
}
}
|
using System;
namespace compiler
{
public enum Kind
{
Constant,
Variable,
Register,
Conditional
}
public struct Result
{
/// <summary>
/// Const, Variable, Register, Conditional
/// </summary>
public int Kind { get; }
/// <summary>
/// Numeric value
/// </summary>
public int Value { get; }
/// <summary>
/// UUID for an identifier
/// </summary>
public int Id { get; }
/// <summary>
/// Register number
/// </summary>
public int Regno { get; }
/// <summary>
/// Comparison Code ??? maybe I forgot what this was
/// </summary>
public int Cc { get; }
/// <summary>
/// True branch offset
/// </summary>
public int TrueValue { get; }
/// <summary>
/// False branch offset
/// </summary>
public int FalseValue { get; }
}
}
|
mit
|
C#
|
e340456dd4382b8d778a7508f0ca03b6f8bae80d
|
Remove using
|
peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,smoogipooo/osu-framework
|
osu.Framework/Platform/DisplayMode.cs
|
osu.Framework/Platform/DisplayMode.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.Drawing;
namespace osu.Framework.Platform
{
/// <summary>
/// Represents a display mode on a given <see cref="Display"/>.
/// </summary>
public readonly struct DisplayMode
{
/// <summary>
/// The pixel format of the display mode, if available.
/// </summary>
public readonly string Format;
/// <summary>
/// The dimensions of the screen resolution in pixels.
/// </summary>
public readonly Size Size;
/// <summary>
/// The number of bits that represent the colour value for each pixel.
/// </summary>
public readonly int BitsPerPixel;
/// <summary>
/// The refresh rate in hertz.
/// </summary>
public readonly int RefreshRate;
/// <summary>
/// The index of the display mode as determined by the windowing backend.
/// </summary>
public readonly int Index;
/// <summary>
/// The index of the display this mode belongs to as determined by the windowing backend.
/// </summary>
public readonly int DisplayIndex;
public DisplayMode(string format, Size size, int bitsPerPixel, int refreshRate, int index, int displayIndex)
{
Format = format ?? "Unknown";
Size = size;
BitsPerPixel = bitsPerPixel;
RefreshRate = refreshRate;
Index = index;
DisplayIndex = displayIndex;
}
public override string ToString() => $"Size: {Size}, BitsPerPixel: {BitsPerPixel}, RefreshRate: {RefreshRate}, Format: {Format}, Index: {Index}, DisplayIndex: {DisplayIndex}";
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Drawing;
namespace osu.Framework.Platform
{
/// <summary>
/// Represents a display mode on a given <see cref="Display"/>.
/// </summary>
public readonly struct DisplayMode
{
/// <summary>
/// The pixel format of the display mode, if available.
/// </summary>
public readonly string Format;
/// <summary>
/// The dimensions of the screen resolution in pixels.
/// </summary>
public readonly Size Size;
/// <summary>
/// The number of bits that represent the colour value for each pixel.
/// </summary>
public readonly int BitsPerPixel;
/// <summary>
/// The refresh rate in hertz.
/// </summary>
public readonly int RefreshRate;
/// <summary>
/// The index of the display mode as determined by the windowing backend.
/// </summary>
public readonly int Index;
/// <summary>
/// The index of the display this mode belongs to as determined by the windowing backend.
/// </summary>
public readonly int DisplayIndex;
public DisplayMode(string format, Size size, int bitsPerPixel, int refreshRate, int index, int displayIndex)
{
Format = format ?? "Unknown";
Size = size;
BitsPerPixel = bitsPerPixel;
RefreshRate = refreshRate;
Index = index;
DisplayIndex = displayIndex;
}
public override string ToString() => $"Size: {Size}, BitsPerPixel: {BitsPerPixel}, RefreshRate: {RefreshRate}, Format: {Format}, Index: {Index}, DisplayIndex: {DisplayIndex}";
}
}
|
mit
|
C#
|
670a30b64bdf1f315898c7a931c0dccc3da7af70
|
Remove usage of `.Result` in `ArchiveReader`
|
peppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,ppy/osu
|
osu.Game/IO/Archives/ArchiveReader.cs
|
osu.Game/IO/Archives/ArchiveReader.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using osu.Framework.IO.Stores;
namespace osu.Game.IO.Archives
{
public abstract class ArchiveReader : IResourceStore<byte[]>
{
/// <summary>
/// Opens a stream for reading a specific file from this archive.
/// </summary>
public abstract Stream GetStream(string name);
public IEnumerable<string> GetAvailableResources() => Filenames;
public abstract void Dispose();
/// <summary>
/// The name of this archive (usually the containing filename).
/// </summary>
public readonly string Name;
protected ArchiveReader(string name)
{
Name = name;
}
public abstract IEnumerable<string> Filenames { get; }
public virtual byte[] Get(string name)
{
using (Stream input = GetStream(name))
{
if (input == null)
return null;
byte[] buffer = new byte[input.Length];
input.Read(buffer);
return buffer;
}
}
public async Task<byte[]> GetAsync(string name, CancellationToken cancellationToken = default)
{
using (Stream input = GetStream(name))
{
if (input == null)
return null;
byte[] buffer = new byte[input.Length];
await input.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
return buffer;
}
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using osu.Framework.IO.Stores;
namespace osu.Game.IO.Archives
{
public abstract class ArchiveReader : IResourceStore<byte[]>
{
/// <summary>
/// Opens a stream for reading a specific file from this archive.
/// </summary>
public abstract Stream GetStream(string name);
public IEnumerable<string> GetAvailableResources() => Filenames;
public abstract void Dispose();
/// <summary>
/// The name of this archive (usually the containing filename).
/// </summary>
public readonly string Name;
protected ArchiveReader(string name)
{
Name = name;
}
public abstract IEnumerable<string> Filenames { get; }
public virtual byte[] Get(string name) => GetAsync(name).Result;
public async Task<byte[]> GetAsync(string name, CancellationToken cancellationToken = default)
{
using (Stream input = GetStream(name))
{
if (input == null)
return null;
byte[] buffer = new byte[input.Length];
await input.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
return buffer;
}
}
}
}
|
mit
|
C#
|
02f26e7bc38149a136b697147dc5c3fd9f3042cc
|
add data member
|
Paymentsense/Dapper.SimpleSave
|
PS.Mothership.Core/PS.Mothership.Core.Common/Dto/Application/ApplicationDetailsMetadataDto.cs
|
PS.Mothership.Core/PS.Mothership.Core.Common/Dto/Application/ApplicationDetailsMetadataDto.cs
|
using System.Collections.Generic;
using System.Runtime.Serialization;
using PS.Mothership.Core.Common.Template.Gen;
namespace PS.Mothership.Core.Common.Dto.Application
{
[DataContract]
public class ApplicationDetailsMetadataDto
{
[DataMember]
public IList<GenBusinessLegalType> BusinessLegalTypes { get; set; }
}
}
|
using System.Collections.Generic;
using System.Runtime.Serialization;
using PS.Mothership.Core.Common.Template.Gen;
namespace PS.Mothership.Core.Common.Dto.Application
{
[DataContract]
public class ApplicationDetailsMetadataDto
{
public IList<GenBusinessLegalType> BusinessLegalTypes { get; set; }
}
}
|
mit
|
C#
|
a0e127f8d1c3c130c117fbc123b26fefa833bae7
|
Remove unused using statements
|
nfleet/.net-sdk
|
NFleetSDK/Data/DepotData.cs
|
NFleetSDK/Data/DepotData.cs
|
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace NFleet.Data
{
public class DepotData : IResponseData, IVersioned
{
public static string MIMEType = "application/vnd.jyu.nfleet.depot";
public static string MIMEVersion = "2.2";
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Info1 { get; set; }
[DataMember]
public List<CapacityData> Capacities { get; set; }
[DataMember]
public LocationData Location { get; set; }
[DataMember]
public List<Link> Meta { get; set; }
[DataMember]
public string Type { get; set; }
[DataMember]
public string DataSource { get; set; }
[IgnoreDataMember]
int IVersioned.VersionNumber { get; set; }
public DepotData()
{
Capacities = new List<CapacityData>();
Meta = new List<Link>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
namespace NFleet.Data
{
public class DepotData : IResponseData, IVersioned
{
public static string MIMEType = "application/vnd.jyu.nfleet.depot";
public static string MIMEVersion = "2.2";
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Info1 { get; set; }
[DataMember]
public List<CapacityData> Capacities { get; set; }
[DataMember]
public LocationData Location { get; set; }
[DataMember]
public List<Link> Meta { get; set; }
[DataMember]
public string Type { get; set; }
[DataMember]
public string DataSource { get; set; }
[IgnoreDataMember]
int IVersioned.VersionNumber { get; set; }
public DepotData()
{
Capacities = new List<CapacityData>();
Meta = new List<Link>();
}
}
}
|
mit
|
C#
|
d2493bc9f9c489401f1577f78ea8e5f9642f9db2
|
fix bug in the RdnRmnSdSy handler
|
PipatPosawad/nChronic
|
src/Chronic/Handlers/RdnRmnSdSyHandler.cs
|
src/Chronic/Handlers/RdnRmnSdSyHandler.cs
|
using Chronic.Tags.Repeaters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chronic.Handlers
{
public class RdnRmnSdSyHandler : IHandler
{
public Span Handle(IList<Token> tokens, Options options)
{
var month = tokens[1].GetTag<RepeaterMonthName>();
var day = tokens[2].GetTag<ScalarDay>().Value;
var year = tokens[3].GetTag<ScalarYear>().Value;
if (Time.IsMonthOverflow(year, (int)month.Value, day))
{
return null;
}
try
{
var start = Time.New(year, (int)month.Value, day);
var end = start.AddDays(1);
return new Span(start, end);
}
catch (ArgumentException)
{
return null;
}
}
}
}
|
using Chronic.Tags.Repeaters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chronic.Handlers
{
public class RdnRmnSdSyHandler : IHandler
{
public Span Handle(IList<Token> tokens, Options options)
{
var month = tokens[1].GetTag<RepeaterMonthName>();
var day = tokens[2].GetTag<ScalarDay>().Value;
var year = tokens[2].GetTag<ScalarYear>().Value;
if (Time.IsMonthOverflow(year, (int)month.Value, day))
{
return null;
}
try
{
var start = Time.New(year, (int)month.Value, day);
var end = start.AddDays(1);
return new Span(start, end);
}
catch (ArgumentException)
{
return null;
}
}
}
}
|
mit
|
C#
|
b44d326439509174dcba3f0bf46376821aa0d46d
|
Add CIV.Interfaces reference in Main
|
lou1306/CIV,lou1306/CIV
|
CIV/Program.cs
|
CIV/Program.cs
|
using static System.Console;
using CIV.Ccs;
using CIV.Interfaces;
namespace CIV
{
class Program
{
static void Main(string[] args)
{
var text = System.IO.File.ReadAllText(args[0]);
var processes = CcsFacade.ParseAll(text);
var trace = CcsFacade.RandomTrace(processes["Prison"], 450);
foreach (var action in trace)
{
WriteLine(action);
}
}
}
}
|
using static System.Console;
using CIV.Ccs;
namespace CIV
{
class Program
{
static void Main(string[] args)
{
var text = System.IO.File.ReadAllText(args[0]);
var processes = CcsFacade.ParseAll(text);
var trace = CcsFacade.RandomTrace(processes["Prison"], 450);
foreach (var action in trace)
{
WriteLine(action);
}
}
}
}
|
mit
|
C#
|
c4529577880047b72a870ddb0ab221b1ee7e7a90
|
add BeginScope as dictionary extension method
|
exceptionless/Foundatio,FoundatioFx/Foundatio
|
src/Foundatio/Logging/LoggerExtensions.cs
|
src/Foundatio/Logging/LoggerExtensions.cs
|
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace Foundatio.Logging {
public static class LoggerExtensions {
public static ILogger GetLogger(this object target) {
return target is IHaveLogger accessor ? accessor.Logger : NullLogger.Instance;
}
public static IDisposable BeginScope(this ILogger logger, string key, object value) {
return logger.BeginScope(new Dictionary<string, object> { { key, value } });
}
}
}
|
using System;
using Foundatio.Logging;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Logging.Internal;
namespace Foundatio.Logging {
public static class LoggerExtensions {
public static ILogger GetLogger(this object target) {
return target is IHaveLogger accessor ? accessor.Logger : NullLogger.Instance;
}
}
}
|
apache-2.0
|
C#
|
b3b3b07f8d47c811230b368c7c18775d1b48efe9
|
Update HtmlDocumentLoadCompleted.cs
|
zzzprojects/html-agility-pack,zzzprojects/html-agility-pack
|
src/HAPLight/HtmlDocumentLoadCompleted.cs
|
src/HAPLight/HtmlDocumentLoadCompleted.cs
|
using System;
namespace HtmlAgilityPack
{
/// <summary>
/// Happens when a document has been loaded
/// </summary>
public class HtmlDocumentLoadCompleted : EventArgs
{
#region Fields
/// <summary>
/// The document that has been loaded
/// </summary>
public HtmlDocument Document{get;set;}
/// <summary>
/// If an error occurred when loading the document, null if not
/// </summary>
public Exception Error;
#endregion
#region C'tors
internal HtmlDocumentLoadCompleted(HtmlDocument doc)
{
Document = doc;
}
internal HtmlDocumentLoadCompleted(Exception err)
{
Error = err;
}
#endregion
}
}
|
using System;
namespace HtmlAgilityPack
{
/// <summary>
/// Happens when a document has been loaded
/// </summary>
public class HtmlDocumentLoadCompleted : EventArgs
{
#region Fields
/// <summary>
/// The document that has been loaded
/// </summary>
public HtmlDocument Document{get;set;}
/// <summary>
/// If an error occured when loading the document, null if not
/// </summary>
public Exception Error;
#endregion
#region C'tors
internal HtmlDocumentLoadCompleted(HtmlDocument doc)
{
Document = doc;
}
internal HtmlDocumentLoadCompleted(Exception err)
{
Error = err;
}
#endregion
}
}
|
mit
|
C#
|
1b480ab285778299ef744a08f2fa776cc37bd3b4
|
Add RestfulJson to ContentType
|
ASP-NET-Core-Boilerplate/Framework,ASP-NET-Core-Boilerplate/Framework,ASP-NET-MVC-Boilerplate/Framework,ASP-NET-Core-Boilerplate/Framework,ASP-NET-Core-Boilerplate/Framework,ASP-NET-MVC-Boilerplate/Framework
|
Source/Boxed.AspNetCore/ContentType.cs
|
Source/Boxed.AspNetCore/ContentType.cs
|
namespace Boxed.AspNetCore
{
/// <summary>
/// A list of internet media types, which are a standard identifier used on the Internet to indicate the type of
/// data that a file contains. Web browsers use them to determine how to display, output or handle files and search
/// engines use them to classify data files on the web.
/// </summary>
public static class ContentType
{
/// <summary>Atom feeds.</summary>
public const string Atom = "application/atom+xml";
/// <summary>HTML; Defined in RFC 2854.</summary>
public const string Html = "text/html";
/// <summary>Form URL Encoded.</summary>
public const string FormUrlEncoded = "application/x-www-form-urlencoded";
/// <summary>GIF image; Defined in RFC 2045 and RFC 2046.</summary>
public const string Gif = "image/gif";
/// <summary>JPEG JFIF image; Defined in RFC 2045 and RFC 2046.</summary>
public const string Jpg = "image/jpeg";
/// <summary>JavaScript Object Notation JSON; Defined in RFC 4627.</summary>
public const string Json = "application/json";
/// <summary>Web App Manifest.</summary>
public const string Manifest = "application/manifest+json";
/// <summary>Multi-part form daata; Defined in RFC 2388.</summary>
public const string MultipartFormData = "multipart/form-data";
/// <summary>Portable Network Graphics; Registered,[8] Defined in RFC 2083.</summary>
public const string Png = "image/png";
/// <summary>REST'ful JavaScript Object Notation JSON; Defined at http://restfuljson.org/.</summary>
public const string RestfulJson = "application/vnd.restful+json";
/// <summary>Rich Site Summary; Defined by Harvard Law.</summary>
public const string Rss = "application/rss+xml";
/// <summary>Textual data; Defined in RFC 2046 and RFC 3676.</summary>
public const string Text = "text/plain";
/// <summary>Extensible Markup Language; Defined in RFC 3023</summary>
public const string Xml = "application/xml";
/// <summary>Compressed ZIP.</summary>
public const string Zip = "application/zip";
}
}
|
namespace Boxed.AspNetCore
{
/// <summary>
/// A list of internet media types, which are a standard identifier used on the Internet to indicate the type of
/// data that a file contains. Web browsers use them to determine how to display, output or handle files and search
/// engines use them to classify data files on the web.
/// </summary>
public static class ContentType
{
/// <summary>Atom feeds.</summary>
public const string Atom = "application/atom+xml";
/// <summary>HTML; Defined in RFC 2854.</summary>
public const string Html = "text/html";
/// <summary>Form URL Encoded.</summary>
public const string FormUrlEncoded = "application/x-www-form-urlencoded";
/// <summary>GIF image; Defined in RFC 2045 and RFC 2046.</summary>
public const string Gif = "image/gif";
/// <summary>JPEG JFIF image; Defined in RFC 2045 and RFC 2046.</summary>
public const string Jpg = "image/jpeg";
/// <summary>JavaScript Object Notation JSON; Defined in RFC 4627.</summary>
public const string Json = "application/json";
/// <summary>Web App Manifest.</summary>
public const string Manifest = "application/manifest+json";
/// <summary>Multi-part form daata; Defined in RFC 2388.</summary>
public const string MultipartFormData = "multipart/form-data";
/// <summary>Portable Network Graphics; Registered,[8] Defined in RFC 2083.</summary>
public const string Png = "image/png";
/// <summary>Rich Site Summary; Defined by Harvard Law.</summary>
public const string Rss = "application/rss+xml";
/// <summary>Textual data; Defined in RFC 2046 and RFC 3676.</summary>
public const string Text = "text/plain";
/// <summary>Extensible Markup Language; Defined in RFC 3023</summary>
public const string Xml = "application/xml";
/// <summary>Compressed ZIP.</summary>
public const string Zip = "application/zip";
}
}
|
mit
|
C#
|
5b3cfc8cd27061cdf739308ffb8489a211cdc5c6
|
add style to score
|
sungry/CS177
|
unityTree/Assets/_Scripts/HUDScript.cs
|
unityTree/Assets/_Scripts/HUDScript.cs
|
using UnityEngine;
using System.Collections;
using UnitySampleAssets._2D;
public class HUDScript : MonoBehaviour {
//Heads up Display
float playerScore;
float currentSpeed;
// Update is called once per frame
void Update ()
{
playerScore += (Time.deltaTime * 10);
//currentSpeed = PlatformerCharacter2D.getMaxSpeed();
}
public void IncreaseScore(int amount)
{
playerScore += amount;
}
void OnDisable()
{
PlayerPrefs.SetInt("Score", (int)(playerScore*10));
}
void OnGUI()
{
if (playerScore > 0)
{
GUI.contentColor = Color.white;
GUI.skin.textArea.fontSize = 22;
GUI.skin.textArea.fontStyle = FontStyle.Bold;
}
else
{
GUI.contentColor = Color.red;
}
string score = ((int)(playerScore * 10)).ToString();
int len = "Score: ".Length + score.Length;
GUI.TextArea(new Rect(10, 10, len*12, 30), "Score: " + (int)(playerScore * 10));
}
}
|
using UnityEngine;
using System.Collections;
using UnitySampleAssets._2D;
public class HUDScript : MonoBehaviour {
//Heads up Display
float playerScore;
float currentSpeed;
// Update is called once per frame
void Update ()
{
playerScore += (Time.deltaTime * 10);
//currentSpeed = PlatformerCharacter2D.getMaxSpeed();
}
public void IncreaseScore(int amount)
{
playerScore += amount;
}
void OnDisable()
{
PlayerPrefs.SetInt("Score", (int)(playerScore*10));
}
void OnGUI()
{
if (playerScore > 0)
{
GUI.contentColor = Color.black;
}
else
{
GUI.contentColor = Color.red;
}
//position 10, 10 100 wide 30 tall
GUI.Label(new Rect(10, 10, 300, 30), "Score: " + (int)(playerScore * 10));
}
}
|
mit
|
C#
|
9a82cbfce44c5c010ce3692b17d5c275c5fb3f23
|
Fix canvas sizing issue
|
steffenWi/xwt,antmicro/xwt,akrisiun/xwt,lytico/xwt,TheBrainTech/xwt,mminns/xwt,mono/xwt,cra0zy/xwt,mminns/xwt,iainx/xwt,hamekoz/xwt,sevoku/xwt,hwthomas/xwt,directhex/xwt,residuum/xwt
|
Xwt.WPF/Xwt.WPFBackend/CanvasBackend.cs
|
Xwt.WPF/Xwt.WPFBackend/CanvasBackend.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xwt.Backends;
using System.Windows;
using SWC = System.Windows.Controls;
namespace Xwt.WPFBackend
{
class CanvasBackend
: WidgetBackend, ICanvasBackend
{
#region ICanvasBackend Members
public CanvasBackend ()
{
Canvas = new ExCanvas ();
Canvas.RenderAction = Render;
}
private ExCanvas Canvas
{
get { return (ExCanvas) Widget; }
set { Widget = value; }
}
private ICanvasEventSink CanvasEventSink
{
get { return (ICanvasEventSink) EventSink; }
}
private void Render (System.Windows.Media.DrawingContext dc)
{
CanvasEventSink.OnDraw (new Xwt.WPFBackend.DrawingContext (dc, Widget.GetScaleFactor ()), new Rectangle (0, 0, Widget.ActualWidth, Widget.ActualHeight));
}
public void QueueDraw ()
{
Canvas.InvalidateVisual ();
}
public void QueueDraw (Rectangle rect)
{
Canvas.InvalidateVisual ();
}
public void AddChild (IWidgetBackend widget, Rectangle bounds)
{
UIElement element = widget.NativeWidget as UIElement;
if (element == null)
throw new ArgumentException ();
if (!Canvas.Children.Contains (element))
Canvas.Children.Add (element);
SetChildBounds (widget, bounds);
}
public void SetChildBounds (IWidgetBackend widget, Rectangle bounds)
{
FrameworkElement element = widget.NativeWidget as FrameworkElement;
if (element == null)
throw new ArgumentException ();
SWC.Canvas.SetTop (element, bounds.Top);
SWC.Canvas.SetLeft (element, bounds.Left);
// We substract the widget margin here because the size we are assigning is the actual size, not including the WPF marings
var h = bounds.Height - ((WidgetBackend)widget).Frontend.Margin.VerticalSpacing;
var w = bounds.Width - ((WidgetBackend)widget).Frontend.Margin.HorizontalSpacing;
h = (h > 0) ? h : 0;
w = (w > 0) ? w : 0;
// Measure the widget again using the allocation constraints. This is necessary
// because WPF widgets my cache some measurement information based on the
// constraints provided in the last Measure call (which when calculating the
// preferred size is normally set to infinite.
element.InvalidateMeasure ();
element.Measure (new System.Windows.Size (w, h));
element.Height = h;
element.Width = w;
element.UpdateLayout ();
}
public void RemoveChild (IWidgetBackend widget)
{
UIElement element = widget.NativeWidget as UIElement;
if (element == null)
throw new ArgumentException ();
Canvas.Children.Remove (element);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xwt.Backends;
using System.Windows;
using SWC = System.Windows.Controls;
namespace Xwt.WPFBackend
{
class CanvasBackend
: WidgetBackend, ICanvasBackend
{
#region ICanvasBackend Members
public CanvasBackend ()
{
Canvas = new ExCanvas ();
Canvas.RenderAction = Render;
}
private ExCanvas Canvas
{
get { return (ExCanvas) Widget; }
set { Widget = value; }
}
private ICanvasEventSink CanvasEventSink
{
get { return (ICanvasEventSink) EventSink; }
}
private void Render (System.Windows.Media.DrawingContext dc)
{
CanvasEventSink.OnDraw (new Xwt.WPFBackend.DrawingContext (dc, Widget.GetScaleFactor ()), new Rectangle (0, 0, Widget.ActualWidth, Widget.ActualHeight));
}
public void QueueDraw ()
{
Canvas.InvalidateVisual ();
}
public void QueueDraw (Rectangle rect)
{
Canvas.InvalidateVisual ();
}
public void AddChild (IWidgetBackend widget, Rectangle bounds)
{
UIElement element = widget.NativeWidget as UIElement;
if (element == null)
throw new ArgumentException ();
if (!Canvas.Children.Contains (element))
Canvas.Children.Add (element);
SetChildBounds (widget, bounds);
}
public void SetChildBounds (IWidgetBackend widget, Rectangle bounds)
{
FrameworkElement element = widget.NativeWidget as FrameworkElement;
if (element == null)
throw new ArgumentException ();
SWC.Canvas.SetTop (element, bounds.Top);
SWC.Canvas.SetLeft (element, bounds.Left);
// We substract the widget margin here because the size we are assigning is the actual size, not including the WPF marings
var h = bounds.Height - ((WidgetBackend)widget).Frontend.Margin.VerticalSpacing;
var w = bounds.Width - ((WidgetBackend)widget).Frontend.Margin.HorizontalSpacing;
element.Height = (h > 0) ? h : 0;
element.Width = (w > 0) ? w : 0;
((FrameworkElement)widget.NativeWidget).UpdateLayout ();
}
public void RemoveChild (IWidgetBackend widget)
{
UIElement element = widget.NativeWidget as UIElement;
if (element == null)
throw new ArgumentException ();
Canvas.Children.Remove (element);
}
#endregion
}
}
|
mit
|
C#
|
6409e1024edb65328ae5923b1c7dd69aecdda3c4
|
use custom app config location for tests
|
config-r/config-r
|
tests/ConfigR.Tests.Acceptance.Roslyn.CSharp/Support/ConfigFile.cs
|
tests/ConfigR.Tests.Acceptance.Roslyn.CSharp/Support/ConfigFile.cs
|
// <copyright file="ConfigFile.cs" company="ConfigR contributors">
// Copyright (c) ConfigR contributors. (configr.net@gmail.com)
// </copyright>
namespace ConfigR.Tests.Acceptance.Roslyn.CSharp.Support
{
using System;
using System.IO;
public static class ConfigFile
{
public static string DefaultPath { get; } = GetDefaultPath();
public static IDisposable Create(string contents)
{
using (var writer = new StreamWriter(DefaultPath))
{
writer.Write(contents);
writer.Flush();
}
return new Disposable(() => File.Delete(DefaultPath));
}
private static string GetDefaultPath()
{
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", "Test.config");
return Path.ChangeExtension(
AppDomain.CurrentDomain.SetupInformation.VSHostingAgnosticConfigurationFile(), "csx");
}
private sealed class Disposable : IDisposable
{
private readonly Action whenDisposed;
public Disposable(Action whenDisposed)
{
this.whenDisposed = whenDisposed;
}
public void Dispose() => this.whenDisposed?.Invoke();
}
}
}
|
// <copyright file="ConfigFile.cs" company="ConfigR contributors">
// Copyright (c) ConfigR contributors. (configr.net@gmail.com)
// </copyright>
namespace ConfigR.Tests.Acceptance.Roslyn.CSharp.Support
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
public static class ConfigFile
{
[SuppressMessage(
"StyleCop.CSharp.LayoutRules",
"SA1500:CurlyBracketsForMultiLineStatementsMustNotShareLine",
Justification = "Bug in StyleCop - see https://stylecop.codeplex.com/workitem/7723.")]
public static string DefaultPath { get; } =
Path.ChangeExtension(AppDomain.CurrentDomain.SetupInformation.VSHostingAgnosticConfigurationFile(), "csx");
public static IDisposable Create(string contents)
{
using (var writer = new StreamWriter(DefaultPath))
{
writer.Write(contents);
writer.Flush();
}
return new Disposable(() => File.Delete(DefaultPath));
}
private sealed class Disposable : IDisposable
{
private readonly Action whenDisposed;
public Disposable(Action whenDisposed)
{
this.whenDisposed = whenDisposed;
}
public void Dispose() => this.whenDisposed?.Invoke();
}
}
}
|
mit
|
C#
|
97871db6299855cf3ca68c9e17d5c21038291034
|
Add comments for Conflict
|
couchbase/couchbase-lite-net,couchbase/couchbase-lite-net,couchbase/couchbase-lite-net
|
src/Couchbase.Lite.Shared/API/Conflict/Conflict.cs
|
src/Couchbase.Lite.Shared/API/Conflict/Conflict.cs
|
//
// Conflict.cs
//
// Copyright (c) 2019 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using JetBrains.Annotations;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace Couchbase.Lite
{
/// <summary>
/// Conflict contains information of the conflicted documents, including local and
/// remote document’s content. The null content means that the document is deleted.
/// </summary>
public class Conflict
{
/// <summary>
/// The conflict resolved document id.
/// </summary>
[NotNull]
public string DocumentID { get; }
/// <summary>
/// The document in local database. If null, the document is deleted.
/// </summary>
[CanBeNull]
public Document LocalDocument { get; }
/// <summary>
/// The document in remote database. If null, the document is deleted.
/// </summary>
[CanBeNull]
public Document RemoteDocument { get; }
internal Conflict(string docID, Document localDoc, Document remoteDoc)
{
Debug.Assert(localDoc != null || remoteDoc != null,
"Local and remote document shouldn't be empty at same time, when resolving conflict.");
DocumentID = docID;
LocalDocument = localDoc;
RemoteDocument = remoteDoc;
}
}
}
|
//
// Conflict.cs
//
// Copyright (c) 2019 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using JetBrains.Annotations;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace Couchbase.Lite
{
public class Conflict
{
/// <summary>
/// The conflict resolved document id.
/// </summary>
[NotNull]
public string DocumentID { get; }
/// <summary>
/// The document in local database. If null, the document is deleted.
/// </summary>
[CanBeNull]
public Document LocalDocument { get; }
/// <summary>
/// The document in remote database. If null, the document is deleted.
/// </summary>
[CanBeNull]
public Document RemoteDocument { get; }
internal Conflict(string docID, Document localDoc, Document remoteDoc)
{
Debug.Assert(localDoc != null || remoteDoc != null,
"Local and remote document shouldn't be empty at same time, when resolving conflict.");
DocumentID = docID;
LocalDocument = localDoc;
RemoteDocument = remoteDoc;
}
}
}
|
apache-2.0
|
C#
|
83d28b0c89d286a56186bef7b106091ccb8bff86
|
fix debug dump of ops commands
|
StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis
|
service/FunctionApp/Messages/OpsMessage.cs
|
service/FunctionApp/Messages/OpsMessage.cs
|
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace FunctionApp.Messages
{
public enum OpsMessageType
{
ProcessReferenceXmldoc = 1,
}
public class OpsMessage
{
public OpsMessageType Type { get; set; }
[JsonExtensionData]
public IDictionary<string, JToken> Arguments { get; set; }
}
}
|
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace FunctionApp.Messages
{
public enum OpsMessageType
{
ProcessReferenceXmldoc,
}
public class OpsMessage
{
public OpsMessageType Type { get; set; }
[JsonExtensionData]
public IDictionary<string, JToken> Arguments { get; set; }
}
}
|
mit
|
C#
|
54d30c21b9aaef61af312c666c8ef7cb4abf9ef7
|
Test fix works
|
hartmannr76/EasyIoC,hartmannr76/EasyIoC
|
EasyIoC/AssemblyFinder.cs
|
EasyIoC/AssemblyFinder.cs
|
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.DependencyModel;
namespace EasyIoC {
public class AssemblyFinder {
private readonly HashSet<string> _defaultIgnoredAssemblies = new HashSet<string>() { "Microsoft.", "System." };
public ImmutableList<Assembly> FindAssemblies(HashSet<string> ignoredAssemblies) {
var ctx = DependencyContext.Default;
ignoredAssemblies = ignoredAssemblies ?? _defaultIgnoredAssemblies;
var assemblyNames = from lib in ctx.RuntimeLibraries
from assemblyName in lib.GetDefaultAssemblyNames(ctx)
where ignoredAssemblies.Any(x => assemblyName.Name.StartsWith(x))
select assemblyName;
var lookup = assemblyNames.ToLookup(x => x.Name).Select(x => x.First());
var asList = lookup.Select(Assembly.Load).ToImmutableList();
return asList;
}
}
}
|
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.DependencyModel;
namespace EasyIoC {
public class AssemblyFinder {
private readonly HashSet<string> _defaultIgnoredAssemblies = new HashSet<string>() { "Microsoft.", "System." };
public ImmutableList<Assembly> FindAssemblies(HashSet<string> ignoredAssemblies) {
var ctx = DependencyContext.Default;
ignoredAssemblies = ignoredAssemblies ?? _defaultIgnoredAssemblies;
var assemblyNames = from li in ctx.RuntimeLibraries
from assemblyName in lib.GetDefaultAssemblyNames(ctx)
where ignoredAssemblies.Any(x => assemblyName.Name.StartsWith(x))
select assemblyName;
var lookup = assemblyNames.ToLookup(x => x.Name).Select(x => x.First());
var asList = lookup.Select(Assembly.Load).ToImmutableList();
return asList;
}
}
}
|
mit
|
C#
|
8f34c75a8742a1754246f2d3383b2fcab48dddcf
|
Revert "Revert "registration of api controllers fixed""
|
borismod/ReSharperTnT,borismod/ReSharperTnT
|
ReSharperTnT/Bootstrapper.cs
|
ReSharperTnT/Bootstrapper.cs
|
using System.Reflection;
using System.Web.Http;
using Autofac;
using Autofac.Integration.WebApi;
namespace ReSharperTnT
{
public class Bootstrapper
{
public static void Init()
{
var bootstrapper = new Bootstrapper();
var container = bootstrapper.CreateContainer();
var autofacWebApiDependencyResolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = autofacWebApiDependencyResolver;
}
private readonly IContainer _container;
public Bootstrapper()
{
var builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterAssemblyTypes(typeof (Bootstrapper).Assembly)
.AsImplementedInterfaces();
_container = builder.Build();
}
public IContainer CreateContainer()
{
return _container;
}
public T Get<T>()
{
return _container.Resolve<T>();
}
}
}
|
using System.Web.Http;
using Autofac;
using Autofac.Integration.WebApi;
namespace ReSharperTnT
{
public class Bootstrapper
{
static Bootstrapper()
{
Init();
}
public static void Init()
{
var bootstrapper = new Bootstrapper();
var container = bootstrapper.CreateContainer();
var autofacWebApiDependencyResolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = autofacWebApiDependencyResolver;
}
private readonly IContainer _container;
public Bootstrapper()
{
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(typeof (Bootstrapper).Assembly)
.AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof (Bootstrapper).Assembly)
.Where(c=>c.Name.EndsWith("Controller"))
.AsSelf();
_container = builder.Build();
}
public IContainer CreateContainer()
{
return _container;
}
public T Get<T>()
{
return _container.Resolve<T>();
}
}
}
|
apache-2.0
|
C#
|
056f8d0c23426f0822bc02690cbb9d5ee46dfb4b
|
Add new fluent syntax: DayOfWeek.Monday.EveryWeek()
|
diaconesq/RecurringDates
|
RecurringDates/Extensions.cs
|
RecurringDates/Extensions.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RecurringDates
{
public static class Extensions
{
public static SetUnionRule Or(this IRule first, params IRule[] otherRules)
{
return new SetUnionRule {Rules = new[] {first}.Concat(otherRules)};
}
public static SetIntersectionRule And(this IRule first, params IRule[] otherRules)
{
return new SetIntersectionRule { Rules = new[] { first }.Concat(otherRules) };
}
public static SetDifferenceRule Except(this IRule includeRule, IRule excludeRule)
{
return new SetDifferenceRule { IncludeRule = includeRule , ExcludeRule = excludeRule };
}
public static NotRule Not(this IRule rule)
{
return new NotRule { ReferencedRule = rule };
}
public static NthInMonthRule NthInMonth(this IRule rule, int nthOccurrence)
{
return new NthInMonthRule {Nth = nthOccurrence, ReferencedRule = rule};
}
public static MonthsFilterRule InMonths(this IRule rule, params Month[] months)
{
return new MonthsFilterRule { Months = months, ReferencedRule = rule };
}
public static DayOfWeekRule EveryWeek(this DayOfWeek dow)
{
return new DayOfWeekRule(dow);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RecurringDates
{
public static class Extensions
{
public static SetUnionRule Or(this IRule first, params IRule[] otherRules)
{
return new SetUnionRule {Rules = new[] {first}.Concat(otherRules)};
}
public static SetIntersectionRule And(this IRule first, params IRule[] otherRules)
{
return new SetIntersectionRule { Rules = new[] { first }.Concat(otherRules) };
}
public static SetDifferenceRule Except(this IRule includeRule, IRule excludeRule)
{
return new SetDifferenceRule { IncludeRule = includeRule , ExcludeRule = excludeRule };
}
public static NotRule Not(this IRule rule)
{
return new NotRule { ReferencedRule = rule };
}
public static NthInMonthRule NthInMonth(this IRule rule, int nthOccurrence)
{
return new NthInMonthRule {Nth = nthOccurrence, ReferencedRule = rule};
}
public static MonthsFilterRule InMonths(this IRule rule, params Month[] months)
{
return new MonthsFilterRule { Months = months, ReferencedRule = rule };
}
}
}
|
bsd-2-clause
|
C#
|
9693d19c9986f611678c092b3eab47c09c7a5e22
|
Use more concrete types
|
LordMike/TMDbLib
|
TMDbLib/Utilities/KnownForConverter.cs
|
TMDbLib/Utilities/KnownForConverter.cs
|
using System;
using Newtonsoft.Json.Linq;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Search;
namespace TMDbLib.Utilities
{
internal class KnownForConverter : JsonCreationConverter<KnownForBase>
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(KnownForBase);
}
protected override KnownForBase GetInstance(JObject jObject)
{
MediaType mediaType = jObject["media_type"].ToObject<MediaType>();
switch (mediaType)
{
case MediaType.Movie:
return new KnownForMovie();
case MediaType.Tv:
return new KnownForTv();
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
|
using System;
using Newtonsoft.Json.Linq;
using TMDbLib.Objects.Search;
namespace TMDbLib.Utilities
{
internal class KnownForConverter : JsonCreationConverter<KnownForBase>
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(KnownForBase);
}
protected override KnownForBase GetInstance(JObject jObject)
{
string mediaType = jObject["media_type"].ToString();
switch (mediaType)
{
case "movie":
return new KnownForMovie();
case "tv":
return new KnownForTv();
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
|
mit
|
C#
|
707817ee38c3a0bd8f19882565a87ee51ac80b09
|
edit about page with correct description
|
wilsonvargas/Cognitive-Service-using-Xamarin.Forms
|
DemoCognitiveServices/DemoCognitiveServices/Views/AboutPage.xaml.cs
|
DemoCognitiveServices/DemoCognitiveServices/Views/AboutPage.xaml.cs
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace DemoCognitiveServices.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class AboutPage : ContentPage
{
public AboutPage()
{
InitializeComponent();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace DemoCognitiveServices.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class AboutPage : ContentPage
{
public AboutPage()
{
InitializeComponent();
BindingContext = new AboutPageViewModel();
}
}
class AboutPageViewModel : INotifyPropertyChanged
{
public AboutPageViewModel()
{
IncreaseCountCommand = new Command(IncreaseCount);
}
int count;
string countDisplay = "You clicked 0 times.";
public string CountDisplay
{
get { return countDisplay; }
set { countDisplay = value; OnPropertyChanged(); }
}
public ICommand IncreaseCountCommand { get; }
void IncreaseCount() =>
CountDisplay = $"You clicked {++count} times";
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged([CallerMemberName]string propertyName = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
|
mit
|
C#
|
31848adf87770e551b9a016fe5fb360c803209b2
|
Address issue #1
|
JSkimming/TorSharp,joelverhagen/TorSharp
|
TorSharp/Tools/Tor/TorControlClient.cs
|
TorSharp/Tools/Tor/TorControlClient.cs
|
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Knapcode.TorSharp.Tools.Tor
{
public class TorControlClient
{
private const string SuccessResponse = "250 OK";
private const int BufferSize = 256;
private TcpClient _tcpClient;
private StreamReader _reader;
private StreamWriter _writer;
public async Task ConnectAsync(string hostname, int port)
{
_tcpClient = new TcpClient();
await _tcpClient.ConnectAsync(hostname, port);
var networkStream = _tcpClient.GetStream();
_reader = new StreamReader(networkStream, Encoding.ASCII, false, BufferSize, true);
_writer = new StreamWriter(networkStream, Encoding.ASCII, BufferSize, true);
}
public async Task AuthenticateAsync(string password)
{
var command = password != null ? $"AUTHENTICATE \"{password}\"" : "AUTHENTICATE";
await SendCommandAsync(command);
}
public async Task CleanCircuitsAsync()
{
await SendCommandAsync("SIGNAL NEWNYM");
}
public void Close()
{
if (_tcpClient != null)
{
_tcpClient.Close();
_reader.Dispose();
_writer.Dispose();
}
}
private async Task<string> SendCommandAsync(string command)
{
if (_tcpClient == null)
{
throw new TorControlException("The Tor control client has not connected.");
}
await _writer.WriteLineAsync(command);
await _writer.FlushAsync();
var response = await _reader.ReadLineAsync();
if (response != SuccessResponse)
{
throw new TorControlException($"The command to authenticate failed with error: {response}");
}
return response;
}
}
}
|
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Knapcode.TorSharp.Tools.Tor
{
public class TorControlClient
{
private const string SuccessResponse = "250 OK";
private const int BufferSize = 256;
private TcpClient _tcpClient;
private StreamReader _reader;
private StreamWriter _writer;
public async Task ConnectAsync(string hostname, int port)
{
_tcpClient = new TcpClient();
await _tcpClient.ConnectAsync(hostname, port);
var networkStream = _tcpClient.GetStream();
_reader = new StreamReader(networkStream, Encoding.ASCII, false, BufferSize, true);
_writer = new StreamWriter(networkStream, Encoding.ASCII, BufferSize, true);
}
public async Task AuthenticateAsync(string password)
{
var command = password != null ? $"AUTHENTICATE \"{password}\"" : "AUTHENTICATE";
await SendCommandAsync(command);
}
public async Task CleanCircuitsAsync()
{
await SendCommandAsync("SIGNAL NEWNYM");
}
public void Close()
{
if (_tcpClient != null)
{
_tcpClient.Close();
_reader.Dispose();
_reader.Dispose();
}
}
private async Task<string> SendCommandAsync(string command)
{
if (_tcpClient == null)
{
throw new TorControlException("The Tor control client has not connected.");
}
await _writer.WriteLineAsync(command);
await _writer.FlushAsync();
var response = await _reader.ReadLineAsync();
if (response != SuccessResponse)
{
throw new TorControlException($"The command to authenticate failed with error: {response}");
}
return response;
}
}
}
|
mit
|
C#
|
0cf7eca272c079b90d15e8ab335725be898dd1be
|
Add missing dependencies to autofac module
|
arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5
|
src/Arkivverket.Arkade/Util/ArkadeAutofacModule.cs
|
src/Arkivverket.Arkade/Util/ArkadeAutofacModule.cs
|
using Arkivverket.Arkade.Core;
using Arkivverket.Arkade.Core.Addml;
using Arkivverket.Arkade.Core.Noark5;
using Arkivverket.Arkade.Identify;
using Arkivverket.Arkade.Logging;
using Arkivverket.Arkade.Tests;
using Arkivverket.Arkade.Tests.Noark5;
using Autofac;
namespace Arkivverket.Arkade.Util
{
public class ArkadeAutofacModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<AddmlDatasetTestEngine>().AsSelf();
builder.RegisterType<AddmlProcessRunner>().AsSelf();
builder.RegisterType<ArchiveContentReader>().As<IArchiveContentReader>();
builder.RegisterType<ArchiveIdentifier>().As<IArchiveIdentifier>();
builder.RegisterType<FlatFileReaderFactory>().AsSelf();
builder.RegisterType<Noark5TestEngine>().AsSelf().SingleInstance();
builder.RegisterType<Noark5TestProvider>().AsSelf();
builder.RegisterType<StatusEventHandler>().As<IStatusEventHandler>().SingleInstance();
builder.RegisterType<TarCompressionUtility>().As<ICompressionUtility>();
builder.RegisterType<TestEngineFactory>().AsSelf();
builder.RegisterType<TestProvider>().As<ITestProvider>();
builder.RegisterType<TestSessionFactory>().AsSelf();
}
}
}
|
using Arkivverket.Arkade.Core;
using Arkivverket.Arkade.Core.Noark5;
using Arkivverket.Arkade.Identify;
using Arkivverket.Arkade.Logging;
using Arkivverket.Arkade.Tests;
using Arkivverket.Arkade.Tests.Noark5;
using Autofac;
namespace Arkivverket.Arkade.Util
{
public class ArkadeAutofacModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<TarCompressionUtility>().As<ICompressionUtility>();
builder.RegisterType<TestSessionFactory>().AsSelf();
builder.RegisterType<ArchiveIdentifier>().As<IArchiveIdentifier>();
builder.RegisterType<Noark5TestEngine>().AsSelf().SingleInstance();
builder.RegisterType<ArchiveContentReader>().As<IArchiveContentReader>();
builder.RegisterType<TestProvider>().As<ITestProvider>();
builder.RegisterType<StatusEventHandler>().As<IStatusEventHandler>().SingleInstance();
builder.RegisterType<Noark5TestProvider>().AsSelf();
}
}
}
|
agpl-3.0
|
C#
|
2c5ed16cd657599aae66fb5607af8c9665e3d79f
|
Update AdminMenu.cs
|
johnnyqian/Orchard,jersiovic/Orchard,rtpHarry/Orchard,AdvantageCS/Orchard,SouleDesigns/SouleDesigns.Orchard,grapto/Orchard.CloudBust,ehe888/Orchard,LaserSrl/Orchard,omidnasri/Orchard,hbulzy/Orchard,jimasp/Orchard,rtpHarry/Orchard,tobydodds/folklife,omidnasri/Orchard,jimasp/Orchard,yersans/Orchard,bedegaming-aleksej/Orchard,sfmskywalker/Orchard,sfmskywalker/Orchard,tobydodds/folklife,IDeliverable/Orchard,jtkech/Orchard,xkproject/Orchard,sfmskywalker/Orchard,brownjordaninternational/OrchardCMS,OrchardCMS/Orchard,rtpHarry/Orchard,bedegaming-aleksej/Orchard,jersiovic/Orchard,fassetar/Orchard,abhishekluv/Orchard,Serlead/Orchard,Lombiq/Orchard,sfmskywalker/Orchard,IDeliverable/Orchard,phillipsj/Orchard,Codinlab/Orchard,hannan-azam/Orchard,aaronamm/Orchard,abhishekluv/Orchard,aaronamm/Orchard,AdvantageCS/Orchard,grapto/Orchard.CloudBust,abhishekluv/Orchard,bedegaming-aleksej/Orchard,ehe888/Orchard,Codinlab/Orchard,Fogolan/OrchardForWork,Dolphinsimon/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,Serlead/Orchard,vairam-svs/Orchard,sfmskywalker/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,jchenga/Orchard,brownjordaninternational/OrchardCMS,Dolphinsimon/Orchard,jimasp/Orchard,IDeliverable/Orchard,tobydodds/folklife,rtpHarry/Orchard,Fogolan/OrchardForWork,vairam-svs/Orchard,li0803/Orchard,xkproject/Orchard,mvarblow/Orchard,SouleDesigns/SouleDesigns.Orchard,grapto/Orchard.CloudBust,Praggie/Orchard,omidnasri/Orchard,fassetar/Orchard,hannan-azam/Orchard,omidnasri/Orchard,hbulzy/Orchard,johnnyqian/Orchard,yersans/Orchard,jersiovic/Orchard,hannan-azam/Orchard,grapto/Orchard.CloudBust,li0803/Orchard,gcsuk/Orchard,johnnyqian/Orchard,li0803/Orchard,Serlead/Orchard,abhishekluv/Orchard,omidnasri/Orchard,johnnyqian/Orchard,AdvantageCS/Orchard,sfmskywalker/Orchard,Praggie/Orchard,tobydodds/folklife,gcsuk/Orchard,aaronamm/Orchard,grapto/Orchard.CloudBust,brownjordaninternational/OrchardCMS,gcsuk/Orchard,abhishekluv/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,tobydodds/folklife,brownjordaninternational/OrchardCMS,jchenga/Orchard,jchenga/Orchard,jagraz/Orchard,ehe888/Orchard,Praggie/Orchard,AdvantageCS/Orchard,vairam-svs/Orchard,LaserSrl/Orchard,mvarblow/Orchard,hannan-azam/Orchard,mvarblow/Orchard,sfmskywalker/Orchard,aaronamm/Orchard,johnnyqian/Orchard,jagraz/Orchard,OrchardCMS/Orchard,SouleDesigns/SouleDesigns.Orchard,hannan-azam/Orchard,hbulzy/Orchard,omidnasri/Orchard,jagraz/Orchard,bedegaming-aleksej/Orchard,OrchardCMS/Orchard,Lombiq/Orchard,vairam-svs/Orchard,brownjordaninternational/OrchardCMS,ehe888/Orchard,jagraz/Orchard,aaronamm/Orchard,jimasp/Orchard,OrchardCMS/Orchard,Praggie/Orchard,omidnasri/Orchard,AdvantageCS/Orchard,mvarblow/Orchard,xkproject/Orchard,SouleDesigns/SouleDesigns.Orchard,Fogolan/OrchardForWork,jchenga/Orchard,rtpHarry/Orchard,jtkech/Orchard,jchenga/Orchard,vairam-svs/Orchard,Codinlab/Orchard,xkproject/Orchard,ehe888/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,jtkech/Orchard,grapto/Orchard.CloudBust,Dolphinsimon/Orchard,Codinlab/Orchard,Codinlab/Orchard,fassetar/Orchard,bedegaming-aleksej/Orchard,mvarblow/Orchard,Lombiq/Orchard,yersans/Orchard,SouleDesigns/SouleDesigns.Orchard,omidnasri/Orchard,yersans/Orchard,jagraz/Orchard,sfmskywalker/Orchard,fassetar/Orchard,hbulzy/Orchard,Serlead/Orchard,abhishekluv/Orchard,jtkech/Orchard,LaserSrl/Orchard,Dolphinsimon/Orchard,LaserSrl/Orchard,Lombiq/Orchard,IDeliverable/Orchard,phillipsj/Orchard,jtkech/Orchard,jersiovic/Orchard,phillipsj/Orchard,li0803/Orchard,Dolphinsimon/Orchard,li0803/Orchard,gcsuk/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,omidnasri/Orchard,phillipsj/Orchard,Lombiq/Orchard,gcsuk/Orchard,OrchardCMS/Orchard,fassetar/Orchard,jersiovic/Orchard,xkproject/Orchard,yersans/Orchard,jimasp/Orchard,LaserSrl/Orchard,Fogolan/OrchardForWork,Serlead/Orchard,Fogolan/OrchardForWork,IDeliverable/Orchard,hbulzy/Orchard,phillipsj/Orchard,tobydodds/folklife,Praggie/Orchard
|
src/Orchard.Web/Modules/Orchard.Alias/AdminMenu.cs
|
src/Orchard.Web/Modules/Orchard.Alias/AdminMenu.cs
|
using Orchard.Environment.Extensions;
using Orchard.Localization;
using Orchard.Security;
using Orchard.UI.Navigation;
namespace Orchard.Alias {
[OrchardFeature("Orchard.Alias.UI")]
public class AdminMenu : INavigationProvider {
public Localizer T { get; set; }
public string MenuName { get { return "admin"; } }
public void GetNavigation(NavigationBuilder builder) {
builder.Add(T("Aliases"), "1.4.1", menu => {
menu.LinkToFirstChild(true);
menu.Add(T("Unmanaged"), "1", item => item.Action("IndexUnmanaged", "Admin", new { area = "Orchard.Alias" }).Permission(StandardPermissions.SiteOwner).LocalNav());
menu.Add(T("Managed"), "2", item => item.Action("IndexManaged", "Admin", new { area = "Orchard.Alias" }).Permission(StandardPermissions.SiteOwner).LocalNav());
});
}
}
}
|
using Orchard.Environment.Extensions;
using Orchard.Localization;
using Orchard.Security;
using Orchard.UI.Navigation;
namespace Orchard.Alias {
[OrchardFeature("Orchard.Alias.UI")]
public class AdminMenu : INavigationProvider {
public Localizer T { get; set; }
public string MenuName { get { return "admin"; } }
public void GetNavigation(NavigationBuilder builder) {
builder.AddImageSet("aliases");
builder.Add(T("Aliases"), "1.4.1", menu => {
menu.LinkToFirstChild(true);
menu.Add(T("Unmanaged"), "1", item => item.Action("IndexUnmanaged", "Admin", new { area = "Orchard.Alias" }).Permission(StandardPermissions.SiteOwner).LocalNav());
menu.Add(T("Managed"), "2", item => item.Action("IndexManaged", "Admin", new { area = "Orchard.Alias" }).Permission(StandardPermissions.SiteOwner).LocalNav());
});
}
}
}
|
bsd-3-clause
|
C#
|
15154930ca516a22b7640235130fd67e95b21cbc
|
Implement PhysicalFileSystem methods
|
appharbor/appharbor-cli
|
src/AppHarbor/PhysicalFileSystem.cs
|
src/AppHarbor/PhysicalFileSystem.cs
|
using System;
using System.IO;
namespace AppHarbor
{
public class PhysicalFileSystem : IFileSystem
{
public void Delete(string path)
{
var directory = new DirectoryInfo(path);
if (directory.Exists)
{
directory.Delete(recursive: true);
return;
}
var file = new FileInfo(path);
if (file.Exists)
{
file.Delete();
}
}
public Stream OpenRead(string path)
{
var file = new FileInfo(path);
if (file.Exists)
{
return file.OpenRead();
}
throw new FileNotFoundException();
}
public Stream OpenWrite(string path)
{
var file = new FileInfo(path);
if (!file.Directory.Exists)
{
file.Directory.Create();
}
return file.OpenWrite();
}
}
}
|
using System;
using System.IO;
namespace AppHarbor
{
public class PhysicalFileSystem : IFileSystem
{
public void Delete(string path)
{
throw new NotImplementedException();
}
public Stream OpenRead(string path)
{
throw new NotImplementedException();
}
public Stream OpenWrite(string path)
{
throw new NotImplementedException();
}
}
}
|
mit
|
C#
|
7b0d4f5f1a8220db10e879837b9740c28e2361b3
|
Initialize links.
|
jmrgn/schema-hypermedia,jmrgn/schema-hypermedia
|
src/Schema.Hypermedia/Models/HypermediaResource.cs
|
src/Schema.Hypermedia/Models/HypermediaResource.cs
|
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace Schema.Hypermedia.Models
{
public abstract class HypermediaResource : IHypermediaResource
{
public IEnumerable<Link> Links { get; set; }
protected HypermediaResource()
{
Links = new List<Link>();
}
public void Validate(JsonSchema schema)
{
Validate(schema, new JsonSerializer());
}
public virtual void Validate(JsonSchema schema, JsonSerializer serializer)
{
var jObj = JObject.FromObject(this, serializer);
IList<string> reasons = new List<string>();
if (!jObj.IsValid(schema, out reasons))
{
var builder = new StringBuilder("Entity is not valid for the given scehma. Reasons: ");
string delim = "";
foreach (var reason in reasons)
{
builder.Append(delim).Append(reason);
delim = ", ";
}
throw new ArgumentException(builder.ToString());
}
}
}
}
|
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace Schema.Hypermedia.Models
{
public abstract class HypermediaResource : IHypermediaResource
{
public IEnumerable<Link> Links { get; set; }
public void Validate(JsonSchema schema)
{
Validate(schema, new JsonSerializer());
}
public virtual void Validate(JsonSchema schema, JsonSerializer serializer)
{
var jObj = JObject.FromObject(this, serializer);
IList<string> reasons = new List<string>();
if (!jObj.IsValid(schema, out reasons))
{
var builder = new StringBuilder("Entity is not valid for the given scehma. Reasons: ");
string delim = "";
foreach (var reason in reasons)
{
builder.Append(delim).Append(reason);
delim = ", ";
}
throw new ArgumentException(builder.ToString());
}
}
}
}
|
apache-2.0
|
C#
|
702ca6fa1f84eea2d5178d64e132c3865c1a9bef
|
add setter for status
|
jasoncavaliere/Nirvana,nirvana-framework/Nirvana,jasoncavaliere/Nirvana,jasoncavaliere/Nirvana,jasoncavaliere/Nirvana
|
src/Nirvana/CQRS/Queue/IQueueController.cs
|
src/Nirvana/CQRS/Queue/IQueueController.cs
|
using System;
using System.Collections.Generic;
using Nirvana.Configuration;
namespace Nirvana.CQRS.Queue
{
public interface IQueueController
{
QueueStatus Status { get; set; }
bool InitializeAll();
//bool StopAll();
// bool StartRoot(string rootName);
// bool StopRoot(string rootName);
//
// bool StartQueue(Type messageType);
// bool StopQueue(Type messageType);
IDictionary<string, QueueReference[]> ByRoot();
QueueReference[] ForRootType(string rootType);
QueueReference[] AllQueues();
QueueReference GetQueueReferenceFor(NirvanaTaskInformation typeRouting);
}
}
|
using System;
using System.Collections.Generic;
using Nirvana.Configuration;
namespace Nirvana.CQRS.Queue
{
public interface IQueueController
{
QueueStatus Status { get; }
bool InitializeAll();
//bool StopAll();
// bool StartRoot(string rootName);
// bool StopRoot(string rootName);
//
// bool StartQueue(Type messageType);
// bool StopQueue(Type messageType);
IDictionary<string, QueueReference[]> ByRoot();
QueueReference[] ForRootType(string rootType);
QueueReference[] AllQueues();
QueueReference GetQueueReferenceFor(NirvanaTaskInformation typeRouting);
}
}
|
apache-2.0
|
C#
|
4a8d25d7cbdfde5a5087519630aa35a7e0d498d7
|
Remove _enabledParticles & ITickable from LeptonPlasma
|
tainicom/Aether
|
Source/Core/LeptonPlasma.cs
|
Source/Core/LeptonPlasma.cs
|
#region License
// Copyright 2015 Kastellanos Nikolaos
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using tainicom.Aether.Elementary;
using tainicom.Aether.Engine.Data;
using Microsoft.Xna.Framework;
using tainicom.Aether.Elementary.Leptons;
namespace tainicom.Aether.Core
{
public class LeptonPlasma: BasePlasma
{
public LeptonPlasma()
{
}
}
}
|
#region License
// Copyright 2015 Kastellanos Nikolaos
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using tainicom.Aether.Elementary;
using tainicom.Aether.Engine.Data;
using Microsoft.Xna.Framework;
using tainicom.Aether.Elementary.Leptons;
namespace tainicom.Aether.Core
{
public class LeptonPlasma: BasePlasma, ITickable
{
EnabledList<IAether> _enabledParticles;
public LeptonPlasma()
{
_enabledParticles = new EnabledList<IAether>();
}
public void Tick(GameTime gameTime)
{
_enabledParticles.Process();
foreach (ILepton item in _enabledParticles)
{
//item.Tick(gameTime);
}
return;
}
protected override void InsertItem(int index, IAether item)
{
base.InsertItem(index, item);
_enabledParticles.Add(item);
return;
}
protected override void RemoveItem(int index)
{
IAether item = this[index];
if (_enabledParticles.Contains(item)) _enabledParticles.Remove(item);
base.RemoveItem(index);
}
public void Enable(ILepton item)
{
_enabledParticles.Enable(item);
}
public void Disable(ILepton item)
{
_enabledParticles.Disable(item);
}
}
}
|
apache-2.0
|
C#
|
ce413bba03ffca04c458096306579ff6e4dc0318
|
Enable tracing for IAP code
|
GoogleCloudPlatform/iap-desktop,GoogleCloudPlatform/iap-desktop
|
Google.Solutions.IapDesktop.Application.Test/FixtureBase.cs
|
Google.Solutions.IapDesktop.Application.Test/FixtureBase.cs
|
//
// Copyright 2019 Google LLC
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
using NUnit.Framework;
using System.Diagnostics;
namespace Google.Solutions.IapDesktop.Application.Test
{
public abstract class FixtureBase
{
private static TraceSource[] Traces = new[]
{
Google.Solutions.Compute.TraceSources.Compute,
Google.Solutions.IapDesktop.Application.TraceSources.IapDesktop
};
[SetUp]
public void SetUpTracing()
{
var listener = new ConsoleTraceListener();
foreach (var trace in Traces)
{
trace.Listeners.Add(listener);
trace.Switch.Level = System.Diagnostics.SourceLevels.Verbose;
}
}
}
}
|
//
// Copyright 2019 Google LLC
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
using NUnit.Framework;
using System.Diagnostics;
namespace Google.Solutions.IapDesktop.Application.Test
{
public abstract class FixtureBase
{
[SetUp]
public void SetUpTracing()
{
TraceSources.IapDesktop.Listeners.Add(new ConsoleTraceListener());
TraceSources.IapDesktop.Switch.Level = SourceLevels.Verbose;
}
}
}
|
apache-2.0
|
C#
|
a2c8ea46bf41df44cf866bdfbd17a0136b0dd1a5
|
Update LineSegmentTests.cs
|
Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D
|
tests/Core2D.UnitTests/Path/Segments/LineSegmentTests.cs
|
tests/Core2D.UnitTests/Path/Segments/LineSegmentTests.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 Core2D.Path.Segments;
using Core2D.Shapes;
using System.Linq;
using Xunit;
namespace Core2D.UnitTests
{
public class LineSegmentTests
{
[Fact]
[Trait("Core2D.Path", "Segments")]
public void GetPoints_Should_Return_All_Segment_Points()
{
var segment = new LineSegment()
{
Point = new PointShape()
};
var target = segment.GetPoints();
var count = target.Count();
Assert.Equal(1, count);
Assert.Contains(segment.Point, target);
}
[Fact]
[Trait("Core2D.Path", "Segments")]
public void ToString_Should_Return_Path_Markup()
{
var target = new LineSegment()
{
Point = new PointShape()
};
var actual = target.ToString();
Assert.Equal("L0,0", actual);
}
}
}
|
// 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 Core2D.Path.Segments;
using Core2D.Shapes;
using System.Linq;
using Xunit;
namespace Core2D.UnitTests
{
public class LineSegmentTests
{
[Fact]
[Trait("Core2D.Path", "Segments")]
public void GetPoints_Should_Return_All_Segment_Points()
{
var segment = new LineSegment()
{
Point = new PointShape()
};
var target = segment.GetPoints();
Assert.Equal(1, target.Count());
Assert.Contains(segment.Point, target);
}
[Fact]
[Trait("Core2D.Path", "Segments")]
public void ToString_Should_Return_Path_Markup()
{
var target = new LineSegment()
{
Point = new PointShape()
};
var actual = target.ToString();
Assert.Equal("L0,0", actual);
}
}
}
|
mit
|
C#
|
3ffba5e79d38518603bfa6352e83b373d5c84caa
|
Remove redudent paramiter
|
wrightg42/todo-list,It423/todo-list
|
Todo-List/Todo-List/Note.cs
|
Todo-List/Todo-List/Note.cs
|
// Note.cs
// <copyright file="Note.cs"> This code is protected under the MIT License. </copyright>
using System.Collections.Generic;
namespace Todo_List
{
/// <summary>
/// A data representation of a note.
/// </summary>
public class Note
{
/// <summary>
/// Initializes a new instance of the <see cref="Note" /> class.
/// </summary>
public Note()
{
this.Title = string.Empty;
this.Categories = new List<string>();
}
/// <summary>
/// Initializes a new instance of the <see cref="Note" /> class.
/// </summary>
/// <param name="title"> The title of the note. </param>
/// <param name="categories"> The categories the note is in. </param>
public Note(string title, List<string> categories)
{
this.Title = title;
this.Categories = categories;
}
/// <summary>
/// Gets or sets the title of the note.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Gets or sets the categories the note is in.
/// </summary>
public List<string> Categories { get; set; }
}
}
|
// Note.cs
// <copyright file="Note.cs"> This code is protected under the MIT License. </copyright>
using System.Collections.Generic;
namespace Todo_List
{
/// <summary>
/// A data representation of a note.
/// </summary>
public class Note
{
/// <summary>
/// Initializes a new instance of the <see cref="Note" /> class.
/// </summary>
public Note()
{
this.Title = string.Empty;
this.Categories = new List<string>();
}
/// <summary>
/// Initializes a new instance of the <see cref="Note" /> class.
/// </summary>
/// <param name="title"> The title of the note. </param>
/// <param name="categories"> The categories the note is in. </param>
/// <param name="content"> The content of the note. </param>
public Note(string title, List<string> categories, string content)
{
this.Title = title;
this.Categories = categories;
}
/// <summary>
/// Gets or sets the title of the note.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Gets or sets the categories the note is in.
/// </summary>
public List<string> Categories { get; set; }
}
}
|
mit
|
C#
|
42673870c4cb4e81435f46e03d70a8f74c230de5
|
Use the generic music icon for the Play Song button
|
babycaseny/banshee,stsundermann/banshee,stsundermann/banshee,Dynalon/banshee-osx,GNOME/banshee,babycaseny/banshee,ixfalia/banshee,arfbtwn/banshee,babycaseny/banshee,dufoli/banshee,Carbenium/banshee,Carbenium/banshee,arfbtwn/banshee,GNOME/banshee,stsundermann/banshee,Dynalon/banshee-osx,babycaseny/banshee,babycaseny/banshee,Dynalon/banshee-osx,ixfalia/banshee,ixfalia/banshee,dufoli/banshee,dufoli/banshee,GNOME/banshee,stsundermann/banshee,babycaseny/banshee,dufoli/banshee,ixfalia/banshee,Dynalon/banshee-osx,babycaseny/banshee,Dynalon/banshee-osx,dufoli/banshee,dufoli/banshee,stsundermann/banshee,Carbenium/banshee,GNOME/banshee,arfbtwn/banshee,Dynalon/banshee-osx,Carbenium/banshee,GNOME/banshee,ixfalia/banshee,Carbenium/banshee,stsundermann/banshee,arfbtwn/banshee,ixfalia/banshee,arfbtwn/banshee,GNOME/banshee,babycaseny/banshee,ixfalia/banshee,stsundermann/banshee,dufoli/banshee,Carbenium/banshee,arfbtwn/banshee,ixfalia/banshee,GNOME/banshee,Dynalon/banshee-osx,stsundermann/banshee,arfbtwn/banshee,arfbtwn/banshee,Dynalon/banshee-osx,GNOME/banshee,dufoli/banshee
|
src/Clients/Muinshee/Muinshee/MuinsheeActions.cs
|
src/Clients/Muinshee/Muinshee/MuinsheeActions.cs
|
//
// MuinsheeActions.cs
//
// Authors:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.Unix;
using Gtk;
using Hyena;
using Banshee.Gui;
namespace Muinshee
{
public class MuinsheeActions : BansheeActionGroup
{
private Banshee.Playlist.PlaylistSource queue;
public MuinsheeActions (Banshee.Playlist.PlaylistSource queue) : base ("muinshee")
{
this.queue = queue;
AddImportant (
new ActionEntry (
"PlaySongAction", null,
Catalog.GetString ("Play _Song"), "S",
Catalog.GetString ("Add a song to the playlist"), OnPlaySong
),
new ActionEntry (
"PlayAlbumAction", null,
Catalog.GetString ("Play _Album"), "A",
Catalog.GetString ("Add an album to the playlist"), OnPlayAlbum
)
);
this["PlaySongAction"].IconName = "audio-x-generic";
this["PlayAlbumAction"].IconName = "media-optical";
// TODO disable certain actions
// Actions.TrackActions.UpdateActions (false, false, "SearchMenu");
AddUiFromFile ("GlobalUI.xml");
}
private void OnPlaySong (object sender, EventArgs args)
{
new SongDialog (queue).TryRun ();
}
private void OnPlayAlbum (object sender, EventArgs args)
{
new AlbumDialog (queue).TryRun ();
}
}
}
|
//
// MuinsheeActions.cs
//
// Authors:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.Unix;
using Gtk;
using Hyena;
using Banshee.Gui;
namespace Muinshee
{
public class MuinsheeActions : BansheeActionGroup
{
private Banshee.Playlist.PlaylistSource queue;
public MuinsheeActions (Banshee.Playlist.PlaylistSource queue) : base ("muinshee")
{
this.queue = queue;
AddImportant (
new ActionEntry (
"PlaySongAction", Stock.Add,
Catalog.GetString ("Play _Song"), "S",
Catalog.GetString ("Add a song to the playlist"), OnPlaySong
),
new ActionEntry (
"PlayAlbumAction", null,
Catalog.GetString ("Play _Album"), "A",
Catalog.GetString ("Add an album to the playlist"), OnPlayAlbum
)
);
this["PlayAlbumAction"].IconName = "media-optical";
// TODO disable certain actions
// Actions.TrackActions.UpdateActions (false, false, "SearchMenu");
AddUiFromFile ("GlobalUI.xml");
}
private void OnPlaySong (object sender, EventArgs args)
{
new SongDialog (queue).TryRun ();
}
private void OnPlayAlbum (object sender, EventArgs args)
{
new AlbumDialog (queue).TryRun ();
}
}
}
|
mit
|
C#
|
7f0ba7e1937cea63678b6dcb369d08e969165e2b
|
fix in creation of IEnumarble collection
|
D4N3-777/Din_Website,D4N3-777/Din_Website,D4N3-777/Din_Website
|
src/Din.Service/Clients/Concrete/TvShowClient.cs
|
src/Din.Service/Clients/Concrete/TvShowClient.cs
|
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Din.Service.Clients.Interfaces;
using Din.Service.Clients.RequestObjects;
using Din.Service.Clients.ResponseObjects;
using Din.Service.Config.Interfaces;
using Newtonsoft.Json;
namespace Din.Service.Clients.Concrete
{
public class TvShowClient : BaseClient, ITvShowClient
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly ITvShowClientConfig _config;
public TvShowClient(IHttpClientFactory httpClientFactory, ITvShowClientConfig config)
{
_httpClientFactory = httpClientFactory;
_config = config;
}
public async Task<IEnumerable<string>> GetCurrentTvShowsAsync()
{
var client = _httpClientFactory.CreateClient();
var response = JsonConvert.DeserializeObject<List<TCTvShowResponse>>(await client.GetAsync(BuildUrl(_config.Url, "series", $"?apikey={_config.Key}")).Result.Content.ReadAsStringAsync());
return response.Select(r => r.Title.ToLower()).AsEnumerable();
}
public async Task<bool> AddTvShowAsync(TCRequest tvShow)
{
tvShow.RootFolderPath = _config.SaveLocation;
var client = _httpClientFactory.CreateClient();
var response = await client.PostAsync(BuildUrl(_config.Url, "series", $"?apikey={_config.Key}"),
new StringContent(JsonConvert.SerializeObject(tvShow)));
return response.StatusCode.Equals(HttpStatusCode.Created);
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Din.Service.Clients.Interfaces;
using Din.Service.Clients.RequestObjects;
using Din.Service.Clients.ResponseObjects;
using Din.Service.Config.Interfaces;
using Newtonsoft.Json;
namespace Din.Service.Clients.Concrete
{
public class TvShowClient : BaseClient, ITvShowClient
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly ITvShowClientConfig _config;
public TvShowClient(IHttpClientFactory httpClientFactory, ITvShowClientConfig config)
{
_httpClientFactory = httpClientFactory;
_config = config;
}
public async Task<IEnumerable<string>> GetCurrentTvShowsAsync()
{
var client = _httpClientFactory.CreateClient();
var response = JsonConvert.DeserializeObject<List<TCTvShowResponse>>(await client.GetAsync(BuildUrl(_config.Url, "series", $"?apikey={_config.Key}")).Result.Content.ReadAsStringAsync());
return response.Select(r => r.Title).AsEnumerable();
}
public async Task<bool> AddTvShowAsync(TCRequest tvShow)
{
tvShow.RootFolderPath = _config.SaveLocation;
var client = _httpClientFactory.CreateClient();
var response = await client.PostAsync(BuildUrl(_config.Url, "series", $"?apikey={_config.Key}"),
new StringContent(JsonConvert.SerializeObject(tvShow)));
return response.StatusCode.Equals(HttpStatusCode.Created);
}
}
}
|
apache-2.0
|
C#
|
1feaac04d6d27b52f620d4d03dd070b0887e41cb
|
Fix Sender Delete Chiamata in corso
|
vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf
|
src/backend/SO115App.SignalR/Sender/GestioneChiamateInCorso/NotificationDeleteChiamataInCorso.cs
|
src/backend/SO115App.SignalR/Sender/GestioneChiamateInCorso/NotificationDeleteChiamataInCorso.cs
|
//-----------------------------------------------------------------------
// <copyright file="NotificationDeleteChiamataInCorso .cs" company="CNVVF">
// Copyright (C) 2017 - CNVVF
//
// This file is part of SOVVF.
// SOVVF is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// SOVVF is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
// </copyright>
//-----------------------------------------------------------------------
using DomainModel.CQRS.Commands.ChiamataInCorsoMarker;
using Microsoft.AspNetCore.SignalR;
using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneChiamateInCorso;
using SO115App.Models.Servizi.Infrastruttura.SistemiEsterni.Competenze;
using SO115App.SignalR.Utility;
using System.Threading.Tasks;
namespace SO115App.SignalR.Sender.GestioneChiamateInCorso
{
public class NotificationDeleteChiamataInCorso : INotificationDeleteChiamataInCorso
{
private readonly IHubContext<NotificationHub> _notificationHubContext;
private readonly GetGerarchiaToSend _getGerarchiaToSend;
private readonly IGetCompetenzeByCoordinateIntervento _getCompetenze;
public NotificationDeleteChiamataInCorso(IHubContext<NotificationHub> NotificationHubContext,
GetGerarchiaToSend getGerarchiaToSend,
IGetCompetenzeByCoordinateIntervento getCompetenze)
{
_notificationHubContext = NotificationHubContext;
_getGerarchiaToSend = getGerarchiaToSend;
_getCompetenze = getCompetenze;
}
public async Task SendNotification(CancellazioneChiamataInCorsoMarkerCommand chiamata)
{
var Competenze = _getCompetenze.GetCompetenzeByCoordinateIntervento(chiamata.ChiamataInCorso.Localita.Coordinate);
var SediDaNotificare = _getGerarchiaToSend.Get(Competenze[0]);
//SediDaNotificare.Add(chiamata.ChiamataInCorso.CodiceSedeOperatore);
foreach (var sede in SediDaNotificare)
await _notificationHubContext.Clients.Group(sede).SendAsync("NotifyChiamataInCorsoMarkerDelete", chiamata.ChiamataInCorso.Id);
}
}
}
|
//-----------------------------------------------------------------------
// <copyright file="NotificationDeleteChiamataInCorso .cs" company="CNVVF">
// Copyright (C) 2017 - CNVVF
//
// This file is part of SOVVF.
// SOVVF is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// SOVVF is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
// </copyright>
//-----------------------------------------------------------------------
using DomainModel.CQRS.Commands.ChiamataInCorsoMarker;
using Microsoft.AspNetCore.SignalR;
using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneChiamateInCorso;
using SO115App.Models.Servizi.Infrastruttura.SistemiEsterni.Competenze;
using SO115App.SignalR.Utility;
using System.Threading.Tasks;
namespace SO115App.SignalR.Sender.GestioneChiamateInCorso
{
public class NotificationDeleteChiamataInCorso : INotificationDeleteChiamataInCorso
{
private readonly IHubContext<NotificationHub> _notificationHubContext;
private readonly GetGerarchiaToSend _getGerarchiaToSend;
private readonly IGetCompetenzeByCoordinateIntervento _getCompetenze;
public NotificationDeleteChiamataInCorso(IHubContext<NotificationHub> NotificationHubContext,
GetGerarchiaToSend getGerarchiaToSend,
IGetCompetenzeByCoordinateIntervento getCompetenze)
{
_notificationHubContext = NotificationHubContext;
_getGerarchiaToSend = getGerarchiaToSend;
_getCompetenze = getCompetenze;
}
public async Task SendNotification(CancellazioneChiamataInCorsoMarkerCommand chiamata)
{
var Competenze = _getCompetenze.GetCompetenzeByCoordinateIntervento(chiamata.ChiamataInCorso.Localita.Coordinate);
var SediDaNotificare = _getGerarchiaToSend.Get(Competenze[0]);
SediDaNotificare.Add(chiamata.ChiamataInCorso.CodiceSedeOperatore);
foreach (var sede in SediDaNotificare)
await _notificationHubContext.Clients.Group(sede).SendAsync("NotifyChiamataInCorsoMarkerDelete", chiamata.ChiamataInCorso.Id);
}
}
}
|
agpl-3.0
|
C#
|
be946d59a69bbded682ac263d1889d844f629182
|
Initialize LinkCommand with an IApplicationConfiguration
|
appharbor/appharbor-cli
|
src/AppHarbor/Commands/LinkCommand.cs
|
src/AppHarbor/Commands/LinkCommand.cs
|
using System;
namespace AppHarbor.Commands
{
public class LinkCommand : ICommand
{
private readonly IApplicationConfiguration _applicationConfiguration;
public LinkCommand(IApplicationConfiguration applicationConfiguration)
{
_applicationConfiguration = applicationConfiguration;
}
public void Execute(string[] arguments)
{
throw new NotImplementedException();
}
}
}
|
using System;
namespace AppHarbor.Commands
{
public class LinkCommand : ICommand
{
public LinkCommand()
{
}
public void Execute(string[] arguments)
{
throw new NotImplementedException();
}
}
}
|
mit
|
C#
|
51d304d584b82f329bca1e639decc1c4bdc23b6f
|
fix polyline test
|
gabornemeth/StravaSharp,gabornemeth/StravaSharp,gabornemeth/StravaSharp,gabornemeth/StravaSharp
|
src/StravaSharp.Tests/PolylineTest.cs
|
src/StravaSharp.Tests/PolylineTest.cs
|
//
// ActivityTest.cs
//
// Author:
// Gabor Nemeth (gabor.nemeth.dev@gmail.com)
//
// Copyright (C) 2015, Gabor Nemeth
//
using Newtonsoft.Json;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace StravaSharp.Tests
{
[TestFixture]
public class PolylineTest
{
[Test]
public async Task DecodeMap()
{
var client = TestHelper.CreateStravaClient();
var activities = await client.Activities.GetAthleteActivities();
Assert.True(activities.Count > 0);
var activity = activities.FirstOrDefault(a => a.Map?.SummaryPolyline != null);
Assert.NotNull(activity);
activity = await client.Activities.Get(activity.Id);
Assert.NotNull(activity);
var points = SharpGeo.Google.PolylineEncoder.Decode(activity.Map.SummaryPolyline);
Assert.NotNull(points);
Assert.True(points.Count > 0);
}
}
}
|
//
// ActivityTest.cs
//
// Author:
// Gabor Nemeth (gabor.nemeth.dev@gmail.com)
//
// Copyright (C) 2015, Gabor Nemeth
//
using Newtonsoft.Json;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace StravaSharp.Tests
{
[TestFixture]
public class PolylineTest
{
[Test]
public async Task DecodeMap()
{
var client = TestHelper.CreateStravaClient();
var activities = await client.Activities.GetAthleteActivities();
Assert.True(activities.Count > 0);
var activity = activities[0];
Assert.NotNull(activity);
activity = await client.Activities.Get(activity.Id);
Assert.NotNull(activity);
var points = SharpGeo.Google.PolylineEncoder.Decode(activity.Map.SummaryPolyline);
Assert.NotNull(points);
Assert.True(points.Count > 0);
}
}
}
|
mit
|
C#
|
16d7f34db2ccf697e46f28e2e1bf57aa4b9eb949
|
fix possible
|
SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments
|
src/CommitmentsV2/SFA.DAS.CommitmentsV2/Models/ApprenticeshipConfirmationStatus.cs
|
src/CommitmentsV2/SFA.DAS.CommitmentsV2/Models/ApprenticeshipConfirmationStatus.cs
|
using System;
using SFA.DAS.CommitmentsV2.Models.Interfaces;
using SFA.DAS.CommitmentsV2.Types;
namespace SFA.DAS.CommitmentsV2.Models
{
public class ApprenticeshipConfirmationStatus : Aggregate
{
public ApprenticeshipConfirmationStatus()
{
}
public ApprenticeshipConfirmationStatus(long apprenticeshipId, DateTime commitmentsApprovedOn, DateTime? confirmationOverdueOn, DateTime? apprenticeshipConfirmedOn)
{
ApprenticeshipId = apprenticeshipId;
CommitmentsApprovedOn = commitmentsApprovedOn;
ConfirmationOverdueOn = confirmationOverdueOn;
ApprenticeshipConfirmedOn = apprenticeshipConfirmedOn;
}
public long ApprenticeshipId { get; set; }
public DateTime CommitmentsApprovedOn { get; set; }
public DateTime? ConfirmationOverdueOn { get; set; }
public DateTime? ApprenticeshipConfirmedOn { get; set; }
public Apprenticeship Apprenticeship { get; set; }
public string ConfirmationStatusSort { get; set; }
public ConfirmationStatus ConfirmationStatus => ApprenticeshipConfirmedOn == null
? ConfirmationStatus.Unconfirmed
: ConfirmationStatus.Confirmed;
public void SetStatusToUnconfirmedIfChangeIsLatest(DateTime newCommitmentsApprovedOn, DateTime newConfirmationOverdueOn)
{
if (CommitmentsApprovedOn < newCommitmentsApprovedOn.AddSeconds(-1))
{
CommitmentsApprovedOn = newCommitmentsApprovedOn;
ConfirmationOverdueOn = newConfirmationOverdueOn;
ApprenticeshipConfirmedOn = null;
}
}
public void SetStatusToConfirmedIfChangeIsLatest(DateTime newCommitmentsApprovedOn, DateTime apprenticeshipConfirmedOn)
{
if (CommitmentsApprovedOn.AddSeconds(-1) <= newCommitmentsApprovedOn)
{
CommitmentsApprovedOn = newCommitmentsApprovedOn;
ApprenticeshipConfirmedOn = apprenticeshipConfirmedOn;
}
}
}
}
|
using System;
using SFA.DAS.CommitmentsV2.Models.Interfaces;
using SFA.DAS.CommitmentsV2.Types;
namespace SFA.DAS.CommitmentsV2.Models
{
public class ApprenticeshipConfirmationStatus : Aggregate
{
public ApprenticeshipConfirmationStatus()
{
}
public ApprenticeshipConfirmationStatus(long apprenticeshipId, DateTime commitmentsApprovedOn, DateTime? confirmationOverdueOn, DateTime? apprenticeshipConfirmedOn)
{
ApprenticeshipId = apprenticeshipId;
CommitmentsApprovedOn = commitmentsApprovedOn;
ConfirmationOverdueOn = confirmationOverdueOn;
ApprenticeshipConfirmedOn = apprenticeshipConfirmedOn;
}
public long ApprenticeshipId { get; set; }
public DateTime CommitmentsApprovedOn { get; set; }
public DateTime? ConfirmationOverdueOn { get; set; }
public DateTime? ApprenticeshipConfirmedOn { get; set; }
public Apprenticeship Apprenticeship { get; set; }
public string ConfirmationStatusSort { get; set; }
public ConfirmationStatus ConfirmationStatus => ApprenticeshipConfirmedOn == null
? ConfirmationStatus.Unconfirmed
: ConfirmationStatus.Confirmed;
public void SetStatusToUnconfirmedIfChangeIsLatest(DateTime newCommitmentsApprovedOn, DateTime newConfirmationOverdueOn)
{
if (CommitmentsApprovedOn.AddSeconds(-1) < newCommitmentsApprovedOn)
{
CommitmentsApprovedOn = newCommitmentsApprovedOn;
ConfirmationOverdueOn = newConfirmationOverdueOn;
ApprenticeshipConfirmedOn = null;
}
}
public void SetStatusToConfirmedIfChangeIsLatest(DateTime newCommitmentsApprovedOn, DateTime apprenticeshipConfirmedOn)
{
if (CommitmentsApprovedOn.AddSeconds(-1) <= newCommitmentsApprovedOn)
{
CommitmentsApprovedOn = newCommitmentsApprovedOn;
ApprenticeshipConfirmedOn = apprenticeshipConfirmedOn;
}
}
}
}
|
mit
|
C#
|
98a877c69f9778609c84d0041ee3c15bb7e36b93
|
fix mathjax script
|
YarGU-Demidov/math-site,YarGU-Demidov/math-site,YarGU-Demidov/math-site,YarGU-Demidov/math-site,YarGU-Demidov/math-site
|
src/MathSite/Views/Shared/Partials/Scripts.cshtml
|
src/MathSite/Views/Shared/Partials/Scripts.cshtml
|
@model CommonViewModel
<!-- jQuery -->
<script src="vendors/jquery/jquery-3.2.0.min.js"></script>
<!-- Outline.js -->
<script src="vendors/outline/outline.js" asp-append-version="true"></script>
<!-- Math formulas -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_CHTML'></script>
<!-- Temp -->
<script src="js/temp.js" asp-append-version="true"></script>
<environment names="Staging,Production">
<!-- Yandex.Metrika counter -->
<script type="text/javascript">
(function(d, w, c) {
(w[c] = w[c] || []).push(function() {
try {
w.yaCounter37239295 = new Ya.Metrika({
id: 37239295,
clickmap: true,
trackLinks: true,
accurateTrackBounce: true,
webvisor: true,
trackHash: true
});
} catch (e) {
}
});
var n = d.getElementsByTagName("script")[0],
s = d.createElement("script"),
f = function() {
n.parentNode.insertBefore(s, n);
};
s.type = "text/javascript";
s.async = true;
s.src = "https://mc.yandex.ru/metrika/watch.js";
if (w.opera == "[object Opera]") {
d.addEventListener("DOMContentLoaded", f, false);
} else {
f();
}
})(document, window, "yandex_metrika_callbacks");
</script>
<noscript>
<div>
<img src="https://mc.yandex.ru/watch/37239295" style="left: -9999px; position: absolute;" alt=""/>
</div>
</noscript>
<!-- /Yandex.Metrika counter -->
</environment>
|
@model CommonViewModel
<!-- jQuery -->
<script src="vendors/jquery/jquery-3.2.0.min.js"></script>
<!-- Outline.js -->
<script src="vendors/outline/outline.js" asp-append-version="true"></script>
<!-- Math formulas -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS_HTML"/>
<!-- Temp -->
<script src="js/temp.js" asp-append-version="true"></script>
<environment names="Staging,Production">
<!-- Yandex.Metrika counter -->
<script type="text/javascript">
(function(d, w, c) {
(w[c] = w[c] || []).push(function() {
try {
w.yaCounter37239295 = new Ya.Metrika({
id: 37239295,
clickmap: true,
trackLinks: true,
accurateTrackBounce: true,
webvisor: true,
trackHash: true
});
} catch (e) {
}
});
var n = d.getElementsByTagName("script")[0],
s = d.createElement("script"),
f = function() {
n.parentNode.insertBefore(s, n);
};
s.type = "text/javascript";
s.async = true;
s.src = "https://mc.yandex.ru/metrika/watch.js";
if (w.opera == "[object Opera]") {
d.addEventListener("DOMContentLoaded", f, false);
} else {
f();
}
})(document, window, "yandex_metrika_callbacks");
</script>
<noscript>
<div>
<img src="https://mc.yandex.ru/watch/37239295" style="left: -9999px; position: absolute;" alt=""/>
</div>
</noscript>
<!-- /Yandex.Metrika counter -->
</environment>
|
mit
|
C#
|
1cdbbd172b91dbde5125666fa2884357aed40c48
|
Use NancyOptions. (#2812)
|
xkproject/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,OrchardCMS/Brochard,OrchardCMS/Brochard,xkproject/Orchard2,petedavis/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2,petedavis/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2
|
src/OrchardCore/OrchardCore.Nancy.Core/Startup.cs
|
src/OrchardCore/OrchardCore.Nancy.Core/Startup.cs
|
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Nancy;
using Nancy.Owin;
using OrchardCore.Modules;
using OrchardCore.Nancy.AssemblyCatalogs;
namespace OrchardCore.Nancy
{
public class Startup : StartupBase
{
public override int Order => -200;
public override void ConfigureServices(IServiceCollection services)
{
services.AddRouting();
}
public override void Configure(IApplicationBuilder app, IRouteBuilder routes, IServiceProvider serviceProvider)
{
var contextAccessor = serviceProvider.GetRequiredService<IHttpContextAccessor>();
var options = serviceProvider.GetService<IOptions<NancyOptions>>();
app.UseOwin(x => x.UseNancy(no =>
{
no.Bootstrapper = new ModularNancyBootstrapper(
new[]
{
(IAssemblyCatalog)new DependencyContextAssemblyCatalog(),
(IAssemblyCatalog)new AmbientAssemblyCatalog(contextAccessor)
});
no.PerformPassThrough = options.Value.PerformPassThrough;
no.EnableClientCertificates = options.Value.EnableClientCertificates;
}));
}
}
}
|
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Nancy;
using Nancy.Owin;
using OrchardCore.Modules;
using OrchardCore.Nancy.AssemblyCatalogs;
namespace OrchardCore.Nancy
{
public class Startup : StartupBase
{
public override int Order => -200;
public override void ConfigureServices(IServiceCollection services)
{
services.AddRouting();
}
public override void Configure(IApplicationBuilder app, IRouteBuilder routes, IServiceProvider serviceProvider)
{
var contextAccessor = serviceProvider.GetRequiredService<IHttpContextAccessor>();
app.UseOwin(x => x.UseNancy(no =>
no.Bootstrapper = new ModularNancyBootstrapper(
new[] {
(IAssemblyCatalog)new DependencyContextAssemblyCatalog(),
(IAssemblyCatalog)new AmbientAssemblyCatalog(contextAccessor)
})));
}
}
}
|
bsd-3-clause
|
C#
|
bd0c793def174fd8e11d3c5ff503d7080f533d1e
|
Use single method to get drive in ExportArgsTests
|
Sitecore/Sitecore-Instance-Manager
|
src/SIM.Tests/Pipelines/Export/ExportArgsTests.cs
|
src/SIM.Tests/Pipelines/Export/ExportArgsTests.cs
|
namespace SIM.Tests.Pipelines.Export
{
using System;
using System.IO;
using System.Linq;
using SIM.Extensions;
using SIM.Pipelines.Export;
using Xunit;
public class ExportArgsTests
{
[Fact]
public void GetTempFolderTest()
{
var drive = GetDrive();
var result = ExportArgs.GetTempFolder(null, $"{drive}inetpub\\wwwroot");
// to eliminate random part
var actual = Path.GetDirectoryName(result);
Assert.Equal(drive, actual);
}
[Fact]
public void GetTempFolderTest_Custom()
{
var drive = GetDrive();
var result = ExportArgs.GetTempFolder($"{drive}Sitecore\\Temp", @"D:\inetpub\wwwroot");
// to eliminate random part
var actual = Path.GetDirectoryName(result);
Assert.Equal($"{drive}Sitecore\\Temp", actual);
}
private string GetDrive()
{
//Try to get disk C as it is quite common.
//Get any disk if it doesn't exist.
var drive = Environment.GetLogicalDrives()
.FirstOrDefault(d => d.EqualsIgnoreCase("c:\\"))
?? Environment.GetLogicalDrives().First();
return drive;
}
}
}
|
namespace SIM.Tests.Pipelines.Export
{
using System;
using System.IO;
using System.Linq;
using SIM.Extensions;
using SIM.Pipelines.Export;
using Xunit;
public class ExportArgsTests
{
[Fact]
public void GetTempFolderTest()
{
//Try to get disk C. Get any disk if it doesn't exist
var drive = Environment.GetLogicalDrives()
.FirstOrDefault(d => d.EqualsIgnoreCase("c:\\"))
?? Environment.GetLogicalDrives().First();
var result = ExportArgs.GetTempFolder(null, $"{drive}inetpub\\wwwroot");
// to eliminate random part
var actual = Path.GetDirectoryName(result);
Assert.Equal(drive, actual);
}
[Fact]
public void GetTempFolderTest_Custom()
{
//Try to get disk C. Get any disk if it doesn't exist
var drive = Environment.GetLogicalDrives()
.FirstOrDefault(d => d.EqualsIgnoreCase("c:\\"))
?? Environment.GetLogicalDrives().First();
var result = ExportArgs.GetTempFolder($"{drive}Sitecore\\Temp", @"D:\inetpub\wwwroot");
// to eliminate random part
var actual = Path.GetDirectoryName(result);
Assert.Equal($"{drive}Sitecore\\Temp", actual);
}
}
}
|
mit
|
C#
|
c98c9419b62353bf68ed1b40b5c798a19d2afdcc
|
Fix 404 bug (should actually return 404 now)
|
nbarbettini/beautiful-rest-api-aspnetcore
|
src/BeautifulRestApi/Filters/LinkRewritingFilter.cs
|
src/BeautifulRestApi/Filters/LinkRewritingFilter.cs
|
using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using BeautifulRestApi.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Routing;
namespace BeautifulRestApi.Filters
{
public class LinkRewritingFilter : IAsyncResultFilter
{
private readonly IUrlHelperFactory _urlHelperFactory;
public LinkRewritingFilter(IUrlHelperFactory urlHelperFactory)
{
_urlHelperFactory = urlHelperFactory;
}
public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
var asObjectResult = context.Result as ObjectResult;
if (asObjectResult == null)
{
await next();
return;
}
var rewriter = new LinkRewriter(_urlHelperFactory.GetUrlHelper(context));
RewriteLinks(asObjectResult.Value, rewriter);
await next();
}
private static void RewriteLinks(object input, LinkRewriter rewriter)
{
var allProperties = input.GetType().GetTypeInfo().GetAllProperties().ToArray();
foreach (var linkProperty in allProperties.Where(p => p.CanWrite && typeof(ILink).IsAssignableFrom(p.PropertyType)))
{
var rewritten = rewriter.Rewrite(linkProperty.GetValue(input) as ILink);
if (rewritten != null)
{
linkProperty.SetValue(input, rewritten);
}
}
foreach (var arrayProperty in allProperties.Where(p => p.PropertyType.IsArray))
{
var array = arrayProperty.GetValue(input) as Array ?? new Array[0];
foreach (var element in array)
{
RewriteLinks(element, rewriter);
}
}
}
}
}
|
using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using BeautifulRestApi.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Routing;
namespace BeautifulRestApi.Filters
{
public class LinkRewritingFilter : IAsyncResultFilter
{
private readonly IUrlHelperFactory _urlHelperFactory;
public LinkRewritingFilter(IUrlHelperFactory urlHelperFactory)
{
_urlHelperFactory = urlHelperFactory;
}
public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
var asObjectResult = context.Result as ObjectResult;
if (asObjectResult == null)
{
return;
}
var rewriter = new LinkRewriter(_urlHelperFactory.GetUrlHelper(context));
RewriteLinks(asObjectResult.Value, rewriter);
await next();
}
private static void RewriteLinks(object input, LinkRewriter rewriter)
{
var allProperties = input.GetType().GetTypeInfo().GetAllProperties().ToArray();
foreach (var linkProperty in allProperties.Where(p => p.CanWrite && typeof(ILink).IsAssignableFrom(p.PropertyType)))
{
var rewritten = rewriter.Rewrite(linkProperty.GetValue(input) as ILink);
if (rewritten != null)
{
linkProperty.SetValue(input, rewritten);
}
}
foreach (var arrayProperty in allProperties.Where(p => p.PropertyType.IsArray))
{
var array = arrayProperty.GetValue(input) as Array ?? new Array[0];
foreach (var element in array)
{
RewriteLinks(element, rewriter);
}
}
}
}
}
|
apache-2.0
|
C#
|
9d31efd24cfd819abaafa057e17d501f89a168f5
|
Fix social buttons not copying setting valus
|
murst/Blogifier.Core,blogifierdotnet/Blogifier.Core,murst/Blogifier.Core,murst/Blogifier.Core,blogifierdotnet/Blogifier.Core
|
src/Blogifier.Core/Services/Social/SocialService.cs
|
src/Blogifier.Core/Services/Social/SocialService.cs
|
using Blogifier.Core.Common;
using Blogifier.Core.Data.Domain;
using Blogifier.Core.Data.Interfaces;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Blogifier.Core.Services.Social
{
public class SocialService : ISocialService
{
IUnitOfWork _db;
public SocialService(IUnitOfWork db)
{
_db = db;
}
public Task<Dictionary<string, string>> GetSocialButtons(Profile profile)
{
var buttons = new Dictionary<string, string>();
foreach (var item in ApplicationSettings.SocialButtons)
{
buttons.Add(item.Key, item.Value);
}
if(profile != null)
{
// override with profile customizations
var dbFields = _db.CustomFields.Find(f => f.CustomType == CustomType.Profile && f.ParentId == profile.Id);
if (dbFields != null && dbFields.Count() > 0)
{
foreach (var field in dbFields)
{
if (buttons.ContainsKey(field.CustomKey))
{
buttons[field.CustomKey] = field.CustomValue;
}
}
}
}
return Task.Run(()=> buttons);
}
}
}
|
using Blogifier.Core.Common;
using Blogifier.Core.Data.Domain;
using Blogifier.Core.Data.Interfaces;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Blogifier.Core.Services.Social
{
public class SocialService : ISocialService
{
IUnitOfWork _db;
public SocialService(IUnitOfWork db)
{
_db = db;
}
public Task<Dictionary<string, string>> GetSocialButtons(Profile profile)
{
var buttons = ApplicationSettings.SocialButtons;
if(profile != null)
{
// override with profile customizations
var dbFields = _db.CustomFields.Find(f => f.CustomType == CustomType.Profile && f.ParentId == profile.Id);
if (dbFields != null && dbFields.Count() > 0)
{
foreach (var field in dbFields)
{
if (buttons.ContainsKey(field.CustomKey))
{
buttons[field.CustomKey] = field.CustomValue;
}
}
}
}
return Task.Run(()=> buttons);
}
}
}
|
mit
|
C#
|
75c8cd46f31abf531b86e0c4a9df0ebf715411a5
|
Update DefaultShapePresenter.cs
|
wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D
|
src/Draw2D.Core/Presenters/DefaultShapePresenter.cs
|
src/Draw2D.Core/Presenters/DefaultShapePresenter.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.Collections.Generic;
using Draw2D.Core.Editor;
namespace Draw2D.Core.Presenters
{
public class DefaultShapePresenter : ShapePresenter
{
public override void DrawContent(object dc, IToolContext context)
{
foreach (var shape in context.CurrentContainer.Guides)
{
shape.Draw(dc, context.Renderer, 0.0, 0.0);
}
foreach (var shape in context.CurrentContainer.Shapes)
{
shape.Draw(dc, context.Renderer, 0.0, 0.0);
}
}
public override void DrawWorking(object dc, IToolContext context)
{
foreach (var shape in context.WorkingContainer.Shapes)
{
shape.Draw(dc, context.Renderer, 0.0, 0.0);
}
}
public override void DrawHelpers(object dc, IToolContext context)
{
DrawHelpers(dc, context, context.CurrentContainer.Shapes, context.Selected);
DrawHelpers(dc, context, context.WorkingContainer.Shapes, context.Selected);
}
public void DrawHelpers(object dc, IToolContext context, IEnumerable<ShapeObject> shapes, ISet<ShapeObject> selected)
{
foreach (var shape in shapes)
{
if (selected.Contains(shape))
{
if (Helpers.TryGetValue(shape.GetType(), out var helper))
{
helper.Draw(dc, context.Renderer, shape, context.Selected);
}
}
}
}
}
}
|
// 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.Collections.Generic;
using Draw2D.Core.Editor;
namespace Draw2D.Core.Presenters
{
public class DefaultShapePresenter : ShapePresenter
{
public override void Draw(object dc, IToolContext context)
{
foreach (var shape in context.CurrentContainer.Guides)
{
shape.Draw(dc, context.Renderer, 0.0, 0.0);
}
foreach (var shape in context.CurrentContainer.Shapes)
{
shape.Draw(dc, context.Renderer, 0.0, 0.0);
}
foreach (var shape in context.WorkingContainer.Shapes)
{
shape.Draw(dc, context.Renderer, 0.0, 0.0);
}
}
public override void DrawHelpers(object dc, IToolContext context)
{
DrawHelpers(dc, context, context.CurrentContainer.Shapes, context.Selected);
DrawHelpers(dc, context, context.WorkingContainer.Shapes, context.Selected);
}
public void DrawHelpers(object dc, IToolContext context, IEnumerable<ShapeObject> shapes, ISet<ShapeObject> selected)
{
foreach (var shape in shapes)
{
if (selected.Contains(shape))
{
if (Helpers.TryGetValue(shape.GetType(), out var helper))
{
helper.Draw(dc, context.Renderer, shape, context.Selected);
}
}
}
}
}
}
|
mit
|
C#
|
d6a705d76cdcf0843fe6a69a88072982d8e728d8
|
support nomnoml diagrams
|
lunet-io/markdig
|
src/Markdig/Extensions/Diagrams/DiagramExtension.cs
|
src/Markdig/Extensions/Diagrams/DiagramExtension.cs
|
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using Markdig.Renderers;
using Markdig.Renderers.Html;
namespace Markdig.Extensions.Diagrams
{
/// <summary>
/// Extension to allow diagrams.
/// </summary>
/// <seealso cref="Markdig.IMarkdownExtension" />
public class DiagramExtension : IMarkdownExtension
{
public void Setup(MarkdownPipelineBuilder pipeline)
{
}
public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)
{
var htmlRenderer = renderer as HtmlRenderer;
if (htmlRenderer != null)
{
var codeRenderer = htmlRenderer.ObjectRenderers.FindExact<CodeBlockRenderer>();
// TODO: Add other well known diagram languages
codeRenderer.BlocksAsDiv.Add("mermaid");
codeRenderer.BlocksAsDiv.Add("nomnoml");
}
}
}
}
|
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using Markdig.Renderers;
using Markdig.Renderers.Html;
namespace Markdig.Extensions.Diagrams
{
/// <summary>
/// Extension to allow diagrams.
/// </summary>
/// <seealso cref="Markdig.IMarkdownExtension" />
public class DiagramExtension : IMarkdownExtension
{
public void Setup(MarkdownPipelineBuilder pipeline)
{
}
public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)
{
var htmlRenderer = renderer as HtmlRenderer;
if (htmlRenderer != null)
{
var codeRenderer = htmlRenderer.ObjectRenderers.FindExact<CodeBlockRenderer>();
// TODO: Add other well known diagram languages
codeRenderer.BlocksAsDiv.Add("mermaid");
}
}
}
}
|
bsd-2-clause
|
C#
|
19cd07a473e5d39e069bd2376cfaf37fce8f0ee6
|
Fix issues related to open dialogs when a player disconnects
|
ikkentim/SampSharp,ikkentim/SampSharp,ikkentim/SampSharp
|
src/SampSharp.Entities/SAMP/Dialogs/DialogSystem.cs
|
src/SampSharp.Entities/SAMP/Dialogs/DialogSystem.cs
|
// SampSharp
// Copyright 2022 Tim Potze
//
// 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.
namespace SampSharp.Entities.SAMP;
/// <summary>Represents a system for handling dialog functionality</summary>
public class DialogSystem : ISystem
{
[Event]
// ReSharper disable once UnusedMember.Local
private void OnPlayerDisconnect(VisibleDialog player, DisconnectReason _)
{
player.ResponseReceived = true;
player.Handler(new DialogResult(DialogResponse.Disconnected, 0, null));
}
[Event]
// ReSharper disable once UnusedMember.Local
private void OnDialogResponse(VisibleDialog player, int dialogId, int response, int listItem, string inputText)
{
if (dialogId != DialogService.DialogId)
return; // Prevent dialog hacks
player.ResponseReceived = true;
player.Handler(new DialogResult(response == 1
? DialogResponse.LeftButton
: DialogResponse.RightButtonOrCancel, listItem, inputText));
player.Destroy();
}
}
|
// SampSharp
// Copyright 2022 Tim Potze
//
// 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.
namespace SampSharp.Entities.SAMP;
/// <summary>Represents a system for handling dialog functionality</summary>
public class DialogSystem : ISystem
{
[Event]
// ReSharper disable once UnusedMember.Local
private void OnPlayerDisconnect(VisibleDialog player, DisconnectReason _)
{
player.Handler(new DialogResult(DialogResponse.Disconnected, 0, null));
}
[Event]
// ReSharper disable once UnusedMember.Local
private void OnDialogResponse(VisibleDialog player, int dialogId, int response, int listItem, string inputText)
{
if (dialogId != DialogService.DialogId)
return; // Prevent dialog hacks
player.ResponseReceived = true;
player.Handler(new DialogResult(response == 1
? DialogResponse.LeftButton
: DialogResponse.RightButtonOrCancel, listItem, inputText));
}
}
|
apache-2.0
|
C#
|
e8c93d0c27b350b60f6a4f5867911c7fcf30385f
|
Change raven configuration
|
Vavro/DragonContracts,Vavro/DragonContracts
|
DragonContracts/DragonContracts/Base/RavenDbController.cs
|
DragonContracts/DragonContracts/Base/RavenDbController.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using DragonContracts.Indexes;
using DragonContracts.Models;
using Raven.Client;
using Raven.Client.Document;
using Raven.Client.Embedded;
using Raven.Client.Indexes;
using Raven.Database.Config;
using Raven.Database.Server.Responders;
namespace DragonContracts.Base
{
public abstract class RavenDbController : ApiController
{
private const int RavenWebUiPort = 8081;
public IDocumentStore Store { get { return LazyDocStore.Value; } }
private static readonly Lazy<IDocumentStore> LazyDocStore = new Lazy<IDocumentStore>(() =>
{
var docStore = new EmbeddableDocumentStore()
{
DataDirectory = "App_Data/Raven",
UseEmbeddedHttpServer = true,
Configuration = { Port = RavenWebUiPort }
};
Raven.Database.Server.NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(RavenWebUiPort);
docStore.Initialize();
IndexCreation.CreateIndexes(typeof(Contracts_SubjectAndNames).Assembly, docStore);
return docStore;
});
public IAsyncDocumentSession Session { get; set; }
public async override Task<HttpResponseMessage> ExecuteAsync(
HttpControllerContext controllerContext,
CancellationToken cancellationToken)
{
using (Session = Store.OpenAsyncSession())
{
var result = await base.ExecuteAsync(controllerContext, cancellationToken);
await Session.SaveChangesAsync();
return result;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using DragonContracts.Indexes;
using DragonContracts.Models;
using Raven.Client;
using Raven.Client.Document;
using Raven.Client.Embedded;
using Raven.Client.Indexes;
using Raven.Database.Config;
using Raven.Database.Server.Responders;
namespace DragonContracts.Base
{
public abstract class RavenDbController : ApiController
{
private const int RavenWebUiPort = 8081;
public IDocumentStore Store { get { return LazyDocStore.Value; } }
private static readonly Lazy<IDocumentStore> LazyDocStore = new Lazy<IDocumentStore>(() =>
{
var docStore = new EmbeddableDocumentStore()
{
DataDirectory = "App_Data/Raven",
UseEmbeddedHttpServer = true
};
docStore.Configuration.Port = RavenWebUiPort;
Raven.Database.Server.NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(RavenWebUiPort);
docStore.Initialize();
IndexCreation.CreateIndexes(typeof(Contracts_SubjectAndNames).Assembly, docStore);
return docStore;
});
public IAsyncDocumentSession Session { get; set; }
public async override Task<HttpResponseMessage> ExecuteAsync(
HttpControllerContext controllerContext,
CancellationToken cancellationToken)
{
using (Session = Store.OpenAsyncSession())
{
var result = await base.ExecuteAsync(controllerContext, cancellationToken);
await Session.SaveChangesAsync();
return result;
}
}
}
}
|
mit
|
C#
|
a10c0a835dcd53ac1a510c927624c887f03f75c0
|
Add missing ARC runtime linker flag
|
gururajios/XamarinBindings,gururajios/XamarinBindings,hanoibanhcuon/XamarinBindings,hanoibanhcuon/XamarinBindings,kushal2905/XamarinBindings-1,andnsx/XamarinBindings,theonlylawislove/XamarinBindings,andnsx/XamarinBindings,kushal2905/XamarinBindings-1
|
AlexTouch.PSPDFKit/PSPDFKit.linkwith.cs
|
AlexTouch.PSPDFKit/PSPDFKit.linkwith.cs
|
using System;
using MonoTouch.ObjCRuntime;
[assembly: LinkWith ("PSPDFKit.a", LinkTarget.ArmV7s | LinkTarget.ArmV7 | LinkTarget.Simulator, ForceLoad = true, IsCxx = true, Frameworks = "MediaPlayer CoreText QuartzCore MessageUI ImageIO CoreMedia CoreGraphics AVFoundation", LinkerFlags = "-lz -ObjC -fobjc-arc")]
|
using System;
using MonoTouch.ObjCRuntime;
[assembly: LinkWith ("PSPDFKit.a", LinkTarget.ArmV7s | LinkTarget.ArmV7 | LinkTarget.Simulator, ForceLoad = true, IsCxx = true, Frameworks = "MediaPlayer CoreText QuartzCore MessageUI ImageIO CoreMedia CoreGraphics AVFoundation", LinkerFlags = "-lz -ObjC")]
|
mit
|
C#
|
e744629a4167586e87e41ab1ba6da547b7f5a530
|
Fix broken obsoletion message
|
NeoAdonis/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,peppy/osu-new,ppy/osu,ppy/osu,peppy/osu,peppy/osu,smoogipooo/osu,NeoAdonis/osu
|
osu.Game/Beatmaps/Formats/IHasComboColours.cs
|
osu.Game/Beatmaps/Formats/IHasComboColours.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using osuTK.Graphics;
namespace osu.Game.Beatmaps.Formats
{
public interface IHasComboColours
{
/// <summary>
/// Retrieves the list of combo colours for presentation only.
/// </summary>
IReadOnlyList<Color4> ComboColours { get; }
/// <summary>
/// The list of custom combo colours.
/// If non-empty, <see cref="ComboColours"/> will return these colours;
/// if empty, <see cref="ComboColours"/> will fall back to default combo colours.
/// </summary>
List<Color4> CustomComboColours { get; }
/// <summary>
/// Adds combo colours to the list.
/// </summary>
[Obsolete("Use CustomComboColours directly.")] // can be removed 20220215
void AddComboColours(params Color4[] colours);
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using osuTK.Graphics;
namespace osu.Game.Beatmaps.Formats
{
public interface IHasComboColours
{
/// <summary>
/// Retrieves the list of combo colours for presentation only.
/// </summary>
IReadOnlyList<Color4> ComboColours { get; }
/// <summary>
/// The list of custom combo colours.
/// If non-empty, <see cref="ComboColours"/> will return these colours;
/// if empty, <see cref="ComboColours"/> will fall back to default combo colours.
/// </summary>
List<Color4> CustomComboColours { get; }
/// <summary>
/// Adds combo colours to the list.
/// </summary>
[Obsolete("Use SkinConfiguration.ComboColours directly.")] // can be removed 20220215
void AddComboColours(params Color4[] colours);
}
}
|
mit
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.