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 |
---|---|---|---|---|---|---|---|---|
cc1d862b644632cde36416d8ce3d87b4eed1d90c | Integrate Unified Label into CCMenuItemFont. | haithemaraissia/CocosSharp,mono/CocosSharp,TukekeSoft/CocosSharp,zmaruo/CocosSharp,mono/CocosSharp,zmaruo/CocosSharp,MSylvia/CocosSharp,MSylvia/CocosSharp,haithemaraissia/CocosSharp,TukekeSoft/CocosSharp | src/menu_nodes/CCMenuItemFont.cs | src/menu_nodes/CCMenuItemFont.cs | using System;
namespace CocosSharp
{
public class CCMenuItemFont : CCMenuItemLabel
{
#region Properties
public static uint FontSize { get; set; }
public static string FontName { get; set; }
#endregion Properties
#region Constructors
public CCMenuItemFont (string labelString, Action<object> selector = null)
: base(new CCLabel(labelString, FontName, FontSize), selector)
{
}
#endregion Constructors
}
} | using System;
namespace CocosSharp
{
public class CCMenuItemFont : CCMenuItemLabelTTF
{
#region Properties
public static uint FontSize { get; set; }
public static string FontName { get; set; }
#endregion Properties
#region Constructors
public CCMenuItemFont (string labelString, Action<object> selector = null)
: base(new CCLabelTtf(labelString, FontName, FontSize), selector)
{
}
#endregion Constructors
}
} | mit | C# |
4fee8c8edd6727371e0c4dc3ced3608659ca5392 | update version | IdentityServer/IdentityServer4.Templates,IdentityServer/IdentityServer4.Templates,IdentityServer/IdentityServer4.Templates | build.cake | build.cake | var target = Argument("target", "Default");
var configuration = Argument<string>("configuration", "Release");
///////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
///////////////////////////////////////////////////////////////////////////////
var buildArtifacts = Directory("./artifacts/packages");
var packageVersion = "1.0.0-aberlour";
///////////////////////////////////////////////////////////////////////////////
// Clean
///////////////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() =>
{
CleanDirectories(new DirectoryPath[] { buildArtifacts });
});
///////////////////////////////////////////////////////////////////////////////
// Copy
///////////////////////////////////////////////////////////////////////////////
Task("Copy")
.IsDependentOn("Clean")
.Does(() =>
{
CreateDirectory("./feed/content");
var files = GetFiles("./src/**/*.*");
CopyFiles(files, "./feed/content", true);
});
///////////////////////////////////////////////////////////////////////////////
// Pack
///////////////////////////////////////////////////////////////////////////////
Task("Pack")
.IsDependentOn("Clean")
.IsDependentOn("Copy")
.Does(() =>
{
var settings = new NuGetPackSettings
{
Version = packageVersion,
OutputDirectory = buildArtifacts
};
if (AppVeyor.IsRunningOnAppVeyor)
{
settings.Version = packageVersion + "-b" + AppVeyor.Environment.Build.Number.ToString().PadLeft(4,'0');
}
NuGetPack("./feed/IdentityServer4.Templates.nuspec", settings);
});
Task("Default")
.IsDependentOn("Pack");
RunTarget(target); | var target = Argument("target", "Default");
var configuration = Argument<string>("configuration", "Release");
///////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
///////////////////////////////////////////////////////////////////////////////
var buildArtifacts = Directory("./artifacts/packages");
var packageVersion = "1.0.0";
///////////////////////////////////////////////////////////////////////////////
// Clean
///////////////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() =>
{
CleanDirectories(new DirectoryPath[] { buildArtifacts });
});
///////////////////////////////////////////////////////////////////////////////
// Copy
///////////////////////////////////////////////////////////////////////////////
Task("Copy")
.IsDependentOn("Clean")
.Does(() =>
{
CreateDirectory("./feed/content");
var files = GetFiles("./src/**/*.*");
CopyFiles(files, "./feed/content", true);
});
///////////////////////////////////////////////////////////////////////////////
// Pack
///////////////////////////////////////////////////////////////////////////////
Task("Pack")
.IsDependentOn("Clean")
.IsDependentOn("Copy")
.Does(() =>
{
var settings = new NuGetPackSettings
{
Version = packageVersion,
OutputDirectory = buildArtifacts
};
if (AppVeyor.IsRunningOnAppVeyor)
{
settings.Version = packageVersion + "-b" + AppVeyor.Environment.Build.Number.ToString().PadLeft(4,'0');
}
NuGetPack("./feed/IdentityServer4.Templates.nuspec", settings);
});
Task("Default")
.IsDependentOn("Pack");
RunTarget(target); | apache-2.0 | C# |
4b1fd7586dc046c84dfeccf06d67ec1f59237c06 | Change output path of .nupkg | Redth/Cake.Android.Adb | build.cake | build.cake | #tool nuget:?package=NUnit.ConsoleRunner&version=3.6.0
var sln = "./Cake.Android.Adb.sln";
var nuspec = "./Cake.Android.Adb.nuspec";
var target = Argument ("target", "all");
var configuration = Argument ("configuration", "Release");
var NUGET_VERSION = Argument("nugetversion", "0.9999");
var SDK_URL_BASE = "https://dl.google.com/android/repository/tools_r{0}-{1}.zip";
var SDK_VERSION = "25.2.3";
Task ("externals")
.WithCriteria (!FileExists ("./android-sdk/android-sdk.zip"))
.Does (() =>
{
var url = string.Format (SDK_URL_BASE, SDK_VERSION, "macosx");
if (IsRunningOnWindows ())
url = string.Format (SDK_URL_BASE, SDK_VERSION, "windows");
EnsureDirectoryExists ("./android-sdk/");
DownloadFile (url, "./android-sdk/android-sdk.zip");
Unzip ("./android-sdk/android-sdk.zip", "./android-sdk/");
// Install platform-tools so we get adb
StartProcess ("./android-sdk/tools/bin/sdkmanager", new ProcessSettings { Arguments = "platform-tools" });
});
Task ("libs").Does (() =>
{
NuGetRestore (sln);
DotNetBuild (sln, c => c.Configuration = configuration);
});
Task ("nuget").IsDependentOn ("libs").Does (() =>
{
NuGetPack (nuspec, new NuGetPackSettings {
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./",
Version = NUGET_VERSION,
// NuGet messes up path on mac, so let's add ./ in front again
BasePath = "././",
});
});
Task("tests").IsDependentOn("libs").Does(() =>
{
NUnit3("./**/bin/" + configuration + "/*.Tests.dll");
});
Task ("clean").Does (() =>
{
CleanDirectories ("./**/bin");
CleanDirectories ("./**/obj");
CleanDirectories ("./**/Components");
CleanDirectories ("./**/tools");
CleanDirectories ("./android-sdk");
DeleteFiles ("./**/*.apk");
});
Task ("all").IsDependentOn("nuget").IsDependentOn ("tests");
RunTarget (target); | #tool nuget:?package=NUnit.ConsoleRunner&version=3.6.0
var sln = "./Cake.Android.Adb.sln";
var nuspec = "./Cake.Android.Adb.nuspec";
var target = Argument ("target", "all");
var configuration = Argument ("configuration", "Release");
var NUGET_VERSION = Argument("nugetversion", "0.9999");
var SDK_URL_BASE = "https://dl.google.com/android/repository/tools_r{0}-{1}.zip";
var SDK_VERSION = "25.2.3";
Task ("externals")
.WithCriteria (!FileExists ("./android-sdk/android-sdk.zip"))
.Does (() =>
{
var url = string.Format (SDK_URL_BASE, SDK_VERSION, "macosx");
if (IsRunningOnWindows ())
url = string.Format (SDK_URL_BASE, SDK_VERSION, "windows");
EnsureDirectoryExists ("./android-sdk/");
DownloadFile (url, "./android-sdk/android-sdk.zip");
Unzip ("./android-sdk/android-sdk.zip", "./android-sdk/");
// Install platform-tools so we get adb
StartProcess ("./android-sdk/tools/bin/sdkmanager", new ProcessSettings { Arguments = "platform-tools" });
});
Task ("libs").Does (() =>
{
NuGetRestore (sln);
DotNetBuild (sln, c => c.Configuration = configuration);
});
Task ("nuget").IsDependentOn ("libs").Does (() =>
{
CreateDirectory ("./nupkg/");
NuGetPack (nuspec, new NuGetPackSettings {
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./nupkg/",
Version = NUGET_VERSION,
// NuGet messes up path on mac, so let's add ./ in front again
BasePath = "././",
});
});
Task("tests").IsDependentOn("libs").Does(() =>
{
NUnit3("./**/bin/" + configuration + "/*.Tests.dll");
});
Task ("clean").Does (() =>
{
CleanDirectories ("./**/bin");
CleanDirectories ("./**/obj");
CleanDirectories ("./**/Components");
CleanDirectories ("./**/tools");
DeleteFiles ("./**/*.apk");
});
Task ("all").IsDependentOn("nuget").IsDependentOn ("tests");
RunTarget (target); | mit | C# |
99df37f32dca7102579e6b7acecaa451ba8854cf | Add input generic type to `IModelDownloader` | ppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu | osu.Game/Database/IModelDownloader.cs | osu.Game/Database/IModelDownloader.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Game.Online.API;
using osu.Framework.Bindables;
namespace osu.Game.Database
{
/// <summary>
/// Represents a <see cref="IModelManager{TModel}"/> that can download new models from an external source.
/// </summary>
/// <typeparam name="TModel">The model type.</typeparam>
/// <typeparam name="T">The model's interface type.</typeparam>
public interface IModelDownloader<TModel, in T> : IPostNotifications
where TModel : class, T
{
/// <summary>
/// Fired when a <typeparamref name="TModel"/> download begins.
/// This is NOT run on the update thread and should be scheduled.
/// </summary>
IBindable<WeakReference<ArchiveDownloadRequest<TModel>>> DownloadBegan { get; }
/// <summary>
/// Fired when a <typeparamref name="TModel"/> download is interrupted, either due to user cancellation or failure.
/// This is NOT run on the update thread and should be scheduled.
/// </summary>
IBindable<WeakReference<ArchiveDownloadRequest<TModel>>> DownloadFailed { get; }
/// <summary>
/// Begin a download for the requested <typeparamref name="TModel"/>.
/// </summary>
/// <param name="model">The <stypeparamref name="TModel"/> to be downloaded.</param>
/// <param name="minimiseDownloadSize">Whether this download should be optimised for slow connections. Generally means extras are not included in the download bundle..</param>
/// <returns>Whether the download was started.</returns>
bool Download(T model, bool minimiseDownloadSize);
/// <summary>
/// Gets an existing <typeparamref name="TModel"/> download request if it exists.
/// </summary>
/// <param name="model">The <typeparamref name="TModel"/> whose request is wanted.</param>
/// <returns>The <see cref="ArchiveDownloadRequest{TModel}"/> object if it exists, otherwise null.</returns>
ArchiveDownloadRequest<TModel> GetExistingDownload(TModel model);
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Game.Online.API;
using osu.Framework.Bindables;
namespace osu.Game.Database
{
/// <summary>
/// Represents a <see cref="IModelManager{TModel}"/> that can download new models from an external source.
/// </summary>
/// <typeparam name="TModel">The model type.</typeparam>
public interface IModelDownloader<TModel> : IPostNotifications
where TModel : class
{
/// <summary>
/// Fired when a <typeparamref name="TModel"/> download begins.
/// This is NOT run on the update thread and should be scheduled.
/// </summary>
IBindable<WeakReference<ArchiveDownloadRequest<TModel>>> DownloadBegan { get; }
/// <summary>
/// Fired when a <typeparamref name="TModel"/> download is interrupted, either due to user cancellation or failure.
/// This is NOT run on the update thread and should be scheduled.
/// </summary>
IBindable<WeakReference<ArchiveDownloadRequest<TModel>>> DownloadFailed { get; }
/// <summary>
/// Begin a download for the requested <typeparamref name="TModel"/>.
/// </summary>
/// <param name="model">The <stypeparamref name="TModel"/> to be downloaded.</param>
/// <param name="minimiseDownloadSize">Whether this download should be optimised for slow connections. Generally means extras are not included in the download bundle..</param>
/// <returns>Whether the download was started.</returns>
bool Download(TModel model, bool minimiseDownloadSize);
/// <summary>
/// Gets an existing <typeparamref name="TModel"/> download request if it exists.
/// </summary>
/// <param name="model">The <typeparamref name="TModel"/> whose request is wanted.</param>
/// <returns>The <see cref="ArchiveDownloadRequest{TModel}"/> object if it exists, otherwise null.</returns>
ArchiveDownloadRequest<TModel> GetExistingDownload(TModel model);
}
}
| mit | C# |
25e3f72659736c8a4e05f88900ef487842619b1f | use req num if it already exits | ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab | Anlab.Mvc/Views/Lab/AddRequestNumber.cshtml | Anlab.Mvc/Views/Lab/AddRequestNumber.cshtml | @using Humanizer
@model AnlabMvc.Models.Order.OrderReviewModel
@{
ViewData["Title"] = "Confirmation";
}
<form asp-controller="Lab" asp-action="AddRequestNumber" asp-route-id="@Model.Order.Id" method="post">
@Html.Hidden("confirm", true)
<div class="form-group">
<span>Request Number:</span>
<span><input type="text" class="form-control" name="requestNum" value="@Model.Order.RequestNum" required /></span>
</div>
<button type="submit" class="btn btn-primary"><i class="fa fa-check" aria-hidden="true">Add Request Number</i></button>
</form>
<br />
<h3>This info is outdated and will be updated from the request number</h3>
@Html.Partial("_OrderDetails")
@section AdditionalStyles
{
@{ await Html.RenderPartialAsync("_DataTableStylePartial"); }
}
@section Scripts
{
@{ await Html.RenderPartialAsync("_DataTableScriptsPartial"); }
<script type="text/javascript">
$(function() {
$("#table").dataTable();
});
</script>
@{ await Html.RenderPartialAsync("_ShowdownScriptsPartial"); }
} | @using Humanizer
@model AnlabMvc.Models.Order.OrderReviewModel
@{
ViewData["Title"] = "Confirmation";
}
<form asp-controller="Lab" asp-action="AddRequestNumber" asp-route-id="@Model.Order.Id" method="post">
@Html.Hidden("confirm", true)
<div class="form-group">
<span>Request Number:</span>
<span><input type="text" class="form-control" name="requestNum" required /></span>
</div>
<button type="submit" class="btn btn-primary"><i class="fa fa-check" aria-hidden="true">Add Request Number</i></button>
</form>
<br />
<h3>This info is outdated and will be updated from the request number</h3>
@Html.Partial("_OrderDetails")
@section AdditionalStyles
{
@{ await Html.RenderPartialAsync("_DataTableStylePartial"); }
}
@section Scripts
{
@{ await Html.RenderPartialAsync("_DataTableScriptsPartial"); }
<script type="text/javascript">
$(function() {
$("#table").dataTable();
});
</script>
@{ await Html.RenderPartialAsync("_ShowdownScriptsPartial"); }
} | mit | C# |
a63edeb65b732baa2783bdedb061e4073f8492fb | Move Shipeditor tests to the Voxelgon.Shipeditor.Tests namespace | Voxelgon/Voxelgon,Voxelgon/Voxelgon | Assets/Editor/Tests/ShipEditor/WallTests.cs | Assets/Editor/Tests/ShipEditor/WallTests.cs | using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using Voxelgon.ShipEditor;
namespace Voxelgon.ShipEditor.Tests {
public class WallTests {
[Test]
public void WallCannotHaveDuplicateVertices() {
//Arrange
var editor = new ShipEditor();
var wall = new Wall(editor);
var nodes = new List<Vector3>();
nodes.Add(new Vector3(5, 8, 3));
//Act
wall.UpdateVertices(nodes, ShipEditor.BuildMode.Polygon);
//Assert
Assert.That(wall.ValidVertex(new Vector3(5, 8, 3)), Is.False);
}
}
} | using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using Voxelgon.ShipEditor;
namespace Voxelgon.Tests {
public class WallTests {
[Test]
public void WallCannotHaveDuplicateVertices() {
//Arrange
var editor = new ShipEditor.ShipEditor();
var wall = new Wall(editor);
var nodes = new List<Vector3>();
nodes.Add(new Vector3(5, 8, 3));
//Act
wall.UpdateVertices(nodes, ShipEditor.ShipEditor.BuildMode.Polygon);
//Assert
Assert.That(wall.ValidVertex(new Vector3(5, 8, 3)), Is.False);
}
}
} | apache-2.0 | C# |
f03920e6e1fe01c6411f8aab77a939470b4b65ba | Fix build on .NET 1.1 | ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,livioc/nhibernate-core,hazzik/nhibernate-core,nkreipke/nhibernate-core,hazzik/nhibernate-core,nkreipke/nhibernate-core,livioc/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,hazzik/nhibernate-core,lnu/nhibernate-core,ngbrown/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core,alobakov/nhibernate-core,ngbrown/nhibernate-core,gliljas/nhibernate-core,fredericDelaporte/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,alobakov/nhibernate-core,livioc/nhibernate-core,ngbrown/nhibernate-core,nkreipke/nhibernate-core,alobakov/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,nhibernate/nhibernate-core,RogerKratz/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,lnu/nhibernate-core | src/NHibernate.Test/FilterTest/Category.cs | src/NHibernate.Test/FilterTest/Category.cs | using System;
using Iesi.Collections;
namespace NHibernate.Test.FilterTest
{
public class Category
{
private long id;
private String name;
private DateTime effectiveStartDate;
private DateTime effectiveEndDate;
private ISet products;
public Category()
{
}
public Category(String name)
{
this.name = name;
}
public Category(String name, DateTime effectiveStartDate, DateTime effectiveEndDate)
{
this.name = name;
this.effectiveStartDate = effectiveStartDate;
this.effectiveEndDate = effectiveEndDate;
}
public virtual long Id
{
get { return id; }
set { id = value; }
}
public virtual string Name
{
get { return name; }
set { name = value; }
}
public virtual DateTime EffectiveStartDate
{
get { return effectiveStartDate; }
set { effectiveStartDate = value; }
}
public virtual DateTime EffectiveEndDate
{
get { return effectiveEndDate; }
set { effectiveEndDate = value; }
}
public virtual ISet Products
{
get { return products; }
set { products = value; }
}
public override bool Equals(Object o)
{
if (this == o)
return true;
if (!(o is Category))
return false;
Category category = (Category) o;
if (!name.Equals(category.name))
{
return false;
}
if (!effectiveEndDate.Equals(category.effectiveEndDate))
{
return false;
}
if (!effectiveStartDate.Equals(category.effectiveStartDate))
{
return false;
}
return true;
}
public override int GetHashCode()
{
int result;
result = name.GetHashCode();
result = 29 * result + effectiveStartDate.GetHashCode();
result = 29 * result + effectiveEndDate.GetHashCode();
return result;
}
}
}
| using System;
using Iesi.Collections;
namespace NHibernate.Test.FilterTest
{
public class Category
{
private long id;
private String name;
private DateTime effectiveStartDate;
private DateTime effectiveEndDate;
private ISet products;
public Category()
{
}
public Category(String name)
{
this.name = name;
}
public Category(String name, DateTime effectiveStartDate, DateTime effectiveEndDate)
{
this.name = name;
this.effectiveStartDate = effectiveStartDate;
this.effectiveEndDate = effectiveEndDate;
}
public virtual long Id
{
get { return id; }
set { id = value; }
}
public virtual string Name
{
get { return name; }
set { name = value; }
}
public virtual DateTime EffectiveStartDate
{
get { return effectiveStartDate; }
set { effectiveStartDate = value; }
}
public virtual DateTime EffectiveEndDate
{
get { return effectiveEndDate; }
set { effectiveEndDate = value; }
}
public virtual ISet Products
{
get { return products; }
set { products = value; }
}
public override bool Equals(Object o)
{
if (this == o)
return true;
if (!(o is Category))
return false;
Category category = (Category) o;
if (!name.Equals(category.name))
{
return false;
}
if (effectiveEndDate != null ?
!effectiveEndDate.Equals(category.effectiveEndDate) :
category.effectiveEndDate != null)
{
return false;
}
if (effectiveStartDate != null ?
!effectiveStartDate.Equals(category.effectiveStartDate) :
category.effectiveStartDate != null)
{
return false;
}
return true;
}
public override int GetHashCode()
{
int result;
result = name.GetHashCode();
result = 29 * result + (effectiveStartDate != null ? effectiveStartDate.GetHashCode() : 0);
result = 29 * result + (effectiveEndDate != null ? effectiveEndDate.GetHashCode() : 0);
return result;
}
}
}
| lgpl-2.1 | C# |
28ab9c614260905205bc2e687893d577bdeea36f | Add LogLevel option to restclient config | Aux/NTwitch,Aux/NTwitch | src/NTwitch.Rest/TwitchRestClientConfig.cs | src/NTwitch.Rest/TwitchRestClientConfig.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NTwitch.Rest
{
public class TwitchRestClientConfig
{
public string BaseUrl { get; set; } = "https://api.twitch.tv/kraken/";
public LogLevel LogLevel { get; set; } = LogLevel.Errors;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NTwitch.Rest
{
public class TwitchRestClientConfig
{
public string BaseUrl { get; set; } = "https://api.twitch.tv/kraken/";
}
}
| mit | C# |
f237324cf84ec5d7f1d9e97fa0156a340129ef50 | Mark RBPackageExporter packages properly GitHub release | redbluegames/unity-mulligan-renamer,redbluegames/unity-bulk-rename | Assets/Editor/RBPackageExporter.cs | Assets/Editor/RBPackageExporter.cs | /* MIT License
Copyright (c) 2016 Edward Rowe, RedBlueGames
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
/// <summary>
/// Tool that helps us export RedBlueTools for use in other projects, as well as for the public
/// </summary>
public class RBPackageExporter
{
private readonly string pathToSettingsFile = System.IO.Path.Combine(Application.dataPath, "RedBlueGames/MulliganRenamer/Editor/RBPackageSettings.cs");
private readonly string pathToSettingsOverrideFile =
Application.dataPath +
System.IO.Path.DirectorySeparatorChar + ".." + System.IO.Path.DirectorySeparatorChar +
"RBPackageSettings.cs";
public void Export(bool includeTestDirectories)
{
var oldSettings = this.SaveFilesForGitHubRelease();
// Export function heavily inspired by this blog post:
// https://medium.com/@neuecc/using-circle-ci-to-build-test-make-unitypackage-on-unity-9f9fa2b3adfd
var root = "RedBlueGames/MulliganRenamer";
var exportPath = "./Mulligan_CI.unitypackage";
var path = Path.Combine(Application.dataPath, root);
var assets = Directory.GetFiles(path, "*", SearchOption.AllDirectories)
.Select(x => "Assets" + x.Replace(Application.dataPath, "").Replace(@"\", "/")).ToArray();
if (!includeTestDirectories)
{
assets = assets.Where(x => !x.Contains("Tests")).ToArray();
}
UnityEngine.Debug.Log("Exporting these files:" + Environment.NewLine + string.Join(Environment.NewLine, assets));
AssetDatabase.ExportPackage(
assets,
exportPath,
ExportPackageOptions.Default);
// Restore the old file so that we don't dirty the repo.
if (!string.IsNullOrEmpty(oldSettings))
{
System.IO.File.WriteAllText(this.pathToSettingsFile, oldSettings);
}
UnityEngine.Debug.Log("Export complete: " + Path.GetFullPath(exportPath));
}
private string SaveFilesForGitHubRelease()
{
var oldSettings = System.IO.File.ReadAllText(this.pathToSettingsFile);
var settingsOverride = System.IO.File.ReadAllText(this.pathToSettingsOverrideFile);
settingsOverride = string.Concat("/* THIS CLASS IS AUTO-GENERATED! DO NOT MODIFY! */ \n", settingsOverride);
System.IO.File.WriteAllText(this.pathToSettingsFile, settingsOverride);
return oldSettings;
}
} | /* MIT License
Copyright (c) 2016 Edward Rowe, RedBlueGames
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
/// <summary>
/// Tool that helps us export RedBlueTools for use in other projects, as well as for the public
/// </summary>
public class RBPackageExporter
{
public void Export(bool includeTestDirectories)
{
// Export function heavily inspired by this blog post:
// https://medium.com/@neuecc/using-circle-ci-to-build-test-make-unitypackage-on-unity-9f9fa2b3adfd
var root = "RedBlueGames/MulliganRenamer";
var exportPath = "./Mulligan_CI.unitypackage";
var path = Path.Combine(Application.dataPath, root);
var assets = Directory.GetFiles(path, "*", SearchOption.AllDirectories)
.Select(x => "Assets" + x.Replace(Application.dataPath, "").Replace(@"\", "/")).ToArray();
if (!includeTestDirectories)
{
assets = assets.Where(x => !x.Contains("Tests")).ToArray();
}
UnityEngine.Debug.Log("Exporting these files:" + Environment.NewLine + string.Join(Environment.NewLine, assets));
AssetDatabase.ExportPackage(
assets,
exportPath,
ExportPackageOptions.Default);
UnityEngine.Debug.Log("Export complete: " + Path.GetFullPath(exportPath));
}
} | mit | C# |
6a8757be12a876cbaf4e7ceb9b6529ac1c490590 | Update DrawGLLine.cs | UnityCommunity/UnityLibrary | Scripts/Helpers/DrawGLLine.cs | Scripts/Helpers/DrawGLLine.cs | using UnityEngine;
// Draws lines with GL : https://docs.unity3d.com/ScriptReference/GL.html
// Usage: Attach this script to gameobject in scene
public class DrawGLLine : MonoBehaviour
{
public Color lineColor = Color.red;
Material lineMaterial;
void Awake()
{
// must be called before trying to draw lines..
CreateLineMaterial();
}
void CreateLineMaterial()
{
// Unity has a built-in shader that is useful for drawing simple colored things
var shader = Shader.Find("Hidden/Internal-Colored");
lineMaterial = new Material(shader);
lineMaterial.hideFlags = HideFlags.HideAndDontSave;
// Turn on alpha blending
lineMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
lineMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
// Turn backface culling off
lineMaterial.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Off);
// Turn off depth writes
lineMaterial.SetInt("_ZWrite", 0);
}
// cannot call this on update, line wont be visible then.. and if used OnPostRender() thats works when attached to camera only
void OnRenderObject()
{
lineMaterial.SetPass(0);
GL.PushMatrix();
GL.MultMatrix(transform.localToWorldMatrix);
GL.Begin(GL.LINES);
GL.Color(lineColor);
// start line from transform position
GL.Vertex(transform.position);
// end line 100 units forward from transform position
GL.Vertex(transform.position + transform.forward * 100);
GL.End();
GL.PopMatrix();
}
}
| using UnityEngine;
// Draws lines with GL : https://docs.unity3d.com/ScriptReference/GL.html
// Usage: Attach this script to gameobject in scene
public class DrawGLLine : MonoBehaviour
{
public Color lineColor = Color.red;
Material lineMaterial;
void CreateLineMaterial()
{
if (!lineMaterial)
{
// Unity has a built-in shader that is useful for drawing simple colored things
var shader = Shader.Find("Hidden/Internal-Colored");
lineMaterial = new Material(shader);
lineMaterial.hideFlags = HideFlags.HideAndDontSave;
// Turn on alpha blending
lineMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
lineMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
// Turn backface culling off
lineMaterial.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Off);
// Turn off depth writes
lineMaterial.SetInt("_ZWrite", 0);
}
}
// cannot call this on update, line wont be visible then.. and if used OnPostRender() thats works when attached to camera only
void OnRenderObject()
{
CreateLineMaterial();
lineMaterial.SetPass(0);
GL.PushMatrix();
GL.MultMatrix(transform.localToWorldMatrix);
GL.Begin(GL.LINES);
GL.Color(lineColor);
// start line from transform position
GL.Vertex(transform.position);
// end line 100 units forward from transform position
GL.Vertex(transform.position + transform.forward * 100);
GL.End();
GL.PopMatrix();
}
}
| mit | C# |
ee4a1e817ddff7b000b842e8726f7102948df326 | rename test to invalid | goshippo/shippo-csharp-client | ShippoTesting/ManifestTest.cs | ShippoTesting/ManifestTest.cs | using NUnit.Framework;
using System;
using System.Collections;
using Shippo;
namespace ShippoTesting {
[TestFixture ()]
public class ManifestTest : ShippoTest {
[Test ()]
public void TestInvalidCreate ()
{
Assert.That (() => ManifestTest.getDefaultObject (),Throws.TypeOf<ShippoException> ());
}
[Test ()]
public void testValidRetrieve ()
{
Manifest testObject = ManifestTest.getDefaultObject ();
Manifest retrievedObject;
retrievedObject = apiResource.RetrieveManifest ((string) testObject.ObjectId);
Assert.AreEqual (testObject.ObjectId, retrievedObject.ObjectId);
}
[Test ()]
public void testListAll ()
{
Hashtable parameters = new Hashtable ();
parameters.Add ("results", "1");
parameters.Add ("page", "1");
var Manifests = apiResource.AllManifests (parameters);
Assert.AreEqual (0, Manifests.Data.Count);
}
public static Manifest getDefaultObject ()
{
Hashtable parameters = new Hashtable ();
parameters.Add ("provider", "USPS");
parameters.Add ("shipment_date", "2014-05-16T23:59:59Z");
parameters.Add ("address_from", AddressTest.getDefaultObject ().ObjectId);
return getAPIResource ().CreateManifest (parameters);
}
}
}
| using NUnit.Framework;
using System;
using System.Collections;
using Shippo;
namespace ShippoTesting {
[TestFixture ()]
public class ManifestTest : ShippoTest {
[Test ()]
public void TestValidCreate ()
{
Assert.That (() => ManifestTest.getDefaultObject (),Throws.TypeOf<ShippoException> ());
}
[Test ()]
public void testValidRetrieve ()
{
Manifest testObject = ManifestTest.getDefaultObject ();
Manifest retrievedObject;
retrievedObject = apiResource.RetrieveManifest ((string) testObject.ObjectId);
Assert.AreEqual (testObject.ObjectId, retrievedObject.ObjectId);
}
[Test ()]
public void testListAll ()
{
Hashtable parameters = new Hashtable ();
parameters.Add ("results", "1");
parameters.Add ("page", "1");
var Manifests = apiResource.AllManifests (parameters);
Assert.AreEqual (0, Manifests.Data.Count);
}
public static Manifest getDefaultObject ()
{
Hashtable parameters = new Hashtable ();
parameters.Add ("provider", "USPS");
parameters.Add ("shipment_date", "2014-05-16T23:59:59Z");
parameters.Add ("address_from", AddressTest.getDefaultObject ().ObjectId);
return getAPIResource ().CreateManifest (parameters);
}
}
}
| apache-2.0 | C# |
53a706d8f58a684317715e65c2f58ad0cbff0455 | Make Bindings read only | rhynodegreat/CSharpGameLibrary,vazgriz/CSharpGameLibrary,vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary | CSGL.Vulkan/DescriptorSetLayout.cs | CSGL.Vulkan/DescriptorSetLayout.cs | using System;
using System.Collections.Generic;
namespace CSGL.Vulkan {
public class DescriptorSetLayoutCreateInfo {
public List<VkDescriptorSetLayoutBinding> bindings;
}
public class DescriptorSetLayout : IDisposable, INative<VkDescriptorSetLayout> {
VkDescriptorSetLayout descriptorSetLayout;
bool disposed;
public Device Device { get; private set; }
public IList<VkDescriptorSetLayoutBinding> Bindings { get; private set; }
public VkDescriptorSetLayout Native {
get {
return descriptorSetLayout;
}
}
public DescriptorSetLayout(Device device, DescriptorSetLayoutCreateInfo info) {
if (device == null) throw new ArgumentNullException(nameof(device));
if (info == null) throw new ArgumentNullException(nameof(info));
Device = device;
CreateDescriptorSetLayout(info);
if (info.bindings != null) Bindings = new List<VkDescriptorSetLayoutBinding>(info.bindings).AsReadOnly();
}
void CreateDescriptorSetLayout(DescriptorSetLayoutCreateInfo mInfo) {
var info = new VkDescriptorSetLayoutCreateInfo();
info.sType = VkStructureType.DescriptorSetLayoutCreateInfo;
var bindingsMarshalled = new MarshalledArray<VkDescriptorSetLayoutBinding>(mInfo.bindings);
info.bindingCount = (uint)bindingsMarshalled.Count;
info.pBindings = bindingsMarshalled.Address;
using (bindingsMarshalled) {
var result = Device.Commands.createDescriptorSetLayout(Device.Native, ref info, Device.Instance.AllocationCallbacks, out descriptorSetLayout);
if (result != VkResult.Success) throw new DescriptorSetLayoutException(result, string.Format("Error creating description set layout: {0}", result));
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
void Dispose(bool disposing) {
if (disposed) return;
Device.Commands.destroyDescriptorSetLayout(Device.Native, descriptorSetLayout, Device.Instance.AllocationCallbacks);
disposed = true;
}
~DescriptorSetLayout() {
Dispose(false);
}
}
public class DescriptorSetLayoutException : VulkanException {
public DescriptorSetLayoutException(VkResult result, string message) : base(result, message) { }
}
}
| using System;
using System.Collections.Generic;
namespace CSGL.Vulkan {
public class DescriptorSetLayoutCreateInfo {
public List<VkDescriptorSetLayoutBinding> bindings;
}
public class DescriptorSetLayout : IDisposable, INative<VkDescriptorSetLayout> {
VkDescriptorSetLayout descriptorSetLayout;
bool disposed;
public Device Device { get; private set; }
public List<VkDescriptorSetLayoutBinding> Bindings { get; private set; }
public VkDescriptorSetLayout Native {
get {
return descriptorSetLayout;
}
}
public DescriptorSetLayout(Device device, DescriptorSetLayoutCreateInfo info) {
if (device == null) throw new ArgumentNullException(nameof(device));
if (info == null) throw new ArgumentNullException(nameof(info));
Device = device;
CreateDescriptorSetLayout(info);
Bindings = new List<VkDescriptorSetLayoutBinding>(info.bindings);
}
void CreateDescriptorSetLayout(DescriptorSetLayoutCreateInfo mInfo) {
var info = new VkDescriptorSetLayoutCreateInfo();
info.sType = VkStructureType.DescriptorSetLayoutCreateInfo;
var bindingsMarshalled = new MarshalledArray<VkDescriptorSetLayoutBinding>(mInfo.bindings);
info.bindingCount = (uint)bindingsMarshalled.Count;
info.pBindings = bindingsMarshalled.Address;
using (bindingsMarshalled) {
var result = Device.Commands.createDescriptorSetLayout(Device.Native, ref info, Device.Instance.AllocationCallbacks, out descriptorSetLayout);
if (result != VkResult.Success) throw new DescriptorSetLayoutException(result, string.Format("Error creating description set layout: {0}", result));
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
void Dispose(bool disposing) {
if (disposed) return;
Device.Commands.destroyDescriptorSetLayout(Device.Native, descriptorSetLayout, Device.Instance.AllocationCallbacks);
disposed = true;
}
~DescriptorSetLayout() {
Dispose(false);
}
}
public class DescriptorSetLayoutException : VulkanException {
public DescriptorSetLayoutException(VkResult result, string message) : base(result, message) { }
}
}
| mit | C# |
8b2b39afa96065739da680f48de13697cf4eb333 | Update code doc | JudoPay/DotNetSDK | JudoPayDotNet/Clients/IPayments.cs | JudoPayDotNet/Clients/IPayments.cs | using System.Threading.Tasks;
using JudoPayDotNet.Errors;
using JudoPayDotNet.Models;
namespace JudoPayDotNet.Clients
{
/// <summary>
/// Provides immediate payment processing using either full card details, or a previously used card token
/// </summary>
/// <remarks>The amount specified by a payment is immediately captured</remarks>
public interface IPayments
{
/// <summary>
/// Creates the specified card payment.
/// </summary>
/// <param name="cardPayment">The card payment.</param>
/// <returns>The receipt for the created card payment</returns>
Task<IResult<ITransactionResult>> Create(CardPaymentModel cardPayment);
/// <summary>
/// Creates the specified token payment.
/// </summary>
/// <param name="tokenPayment">The token payment.</param>
/// <returns>The receipt for the created token payment</returns>
Task<IResult<ITransactionResult>> Create(TokenPaymentModel tokenPayment);
/// <summary>
/// Creates the specified Apple Pay payment.
/// </summary>
/// <param name="pkPayment">The Apple Pay payment.</param>
/// <returns>The receipt for the created Apple Pay payment</returns>
Task<IResult<ITransactionResult>> Create(PKPaymentModel pkPayment);
/// <summary>
/// Creates the specified Android Pay payment.
/// </summary>
/// <param name="androidPayment">The Android Pay payment.</param>
/// <returns>The receipt for the created Android Pay payment</returns>
Task<IResult<ITransactionResult>> Create(AndroidPaymentModel androidPayment);
/// <summary>
/// Validates the specified card payment.
/// </summary>
/// <param name="cardPayment">The card payment.</param>
/// <returns>If the card payment is valid</returns>
Task<IResult<JudoApiErrorModel>> Validate(CardPaymentModel cardPayment);
/// <summary>
/// Validates the specified token payment.
/// </summary>
/// <param name="tokenPayment">The token payment.</param>
/// <returns>If the token payment is valid</returns>
Task<IResult<JudoApiErrorModel>> Validate(TokenPaymentModel tokenPayment);
/// <summary>
/// Validates the specified apple payment.
/// </summary>
/// <param name="pkPayment">The apple payment.</param>
/// <returns>If the apple payment is valid</returns>
Task<IResult<JudoApiErrorModel>> Validate(PKPaymentModel pkPayment);
}
} | using System.Threading.Tasks;
using JudoPayDotNet.Errors;
using JudoPayDotNet.Models;
namespace JudoPayDotNet.Clients
{
/// <summary>
/// Provides immediate payment processing using either full card details, or a previously used card token
/// </summary>
/// <remarks>The amount specified by a payment is immediately captured</remarks>
public interface IPayments
{
/// <summary>
/// Creates the specified card payment.
/// </summary>
/// <param name="cardPayment">The card payment.</param>
/// <returns>The receipt for the created card payment</returns>
Task<IResult<ITransactionResult>> Create(CardPaymentModel cardPayment);
/// <summary>
/// Creates the specified token payment.
/// </summary>
/// <param name="tokenPayment">The token payment.</param>
/// <returns>The receipt for the created token payment</returns>
Task<IResult<ITransactionResult>> Create(TokenPaymentModel tokenPayment);
/// <summary>
/// Creates the specified Apple Pay payment.
/// </summary>
/// <param name="pkPayment">The Apple Pay payment.</param>
/// <returns>The receipt for the created Apple Pay payment</returns>
Task<IResult<ITransactionResult>> Create(PKPaymentModel pkPayment);
/// <summary>
/// Creates the specified Android Pay payment.
/// </summary>
/// <param name="androidPayment">The Android Pay payment.</param>
/// <returns>The receipt for the created Android Pay payment</returns>
Task<IResult<ITransactionResult>> Create(AndroidPaymentModel androidPayment);
/// <summary>
/// Validates the specified card payment.
/// </summary>
/// <param name="cardPayment">The card payment.</param>
/// <returns>If the card payment is valid</returns>
Task<IResult<JudoApiErrorModel>> Validate(CardPaymentModel cardPayment);
/// <summary>
/// Validates the specified token payment.
/// </summary>
/// <param name="tokenPayment">The token payment.</param>
/// <returns>If the token payment is valid</returns>
Task<IResult<JudoApiErrorModel>> Validate(TokenPaymentModel tokenPayment);
/// <summary>
/// Validates the specified apple payment.
/// </summary>
/// <param name="pkPayment">The apple payment.</param>
/// <returns>If the apple payment is valid</returns>
Task<IResult<JudoApiErrorModel>> Validate(PKPaymentModel pkPayment);
}
} | mit | C# |
f023563a1f6dbdb8b02ca30815ec53bfc89d86fa | implement loading and saving events | Pondidum/Ledger,Pondidum/Ledger | Ledger.Stores.Fs/FileEventStore.cs | Ledger.Stores.Fs/FileEventStore.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Ledger.Infrastructure;
using Newtonsoft.Json;
namespace Ledger.Stores.Fs
{
public class FileEventStore : IEventStore
{
private readonly string _directory;
public FileEventStore(string directory)
{
_directory = directory;
}
private string EventFile<TKey>()
{
return Path.Combine(_directory, typeof(TKey).Name + ".events.json");
}
private string SnapshotFile<TKey>()
{
return Path.Combine(_directory, typeof(TKey).Name + ".snapshots.json");
}
private void AppendTo(string filepath, Action<StreamWriter> action)
{
using(var fs = new FileStream(filepath, FileMode.Append))
using (var sw = new StreamWriter(fs))
{
action(sw);
}
}
private IEnumerable<TDto> ReadFrom<TDto>(string filepath)
{
using (var fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var sr = new StreamReader(fs))
{
string line;
while ((line = sr.ReadLine()) != null)
{
yield return JsonConvert.DeserializeObject<TDto>(line);
}
}
}
public void SaveEvents<TKey>(TKey aggegateID, IEnumerable<DomainEvent> changes)
{
AppendTo(EventFile<TKey>(), file =>
{
changes.ForEach(change =>
{
var dto = new EventDto<TKey> {ID = aggegateID, Event = change};
var json = JsonConvert.SerializeObject(dto);
file.WriteLine(json);
});
});
}
public void SaveSnapshot<TKey>(TKey aggregateID, ISequenced snapshot)
{
AppendTo(SnapshotFile<TKey>(), file =>
{
var dto = new SnapshotDto<TKey> {ID = aggregateID, Snapshot = snapshot};
var json = JsonConvert.SerializeObject(dto);
file.WriteLine(json);
});
}
public int? GetLatestSequenceIDFor<TKey>(TKey aggegateID)
{
return LoadEvents(aggegateID)
.Select(e => (int?) e.SequenceID)
.Max();
}
public IEnumerable<DomainEvent> LoadEvents<TKey>(TKey aggegateID)
{
return ReadFrom<EventDto<TKey>>(EventFile<TKey>())
.Where(dto => Equals(dto.ID, aggegateID))
.Select(dto => dto.Event);
}
public IEnumerable<DomainEvent> LoadEventsSince<TKey>(TKey aggegateID, int sequenceID)
{
return LoadEvents(aggegateID)
.Where(e => e.SequenceID > sequenceID);
}
public ISequenced GetLatestSnapshotFor<TKey>(TKey aggegateID)
{
return ReadFrom<SnapshotDto<TKey>>(SnapshotFile<TKey>())
.Where(dto => Equals(dto.ID, aggegateID))
.Select(dto => dto.Snapshot)
.Cast<ISequenced>()
.Last();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using Ledger.Infrastructure;
using Newtonsoft.Json;
namespace Ledger.Stores.Fs
{
public class FileEventStore : IEventStore
{
private readonly string _directory;
public FileEventStore(string directory)
{
_directory = directory;
}
private string EventFile<TKey>()
{
return Path.Combine(_directory, typeof(TKey).Name + ".events.json");
}
private string SnapshotFile<TKey>()
{
return Path.Combine(_directory, typeof(TKey).Name + ".snapshots.json");
}
private void AppendTo(string filepath, Action<StreamWriter> action)
{
using(var fs = new FileStream(filepath, FileMode.Append))
using (var sw = new StreamWriter(fs))
{
action(sw);
}
}
public void SaveEvents<TKey>(TKey aggegateID, IEnumerable<DomainEvent> changes)
{
AppendTo(EventFile<TKey>(), file =>
{
changes.ForEach(change =>
{
var dto = new EventDto<TKey> {ID = aggegateID, Event = change};
var json = JsonConvert.SerializeObject(dto);
file.WriteLine(json);
});
});
}
public void SaveSnapshot<TKey>(TKey aggregateID, ISequenced snapshot)
{
AppendTo(SnapshotFile<TKey>(), file =>
{
var dto = new SnapshotDto<TKey> {ID = aggregateID, Snapshot = snapshot};
var json = JsonConvert.SerializeObject(dto);
file.WriteLine(json);
});
}
public int? GetLatestSequenceIDFor<TKey>(TKey aggegateID)
{
throw new System.NotImplementedException();
}
public IEnumerable<DomainEvent> LoadEvents<TKey>(TKey aggegateID)
{
throw new System.NotImplementedException();
}
public IEnumerable<DomainEvent> LoadEventsSince<TKey>(TKey aggegateID, int sequenceID)
{
throw new System.NotImplementedException();
}
public ISequenced GetLatestSnapshotFor<TKey>(TKey aggegateID)
{
throw new System.NotImplementedException();
}
}
}
| lgpl-2.1 | C# |
71e7032269b4143106630ef8d6ad1f548fe2a2e1 | Hide unwanted buttons in the pdfjs version of the PDF viewer | BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork | src/BloomExe/Publish/PdfViewer.cs | src/BloomExe/Publish/PdfViewer.cs | // Copyright (c) 2014 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Bloom.Properties;
using Gecko;
using Palaso.IO;
namespace Bloom.Publish
{
/// <summary>
/// Wrapper class that wraps either a Gecko web browser that displays the PDF file through
/// pdf.js, or the Adobe Reader control. Which one is used depends on the operating system
/// (Linux always uses pdf.js) and the UseAdobePdfViewer setting in the config file.
/// </summary>
public partial class PdfViewer : UserControl
{
private Control _pdfViewerControl;
public PdfViewer()
{
InitializeComponent();
#if !__MonoCS__
if (Settings.Default.UseAdobePdfViewer)
{
_pdfViewerControl = new AdobeReaderControl();
}
else
#endif
{
_pdfViewerControl = new GeckoWebBrowser();
}
SuspendLayout();
_pdfViewerControl.BackColor = Color.White;
_pdfViewerControl.Dock = DockStyle.Fill;
_pdfViewerControl.Name = "_pdfViewerControl";
_pdfViewerControl.TabIndex = 0;
AutoScaleDimensions = new SizeF(6F, 13F);
AutoScaleMode = AutoScaleMode.Font;
Controls.Add(_pdfViewerControl);
Name = "PdfViewer";
ResumeLayout(false);
}
public bool ShowPdf(string pdfFile)
{
#if !__MonoCS__
if (Settings.Default.UseAdobePdfViewer)
return ((AdobeReaderControl)_pdfViewerControl).ShowPdf(pdfFile);
#endif
var url = string.Format("{0}{1}?file=/bloom/{2}", Bloom.web.ServerBase.PathEndingInSlash,
FileLocator.GetFileDistributedWithApplication("pdf/web/viewer.html"), pdfFile);
var browser = ((GeckoWebBrowser)_pdfViewerControl);
browser.Navigate(url);
browser.DocumentCompleted += (sender, args) =>
{
// We want to suppress several of the buttons that the control normally shows.
// It's nice if we don't have to modify the html and related files, because they are unzipped from a package we install
// from a source I'm not sure we control, and installed into a directory we can't modify at runtime.
// A workaround is to tweak the stylesheet to hide them. The actual buttons (and two menu items) are easily
// hidden by ID.
// Unfortunately we're getting rid of a complete group in the pull-down menu, which leaves an ugly pair of
// adjacent separators. And the separators don't have IDs so we can't easily select just one to hide.
// Fortunately there are no other divs in the parent (besides the separator) so we just hide the second one.
// This is unfortunately rather fragile and may not do exactly what we want if the viewer.html file
// defining the pdfjs viewer changes.
GeckoStyleSheet stylesheet = browser.Document.StyleSheets.First();
stylesheet.CssRules.Add("#openFile, #print, #download, #viewBookmark, #pageRotateCw, #pageRotateCcw, #secondaryToolbarButtonContainer div:nth-of-type(2) {display: none}");
};
return true;
}
public void Print()
{
#if !__MonoCS__
if (Settings.Default.UseAdobePdfViewer)
{
((AdobeReaderControl)_pdfViewerControl).Print();
return;
}
#endif
// TODO
throw new NotImplementedException("This used to call _adobeReaderControl.Print, but that doesn't exist on GeckoBrowser");
}
}
}
| // Copyright (c) 2014 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.Drawing;
using System.Windows.Forms;
using Bloom.Properties;
using Gecko;
using Palaso.IO;
namespace Bloom.Publish
{
/// <summary>
/// Wrapper class that wraps either a Gecko web browser that displays the PDF file through
/// pdf.js, or the Adobe Reader control. Which one is used depends on the operating system
/// (Linux always uses pdf.js) and the UseAdobePdfViewer setting in the config file.
/// </summary>
public partial class PdfViewer : UserControl
{
private Control _pdfViewerControl;
public PdfViewer()
{
InitializeComponent();
#if !__MonoCS__
if (Settings.Default.UseAdobePdfViewer)
{
_pdfViewerControl = new AdobeReaderControl();
}
else
#endif
{
_pdfViewerControl = new GeckoWebBrowser();
}
SuspendLayout();
_pdfViewerControl.BackColor = Color.White;
_pdfViewerControl.Dock = DockStyle.Fill;
_pdfViewerControl.Name = "_pdfViewerControl";
_pdfViewerControl.TabIndex = 0;
AutoScaleDimensions = new SizeF(6F, 13F);
AutoScaleMode = AutoScaleMode.Font;
Controls.Add(_pdfViewerControl);
Name = "PdfViewer";
ResumeLayout(false);
}
public bool ShowPdf(string pdfFile)
{
#if !__MonoCS__
if (Settings.Default.UseAdobePdfViewer)
return ((AdobeReaderControl)_pdfViewerControl).ShowPdf(pdfFile);
#endif
var url = string.Format("{0}{1}?file=/bloom/{2}", Bloom.web.ServerBase.PathEndingInSlash,
FileLocator.GetFileDistributedWithApplication("pdf/web/viewer.html"), pdfFile);
((GeckoWebBrowser)_pdfViewerControl).Navigate(url);
return true;
}
public void Print()
{
#if !__MonoCS__
if (Settings.Default.UseAdobePdfViewer)
{
((AdobeReaderControl)_pdfViewerControl).Print();
return;
}
#endif
// TODO
throw new NotImplementedException("This used to call _adobeReaderControl.Print, but that doesn't exist on GeckoBrowser");
}
}
}
| mit | C# |
afa42e4ddce4f5e6cbdae055ea60ecbe52b9a49a | make EndSession public #2469 | MienDev/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4 | src/Models/Messages/EndSession.cs | src/Models/Messages/EndSession.cs | // Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Collections.Generic;
namespace IdentityServer4.Models
{
/// <summary>
/// Models the data necessary for end session to trigger single signout.
/// </summary>
public class EndSession
{
/// <summary>
/// The SubjectId of the user.
/// </summary>
public string SubjectId { get; set; }
/// <summary>
/// The session Id of the user's authentication session.
/// </summary>
public string SessionId { get; set; }
/// <summary>
/// The list of client Ids that the user has authenticated to.
/// </summary>
public IEnumerable<string> ClientIds { get; set; }
}
}
| // Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Collections.Generic;
namespace IdentityServer4.Models
{
/// <summary>
/// Models the data necessary for end session to trigger single signout.
/// </summary>
internal class EndSession
{
public string SubjectId { get; set; }
public string SessionId { get; set; }
public IEnumerable<string> ClientIds { get; set; }
}
}
| apache-2.0 | C# |
00e974794076c241779694f6ec988a8ccf204044 | Test scene visual improvements | UselessToucan/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,peppy/osu-new,NeoAdonis/osu,ppy/osu,peppy/osu | osu.Game.Tests/Visual/Online/TestSceneProfileLineChart.cs | osu.Game.Tests/Visual/Online/TestSceneProfileLineChart.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Overlays.Profile.Sections.Historical;
using osu.Framework.Graphics;
using static osu.Game.Users.User;
using System;
using osu.Game.Overlays;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Tests.Visual.Online
{
public class TestSceneProfileLineChart : OsuTestScene
{
[Cached]
private readonly OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Pink);
public TestSceneProfileLineChart()
{
var values = new[]
{
new UserHistoryCount { Date = new DateTime(2010, 5, 1), Count = 1000 },
new UserHistoryCount { Date = new DateTime(2010, 6, 1), Count = 20 },
new UserHistoryCount { Date = new DateTime(2010, 7, 1), Count = 20000 },
new UserHistoryCount { Date = new DateTime(2010, 8, 1), Count = 30 },
new UserHistoryCount { Date = new DateTime(2010, 9, 1), Count = 50 },
new UserHistoryCount { Date = new DateTime(2010, 10, 1), Count = 2000 },
new UserHistoryCount { Date = new DateTime(2010, 11, 1), Count = 2100 }
};
AddRange(new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = colourProvider.Background4
},
new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Padding = new MarginPadding { Horizontal = 50 },
Child = new ProfileLineChart
{
Values = values
}
}
});
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Overlays.Profile.Sections.Historical;
using osu.Framework.Graphics;
using static osu.Game.Users.User;
using System;
using osu.Game.Overlays;
using osu.Framework.Allocation;
namespace osu.Game.Tests.Visual.Online
{
public class TestSceneProfileLineChart : OsuTestScene
{
[Cached]
private readonly OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Pink);
public TestSceneProfileLineChart()
{
var values = new[]
{
new UserHistoryCount { Date = new DateTime(2010, 5, 1), Count = 1000 },
new UserHistoryCount { Date = new DateTime(2010, 6, 1), Count = 20 },
new UserHistoryCount { Date = new DateTime(2010, 7, 1), Count = 20000 },
new UserHistoryCount { Date = new DateTime(2010, 8, 1), Count = 30 },
new UserHistoryCount { Date = new DateTime(2010, 9, 1), Count = 50 },
new UserHistoryCount { Date = new DateTime(2010, 10, 1), Count = 2000 },
new UserHistoryCount { Date = new DateTime(2010, 11, 1), Count = 2100 }
};
Add(new ProfileLineChart
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Values = values
});
}
}
}
| mit | C# |
155ca3a24a6afe32e5909ed159d7d084f0fd5946 | Add UserAgent to request | Pathio/excel-requests | Requests/Providers/HttpProvider.cs | Requests/Providers/HttpProvider.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Newtonsoft.Json.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Requests.Providers
{
public class HttpProvider
{
public JToken Get(string url, Dictionary<string, string> headers)
{
var request = WebRequest.Create(url) as HttpWebRequest;
var response = new JObject();
request.ProtocolVersion = HttpVersion.Version10;
request.KeepAlive = false;
request.ServicePoint.Expect100Continue = false;
request.UserAgent = "Excel-Requests";
foreach (var header in headers)
request.Headers.Add(header.Key, header.Value);
using (var httpResponse = request.GetResponse() as HttpWebResponse)
{
response.Add("Text", JValue.CreateNull());
response.Add("StatusCode", (int)httpResponse.StatusCode);
response.Add("StatusDescription", httpResponse.StatusDescription);
response.Add("ContentType", httpResponse.ContentType);
response.Add("Method", httpResponse.Method);
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
using (var reader = new System.IO.StreamReader(httpResponse.GetResponseStream()))
{
var text = reader.ReadToEnd();
response["Text"] = text;
if(httpResponse.ContentType.ToLower().Contains("application/json"))
response.Add("Json", Parser.Parse(text));
}
}
}
return response;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Newtonsoft.Json.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Requests.Providers
{
public class HttpProvider
{
public JToken Get(string url, Dictionary<string, string> headers)
{
var request = WebRequest.Create(url) as HttpWebRequest;
var response = new JObject();
request.ProtocolVersion = HttpVersion.Version10;
request.KeepAlive = false;
request.ServicePoint.Expect100Continue = false;
foreach (var header in headers)
request.Headers.Add(header.Key, header.Value);
using (var httpResponse = request.GetResponse() as HttpWebResponse)
{
response.Add("Text", JValue.CreateNull());
response.Add("StatusCode", (int)httpResponse.StatusCode);
response.Add("StatusDescription", httpResponse.StatusDescription);
response.Add("ContentType", httpResponse.ContentType);
response.Add("Method", httpResponse.Method);
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
using (var reader = new System.IO.StreamReader(httpResponse.GetResponseStream()))
{
var text = reader.ReadToEnd();
response["Text"] = text;
if(httpResponse.ContentType.ToLower().Contains("application/json"))
response.Add("Json", Parser.Parse(text));
}
}
}
return response;
}
}
}
| apache-2.0 | C# |
6e4efdd1b11dde4ad43bcee7c1745a7374bf482e | Add test coverage for per-ruleset setup screens | smoogipoo/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,ppy/osu,ppy/osu,peppy/osu-new,peppy/osu,NeoAdonis/osu,peppy/osu,smoogipooo/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu | osu.Game.Tests/Visual/Editing/TestSceneSetupScreen.cs | osu.Game.Tests/Visual/Editing/TestSceneSetupScreen.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Catch;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Beatmaps;
using osu.Game.Rulesets.Taiko;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Setup;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestSceneSetupScreen : EditorClockTestScene
{
[Cached(typeof(EditorBeatmap))]
[Cached(typeof(IBeatSnapProvider))]
private readonly EditorBeatmap editorBeatmap;
public TestSceneSetupScreen()
{
editorBeatmap = new EditorBeatmap(new OsuBeatmap());
}
[Test]
public void TestOsu() => runForRuleset(new OsuRuleset().RulesetInfo);
[Test]
public void TestTaiko() => runForRuleset(new TaikoRuleset().RulesetInfo);
[Test]
public void TestCatch() => runForRuleset(new CatchRuleset().RulesetInfo);
[Test]
public void TestMania() => runForRuleset(new ManiaRuleset().RulesetInfo);
private void runForRuleset(RulesetInfo rulesetInfo)
{
AddStep("create screen", () =>
{
editorBeatmap.BeatmapInfo.Ruleset = rulesetInfo;
Beatmap.Value = CreateWorkingBeatmap(editorBeatmap.PlayableBeatmap);
Child = new SetupScreen
{
State = { Value = Visibility.Visible },
};
});
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu.Beatmaps;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Setup;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestSceneSetupScreen : EditorClockTestScene
{
[Cached(typeof(EditorBeatmap))]
[Cached(typeof(IBeatSnapProvider))]
private readonly EditorBeatmap editorBeatmap;
public TestSceneSetupScreen()
{
editorBeatmap = new EditorBeatmap(new OsuBeatmap());
}
[BackgroundDependencyLoader]
private void load()
{
Beatmap.Value = CreateWorkingBeatmap(editorBeatmap.PlayableBeatmap);
Child = new SetupScreen
{
State = { Value = Visibility.Visible },
};
}
}
}
| mit | C# |
85d4c0d54e7070066ba234753782fc2cfad246b3 | Update SettingsEngine.cs | dimmpixeye/Unity3dTools | Runtime/Settings/SettingsEngine.cs | Runtime/Settings/SettingsEngine.cs | // Project : ACTORS
// Contacts : Pixeye - [email protected]
using System;
namespace Pixeye.Framework
{
[Serializable]
public class SettingsEngine
{
public int SizeEntities = 1024;
public int SizeComponents = 256;
public int SizeGenerations = 4;
public int SizeProcessors = 256;
public string DataNamespace = "";
}
}
| // Project : ACTORS
// Contacts : Pixeye - [email protected]
using System;
namespace Pixeye.Framework
{
[Serializable]
public class SettingsEngine
{
public int SizeEntities = 1024;
public int SizeComponents = 256;
public int SizeGenerations = 4;
public int SizeProcessors = 256;
public string DataNamespace = "Pixeye.Source";
}
} | mit | C# |
9127dcea24fb4d9ae9e69020345bded9bd243b22 | update sample | dreign/ComBoost,dreign/ComBoost | Samples/Company.Entity/Employee.cs | Samples/Company.Entity/Employee.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Company.Entity
{
[DisplayName("员工")]
[DisplayColumn("Name")]
[Parent(typeof(EmployeeGroup), "Group")]
[EntityAuthentication(AllowAnonymous = false, ViewRolesRequired = new string[] { "Admin" })]
public class Employee : UserBase
{
[Searchable]
[Display(Name = "员工姓名", Order = 0)]
[Required]
public virtual string Name { get; set; }
[Display(Name = "员工组", Order = 10)]
[Required]
public virtual EmployeeGroup Group { get; set; }
[Searchable]
[Display(Name = "性别", Order = 20)]
[CustomDataType(CustomDataType.Sex)]
[Required]
public virtual bool Sex { get; set; }
[Display(Name = "创建日期", Order = 20)]
[Hide(IsHiddenOnView = false)]
public override DateTime CreateDate { get { return base.CreateDate; } set { base.CreateDate = value; } }
public override bool IsInRole(string role)
{
return Group.Power.ToString() == role;
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Company.Entity
{
[DisplayName("员工")]
[DisplayColumn("Name")]
[Parent(typeof(EmployeeGroup), "Group")]
[EntityAuthentication(AllowAnonymous = false, ViewRolesRequired = new string[] { "Admin" })]
public class Employee : UserBase
{
[Display(Name = "员工姓名", Order = 0)]
[Required]
public virtual string Name { get; set; }
[Display(Name = "员工组", Order = 10)]
[Required]
public virtual EmployeeGroup Group { get; set; }
[Display(Name = "性别", Order = 20)]
[CustomDataType(CustomDataType.Sex)]
[Required]
public virtual bool Sex { get; set; }
[Display(Name = "创建日期", Order = 20)]
[Hide(IsHiddenOnView = false)]
public override DateTime CreateDate { get { return base.CreateDate; } set { base.CreateDate = value; } }
public override bool IsInRole(string role)
{
return Group.Power.ToString() == role;
}
}
}
| mit | C# |
4f71c3400ae689bf42f5cfd7f246f75063e998b0 | Fix broken links in Room.Index view | johanhelsing/vaskelista,johanhelsing/vaskelista | Vaskelista/Views/Room/Index.cshtml | Vaskelista/Views/Room/Index.cshtml | @model IEnumerable<Vaskelista.Models.Room>
@{
ViewBag.Title = "Index";
}
<h2>Romoversikt</h2>
<p>
<a href="@Url.Action("Index", "Task")" class="btn btn-default"><i class="fa fa-list"></i> Planlagte oppgaver</a>
<a href="@Url.Action("Create")" class="btn btn-default"><i class="fa fa-plus"></i> Nytt rom</a>
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td class="vert-align">
@Html.DisplayFor(modelItem => item.Name)
</td>
<td class="vert-align">
<a href="@Url.Action("Edit", new { id = item.RoomId })" class="btn btn-default btn-sm"><i class="fa fa-edit"></i> Endre</a>
<a href="@Url.Action("Details", new { id = item.RoomId })" class="btn btn-default btn-sm"><i class="fa fa-info"></i> Detaljer</a>
</td>
</tr>
}
</table>
| @model IEnumerable<Vaskelista.Models.Room>
@{
ViewBag.Title = "Index";
}
<h2>Romoversikt</h2>
<p>
<a href="@Url.Action("Index", "Task")" class="btn btn-default"><i class="fa fa-list"></i> Planlagte oppgaver</a>
<a href="@Url.Action("Create")" class="btn btn-default"><i class="fa fa-plus"></i> Nytt rom</a>
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td class="vert-align">
@Html.DisplayFor(modelItem => item.Name)
</td>
<td class="vert-align">
<a href="@Url.Action("Edit")" class="btn btn-default btn-sm"><i class="fa fa-edit"></i> Endre</a>
<a href="@Url.Action("Details")" class="btn btn-default btn-sm"><i class="fa fa-info"></i> Detaljer</a>
</td>
</tr>
}
</table>
| mit | C# |
bc9ce69c433e88d32e831e812a37b38952be61be | Fix parse order bug (For example, "321" parsed value as 123) | fanoI/Cosmos,zhangwenquan/Cosmos,sgetaz/Cosmos,kant2002/Cosmos-1,zdimension/Cosmos,MetSystem/Cosmos,fanoI/Cosmos,Cyber4/Cosmos,trivalik/Cosmos,Cyber4/Cosmos,jp2masa/Cosmos,zhangwenquan/Cosmos,CosmosOS/Cosmos,MetSystem/Cosmos,trivalik/Cosmos,fanoI/Cosmos,MyvarHD/Cosmos,kant2002/Cosmos-1,zarlo/Cosmos,trivalik/Cosmos,MyvarHD/Cosmos,zdimension/Cosmos,zarlo/Cosmos,tgiphil/Cosmos,Cyber4/Cosmos,MetSystem/Cosmos,kant2002/Cosmos-1,jp2masa/Cosmos,MetSystem/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,MetSystem/Cosmos,tgiphil/Cosmos,MyvarHD/Cosmos,zdimension/Cosmos,sgetaz/Cosmos,zhangwenquan/Cosmos,sgetaz/Cosmos,sgetaz/Cosmos,MyvarHD/Cosmos,zdimension/Cosmos,Cyber4/Cosmos,jp2masa/Cosmos,Cyber4/Cosmos,zdimension/Cosmos,zarlo/Cosmos,zhangwenquan/Cosmos,kant2002/Cosmos-1,MyvarHD/Cosmos,zhangwenquan/Cosmos,CosmosOS/Cosmos,tgiphil/Cosmos,CosmosOS/Cosmos,sgetaz/Cosmos | source2/Kernel/System/Cosmos.System.Plugs.System/Int32Impl.cs | source2/Kernel/System/Cosmos.System.Plugs.System/Int32Impl.cs | using System;
using System.Collections.Generic;
using System.Text;
using Cosmos.IL2CPU.Plugs;
namespace Cosmos.System.Plugs.System {
[Plug(Target = typeof(Int32))]
public class Int32Impl {
protected static readonly string Digits = "0123456789";
// error during compile about "Plug needed."
// Error 11 Plug needed. System.RuntimeTypeHandle System.Type.get_TypeHandle()
//at Cosmos.IL2CPU.ILScanner.ScanMethod(MethodBase aMethod, Boolean aIsPlug) in M:\source\Cosmos\source2\IL2CPU\Cosmos.IL2CPU\ILScanner.cs:line 658
//at Cosmos.IL2CPU.ILScanner.ScanQueue() in M:\source\Cosmos\source2\IL2CPU\Cosmos.IL2CPU\ILScanner.cs:line 774
//at Cosmos.IL2CPU.ILScanner.Execute(MethodBase aStartMethod) in M:\source\Cosmos\source2\IL2CPU\Cosmos.IL2CPU\ILScanner.cs:line 279
//at Cosmos.Build.MSBuild.IL2CPU.Execute() in M:\source\Cosmos\source2\Build\Cosmos.Build.MSBuild\IL2CPU.cs:line 250 C:\Program Files (x86)\MSBuild\Cosmos\Cosmos.targets 32 10 Guess (source2\Demos\Guess\Guess)
// for instance ones still declare as static but add a aThis argument first of same type as target
public static int Parse(string s)
{
int xResult = 0;
//Bug: Parse by reverse order, for example, "321" parsed as value 123
//for (int i = s.Length - 1; i >= 0; i--)
for (int i = 0; i <= s.Length - 1; i++)
{
xResult = xResult * 10;
int j = s[i] - '0';
if (j < 0 || j > 9)
{
throw new Exception("Non numeric digit found in int.parse");
}
xResult = xResult + j;
}
return xResult;
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using Cosmos.IL2CPU.Plugs;
namespace Cosmos.System.Plugs.System {
[Plug(Target = typeof(Int32))]
public class Int32Impl {
protected static readonly string Digits = "0123456789";
// error during compile about "Plug needed."
// Error 11 Plug needed. System.RuntimeTypeHandle System.Type.get_TypeHandle()
//at Cosmos.IL2CPU.ILScanner.ScanMethod(MethodBase aMethod, Boolean aIsPlug) in M:\source\Cosmos\source2\IL2CPU\Cosmos.IL2CPU\ILScanner.cs:line 658
//at Cosmos.IL2CPU.ILScanner.ScanQueue() in M:\source\Cosmos\source2\IL2CPU\Cosmos.IL2CPU\ILScanner.cs:line 774
//at Cosmos.IL2CPU.ILScanner.Execute(MethodBase aStartMethod) in M:\source\Cosmos\source2\IL2CPU\Cosmos.IL2CPU\ILScanner.cs:line 279
//at Cosmos.Build.MSBuild.IL2CPU.Execute() in M:\source\Cosmos\source2\Build\Cosmos.Build.MSBuild\IL2CPU.cs:line 250 C:\Program Files (x86)\MSBuild\Cosmos\Cosmos.targets 32 10 Guess (source2\Demos\Guess\Guess)
// for instance ones still declare as static but add a aThis argument first of same type as target
public static int Parse(string s)
{
int xResult = 0;
for (int i = s.Length - 1; i >= 0; i--)
{
xResult = xResult * 10;
int j = s[i] - '0';
if (j < 0 || j > 9)
{
throw new Exception("Non numeric digit found in int.parse");
}
xResult = xResult + j;
}
return xResult;
}
}
}
| bsd-3-clause | C# |
a2f46f983d20249b56921b0198903a70a858e74e | Update IComplier.Extension.cs | NMSLanX/Natasha | src/Natasha/Core/Engine/ComplierModule/IComplier.Extension.cs | src/Natasha/Core/Engine/ComplierModule/IComplier.Extension.cs | using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Formatting;
using System.Collections.Generic;
namespace Natasha.Complier
{
public static class IComplierExtension
{
private readonly static AdhocWorkspace _workSpace;
private readonly static CSharpParseOptions _options;
static IComplierExtension()
{
_workSpace = new AdhocWorkspace();
_workSpace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId("formatter"), VersionStamp.Default));
_options = new CSharpParseOptions(LanguageVersion.Latest);
}
public static void Deconstruct(
this string text,
out SyntaxTree tree,
out string formatter,
out IEnumerable<Diagnostic> errors)
{
tree = CSharpSyntaxTree.ParseText(text.Trim(), _options);
SyntaxNode root = Formatter.Format(tree.GetCompilationUnitRoot(), _workSpace);
tree = root.SyntaxTree;
formatter = root.ToString();
errors = root.GetDiagnostics();
}
}
}
| using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Natasha.Complier
{
public static class IComplierExtension
{
private readonly static AdhocWorkspace _workSpace;
private readonly static CSharpParseOptions _options;
static IComplierExtension()
{
_workSpace = new AdhocWorkspace();
_workSpace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId("formatter"), VersionStamp.Default));
_options = new CSharpParseOptions(LanguageVersion.Latest);
}
public static void Deconstruct(
this string text,
out SyntaxTree tree,
out string formatter,
out IEnumerable<Diagnostic> errors)
{
tree = CSharpSyntaxTree.ParseText(text.Trim(), _options);
SyntaxNode root = Formatter.Format(tree.GetCompilationUnitRoot(), _workSpace);
tree = root.SyntaxTree;
formatter = root.ToString();
errors = root.GetDiagnostics();
}
}
}
| mpl-2.0 | C# |
088af5675ff1d66417b94c75a6bd0ca078ecdb93 | Bump Version | BrianLima/UWPHook | UWPHook/Properties/AssemblyInfo.cs | UWPHook/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("UWPHook")]
[assembly: AssemblyDescription("Add your UWP games and apps to Steam!")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Briano")]
[assembly: AssemblyProduct("UWPHook")]
[assembly: AssemblyCopyright("Copyright Brian Lima © 2016")]
[assembly: AssemblyTrademark("Briano")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.5.0.0")]
[assembly: AssemblyFileVersion("2.5.0.0")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("UWPHook")]
[assembly: AssemblyDescription("Add your UWP games and apps to Steam!")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Briano")]
[assembly: AssemblyProduct("UWPHook")]
[assembly: AssemblyCopyright("Copyright Brian Lima © 2016")]
[assembly: AssemblyTrademark("Briano")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.3.0.0")]
[assembly: AssemblyFileVersion("2.3.0.0")]
| mit | C# |
80e8fe72a4a7b9b2f5e1a82adb2cd8164889c48b | Add missing function to interface | projecteon/thecollection,projecteon/thecollection,projecteon/thecollection,projecteon/thecollection | TheCollection.Business/ISearchRepository.cs | TheCollection.Business/ISearchRepository.cs | namespace TheCollection.Business {
using System.Collections.Generic;
using System.Threading.Tasks;
public interface ISearchRepository<T> where T : class {
Task<IEnumerable<T>> SearchAsync(string searchterm, int top = 0);
Task<long> SearchRowCountAsync(string searchterm);
}
}
| namespace TheCollection.Business {
using System.Collections.Generic;
using System.Threading.Tasks;
public interface ISearchRepository<T> where T : class {
Task<IEnumerable<T>> SearchAsync(string searchterm, int top = 0);
}
}
| apache-2.0 | C# |
3f77789b2f05ad8f4616b9a62568b81a70940835 | Clean up controller initialization on Android | MilenPavlov/PortableRazorStarterKit,xamarin/PortableRazorStarterKit,MilenPavlov/PortableRazorStarterKit,xamarin/PortableRazorStarterKit | PortableCongress/AndroidCongress/MainActivity.cs | PortableCongress/AndroidCongress/MainActivity.cs | using System;
using Android.App;
using Android.Content;
using Android.Webkit;
using Android.OS;
using Congress;
using PortableCongress;
namespace AndroidCongress
{
[Activity (Label = "@string/app_name", MainLauncher = true, ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait)]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
Congress.ResourceManager.EnsureResources (
typeof(PortableCongress.Politician).Assembly,
String.Format ("/data/data/{0}/files", Application.Context.PackageName));
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
var webView = FindViewById<WebView> (Resource.Id.webView);
// Use subclassed WebViewClient to intercept hybrid native calls
var webViewClient = new HybridWebViewClient ();
var politicianController = new PoliticianController (
new HybridWebView (webView),
new DataAccess ());
PortableRazor.RouteHandler.RegisterController ("Politician", politicianController);
webView.SetWebViewClient (webViewClient);
webView.Settings.CacheMode = CacheModes.CacheElseNetwork;
webView.Settings.JavaScriptEnabled = true;
webView.SetWebChromeClient (new HybridWebChromeClient (this));
politicianController.ShowPoliticianList ();
}
class HybridWebViewClient : WebViewClient {
public override bool ShouldOverrideUrlLoading (WebView webView, string url) {
var handled = PortableRazor.RouteHandler.HandleRequest (url);
return handled;
}
}
class HybridWebChromeClient : WebChromeClient {
Context context;
public HybridWebChromeClient (Context context) : base () {
this.context = context;
}
public override bool OnJsAlert (WebView view, string url, string message, JsResult result) {
var alertDialogBuilder = new AlertDialog.Builder (context)
.SetMessage (message)
.SetCancelable (false)
.SetPositiveButton ("Ok", (sender, args) => {
result.Confirm ();
});
alertDialogBuilder.Create().Show();
return true;
}
public override bool OnJsConfirm (WebView view, string url, string message, JsResult result) {
var alertDialogBuilder = new AlertDialog.Builder (context)
.SetMessage (message)
.SetCancelable (false)
.SetPositiveButton ("Ok", (sender, args) => {
result.Confirm();
})
.SetNegativeButton ("Cancel", (sender, args) => {
result.Cancel();
});
alertDialogBuilder.Create().Show();
return true;
}
}
}
}
| using System;
using Android.App;
using Android.Content;
using Android.Webkit;
using Android.OS;
using Congress;
using PortableCongress;
namespace AndroidCongress
{
[Activity (Label = "@string/app_name", MainLauncher = true, ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait)]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
Congress.ResourceManager.EnsureResources (
typeof(PortableCongress.Politician).Assembly,
String.Format ("/data/data/{0}/files", Application.Context.PackageName));
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
var webView = FindViewById<WebView> (Resource.Id.webView);
// Use subclassed WebViewClient to intercept hybrid native calls
var webViewClient = new HybridWebViewClient ();
var politicianController = new PoliticianController (
new HybridWebView (webView),
new DataAccess ());
webViewClient.SetPoliticianController (politicianController);
PortableRazor.RouteHandler.RegisterController ("Politician", politicianController);
webView.SetWebViewClient (webViewClient);
webView.Settings.CacheMode = CacheModes.CacheElseNetwork;
webView.Settings.JavaScriptEnabled = true;
webView.SetWebChromeClient (new HybridWebChromeClient (this));
webViewClient.ShowPoliticianList ();
}
class HybridWebViewClient : WebViewClient {
PoliticianController politicianController;
public void SetPoliticianController(PoliticianController controller) {
politicianController = controller;
}
public void ShowPoliticianList() {
politicianController.ShowPoliticianList ();
}
public override bool ShouldOverrideUrlLoading (WebView webView, string url) {
var handled = PortableRazor.RouteHandler.HandleRequest (url);
return handled;
}
}
class HybridWebChromeClient : WebChromeClient {
Context context;
public HybridWebChromeClient (Context context) : base () {
this.context = context;
}
public override bool OnJsAlert (WebView view, string url, string message, JsResult result) {
var alertDialogBuilder = new AlertDialog.Builder (context)
.SetMessage (message)
.SetCancelable (false)
.SetPositiveButton ("Ok", (sender, args) => {
result.Confirm ();
});
alertDialogBuilder.Create().Show();
return true;
}
public override bool OnJsConfirm (WebView view, string url, string message, JsResult result) {
var alertDialogBuilder = new AlertDialog.Builder (context)
.SetMessage (message)
.SetCancelable (false)
.SetPositiveButton ("Ok", (sender, args) => {
result.Confirm();
})
.SetNegativeButton ("Cancel", (sender, args) => {
result.Cancel();
});
alertDialogBuilder.Create().Show();
return true;
}
}
}
}
| mit | C# |
043313a95c4a7fddc108eacc9d3bb7fa586a9f53 | Bump version. | realartists/chargebee-dotnet | RealArtists.ChargeBee/Properties/AssemblyInfo.cs | RealArtists.ChargeBee/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RealArtists.ChargeBee")]
[assembly: AssemblyDescription("Modern .NET client library for integrating with the ChargeBee service.")]
[assembly: AssemblyConfiguration("")]
[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("da556ed8-6c79-415f-97e0-6c37c83ef84b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.2")]
[assembly: AssemblyFileVersion("0.1.2")]
[assembly: AssemblyCompanyAttribute("kogir")]
[assembly: AssemblyProductAttribute("RealArtists.ChargeBee")]
[assembly: AssemblyCopyrightAttribute("©ChargeBee Inc. and Nick Sivo. See LICENSE.")]
| 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("RealArtists.ChargeBee")]
[assembly: AssemblyDescription("Modern .NET client library for integrating with the ChargeBee service.")]
[assembly: AssemblyConfiguration("")]
[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("da556ed8-6c79-415f-97e0-6c37c83ef84b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.1")]
[assembly: AssemblyFileVersion("0.1.1")]
[assembly: AssemblyCompanyAttribute("kogir")]
[assembly: AssemblyProductAttribute("RealArtists.ChargeBee")]
[assembly: AssemblyCopyrightAttribute("©ChargeBee Inc. and Nick Sivo. See LICENSE.")]
| mit | C# |
62cc3dcdfcfaff789350fbda3979f0ae0cc45701 | Prepend debug messages in the web chat example. | mdevilliers/SignalR.RabbitMq,mdevilliers/SignalR.RabbitMq,slovely/SignalR.RabbitMq,slovely/SignalR.RabbitMq | SignalR.RabbitMq.Example/Views/Home/Index.cshtml | SignalR.RabbitMq.Example/Views/Home/Index.cshtml | @{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<input type="text" id="msg" />
<a id="broadcast" href="#">Send message</a>
<p>Messages : </p>
<ul id="messages"> </ul>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var chat = $.connection.chat;
$.connection.hub.logging = true;
// Declare a function on the chat hub so the server can invoke it
chat.client.addMessage = function (message, from) {
$('#messages').prepend('<li>' + message + " from " + from + '</li>');
};
chat.client.onConsoleMessage = function (message) {
$('#messages').prepend('<li> From the console application : ' + message + '</li>');
};
$("#broadcast").click(function () {
// Call the chat method on the server
chat.server.send($('#msg').val())
.done(function () {
console.log('Success!');
})
.fail(function (e) {
console.warn(e);
});
});
$("#broadcast").hide();
// Start the connection
$.connection.hub.start({transport: 'auto'},function () {
$("#broadcast").show();
console.log("Success");
});
});
</script>
| @{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<input type="text" id="msg" />
<a id="broadcast" href="#">Send message</a>
<p>Messages : </p>
<ul id="messages"> </ul>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var chat = $.connection.chat;
$.connection.hub.logging = true;
// Declare a function on the chat hub so the server can invoke it
chat.client.addMessage = function (message, from) {
$('#messages').append('<li>' + message + " from " + from + '</li>');
};
chat.client.onConsoleMessage = function (message) {
$('#messages').append('<li> From the console application : ' + message + '</li>');
};
$("#broadcast").click(function () {
// Call the chat method on the server
chat.server.send($('#msg').val())
.done(function () {
console.log('Success!');
})
.fail(function (e) {
console.warn(e);
});
});
$("#broadcast").hide();
// Start the connection
$.connection.hub.start({transport: 'auto'},function () {
$("#broadcast").show();
console.log("Success");
});
});
</script>
| mit | C# |
75fc8bb5389f7ee25f0ea66f424ebf0262694223 | Verify patterns are not repeatable. | JornWildt/ZimmerBot | ZimmerBot.Core.Tests/BotTests/RepeatableTests.cs | ZimmerBot.Core.Tests/BotTests/RepeatableTests.cs | using NUnit.Framework;
namespace ZimmerBot.Core.Tests.BotTests
{
[TestFixture]
public class RepeatableTests : TestHelper
{
[Test]
public void NormalyOutputDoesNotRepeat()
{
BuildBot(@"
> help
: It is okay
> Help
! weight 0.999
: It is done
");
AssertDialog("help", "It is okay");
AssertDialog("help", "It is done");
}
[Test]
public void NormalyOutputDoesNotRepeat_ForPatterns()
{
BuildBot(@"
! pattern (intent = help)
{
> help
}
>> help
: It is okay
>> Help
! weight 0.999
: It is done
");
AssertDialog("help", "It is okay");
AssertDialog("help", "It is done");
}
[Test]
public void CanMarkRuleAsRepeatable()
{
BuildBot(@"
> help
: It is okay
! repeatable
");
AssertDialog("help", "It is okay");
AssertDialog("help", "It is okay");
}
[Test]
public void CallStatementsMakeRuleRepeatle()
{
BuildBot(@"
> help
: It is okay
! call General.Echo(""aaa"")
");
AssertDialog("help", "It is okay");
AssertDialog("help", "It is okay");
}
[Test]
public void CanMarkAsNonRepeatable()
{
BuildBot(@"
> help
: It is okay
! not_repeatable
! call General.Echo(""aaa"")
> help
! weight 0.999
: It is done
");
AssertDialog("help", "It is okay");
AssertDialog("help", "It is done");
}
}
}
| using NUnit.Framework;
namespace ZimmerBot.Core.Tests.BotTests
{
[TestFixture]
public class RepeatableTests : TestHelper
{
[Test]
public void NormalyOutputDoesNotRepeat()
{
BuildBot(@"
> help
: It is okay
> Help
! weight 0.999
: It is done
");
AssertDialog("help", "It is okay");
AssertDialog("help", "It is done");
}
[Test]
public void CanMarkRuleAsRepeatable()
{
BuildBot(@"
> help
: It is okay
! repeatable
");
AssertDialog("help", "It is okay");
AssertDialog("help", "It is okay");
}
[Test]
public void CallStatementsMakeRuleRepeatle()
{
BuildBot(@"
> help
: It is okay
! call General.Echo(""aaa"")
");
AssertDialog("help", "It is okay");
AssertDialog("help", "It is okay");
}
[Test]
public void CanMarkAsNonRepeatable()
{
BuildBot(@"
> help
: It is okay
! not_repeatable
! call General.Echo(""aaa"")
> help
! weight 0.999
: It is done
");
AssertDialog("help", "It is okay");
AssertDialog("help", "It is done");
}
}
}
| mit | C# |
5c9c787551992ccc9a90d48cf313cfbe00e5815f | Make ColorChanger color name agnostic | jshou/party-game,mikelovesrobots/unity3d-base,mikelovesrobots/daft-pong,mikelovesrobots/unity3d-game-of-life,mikelovesrobots/throw-a-ball-tutorial,mikelovesrobots/daft-pong | app/Assets/Scripts/ColorChanger.cs | app/Assets/Scripts/ColorChanger.cs | using UnityEngine;
using System.Collections;
public class ColorChanger : MonoBehaviour {
public Renderer[] Renderers;
public string ColorName = "_TintColor";
public void ChangeColor(Color color) {
foreach (var renderer in Renderers) {
renderer.material.SetColor(ColorName, color);
}
}
}
| using UnityEngine;
using System.Collections;
public class ColorChanger : MonoBehaviour {
public Renderer[] Renderers;
public void ChangeColor(Color color) {
foreach (var renderer in Renderers) {
renderer.material.color = color;
}
}
}
| mit | C# |
61b4ed4b2c0c033aec01f5fa6dc6ce261dc40d0c | Allow changing log filename | LibertyLocked/webscripthook,LibertyLocked/webscripthook,LibertyLocked/webscripthook,LibertyLocked/webscripthook | webscripthook-plugin/Logger.cs | webscripthook-plugin/Logger.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace WebScriptHook
{
class Logger
{
public static string Location
{
get;
set;
}
public static bool Enable
{
get;
set;
}
public static void Log(object message)
{
if (Enable)
{
File.AppendAllText(Location, DateTime.Now + " : " + message + Environment.NewLine);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace WebScriptHook
{
class Logger
{
public static bool Enable = false;
public static void Log(object message)
{
if (Enable)
{
File.AppendAllText(@".\scripts\WebScriptHook.log", DateTime.Now + " : " + message + Environment.NewLine);
}
}
}
}
| mit | C# |
87601de2da2cb91d459490ccc5fd17b5bf26c625 | Update exporter efficiency test to cover both delta and cumulative (#2541) | open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet | test/OpenTelemetry.Tests/Metrics/MemoryEfficiencyTests.cs | test/OpenTelemetry.Tests/Metrics/MemoryEfficiencyTests.cs | // <copyright file="MemoryEfficiencyTests.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System.Collections.Generic;
using System.Diagnostics.Metrics;
using OpenTelemetry.Exporter;
using OpenTelemetry.Tests;
using Xunit;
namespace OpenTelemetry.Metrics.Tests
{
public class MemoryEfficiencyTests
{
[Theory(Skip = "To be run after https://github.com/open-telemetry/opentelemetry-dotnet/issues/2524 is fixed")]
[InlineData(AggregationTemporality.Cumulative)]
[InlineData(AggregationTemporality.Delta)]
public void ExportOnlyWhenPointChanged(AggregationTemporality temporality)
{
using var meter = new Meter(Utils.GetCurrentMethodName(), "1.0");
var exportedItems = new List<Metric>();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddReader(
new BaseExportingMetricReader(new InMemoryExporter<Metric>(exportedItems))
{
PreferredAggregationTemporality = temporality,
})
.Build();
var counter = meter.CreateCounter<long>("meter");
counter.Add(10, new KeyValuePair<string, object>("tag1", "value1"));
meterProvider.ForceFlush();
Assert.Single(exportedItems);
exportedItems.Clear();
meterProvider.ForceFlush();
Assert.Empty(exportedItems);
}
}
}
| // <copyright file="MemoryEfficiencyTests.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System.Collections.Generic;
using System.Diagnostics.Metrics;
using OpenTelemetry.Tests;
using Xunit;
namespace OpenTelemetry.Metrics.Tests
{
public class MemoryEfficiencyTests
{
[Fact(Skip = "To be run after https://github.com/open-telemetry/opentelemetry-dotnet/issues/2361 is fixed")]
public void CumulativeOnlyExportWhenPointChanged()
{
using var meter = new Meter(Utils.GetCurrentMethodName(), "1.0");
var exportedItems = new List<Metric>();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(exportedItems)
.Build();
var counter = meter.CreateCounter<long>("meter");
counter.Add(10, new KeyValuePair<string, object>("tag1", "value1"));
meterProvider.ForceFlush();
Assert.Single(exportedItems);
exportedItems.Clear();
meterProvider.ForceFlush();
Assert.Empty(exportedItems);
}
}
}
| apache-2.0 | C# |
080e5eb4444c6e21e6fd6249f06a0fa876681c24 | Use better markdown help | joinrpg/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net | Joinrpg/Views/Shared/EditorTemplates/MarkdownString.cshtml | Joinrpg/Views/Shared/EditorTemplates/MarkdownString.cshtml | @model JoinRpg.DataModel.MarkdownString
@{
var requiredMsg = new MvcHtmlString("");
var validation = false;
foreach (var attr in @Html.GetUnobtrusiveValidationAttributes(@ViewData.TemplateInfo.HtmlFieldPrefix, @ViewData.ModelMetadata))
{
if (attr.Key == "data-val-required")
{
requiredMsg = new MvcHtmlString("data-val-required='" + HttpUtility.HtmlAttributeEncode((string) attr.Value) + "'");
validation = true;
}
}
}
<textarea
class="form-control"
cols="100"
id="@(ViewData.TemplateInfo.HtmlFieldPrefix)_Contents"
name="@(ViewData.TemplateInfo.HtmlFieldPrefix).Contents"
@requiredMsg @(validation ? "data-val=true" : "")
rows="4">@(Model == null ? "" : Model.Contents)</textarea>
@if (validation)
{
@Html.ValidationMessageFor(model => Model.Contents, "", new { @class = "text-danger" })
}
<div class="help-block">Можно использовать <a href="http://commonmark.org/help/" target="_blank">MarkDown</a> (**<b>полужирный</b>**, _<i>курсив</i>_)</div> | @model JoinRpg.DataModel.MarkdownString
@{
var requiredMsg = new MvcHtmlString("");
var validation = false;
foreach (var attr in @Html.GetUnobtrusiveValidationAttributes(@ViewData.TemplateInfo.HtmlFieldPrefix, @ViewData.ModelMetadata))
{
if (attr.Key == "data-val-required")
{
requiredMsg = new MvcHtmlString("data-val-required='" + HttpUtility.HtmlAttributeEncode((string) attr.Value) + "'");
validation = true;
}
}
}
<textarea
class="form-control"
cols="100"
id="@(ViewData.TemplateInfo.HtmlFieldPrefix)_Contents"
name="@(ViewData.TemplateInfo.HtmlFieldPrefix).Contents"
@requiredMsg @(validation ? "data-val=true" : "")
rows="4">@(Model == null ? "" : Model.Contents)</textarea>
@if (validation)
{
@Html.ValidationMessageFor(model => Model.Contents, "", new { @class = "text-danger" })
}
<div class="help-block">Можно использовать <a href="http://daringfireball.net/projects/markdown/syntax" target="_blank">MarkDown</a> (**<b>полужирный</b>**, _<i>курсив</i>_)</div> | mit | C# |
d6191de31e14bdc1bfa53a997e741d9ed9ae85b8 | Make AuthorizationResult constructor public to allow for mocking | nozzlegear/ShopifySharp,clement911/ShopifySharp | ShopifySharp/Services/Authorization/AuthorizationResult.cs | ShopifySharp/Services/Authorization/AuthorizationResult.cs | namespace ShopifySharp
{
public class AuthorizationResult
{
public string AccessToken { get; }
public string[] GrantedScopes { get; }
public AuthorizationResult(string accessToken, string[] grantedScopes)
{
this.AccessToken = accessToken;
this.GrantedScopes = grantedScopes;
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace ShopifySharp
{
public class AuthorizationResult
{
public string AccessToken { get; }
public string[] GrantedScopes { get; }
internal AuthorizationResult(string accessToken, string[] grantedScopes)
{
this.AccessToken = accessToken;
this.GrantedScopes = grantedScopes;
}
}
}
| mit | C# |
afe745f308e1ea870aa1d44e36042de8ab6f3a25 | refactor usings in data | nProdanov/Team-French-75 | TravelAgency/TravelAgency.Data/Migrations/Configuration.cs | TravelAgency/TravelAgency.Data/Migrations/Configuration.cs | using System.Data.Entity.Migrations;
namespace TravelAgency.Data.Migrations
{
public sealed class Configuration : DbMigrationsConfiguration<TravelAgency.Data.TravelAgencyDbContext>
{
public Configuration()
{
this.AutomaticMigrationsEnabled = true;
this.ContextKey = "TravelAgency.Data.TravelAgencyDbContext";
}
protected override void Seed(TravelAgencyDbContext context)
{
}
}
}
| using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using TravelAgency.Models;
namespace TravelAgency.Data.Migrations
{
public sealed class Configuration : DbMigrationsConfiguration<TravelAgency.Data.TravelAgencyDbContext>
{
public Configuration()
{
this.AutomaticMigrationsEnabled = true;
this.ContextKey = "TravelAgency.Data.TravelAgencyDbContext";
}
protected override void Seed(TravelAgencyDbContext context)
{
}
}
}
| mit | C# |
8e177231b5e8fa962813a190ae3b72bfb46952fe | Fix retry in RemoteZipManager tp retry before opening the stream, otherwise we get a closed stream on the retry | fashaikh/SimpleWAWS,fashaikh/SimpleWAWS,projectkudu/SimpleWAWS,projectkudu/SimpleWAWS,davidebbo/SimpleWAWS,davidebbo/SimpleWAWS,projectkudu/SimpleWAWS,projectkudu/SimpleWAWS,davidebbo/SimpleWAWS,davidebbo/SimpleWAWS,projectkudu/TryAppService,fashaikh/SimpleWAWS,projectkudu/TryAppService,projectkudu/TryAppService,projectkudu/TryAppService,fashaikh/SimpleWAWS | SimpleWAWS/Kudu/RemoteZipManager.cs | SimpleWAWS/Kudu/RemoteZipManager.cs | using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Kudu.Client.Infrastructure;
using SimpleWAWS.Code;
namespace Kudu.Client.Zip
{
public class RemoteZipManager : KuduRemoteClientBase
{
private int _retryCount;
public RemoteZipManager(string serviceUrl, ICredentials credentials = null, HttpMessageHandler handler = null, int retryCount = 0)
: base(serviceUrl, credentials, handler)
{
_retryCount = retryCount;
}
private async Task PutZipStreamAsync(string path, Stream zipFile)
{
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Put;
request.RequestUri = new Uri(path, UriKind.Relative);
request.Headers.IfMatch.Add(EntityTagHeaderValue.Any);
request.Content = new StreamContent(zipFile);
await Client.SendAsync(request);
}
}
public async Task PutZipFileAsync(string path, string localZipPath)
{
await RetryHelper.Retry(async () =>
{
using (var stream = File.OpenRead(localZipPath))
{
await PutZipStreamAsync(path, stream);
}
}, _retryCount);
}
public async Task<Stream> GetZipFileStreamAsync(string path)
{
var response = await Client.GetAsync(new Uri(path, UriKind.Relative), HttpCompletionOption.ResponseHeadersRead);
return await response.Content.ReadAsStreamAsync();
}
}
}
| using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Kudu.Client.Infrastructure;
using SimpleWAWS.Code;
namespace Kudu.Client.Zip
{
public class RemoteZipManager : KuduRemoteClientBase
{
private int _retryCount;
public RemoteZipManager(string serviceUrl, ICredentials credentials = null, HttpMessageHandler handler = null, int retryCount = 0)
: base(serviceUrl, credentials, handler)
{
_retryCount = retryCount;
}
private async Task PutZipStreamAsync(string path, Stream zipFile)
{
await RetryHelper.Retry(async () =>
{
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Put;
request.RequestUri = new Uri(path, UriKind.Relative);
request.Headers.IfMatch.Add(EntityTagHeaderValue.Any);
request.Content = new StreamContent(zipFile);
await Client.SendAsync(request);
}
}, _retryCount);
}
public async Task PutZipFileAsync(string path, string localZipPath)
{
using (var stream = File.OpenRead(localZipPath))
{
await PutZipStreamAsync(path, stream);
}
}
public async Task<Stream> GetZipFileStreamAsync(string path)
{
var response = await Client.GetAsync(new Uri(path, UriKind.Relative), HttpCompletionOption.ResponseHeadersRead);
return await response.Content.ReadAsStreamAsync();
}
}
}
| apache-2.0 | C# |
e6e210c0dca11ace35f57d031ace5d7f00c2f244 | Update assembly info. | CoraleStudios/Colore,danpierce1/Colore,WolfspiritM/Colore,Sharparam/Colore | Colore/Properties/AssemblyInfo.cs | Colore/Properties/AssemblyInfo.cs | // ---------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="">
// Copyright © 2015 by Adam Hellberg and Brandon Scott.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Disclaimer: Colore is in no way affiliated
// with Razer and/or any of its employees and/or licensors.
// Adam Hellberg and Brandon Scott do not take responsibility for any harm caused, direct
// or indirect, to any Razer peripherals via the use of Colore.
//
// "Razer" is a trademark of Razer USA Ltd.
// </copyright>
// ---------------------------------------------------------------------------------------
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("Colore")]
[assembly: AssemblyDescription("A C#/.NET library for interacting with Razer's Chroma SDK.")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Colore")]
[assembly: AssemblyCopyright("Copyright © 2015 by Adam Hellberg and Brandon Scott.")]
[assembly: AssemblyTrademark("")]
#if DEBUG
#if WIN64
[assembly: AssemblyConfiguration("Debug (x64)")]
#elif WIN32
[assembly: AssemblyConfiguration("Debug (x86)")]
#else
[assembly: AssemblyConfiguration("Debug")]
#endif
#else
#if WIN64
[assembly: AssemblyConfiguration("Release (x64)")]
#elif WIN32
[assembly: AssemblyConfiguration("Release (x86)")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
#endif
// 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("37548d1c-8a88-45bd-a732-a6d069799398")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| // ---------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="">
// Copyright © 2015 by Adam Hellberg and Brandon Scott.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Disclaimer: Colore is in no way affiliated
// with Razer and/or any of its employees and/or licensors.
// Adam Hellberg and Brandon Scott do not take responsibility for any harm caused, direct
// or indirect, to any Razer peripherals via the use of Colore.
//
// "Razer" is a trademark of Razer USA Ltd.
// </copyright>
// ---------------------------------------------------------------------------------------
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("Colore")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Colore")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("37548d1c-8a88-45bd-a732-a6d069799398")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
8697404ea98ca3016228a6581e41987328bce705 | Use HashCode | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Helpers/HashHelpers.cs | WalletWasabi/Helpers/HashHelpers.cs | using System;
using System.Security.Cryptography;
using System.Text;
namespace WalletWasabi.Helpers
{
public static class HashHelpers
{
public static string GenerateSha256Hash(string input)
{
using var sha256 = SHA256.Create();
var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(input));
return ByteHelpers.ToHex(hash);
}
public static byte[] GenerateSha256Hash(byte[] input)
{
using var sha256 = SHA256.Create();
var hash = sha256.ComputeHash(input);
return hash;
}
public static int ComputeHashCode(params byte[] data)
{
var hash = new HashCode();
foreach (var element in data)
{
hash.Add(element);
}
return hash.ToHashCode();
}
}
}
| using System;
using System.Security.Cryptography;
using System.Text;
namespace WalletWasabi.Helpers
{
public static class HashHelpers
{
public static string GenerateSha256Hash(string input)
{
using var sha256 = SHA256.Create();
var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(input));
return ByteHelpers.ToHex(hash);
}
public static byte[] GenerateSha256Hash(byte[] input)
{
using var sha256 = SHA256.Create();
var hash = sha256.ComputeHash(input);
return hash;
}
/// <summary>
/// https://stackoverflow.com/a/468084/2061103
/// </summary>
public static int ComputeHashCode(params byte[] data)
{
unchecked
{
const int P = 16777619;
int hash = (int)2166136261;
for (int i = 0; i < data.Length; i++)
{
hash = (hash ^ data[i]) * P;
}
hash += hash << 13;
hash ^= hash >> 7;
hash += hash << 3;
hash ^= hash >> 17;
hash += hash << 5;
return hash;
}
}
}
}
| mit | C# |
3a6372d2d760fd9c16f51630e0df89ee66381899 | Comment about markdown | wallymathieu/dotnet_web_security_101,wallymathieu/dotnet_web_security_101,wallymathieu/dotnet_web_security_101 | Example/Views/XSS/Markdown.cshtml | Example/Views/XSS/Markdown.cshtml | @{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container body-content">
<h1>
Markdown
</h1>
<p>
Markdown has become really popular due to it's use on popular programming sites such as stackoverflow and github.
</p>
<p>Markdown is not <a href="http://daringfireball.net/projects/markdown/syntax#html">intended</a> as protection against script injection.
It can be used as a replacement for BBCode though (by html encoding the text and then running it through markdown renderer).</p>
<div class="row">
<div class="col-md-4">
<h2>Input</h2>
@using (Html.BeginForm())
{
<p>
@Html.TextArea("value.Value", ViewData["value"] as string, 10, 100, new Dictionary<string, object>())
</p>
<p>
<input type="submit" value="Submit" />
</p>
}
</div>
<div class="col-md-4">
<h2>Rendered</h2>
@Html.Raw(new MarkdownSharp.Markdown().Transform(Html.Encode(ViewData["value"] ?? string.Empty)
</div>
</div>
</div> | @{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container body-content">
<h1>
Markdown
</h1>
<p>
Markdown has become really popular due to it's use on popular programming sites such as stackoverflow and github.
</p>
<div class="row">
<div class="col-md-4">
<h2>Input</h2>
@using (Html.BeginForm())
{
<p>
@Html.TextArea("value.Value", ViewData["value"] as string, 10, 100, new Dictionary<string, object>())
</p>
<p>
<input type="submit" value="Submit" />
</p>
}
</div>
<div class="col-md-4">
<h2>Rendered</h2>
@Html.Raw(new MarkdownSharp.Markdown().Transform(Html.Encode(ViewData["value"] ?? string.Empty)))
</div>
</div>
</div> | mit | C# |
d421257dfa23f73705b5527c738781e901075ab9 | fix build error | aloneguid/support | src/NetBox/Extensions/EnumExtensions.cs | src/NetBox/Extensions/EnumExtensions.cs | using NetBox.Model;
#if (NETFULL || NETSTANDARD20)
using System.Reflection;
#endif
namespace System
{
/// <summary>
/// Enum extensions methods
/// </summary>
public static class EnumExtensions
{
#if (NETFULL || NETSTANDARD20)
/// <summary>
/// Gets attribute value for enums marked with <see cref="EnumTagAttribute"/>
/// </summary>
/// <param name="enumValue">Enumeration value</param>
/// <returns>Tag if enum member is marked, otherwise null</returns>
public static EnumTagAttribute GetEnumTag(this Enum enumValue)
{
Type t = enumValue.GetType();
string memberName = enumValue.ToString();
MemberInfo[] infos = t.GetMember(memberName);
if(infos != null && infos.Length > 0)
{
Attribute attr = infos[0].GetCustomAttribute(typeof(EnumTagAttribute), false);
if (attr != null) return (EnumTagAttribute)attr;
}
return null;
}
#endif
}
}
| using NetBox.Model;
#if NETFULL
using System.Reflection;
#endif
namespace System
{
/// <summary>
/// Enum extensions methods
/// </summary>
public static class EnumExtensions
{
#if (NETFULL || NETSTANDARD20)
/// <summary>
/// Gets attribute value for enums marked with <see cref="EnumTagAttribute"/>
/// </summary>
/// <param name="enumValue">Enumeration value</param>
/// <returns>Tag if enum member is marked, otherwise null</returns>
public static EnumTagAttribute GetEnumTag(this Enum enumValue)
{
Type t = enumValue.GetType();
string memberName = enumValue.ToString();
MemberInfo[] infos = t.GetMember(memberName);
if(infos != null && infos.Length > 0)
{
Attribute attr = infos[0].GetCustomAttribute(typeof(EnumTagAttribute), false);
if (attr != null) return (EnumTagAttribute)attr;
}
return null;
}
#endif
}
}
| mit | C# |
0c68b77010d202d4db0e5dcf4ddb960123d08cd3 | Load lion using XAML (todo: Render using AGG rasterizer) | dotMorten/AntiGrainRT,dotMorten/AntiGrainRT,dotMorten/AntiGrainRT,dotMorten/AntiGrainRT,dotMorten/AntiGrainRT,dotMorten/AntiGrainRT | src/AntiGrainDemoApp/MainPage.xaml.cs | src/AntiGrainDemoApp/MainPage.xaml.cs | using AntiGrainRT;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI;
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 AntiGrainDemoApp
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
CreateImage();
LoadLion();
}
private async void LoadLion()
{
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///LionShape.Txt"));
string shapeString = "";
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
shapeString = new StreamReader(fileStream.AsStreamForRead()).ReadToEnd();
}
Grid g = new Grid()
{
Background = new SolidColorBrush(Colors.CornflowerBlue),
VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top,
HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left
};
foreach(var shape in ShapeReader.Parse(shapeString))
{
var p = new Windows.UI.Xaml.Shapes.Path() { Data = shape.Geometry, Fill = new SolidColorBrush(shape.Color) };
g.Children.Add(p);
}
LayoutRoot.Children.Add(g);
}
private async void CreateImage()
{
var c = new RenderingBuffer(100, 100, Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8);
for (uint i = 0; i < c.PixelWidth; i++)
{
c.SetPixel(i, i, Colors.Blue);
}
var src = await c.CreateImageSourceAsync();
Image img = new Image() { Source = src };
LayoutRoot.Children.Add(img);
}
}
}
| using AntiGrainRT;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
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 AntiGrainDemoApp
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
CreateImage();
}
private async void CreateImage()
{
var c = new RenderingBuffer(100, 100, Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8);
for (uint i = 0; i < c.PixelWidth; i++)
{
c.SetPixel(i, i, Colors.Blue);
}
var src = await c.CreateImageSourceAsync();
Image img = new Image() { Source = src };
LayoutRoot.Children.Add(img);
}
}
}
| mit | C# |
ba26168812d1babaafe9abcd0184c6ee91e26e3d | Mark DateTimeZoneProviders.Default as obsolete. Fixes issue 184. | jskeet/nodatime,zaccharles/nodatime,zaccharles/nodatime,malcolmr/nodatime,BenJenkinson/nodatime,zaccharles/nodatime,zaccharles/nodatime,zaccharles/nodatime,zaccharles/nodatime,jskeet/nodatime,malcolmr/nodatime,nodatime/nodatime,BenJenkinson/nodatime,nodatime/nodatime,malcolmr/nodatime,malcolmr/nodatime | src/NodaTime/DateTimeZoneProviders.cs | src/NodaTime/DateTimeZoneProviders.cs | // Copyright 2012 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using NodaTime.TimeZones;
namespace NodaTime
{
/// <summary>
/// Static access to date/time zone providers built into Noda Time. These are all thread-safe and caching.
/// </summary>
public static class DateTimeZoneProviders
{
private static readonly DateTimeZoneCache tzdbFactory = new DateTimeZoneCache(TzdbDateTimeZoneSource.Default);
/// <summary>
/// Gets the TZDB time zone provider.
/// This always returns the same value as the <see cref="Tzdb"/> property.
/// </summary>
/// <seealso cref="Tzdb"/>
[Obsolete("Use DateTimeZoneProviders.Tzdb instead")]
public static IDateTimeZoneProvider Default { get { return Tzdb; } }
/// <summary>
/// Gets a time zone provider which uses a <see cref="TzdbDateTimeZoneSource"/>.
/// The underlying source is <see cref="TzdbDateTimeZoneSource.Default"/>, which is initialized from
/// resources within the NodaTime assembly.
/// </summary>
public static IDateTimeZoneProvider Tzdb { get { return tzdbFactory; } }
#if !PCL
private static readonly DateTimeZoneCache bclFactory = new DateTimeZoneCache(new BclDateTimeZoneSource());
/// <summary>
/// Gets a time zone provider which uses a <see cref="BclDateTimeZoneSource"/>.
/// </summary>
public static IDateTimeZoneProvider Bcl { get { return bclFactory; } }
#endif
}
}
| // Copyright 2012 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.TimeZones;
namespace NodaTime
{
/// <summary>
/// Static access to date/time zone providers built into Noda Time. These are all thread-safe and caching.
/// </summary>
public static class DateTimeZoneProviders
{
private static readonly DateTimeZoneCache tzdbFactory = new DateTimeZoneCache(TzdbDateTimeZoneSource.Default);
/// <summary>
/// Gets the default time zone provider, which is initialized from resources within the NodaTime assembly.
/// </summary>
/// <remarks>
/// Currently this returns the same value as the <see cref="Tzdb"/> property.
/// </remarks>
public static IDateTimeZoneProvider Default { get { return Tzdb; } }
/// <summary>
/// Gets a time zone provider which uses a <see cref="TzdbDateTimeZoneSource"/>.
/// The underlying source is <see cref="TzdbDateTimeZoneSource.Default"/>, which is initialized from
/// resources within the NodaTime assembly.
/// </summary>
public static IDateTimeZoneProvider Tzdb { get { return tzdbFactory; } }
#if !PCL
private static readonly DateTimeZoneCache bclFactory = new DateTimeZoneCache(new BclDateTimeZoneSource());
/// <summary>
/// Gets a time zone provider which uses a <see cref="BclDateTimeZoneSource"/>.
/// </summary>
public static IDateTimeZoneProvider Bcl { get { return bclFactory; } }
#endif
}
}
| apache-2.0 | C# |
16a29fad04b22dc50b97cccf37c0126504327f1d | enhance query parser for QueryUtils | oelite/RESTme | OElite.Restme.Utils/QueryUtils.cs | OElite.Restme.Utils/QueryUtils.cs | using System.Collections.Generic;
using System.Net;
namespace OElite
{
public static class QueryUtils
{
public static Dictionary<string, string> IdentifyQueryParams(this string value)
{
Dictionary<string, string> result = new Dictionary<string, string>();
var paramIndex = value?.IndexOf('?');
if (!(paramIndex >= 0)) return result;
if (paramIndex >= 0) value = value.Substring(paramIndex.GetValueOrDefault() + 1);
var paramPairs = value.Split('&');
foreach (var pair in paramPairs)
{
var pairArray = pair.Split('=');
if (pairArray?.Length != 2) continue;
var kKey = pairArray[0].Trim();
var kValue = WebUtility.UrlDecode(pairArray[1].Trim());
//note: BUG Identified: when multiple parameters with same name appears this will throw an exception
result.Add(kKey, kValue);
}
return result;
}
public static string ParseIntoQueryString(this Dictionary<string, string> values,
bool includeQuestionMark = true, bool encode = true)
{
string result = null;
if (values?.Count > 0)
{
var index = 0;
foreach (var k in values.Keys)
{
result = index == 0
? $"{k}={(encode ? WebUtility.UrlEncode(values[k]) : values[k])}"
: result + $"&{k}={(encode ? WebUtility.UrlEncode(values[k]) : values[k])}";
index++;
}
}
if (includeQuestionMark && result.IsNotNullOrEmpty())
result = $"?{result}";
return result;
}
}
} | using System.Collections.Generic;
using System.Net;
namespace OElite
{
public static class QueryUtils
{
public static Dictionary<string, string> IdentifyQueryParams(this string value)
{
Dictionary<string, string> result = new Dictionary<string, string>();
var paramIndex = value?.IndexOf('?');
if (!(paramIndex >= 0)) return result;
var paramPairs = value.Substring(paramIndex.GetValueOrDefault() + 1).Split('&');
foreach (var pair in paramPairs)
{
var pairArray = pair.Split('=');
if (pairArray?.Length != 2) continue;
var kKey = pairArray[0].Trim();
var kValue = WebUtility.UrlDecode(pairArray[1].Trim());
//note: BUG Identified: when multiple parameters with same name appears this will throw an exception
result.Add(kKey, kValue);
}
return result;
}
public static string ParseIntoQueryString(this Dictionary<string, string> values,
bool includeQuestionMark = true, bool encode = true)
{
string result = null;
if (values?.Count > 0)
{
var index = 0;
foreach (var k in values.Keys)
{
result = index == 0
? $"{k}={(encode ? WebUtility.UrlEncode(values[k]) : values[k])}"
: result + $"&{k}={(encode ? WebUtility.UrlEncode(values[k]) : values[k])}";
index++;
}
}
if (includeQuestionMark && result.IsNotNullOrEmpty())
result = $"?{result}";
return result;
}
}
} | mit | C# |
e1a821553d7fee52e5adc1ad41bc079eb9081080 | Fix mapiemail recipient bug. | ermshiperete/libpalaso,chrisvire/libpalaso,sillsdev/libpalaso,sillsdev/libpalaso,marksvc/libpalaso,hatton/libpalaso,glasseyes/libpalaso,mccarthyrb/libpalaso,glasseyes/libpalaso,darcywong00/libpalaso,mccarthyrb/libpalaso,sillsdev/libpalaso,ddaspit/libpalaso,hatton/libpalaso,gtryus/libpalaso,tombogle/libpalaso,JohnThomson/libpalaso,gtryus/libpalaso,gmartin7/libpalaso,andrew-polk/libpalaso,chrisvire/libpalaso,gmartin7/libpalaso,tombogle/libpalaso,glasseyes/libpalaso,tombogle/libpalaso,gmartin7/libpalaso,darcywong00/libpalaso,ddaspit/libpalaso,glasseyes/libpalaso,marksvc/libpalaso,gmartin7/libpalaso,hatton/libpalaso,JohnThomson/libpalaso,hatton/libpalaso,mccarthyrb/libpalaso,sillsdev/libpalaso,ermshiperete/libpalaso,ddaspit/libpalaso,darcywong00/libpalaso,mccarthyrb/libpalaso,ermshiperete/libpalaso,marksvc/libpalaso,andrew-polk/libpalaso,chrisvire/libpalaso,ddaspit/libpalaso,andrew-polk/libpalaso,gtryus/libpalaso,gtryus/libpalaso,tombogle/libpalaso,andrew-polk/libpalaso,JohnThomson/libpalaso,ermshiperete/libpalaso,chrisvire/libpalaso,JohnThomson/libpalaso | Palaso/Email/MapiEmailProvider.cs | Palaso/Email/MapiEmailProvider.cs | using System;
using System.Diagnostics;
namespace Palaso.Email
{
public class MapiEmailProvider : IEmailProvider
{
public IEmailMessage CreateMessage()
{
return new EmailMessage();
}
public bool SendMessage(IEmailMessage message)
{
var mapi = new MAPI();
foreach (string recipient in message.To)
{
Debug.Assert(!string.IsNullOrEmpty(recipient),"Email address for reporting is empty");
mapi.AddRecipientTo(recipient);
}
foreach (string recipient in message.Cc)
{
mapi.AddRecipientCc(recipient);
}
foreach (string recipient in message.Bcc)
{
mapi.AddRecipientBcc(recipient);
}
foreach (string attachmentFilePath in message.AttachmentFilePath)
{
mapi.AddAttachment(attachmentFilePath);
}
//this one is better if it works (and it does for Microsoft emailers), but
//return mapi.SendMailDirect(message.Subject, message.Body);
//this one works for thunderbird, too. It opens a window rather than just sending:
return mapi.SendMailPopup(message.Subject, message.Body);
}
}
} | using System;
using System.Diagnostics;
namespace Palaso.Email
{
public class MapiEmailProvider : IEmailProvider
{
public IEmailMessage CreateMessage()
{
return new EmailMessage();
}
public bool SendMessage(IEmailMessage message)
{
var mapi = new MAPI();
foreach (string recipient in message.To)
{
Debug.Assert(string.IsNullOrEmpty(recipient),"Email address for reporting is empty");
mapi.AddRecipientTo(recipient);
}
foreach (string recipient in message.Cc)
{
mapi.AddRecipientCc(recipient);
}
foreach (string recipient in message.Bcc)
{
mapi.AddRecipientBcc(recipient);
}
foreach (string attachmentFilePath in message.AttachmentFilePath)
{
mapi.AddAttachment(attachmentFilePath);
}
//this one is better if it works (and it does for Microsoft emailers), but
//return mapi.SendMailDirect(message.Subject, message.Body);
//this one works for thunderbird, too. It opens a window rather than just sending:
return mapi.SendMailPopup(message.Subject, message.Body);
}
}
} | mit | C# |
4d988276b6f8adaef0ae5a3ceaa96c7dbe9868a2 | Apply SettingsAssembly attribute | lukyad/Eco | Sample/Properties/AssemblyInfo.cs | Sample/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Eco.Attributes;
// 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("Sample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MICROSOFT")]
[assembly: AssemblyProduct("Sample")]
[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("10882788-67f9-4dbc-83bf-5fe8e888494b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: SettingsAssembly]
| 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("Sample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MICROSOFT")]
[assembly: AssemblyProduct("Sample")]
[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("10882788-67f9-4dbc-83bf-5fe8e888494b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
55f9dd33bb93992e60a26960c4dffa120c9807d0 | Revert "Simplify default ETW providers" | ericeil/xunit-performance,Microsoft/xunit-performance,visia/xunit-performance,mmitche/xunit-performance,Microsoft/xunit-performance,pharring/xunit-performance,ianhays/xunit-performance | src/xunit.performance.run/ETWLogging.cs | src/xunit.performance.run/ETWLogging.cs | using Microsoft.Diagnostics.Tracing;
using Microsoft.Diagnostics.Tracing.Parsers;
using Microsoft.Diagnostics.Tracing.Parsers.Clr;
using Microsoft.ProcessDomain;
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.Xunit.Performance
{
static class ETWLogging
{
static readonly Guid BenchmarkEventSourceGuid = Guid.Parse("A3B447A8-6549-4158-9BAD-76D442A47061");
static readonly ProviderInfo[] RequiredProviders = new ProviderInfo[]
{
new KernelProviderInfo()
{
Keywords = (ulong)KernelTraceEventParser.Keywords.Process | (ulong)KernelTraceEventParser.Keywords.Profile,
StackKeywords = (ulong)KernelTraceEventParser.Keywords.Profile
},
new UserProviderInfo()
{
ProviderGuid = BenchmarkEventSourceGuid,
Level = TraceEventLevel.Verbose,
Keywords = ulong.MaxValue,
},
new UserProviderInfo()
{
ProviderGuid = ClrTraceEventParser.ProviderGuid,
Level = TraceEventLevel.Informational,
Keywords =
(
(ulong)ClrTraceEventParser.Keywords.Jit |
(ulong)ClrTraceEventParser.Keywords.JittedMethodILToNativeMap |
(ulong)ClrTraceEventParser.Keywords.Loader |
(ulong)ClrTraceEventParser.Keywords.Exception |
(ulong)ClrTraceEventParser.Keywords.GC
),
}
};
public static ProcDomain _loggerDomain = ProcDomain.CreateDomain("Logger", ".\\xunit.performance.logger.exe", runElevated: true);
private class Stopper : IDisposable
{
private string _session;
public Stopper(string session) { _session = session; }
public void Dispose()
{
_loggerDomain.ExecuteAsync(() => Logger.Stop(_session)).Wait();
}
}
public static async Task<IDisposable> StartAsync(string filename, IEnumerable<ProviderInfo> providers)
{
var allProviders = RequiredProviders.Concat(providers).ToArray();
var sessionName = await _loggerDomain.ExecuteAsync(() => Logger.Start(filename, allProviders, 128));
return new Stopper(sessionName);
}
}
}
| using Microsoft.Diagnostics.Tracing;
using Microsoft.Diagnostics.Tracing.Parsers;
using Microsoft.Diagnostics.Tracing.Parsers.Clr;
using Microsoft.ProcessDomain;
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.Xunit.Performance
{
static class ETWLogging
{
static readonly Guid BenchmarkEventSourceGuid = Guid.Parse("A3B447A8-6549-4158-9BAD-76D442A47061");
static readonly ProviderInfo[] RequiredProviders = new ProviderInfo[]
{
new KernelProviderInfo()
{
Keywords = (ulong)KernelTraceEventParser.Keywords.Process
},
new UserProviderInfo()
{
ProviderGuid = BenchmarkEventSourceGuid,
Level = TraceEventLevel.Verbose,
Keywords = ulong.MaxValue,
},
};
public static ProcDomain _loggerDomain = ProcDomain.CreateDomain("Logger", ".\\xunit.performance.logger.exe", runElevated: true);
private class Stopper : IDisposable
{
private string _session;
public Stopper(string session) { _session = session; }
public void Dispose()
{
_loggerDomain.ExecuteAsync(() => Logger.Stop(_session)).Wait();
}
}
public static async Task<IDisposable> StartAsync(string filename, IEnumerable<ProviderInfo> providers)
{
var allProviders = RequiredProviders.Concat(providers).ToArray();
var sessionName = await _loggerDomain.ExecuteAsync(() => Logger.Start(filename, allProviders, 128));
return new Stopper(sessionName);
}
}
}
| mit | C# |
565916c6ec06048ba6350b908edc5bef48b6b1ac | Update version number. | Damnae/storybrew | editor/Properties/AssemblyInfo.cs | editor/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("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[assembly: AssemblyCopyright("Copyright © Damnae 2016")]
[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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// 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.68.*")]
| 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("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[assembly: AssemblyCopyright("Copyright © Damnae 2016")]
[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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// 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.67.*")]
| mit | C# |
180b27cd3505965673b96c1ff43f2c9ef0e80a44 | Fix typo in common on ILog | mattgwagner/CertiPay.Common | CertiPay.Common/Logging/ILog.cs | CertiPay.Common/Logging/ILog.cs | namespace CertiPay.Common.Logging
{
using System;
/// <summary>
/// A generic interface for writing log entries to various destinations. The intent behind this interface
/// is to avoid taking a direct dependency on a logger implementation or abstraction (i.e. commons.logging).
/// </summary>
/// <remarks>
/// This interface is inspired after LibLog by DamianH and RavenDB's logging abstractions
/// </remarks>
public interface ILog
{
/// <summary>
/// Log a templated message at the given log level with properties
/// </summary>
/// <param name="level">An enumeration representing the different levels of attention for logging</param>
/// <param name="messageTemplate">A string message that accepted templated values (either {0} {1} or {prop_1} {prop_2}) a la String.Format</param>
/// <param name="propertyValues">The properties to replace in the message template</param>
void Log(LogLevel level, string messageTemplate, params object[] propertyValues);
/// <summary>
/// Log a templated message at the given log level with properties
/// </summary>
/// <typeparam name="TException">The exception that occurred to log the stack trace for</typeparam>
/// <param name="level">An enumeration representing the different levels of attention for logging</param>
/// <param name="messageTemplate">A string message that accepted templated values (either {0} {1} or {prop_1} {prop_2}) a la String.Format</param>
/// <param name="propertyValues">The properties to replace in the message template</param>
void Log<TException>(LogLevel level, string messageTemplate, TException exception, params object[] propertyValues) where TException : Exception;
/// <summary>
/// Provide additional context for the log entry that might not necessarily be represented in the message output
/// </summary>
/// <param name="propertyName">The name to store the context with</param>
/// <param name="value">The value to store</param>
/// <param name="destructureObjects">If true, will destructure (serialize) the object for storage. Defaults to false.</param>
ILog WithContext(String propertyName, Object value, Boolean destructureObjects = false);
}
} | namespace CertiPay.Common.Logging
{
using System;
/// <summary>
/// A generic interface for writing log entries to various destinations. The intent behind this interface
/// is to avoid taking a direct dependency on a logger implementation or abstraction (i.e. commons.logging).
/// </summary>
/// <remarks>
/// This interface is inspired after LibLog by DamianH and RavenDB's logging abstractions
/// </remarks>
public interface ILog
{
/// <summary>
/// Log a templated message at the given log level with properties
/// </summary>
/// <param name="level">An enumeration representing the different levels of attention for logging</param>
/// <param name="messageTemplate">A string message that accepted templated values (either {0} {1} or {prop_1} {prop_2}) a la String.Format</param>
/// <param name="propertyValues">The properties to replace in the message template</param>
void Log(LogLevel level, string messageTemplate, params object[] propertyValues);
/// <summary>
/// Log a templated message at the given log level with properties
/// </summary>
/// <typeparam name="TException">The exception that occurred to log the stack trace for</typeparam>
/// <param name="level">An enumeration representing the different levels of attention for logging</param>
/// <param name="messageTemplate">A string message that accepted templated values (either {0} {1} or {prop_1} {prop_2}) a la String.Format</param>
/// <param name="propertyValues">The properties to replace in the message template</param>
void Log<TException>(LogLevel level, string messageTemplate, TException exception, params object[] propertyValues) where TException : Exception;
/// <summary>
/// Provide additional context for the log entry that might not necessarily be represented in the message output
/// </summary>
/// <param name="propertyName">The name to store the context with</param>
/// <param name="value">The value to store</param>
/// <param name="destructureObjects">If true, will desutrcuture (serialized) the object for storage. Defaults to false.</param>
ILog WithContext(String propertyName, Object value, Boolean destructureObjects = false);
}
} | mit | C# |
ea501260c7f2497c6fb9dae48b326c084aac9b07 | Fix broken build by adding missing namespaces in ProtoBufServiceClient | ZocDoc/ServiceStack,nataren/NServiceKit,ZocDoc/ServiceStack,nataren/NServiceKit,NServiceKit/NServiceKit,NServiceKit/NServiceKit,NServiceKit/NServiceKit,MindTouch/NServiceKit,MindTouch/NServiceKit,nataren/NServiceKit,MindTouch/NServiceKit,timba/NServiceKit,ZocDoc/ServiceStack,NServiceKit/NServiceKit,ZocDoc/ServiceStack,nataren/NServiceKit,timba/NServiceKit,MindTouch/NServiceKit,timba/NServiceKit,timba/NServiceKit | src/ServiceStack.Plugins.ProtoBuf/ProtoBufServiceClient.cs | src/ServiceStack.Plugins.ProtoBuf/ProtoBufServiceClient.cs | using System;
using System.Runtime.Serialization;
using ProtoBuf;
using System.IO;
using ServiceStack.ServiceClient.Web;
using ServiceStack.ServiceHost;
namespace ServiceStack.Plugins.ProtoBuf
{
public class ProtoBufServiceClient : ServiceClientBase
{
public override string Format
{
get { return "x-protobuf"; }
}
public ProtoBufServiceClient(string baseUri)
{
SetBaseUri(baseUri);
}
public ProtoBufServiceClient(string syncReplyBaseUri, string asyncOneWayBaseUri)
: base(syncReplyBaseUri, asyncOneWayBaseUri) {}
public override void SerializeToStream(IRequestContext requestContext, object request, Stream stream)
{
try
{
Serializer.NonGeneric.Serialize(stream, request);
}
catch (Exception ex)
{
throw new SerializationException("ProtoBufServiceClient: Error serializing: " + ex.Message, ex);
}
}
public override T DeserializeFromStream<T>(Stream stream)
{
try
{
return Serializer.Deserialize<T>(stream);
}
catch (Exception ex)
{
throw new SerializationException("ProtoBufServiceClient: Error deserializing: " + ex.Message, ex);
}
}
public override string ContentType
{
get { return Common.Web.ContentType.ProtoBuf; }
}
public override StreamDeserializerDelegate StreamDeserializer
{
get { return Deserialize; }
}
private static object Deserialize(Type type, Stream source)
{
try
{
return Serializer.NonGeneric.Deserialize(type, source);
}
catch (Exception ex)
{
throw new SerializationException("ProtoBufServiceClient: Error deserializing: " + ex.Message, ex);
}
}
}
}
| using ProtoBuf;
using System.IO;
using ServiceStack.ServiceClient.Web;
using ServiceStack.ServiceHost;
namespace ServiceStack.Plugins.ProtoBuf
{
public class ProtoBufServiceClient : ServiceClientBase
{
public override string Format
{
get { return "x-protobuf"; }
}
public ProtoBufServiceClient(string baseUri)
{
SetBaseUri(baseUri);
}
public ProtoBufServiceClient(string syncReplyBaseUri, string asyncOneWayBaseUri)
: base(syncReplyBaseUri, asyncOneWayBaseUri) {}
public override void SerializeToStream(IRequestContext requestContext, object request, Stream stream)
{
try
{
Serializer.NonGeneric.Serialize(stream, request);
}
catch (Exception ex)
{
throw new SerializationException("ProtoBufServiceClient: Error serializing: " + ex.Message, ex);
}
}
public override T DeserializeFromStream<T>(Stream stream)
{
try
{
return Serializer.Deserialize<T>(stream);
}
catch (Exception ex)
{
throw new SerializationException("ProtoBufServiceClient: Error deserializing: " + ex.Message, ex);
}
}
public override string ContentType
{
get { return Common.Web.ContentType.ProtoBuf; }
}
public override StreamDeserializerDelegate StreamDeserializer
{
get { return Deserialize; }
}
private static object Deserialize(Type type, Stream source)
{
try
{
return Serializer.NonGeneric.Deserialize(type, source);
}
catch (Exception ex)
{
throw new SerializationException("ProtoBufServiceClient: Error deserializing: " + ex.Message, ex);
}
}
}
}
| bsd-3-clause | C# |
50f8eb6f7aa90bdd2170a0cfca0c6e48460aa475 | Check if appharbour will trigger a build | valentinvs/GamersPortal,valentinvs/GamersPortal | GamePortal/GamePortal.WebSite/Views/Games/Index.cshtml | GamePortal/GamePortal.WebSite/Views/Games/Index.cshtml | @{
ViewBag.Title = "GAMES";
}
<h2>GAMES:</h2>
<p>list all games here!!!</p> | @{
ViewBag.Title = "GAMES";
}
<h2>GAMES:</h2>
<p>list all games here</p> | mit | C# |
55f7335fd5b12dc6ce15b204f315de2f2feb8e2a | Test file output using char name and total level. | JDCain/FG5eXmlToPdf | FG5eXmlToPdf.Tests/UnitTest1.cs | FG5eXmlToPdf.Tests/UnitTest1.cs | using System;
using System.Linq;
using FG5eXmlToPDF;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace FG5eXmlToPdf.Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void ReadWriteTest()
{
var currentDirectory = System.IO.Directory.GetCurrentDirectory();
var character = FG5eXml.LoadCharacter($@"{currentDirectory}\rita.xml");
var charName = character.Properities.FirstOrDefault((x) => x.Name == "Name")?.Value;
var level = character.Properities.FirstOrDefault((x) => x.Name == "LevelTotal")?.Value;
FG5ePdf.Write(
character,
$@"{currentDirectory}\{charName} ({level}).pdf");
}
}
}
| using System;
using FG5eXmlToPDF;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace FG5eXmlToPdf.Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void ReadWriteTest()
{
var currentDirectory = System.IO.Directory.GetCurrentDirectory();
var character = FG5eXml.LoadCharacter($@"{currentDirectory}\rita.xml");
FG5ePdf.Write(
character,
$@"{currentDirectory}\out.pdf");
}
}
}
| mit | C# |
1a070df22e87fc09e5d42d6952d44c3f16a69c10 | Fix version 0.5.0 | Tri125/lama,Lan-Manager/lama | Lama/Properties/AssemblyInfo.cs | Lama/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("Lama")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lama")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
//Pour commencer à générer des applications localisables, définissez
//<UICulture>CultureUtiliséePourCoder</UICulture> dans votre fichier .csproj
//dans <PropertyGroup>. Par exemple, si vous utilisez le français
//dans vos fichiers sources, définissez <UICulture> à fr-FR. Puis, supprimez les marques de commentaire de
//l'attribut NeutralResourceLanguage ci-dessous. Mettez à jour "fr-FR" dans
//la ligne ci-après pour qu'elle corresponde au paramètre UICulture du fichier projet.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //où se trouvent les dictionnaires de ressources spécifiques à un thème
//(utilisé si une ressource est introuvable dans la page,
// ou dictionnaires de ressources de l'application)
ResourceDictionaryLocation.SourceAssembly //où se trouve le dictionnaire de ressources générique
//(utilisé si une ressource est introuvable dans la page,
// dans l'application ou dans l'un des dictionnaires de ressources spécifiques à un thème)
)]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("0.5.0.0")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("Lama")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lama")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
//Pour commencer à générer des applications localisables, définissez
//<UICulture>CultureUtiliséePourCoder</UICulture> dans votre fichier .csproj
//dans <PropertyGroup>. Par exemple, si vous utilisez le français
//dans vos fichiers sources, définissez <UICulture> à fr-FR. Puis, supprimez les marques de commentaire de
//l'attribut NeutralResourceLanguage ci-dessous. Mettez à jour "fr-FR" dans
//la ligne ci-après pour qu'elle corresponde au paramètre UICulture du fichier projet.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //où se trouvent les dictionnaires de ressources spécifiques à un thème
//(utilisé si une ressource est introuvable dans la page,
// ou dictionnaires de ressources de l'application)
ResourceDictionaryLocation.SourceAssembly //où se trouve le dictionnaire de ressources générique
//(utilisé si une ressource est introuvable dans la page,
// dans l'application ou dans l'un des dictionnaires de ressources spécifiques à un thème)
)]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
f0d097ed1234a9a45ab42451c52bba8afc4ac37d | Make Cursor disposable. | SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,Perspex/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia | src/Avalonia.Input/Cursor.cs | src/Avalonia.Input/Cursor.cs | using System;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
#nullable enable
namespace Avalonia.Input
{
public enum StandardCursorType
{
Arrow,
Ibeam,
Wait,
Cross,
UpArrow,
SizeWestEast,
SizeNorthSouth,
SizeAll,
No,
Hand,
AppStarting,
Help,
TopSide,
BottomSide,
LeftSide,
RightSide,
TopLeftCorner,
TopRightCorner,
BottomLeftCorner,
BottomRightCorner,
DragMove,
DragCopy,
DragLink,
None,
[Obsolete("Use BottomSide")]
BottomSize = BottomSide
// Not available in GTK directly, see http://www.pixelbeat.org/programming/x_cursors/
// We might enable them later, preferably, by loading pixmax direclty from theme with fallback image
// SizeNorthWestSouthEast,
// SizeNorthEastSouthWest,
}
public class Cursor : IDisposable
{
public static readonly Cursor Default = new Cursor(StandardCursorType.Arrow);
internal Cursor(ICursorImpl platformImpl)
{
PlatformImpl = platformImpl;
}
public Cursor(StandardCursorType cursorType)
: this(GetCursorFactory().GetCursor(cursorType))
{
}
public Cursor(IBitmap cursor, PixelPoint hotSpot)
: this(GetCursorFactory().CreateCursor(cursor.PlatformImpl.Item, hotSpot))
{
}
public ICursorImpl PlatformImpl { get; }
public void Dispose() => PlatformImpl.Dispose();
public static Cursor Parse(string s)
{
return Enum.TryParse<StandardCursorType>(s, true, out var t) ?
new Cursor(t) :
throw new ArgumentException($"Unrecognized cursor type '{s}'.");
}
private static ICursorFactory GetCursorFactory()
{
return AvaloniaLocator.Current.GetService<ICursorFactory>() ??
throw new Exception("Could not create Cursor: ICursorFactory not registered.");
}
}
}
| using System;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
#nullable enable
namespace Avalonia.Input
{
/*
=========================================================================================
NOTE: Cursors are NOT disposable and are cached in platform implementation.
To support loading custom cursors some measures about that should be taken beforehand
=========================================================================================
*/
public enum StandardCursorType
{
Arrow,
Ibeam,
Wait,
Cross,
UpArrow,
SizeWestEast,
SizeNorthSouth,
SizeAll,
No,
Hand,
AppStarting,
Help,
TopSide,
BottomSide,
LeftSide,
RightSide,
TopLeftCorner,
TopRightCorner,
BottomLeftCorner,
BottomRightCorner,
DragMove,
DragCopy,
DragLink,
None,
[Obsolete("Use BottomSide")]
BottomSize = BottomSide
// Not available in GTK directly, see http://www.pixelbeat.org/programming/x_cursors/
// We might enable them later, preferably, by loading pixmax direclty from theme with fallback image
// SizeNorthWestSouthEast,
// SizeNorthEastSouthWest,
}
public class Cursor
{
public static readonly Cursor Default = new Cursor(StandardCursorType.Arrow);
internal Cursor(ICursorImpl platformImpl)
{
PlatformImpl = platformImpl;
}
public Cursor(StandardCursorType cursorType)
: this(GetCursorFactory().GetCursor(cursorType))
{
}
public Cursor(IBitmap cursor, PixelPoint hotSpot)
: this(GetCursorFactory().CreateCursor(cursor.PlatformImpl.Item, hotSpot))
{
}
public ICursorImpl PlatformImpl { get; }
public static Cursor Parse(string s)
{
return Enum.TryParse<StandardCursorType>(s, true, out var t) ?
new Cursor(t) :
throw new ArgumentException($"Unrecognized cursor type '{s}'.");
}
private static ICursorFactory GetCursorFactory()
{
return AvaloniaLocator.Current.GetService<ICursorFactory>() ??
throw new Exception("Could not create Cursor: ICursorFactory not registered.");
}
}
}
| mit | C# |
01dea2af7da29b0338699e86e77424eafcaec8dc | Fix typo in comment | mholo65/cake,RehanSaeed/cake,Sam13/cake,DixonD-git/cake,adamhathcock/cake,Julien-Mialon/cake,Sam13/cake,phenixdotnet/cake,vlesierse/cake,vlesierse/cake,ferventcoder/cake,patriksvensson/cake,cake-build/cake,phenixdotnet/cake,thomaslevesque/cake,patriksvensson/cake,mholo65/cake,daveaglick/cake,gep13/cake,devlead/cake,ferventcoder/cake,daveaglick/cake,RehanSaeed/cake,thomaslevesque/cake,adamhathcock/cake,robgha01/cake,cake-build/cake,robgha01/cake,Julien-Mialon/cake,gep13/cake,devlead/cake | src/Cake.Core/IO/IProcess.cs | src/Cake.Core/IO/IProcess.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
namespace Cake.Core.IO
{
/// <summary>
/// Represents a process.
/// </summary>
public interface IProcess : IDisposable
{
/// <summary>
/// Waits for the process to exit.
/// </summary>
void WaitForExit();
/// <summary>
/// Waits for the process to exit with possible timeout for command.
/// </summary>
/// <param name="milliseconds">The amount of time, in milliseconds, to wait for the associated process to exit. The maximum is the largest possible value of a 32-bit integer, which represents infinity to the operating system.</param>
/// <returns>true if the associated process has exited; otherwise, false.</returns>
bool WaitForExit(int milliseconds);
/// <summary>
/// Gets the exit code of the process.
/// </summary>
/// <returns>The exit code of the process.</returns>
int GetExitCode();
/// <summary>
/// Get the standard error of process.
/// </summary>
/// <returns>Returns process error output if <see cref="ProcessSettings.RedirectStandardError">RedirectStandardError</see> is true</returns>
IEnumerable<string> GetStandardError();
/// <summary>
/// Get the standard output of process
/// </summary>
/// <returns>Returns process output if <see cref="ProcessSettings.RedirectStandardOutput">RedirectStandardOutput</see> is true</returns>
IEnumerable<string> GetStandardOutput();
/// <summary>
/// Immediately stops the associated process.
/// </summary>
void Kill();
}
} | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
namespace Cake.Core.IO
{
/// <summary>
/// Represents a process.
/// </summary>
public interface IProcess : IDisposable
{
/// <summary>
/// Waits for the process to exit.
/// </summary>
void WaitForExit();
/// <summary>
/// Waits for the process to exit with possible timeout for command.
/// </summary>
/// <param name="milliseconds">The amount of time, in milliseconds, to wait for the associated process to exit. The maximum is the largest possible value of a 32-bit integer, which represents infinity to the operating system.</param>
/// <returns>true if the associated process has exited; otherwise, false.</returns>
bool WaitForExit(int milliseconds);
/// <summary>
/// Gets the exit code of the process.
/// </summary>
/// <returns>The exit code of the process.</returns>
int GetExitCode();
/// <summary>
/// Get the standard error of process.
/// </summary>
/// <returns>Returns process error output <see cref="ProcessSettings.RedirectStandardError">RedirectStandardError</see> is true</returns>
IEnumerable<string> GetStandardError();
/// <summary>
/// Get the standard output of process
/// </summary>
/// <returns>Returns process output <see cref="ProcessSettings.RedirectStandardOutput">RedirectStandardOutput</see> is true</returns>
IEnumerable<string> GetStandardOutput();
/// <summary>
/// Immediately stops the associated process.
/// </summary>
void Kill();
}
} | mit | C# |
b4b5f0b12c6c9790ec2d744c037cb927232f011b | Update install button | martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site | src/LondonTravel.Site/Views/Home/Index.cshtml | src/LondonTravel.Site/Views/Home/Index.cshtml | @inject SiteOptions Options
@{
ViewBag.Title = "Home";
}
<div class="jumbotron">
<h1>London Travel</h1>
<p class="lead">
An Amazon Alexa skill for checking the status of travel in London.
</p>
<p>
<a class="btn btn-primary" id="link-install" href="@Options?.ExternalLinks?.Skill" rel="noopener" target="_blank" title="Install London Travel for Amazon Alexa from amazon.co.uk">Install <i class="fa fa-external-link" aria-hidden="true"></i></a>
</p>
</div>
| @inject SiteOptions Options
@{
ViewBag.Title = "Home";
}
<div class="jumbotron">
<h1>London Travel</h1>
<p class="lead">
An Amazon Alexa skill for checking the status of travel in London.
</p>
<p>
<a class="btn btn-primary" id="link-install" href="@Options?.ExternalLinks?.Skill" rel="noopener" target="_blank" title="Install London Travel for Amazon Alexa">Install »</a>
</p>
</div>
| apache-2.0 | C# |
a6bb67cb7769f373210d5fd76caec49eb56eb2d3 | Update NSucceed.cs | NMSLanX/Natasha | src/Natasha/Core/Engine/LogModule/NSucceed.cs | src/Natasha/Core/Engine/LogModule/NSucceed.cs | using Microsoft.CodeAnalysis.CSharp;
using Natasha.Log.Model;
using System;
using System.Reflection;
namespace Natasha.Log
{
public class NSucceed : ALogWrite
{
public static bool Enabled;
static NSucceed() => Enabled = true;
public override void Write()
{
NWriter<NSucceed>.Recoder(Buffer);
}
public void Handler(CSharpCompilation compilation)
{
Buffer.AppendLine($"\r\n\r\n========================Succeed : {compilation.AssemblyName}========================\r\n");
WrapperCode(compilation.SyntaxTrees);
Buffer.AppendLine("\r\n\r\n-----------------------------------------------succeed------------------------------------------------");
Buffer.AppendLine($"\r\n Time :\t\t{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
Buffer.AppendLine($"\r\n Lauguage :\t{compilation.Language} & {compilation.LanguageVersion}");
Buffer.AppendLine($"\r\n Target :\t\t{compilation.AssemblyName}");
Buffer.AppendLine($"\r\n Assembly : \t{compilation.AssemblyName}");
Buffer.AppendLine("\r\n--------------------------------------------------------------------------------------------------------");
Buffer.AppendLine("\r\n====================================================================");
}
}
}
| using Microsoft.CodeAnalysis.CSharp;
using Natasha.Log.Model;
using System;
using System.Reflection;
namespace Natasha.Log
{
public class NSucceed : ALogWrite
{
public static bool Enabled;
static NSucceed() => Enabled = true;
public override void Write()
{
NWriter<NSucceed>.Recoder(Buffer);
}
public void Handler(CSharpCompilation compilation)
{
Buffer.AppendLine($"\r\n\r\n========================Succeed : {compilation.AssemblyName}========================\r\n");
WrapperCode(compilation.SyntaxTrees);
Buffer.AppendLine("\r\n\r\n-----------------------------------------------succeed------------------------------------------------");
Buffer.AppendLine($"\r\n Time :\t\t{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
Buffer.AppendLine($"\r\n Lauguage :\t{compilation.Language} & {compilation.LanguageVersion}");
Buffer.AppendLine($"\r\n Target :\t{compilation.AssemblyName}");
Buffer.AppendLine($"\r\n Assembly : \t{compilation.AssemblyName}");
Buffer.AppendLine("\r\n--------------------------------------------------------------------------------------------------------");
Buffer.AppendLine("\r\n====================================================================");
}
}
}
| mpl-2.0 | C# |
858d050072bb919ed34ff1aebfea9c0fcdd56f60 | simplify serializer | 421p/AllyTalks,421p/AllyTalks,421p/AllyTalks,421p/AllyTalks | frontend/Model/Message/MessageSerializer.cs | frontend/Model/Message/MessageSerializer.cs | using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace AllyTalksClient.Model.Message {
public static class MessageSerializer {
public static string SerializeMessage(Message message)
{
return JsonConvert.SerializeObject(message);
}
public static Message DeserializeMessage(string data)
{
return JsonConvert.DeserializeObject<Message>(data);
}
}
} | using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace AllyTalksClient.Model.Message {
public static class MessageSerializer {
public static string SerializeMessage(Message message)
{
return JsonConvert.SerializeObject(message);
}
public static Message DeserializeMessage(string data)
{
var json = JObject.Parse(data);
var type = (string) json["type"];
switch (type) {
case MessageType.Message:
return JsonConvert.DeserializeObject<Message>(data);
case MessageType.Error:
return JsonConvert.DeserializeObject<Message>(data);
case MessageType.Auth:
return JsonConvert.DeserializeObject<Message>(data);
default:
throw new Exception("Can not handle this kind of message yet.");
}
}
}
} | bsd-2-clause | C# |
070fdc4cb25ddcab46dd5af9c156a3d1ecb48c91 | Add text for debug purposes to see if the job has been running | jonasf/tv-show-reminder | TvShowReminderWorker/Program.cs | TvShowReminderWorker/Program.cs | using System;
namespace TvShowReminderWorker
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("I am the web job, I ran at {0}", DateTime.Now);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TvShowReminderWorker
{
class Program
{
static void Main(string[] args)
{
}
}
}
| mit | C# |
f9ea4a70e7a5c291a9b0cfeb63805a58d03794ea | fix FluentStackSpecs | hitesh97/xbehave.net,xbehave/xbehave.net,mvalipour/xbehave.net,hitesh97/xbehave.net,modulexcite/xbehave.net,mvalipour/xbehave.net,adamralph/xbehave.net,modulexcite/xbehave.net | src/Xbehave.Samples.Net40/FluentStackSpecs.cs | src/Xbehave.Samples.Net40/FluentStackSpecs.cs | // <copyright file="FluentStackSpecs.cs" company="Adam Ralph">
// Copyright (c) Adam Ralph. All rights reserved.
// </copyright>
namespace Xbehave.Samples
{
using System.Collections.Generic;
using FluentAssertions;
using Xbehave;
public class FluentStackSpecs
{
[Scenario]
public void Push()
{
var target = default(Stack<int>);
var element = default(int);
_
.Given("an element", () => element = 11)
.And("a stack", () => target = new Stack<int>())
.When("pushing the element", () => target.Push(element))
.Then("the target should not be empty", () => target.Should().NotBeEmpty())
.And("the target peek should be the element", () => target.Peek().Should().Be(element))
.AndInIsolation("the target peek should be the element", () => target.Peek().Should().Be(element))
.AndSkip("the target peek should be the element", "because I can", () => target.Peek().Should().Be(element));
}
}
}
| // <copyright file="FluentStackSpecs.cs" company="Adam Ralph">
// Copyright (c) Adam Ralph. All rights reserved.
// </copyright>
namespace Xbehave.Samples
{
using System.Collections.Generic;
using FluentAssertions;
using Xbehave;
public class FluentStackSpecs
{
[Scenario]
public void Push()
{
var target = default(Stack<int>);
var element = default(int);
_
.Given(
"an element",
() =>
{
element = 11;
target = new Stack<int>();
})
.When("pushing the element", () => target.Push(element))
.Then("the target should not be empty", () => target.Should().NotBeEmpty())
.And("the target peek should be the element", () => target.Peek().Should().Be(element))
.And("in isolation the target peek should be the element", () => target.Peek().Should().Be(element), inIsolation: true)
.And("skip the target peek should be the element", () => target.Peek().Should().Be(element), skip: "because I can");
}
}
}
| mit | C# |
c15bb6b928a4130d1515e8db07dd2e9f071dccfb | Add beatmap hash to MultiplayerRoomSettings | peppy/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,smoogipooo/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu-new,NeoAdonis/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,ppy/osu | osu.Game/Online/RealtimeMultiplayer/MultiplayerRoomSettings.cs | osu.Game/Online/RealtimeMultiplayer/MultiplayerRoomSettings.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Game.Online.API;
namespace osu.Game.Online.RealtimeMultiplayer
{
[Serializable]
public class MultiplayerRoomSettings : IEquatable<MultiplayerRoomSettings>
{
public int BeatmapID { get; set; }
public int RulesetID { get; set; }
public string BeatmapChecksum { get; set; } = string.Empty;
public string Name { get; set; } = "Unnamed room";
[NotNull]
public IEnumerable<APIMod> Mods { get; set; } = Enumerable.Empty<APIMod>();
public bool Equals(MultiplayerRoomSettings other)
=> BeatmapID == other.BeatmapID
&& BeatmapChecksum == other.BeatmapChecksum
&& Mods.SequenceEqual(other.Mods)
&& RulesetID == other.RulesetID
&& Name.Equals(other.Name, StringComparison.Ordinal);
public override string ToString() => $"Name:{Name} Beatmap:{BeatmapID} ({BeatmapChecksum}) Mods:{string.Join(',', Mods)} Ruleset:{RulesetID}";
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Game.Online.API;
namespace osu.Game.Online.RealtimeMultiplayer
{
[Serializable]
public class MultiplayerRoomSettings : IEquatable<MultiplayerRoomSettings>
{
public int BeatmapID { get; set; }
public int RulesetID { get; set; }
public string Name { get; set; } = "Unnamed room";
[NotNull]
public IEnumerable<APIMod> Mods { get; set; } = Enumerable.Empty<APIMod>();
public bool Equals(MultiplayerRoomSettings other) => BeatmapID == other.BeatmapID && Mods.SequenceEqual(other.Mods) && RulesetID == other.RulesetID && Name.Equals(other.Name, StringComparison.Ordinal);
public override string ToString() => $"Name:{Name} Beatmap:{BeatmapID} Mods:{string.Join(',', Mods)} Ruleset:{RulesetID}";
}
}
| mit | C# |
c7a6d9d65b828e0631047619d02ec622ee2fa7a3 | remove XML comments | mika-f/Sagitta | Source/PixivNet/Extensions/TaskExtension.cs | Source/PixivNet/Extensions/TaskExtension.cs | using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace Pixiv.Extensions
{
public static class TaskExtension
{
public static ConfiguredTaskAwaitable<T> Stay<T>(this Task<T> task)
{
return task.ConfigureAwait(false);
}
}
} | using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace Pixiv.Extensions
{
/// <summary>
/// <see cref="Task{TResult}" /> 拡張
/// </summary>
public static class TaskExtension
{
/// <summary>
/// `ConfigureAwait(false)` を行います。
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="obj">
/// <see cref="Task{TResult}" />
/// </param>
/// <returns></returns>
public static ConfiguredTaskAwaitable<T> Stay<T>(this Task<T> obj)
{
return obj.ConfigureAwait(false);
}
}
} | mit | C# |
42947fe53609630c7d121a0e8e103aba1735c51f | Make Comment immutable | Fredi/NetIRC | src/NetIRC/Messages/KickMessage.cs | src/NetIRC/Messages/KickMessage.cs | namespace NetIRC.Messages
{
public class KickMessage : IRCMessage, IServerMessage
{
public string KickedBy { get; }
public string Channel { get; }
public string Nick { get; }
public string Comment { get; }
public KickMessage(ParsedIRCMessage parsedMessage)
{
KickedBy = parsedMessage.Prefix.From;
Channel = parsedMessage.Parameters[0];
Nick = parsedMessage.Parameters[1];
Comment = parsedMessage.Trailing;
}
}
}
| namespace NetIRC.Messages
{
public class KickMessage : IRCMessage, IServerMessage
{
public string KickedBy { get; }
public string Channel { get; }
public string Nick { get; }
public string Comment { get; set; }
public KickMessage(ParsedIRCMessage parsedMessage)
{
KickedBy = parsedMessage.Prefix.From;
Channel = parsedMessage.Parameters[0];
Nick = parsedMessage.Parameters[1];
Comment = parsedMessage.Trailing;
}
}
}
| mit | C# |
8859653c08b1dbb7af0442316c29b4c9c4372877 | Fix error when vessel parts > max allowed parts | gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer | LmpClient/Windows/BannedParts/BannedPartsResourcesWindow.cs | LmpClient/Windows/BannedParts/BannedPartsResourcesWindow.cs | using LmpClient.Base;
using LmpClient.Localization;
using LmpCommon.Enums;
using UnityEngine;
namespace LmpClient.Windows.BannedParts
{
public partial class BannedPartsResourcesWindow : Window<BannedPartsResourcesWindow>
{
#region Fields
private const float WindowHeight = 300;
private const float WindowWidth = 400;
private static string[] _bannedParts = new string[0];
private static string[] _bannedResources = new string[0];
private static int _partCount = 0;
private static string _vesselName;
private static bool _display;
public override bool Display
{
get => base.Display && _display && MainSystem.NetworkState >= ClientState.Running && HighLogic.LoadedScene >= GameScenes.SPACECENTER;
set => base.Display = _display = value;
}
#endregion
protected override void DrawGui()
{
WindowRect = FixWindowPos(GUILayout.Window(6718 + MainSystem.WindowOffset, WindowRect, DrawContent,
LocalizationContainer.BannedPartsResourcesWindowText.Title, LayoutOptions));
}
public override void SetStyles()
{
WindowRect = new Rect(Screen.width / 2f - WindowWidth / 2f, Screen.height / 2f - WindowHeight / 2f, WindowWidth, WindowHeight);
MoveRect = new Rect(0, 0, int.MaxValue, TitleHeight);
LayoutOptions = new GUILayoutOption[4];
LayoutOptions[0] = GUILayout.MinWidth(WindowWidth);
LayoutOptions[1] = GUILayout.MaxWidth(WindowWidth);
LayoutOptions[2] = GUILayout.MinHeight(WindowHeight);
LayoutOptions[3] = GUILayout.MaxHeight(WindowHeight);
ScrollPos = new Vector2();
}
public void DisplayBannedPartsResourcesDialog(string vesselName, string[] bannedParts, string[] bannedResources, int partCount = 0)
{
if (!Display)
{
_vesselName = vesselName;
_bannedParts = bannedParts;
_bannedResources = bannedResources;
_partCount = partCount;
Display = true;
}
}
}
}
| using LmpClient.Base;
using LmpClient.Localization;
using LmpCommon.Enums;
using UnityEngine;
namespace LmpClient.Windows.BannedParts
{
public partial class BannedPartsResourcesWindow : Window<BannedPartsResourcesWindow>
{
#region Fields
private const float WindowHeight = 300;
private const float WindowWidth = 400;
private static string[] _bannedParts = new string[0];
private static string[] _bannedResources = new string[0];
private static int _partCount = 0;
private static string _vesselName;
private static bool _display;
public override bool Display
{
get => base.Display && _display && MainSystem.NetworkState >= ClientState.Running && HighLogic.LoadedScene >= GameScenes.SPACECENTER;
set => base.Display = _display = value;
}
#endregion
protected override void DrawGui()
{
WindowRect = FixWindowPos(GUILayout.Window(6718 + MainSystem.WindowOffset, WindowRect, DrawContent,
LocalizationContainer.BannedPartsResourcesWindowText.Title, LayoutOptions));
}
public override void SetStyles()
{
WindowRect = new Rect(Screen.width / 2f - WindowWidth / 2f, Screen.height / 2f - WindowHeight / 2f, WindowWidth, WindowHeight);
MoveRect = new Rect(0, 0, int.MaxValue, TitleHeight);
LayoutOptions = new GUILayoutOption[4];
LayoutOptions[0] = GUILayout.MinWidth(WindowWidth);
LayoutOptions[1] = GUILayout.MaxWidth(WindowWidth);
LayoutOptions[2] = GUILayout.MinHeight(WindowHeight);
LayoutOptions[3] = GUILayout.MaxHeight(WindowHeight);
ScrollPos = new Vector2();
}
public void DisplayBannedPartsResourcesDialog(string vesselName, string[] bannedParts, string[] bannedResources, int partCount = 0)
{
if (!Display)
{
_vesselName = vesselName;
_bannedParts = bannedParts;
_bannedResources = bannedResources;
_partCount = 0;
Display = true;
}
}
}
}
| mit | C# |
4116b5173c868564071f0d39b71193b374dd689d | Use index operator instead of linq | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Extensions/StringExtensions.cs | WalletWasabi/Extensions/StringExtensions.cs | using System.Linq;
namespace System
{
public static class StringExtensions
{
public static bool Equals(this string source, string value, StringComparison comparisonType, bool trimmed)
{
if (comparisonType == StringComparison.Ordinal)
{
if (trimmed)
{
return string.CompareOrdinal(source.Trim(), value.Trim()) == 0;
}
return string.CompareOrdinal(source, value) == 0;
}
if (trimmed)
{
return source.Trim().Equals(value.Trim(), comparisonType);
}
return source.Equals(value, comparisonType);
}
public static bool Contains(this string source, string toCheck, StringComparison comp)
{
return source.IndexOf(toCheck, comp) >= 0;
}
public static string[] Split(this string me, string separator, StringSplitOptions options = StringSplitOptions.None)
{
return me.Split(separator.ToCharArray(), options);
}
/// <summary>
/// Removes one leading and trailing occurrence of the specified string
/// </summary>
public static string Trim(this string me, string trimString, StringComparison comparisonType)
{
return me.TrimStart(trimString, comparisonType).TrimEnd(trimString, comparisonType);
}
/// <summary>
/// Removes one leading occurrence of the specified string
/// </summary>
public static string TrimStart(this string me, string trimString, StringComparison comparisonType)
{
if (me.StartsWith(trimString, comparisonType))
{
return me.Substring(trimString.Length);
}
return me;
}
/// <summary>
/// Removes one trailing occurrence of the specified string
/// </summary>
public static string TrimEnd(this string me, string trimString, StringComparison comparisonType)
{
if (me.EndsWith(trimString, comparisonType))
{
return me.Substring(0, me.Length - trimString.Length);
}
return me;
}
/// <summary>
/// Returns true if the string contains leading or trailing whitespace, otherwise returns false.
/// </summary>
public static bool IsTrimable(this string me)
{
if (me.Length == 0)
{
return false;
}
return char.IsWhiteSpace(me[0]) || char.IsWhiteSpace(me[^0]);
}
}
}
| using System.Linq;
namespace System
{
public static class StringExtensions
{
public static bool Equals(this string source, string value, StringComparison comparisonType, bool trimmed)
{
if (comparisonType == StringComparison.Ordinal)
{
if (trimmed)
{
return string.CompareOrdinal(source.Trim(), value.Trim()) == 0;
}
return string.CompareOrdinal(source, value) == 0;
}
if (trimmed)
{
return source.Trim().Equals(value.Trim(), comparisonType);
}
return source.Equals(value, comparisonType);
}
public static bool Contains(this string source, string toCheck, StringComparison comp)
{
return source.IndexOf(toCheck, comp) >= 0;
}
public static string[] Split(this string me, string separator, StringSplitOptions options = StringSplitOptions.None)
{
return me.Split(separator.ToCharArray(), options);
}
/// <summary>
/// Removes one leading and trailing occurrence of the specified string
/// </summary>
public static string Trim(this string me, string trimString, StringComparison comparisonType)
{
return me.TrimStart(trimString, comparisonType).TrimEnd(trimString, comparisonType);
}
/// <summary>
/// Removes one leading occurrence of the specified string
/// </summary>
public static string TrimStart(this string me, string trimString, StringComparison comparisonType)
{
if (me.StartsWith(trimString, comparisonType))
{
return me.Substring(trimString.Length);
}
return me;
}
/// <summary>
/// Removes one trailing occurrence of the specified string
/// </summary>
public static string TrimEnd(this string me, string trimString, StringComparison comparisonType)
{
if (me.EndsWith(trimString, comparisonType))
{
return me.Substring(0, me.Length - trimString.Length);
}
return me;
}
/// <summary>
/// Returns true if the string contains leading or trailing whitespace, otherwise returns false.
/// </summary>
public static bool IsTrimable(this string me)
{
if (me.Length == 0)
{
return false;
}
return char.IsWhiteSpace(me.First()) || char.IsWhiteSpace(me.Last());
}
}
}
| mit | C# |
d261ee21729752fbbfbe0e4b596f0b234318f3ef | add UnmintedTx to track rollback replay info | ArsenShnurkov/BitSharp | BitSharp.Core/Domain/BlockTxKey.cs | BitSharp.Core/Domain/BlockTxKey.cs | using BitSharp.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BitSharp.Core.Domain
{
public class BlockTxKey
{
private readonly UInt256 blockHash;
private readonly int txIndex;
public BlockTxKey(UInt256 blockHash, int txIndex)
{
this.blockHash = blockHash;
this.txIndex = txIndex;
}
public UInt256 BlockHash { get { return this.blockHash; } }
public int TxIndex { get { return this.txIndex; } }
public override bool Equals(object obj)
{
if (!(obj is BlockTxKey))
return false;
var other = (BlockTxKey)obj;
return other.blockHash == this.blockHash && other.txIndex == this.txIndex;
}
public override int GetHashCode()
{
return this.blockHash.GetHashCode() ^ this.txIndex.GetHashCode();
}
}
}
| using BitSharp.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BitSharp.Core.Domain
{
internal class BlockTxKey
{
private readonly UInt256 blockHash;
private readonly int txIndex;
public BlockTxKey(UInt256 blockHash, int txIndex)
{
this.blockHash = blockHash;
this.txIndex = txIndex;
}
public UInt256 BlockHash { get { return this.blockHash; } }
public int TxIndex { get { return this.txIndex; } }
}
}
| unlicense | C# |
cb66064c83d4271fd5b580a25b321bfad9d19e5f | Add another testing method to SubBoundObject | windygu/CefSharp,AJDev77/CefSharp,battewr/CefSharp,windygu/CefSharp,jamespearce2006/CefSharp,rlmcneary2/CefSharp,ITGlobal/CefSharp,windygu/CefSharp,battewr/CefSharp,ITGlobal/CefSharp,joshvera/CefSharp,NumbersInternational/CefSharp,ruisebastiao/CefSharp,rlmcneary2/CefSharp,dga711/CefSharp,NumbersInternational/CefSharp,Octopus-ITSM/CefSharp,Octopus-ITSM/CefSharp,VioletLife/CefSharp,Livit/CefSharp,Haraguroicha/CefSharp,wangzheng888520/CefSharp,illfang/CefSharp,twxstar/CefSharp,gregmartinhtc/CefSharp,rover886/CefSharp,VioletLife/CefSharp,joshvera/CefSharp,haozhouxu/CefSharp,gregmartinhtc/CefSharp,dga711/CefSharp,illfang/CefSharp,rover886/CefSharp,twxstar/CefSharp,ruisebastiao/CefSharp,ITGlobal/CefSharp,NumbersInternational/CefSharp,gregmartinhtc/CefSharp,AJDev77/CefSharp,rover886/CefSharp,jamespearce2006/CefSharp,joshvera/CefSharp,haozhouxu/CefSharp,ruisebastiao/CefSharp,battewr/CefSharp,windygu/CefSharp,yoder/CefSharp,wangzheng888520/CefSharp,ruisebastiao/CefSharp,haozhouxu/CefSharp,Octopus-ITSM/CefSharp,jamespearce2006/CefSharp,VioletLife/CefSharp,illfang/CefSharp,zhangjingpu/CefSharp,yoder/CefSharp,rlmcneary2/CefSharp,Haraguroicha/CefSharp,zhangjingpu/CefSharp,ITGlobal/CefSharp,jamespearce2006/CefSharp,wangzheng888520/CefSharp,VioletLife/CefSharp,Haraguroicha/CefSharp,Octopus-ITSM/CefSharp,AJDev77/CefSharp,Livit/CefSharp,zhangjingpu/CefSharp,NumbersInternational/CefSharp,zhangjingpu/CefSharp,Haraguroicha/CefSharp,rover886/CefSharp,wangzheng888520/CefSharp,yoder/CefSharp,illfang/CefSharp,gregmartinhtc/CefSharp,dga711/CefSharp,Livit/CefSharp,jamespearce2006/CefSharp,Livit/CefSharp,AJDev77/CefSharp,twxstar/CefSharp,joshvera/CefSharp,rover886/CefSharp,twxstar/CefSharp,dga711/CefSharp,haozhouxu/CefSharp,yoder/CefSharp,rlmcneary2/CefSharp,battewr/CefSharp,Haraguroicha/CefSharp | CefSharp.Example/SubBoundObject.cs | CefSharp.Example/SubBoundObject.cs | namespace CefSharp.Example
{
public class SubBoundObject
{
public string SimpleProperty { get; set; }
public SubBoundObject()
{
SimpleProperty = "This is a very simple property.";
}
public string GetMyType()
{
return "My Type is " + GetType();
}
public string EchoSimpleProperty()
{
return SimpleProperty;
}
}
}
| namespace CefSharp.Example
{
public class SubBoundObject
{
public string SimpleProperty { get; set; }
public SubBoundObject()
{
SimpleProperty = "This is a very simple property.";
}
public string GetMyType()
{
return "My Type is " + GetType();
}
}
}
| bsd-3-clause | C# |
c794901275b98790f393ad68bfdde406f0c51cfa | Add test extension for easier waiting for analysis completion. | DartVS/DartVS,modulexcite/DartVS,modulexcite/DartVS,DartVS/DartVS,DartVS/DartVS,modulexcite/DartVS | DanTup.DartAnalysis.Tests/Tests.cs | DanTup.DartAnalysis.Tests/Tests.cs | using System;
using System.IO;
using System.Reactive.Linq;
using System.Reflection;
using DanTup.DartAnalysis.Json;
namespace DanTup.DartAnalysis.Tests
{
public abstract class Tests
{
protected string SdkFolder
{
// Hijack ENV-reading property
get { return DanTup.DartVS.DartAnalysisService.SdkPath; }
}
string CodebaseRoot = Path.GetFullPath(new Uri(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase), @"..\..\..\")).AbsolutePath); // up out of debug, bin, Tests
protected string ServerScript { get { return Path.Combine(CodebaseRoot, "Dart\\AnalysisServer.dart"); } }
protected string SampleDartProject { get { return Path.Combine(CodebaseRoot, "DanTup.DartAnalysis.Tests.SampleDartProject"); } }
protected string HelloWorldFile { get { return SampleDartProject + @"\hello_world.dart"; } }
protected string SingleTypeErrorFile { get { return SampleDartProject + @"\single_type_error.dart"; } }
protected DartAnalysisService CreateTestService()
{
var service = new DartAnalysisService(SdkFolder, ServerScript);
service.SetServerSubscriptions(new[] { ServerService.Status }).Wait();
return service;
}
}
public static class TestExtensions
{
public static void WaitForAnalysis(this DartAnalysisService service)
{
service
.ServerStatusNotification
.FirstAsync(n => n.Analysis.Analyzing == false)
.Wait();
}
}
}
| using System;
using System.IO;
using System.Reflection;
using DanTup.DartAnalysis.Json;
namespace DanTup.DartAnalysis.Tests
{
public abstract class Tests
{
protected string SdkFolder
{
// Hijack ENV-reading property
get { return DanTup.DartVS.DartAnalysisService.SdkPath; }
}
string CodebaseRoot = Path.GetFullPath(new Uri(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase), @"..\..\..\")).AbsolutePath); // up out of debug, bin, Tests
protected string ServerScript { get { return Path.Combine(CodebaseRoot, "Dart\\AnalysisServer.dart"); } }
protected string SampleDartProject { get { return Path.Combine(CodebaseRoot, "DanTup.DartAnalysis.Tests.SampleDartProject"); } }
protected string HelloWorldFile { get { return SampleDartProject + @"\hello_world.dart"; } }
protected string SingleTypeErrorFile { get { return SampleDartProject + @"\single_type_error.dart"; } }
protected DartAnalysisService CreateTestService()
{
var service = new DartAnalysisService(SdkFolder, ServerScript);
service.SetServerSubscriptions(new[] { ServerService.Status }).Wait();
return service;
}
}
}
| mit | C# |
624e1e30d06b0cdc01e47cd1876569607426c8b2 | use cancellation support in AsyncDemoItem | Insire/MvvmScarletToolkit,Insire/MvvmScarletToolkit | DemoApp/ViewModel/AsyncDemoItem.cs | DemoApp/ViewModel/AsyncDemoItem.cs | using MvvmScarletToolkit;
using MvvmScarletToolkit.Observables;
using System.Threading;
using System.Threading.Tasks;
namespace DemoApp
{
public class AsyncDemoItem : BusinessViewModelBase
{
private string _displayName;
public string DisplayName
{
get { return _displayName; }
set { SetValue(ref _displayName, value); }
}
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set { SetValue(ref _isSelected, value); }
}
public AsyncDemoItem(ICommandBuilder commandBuilder)
: base(commandBuilder)
{
DisplayName = "unknown";
}
public AsyncDemoItem(ICommandBuilder commandBuilder, string displayName)
: this(commandBuilder)
{
DisplayName = displayName;
}
protected override Task UnloadInternal(CancellationToken token)
{
return Task.Delay(2000, token);
}
protected override Task RefreshInternal(CancellationToken token)
{
return Task.Delay(2000, token);
}
}
}
| using MvvmScarletToolkit;
using MvvmScarletToolkit.Observables;
using System.Threading;
using System.Threading.Tasks;
namespace DemoApp
{
public class AsyncDemoItem : BusinessViewModelBase
{
private string _displayName;
public string DisplayName
{
get { return _displayName; }
set { SetValue(ref _displayName, value); }
}
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set { SetValue(ref _isSelected, value); }
}
public AsyncDemoItem(ICommandBuilder commandBuilder)
: base(commandBuilder)
{
DisplayName = "unknown";
}
public AsyncDemoItem(ICommandBuilder commandBuilder, string displayName)
: this(commandBuilder)
{
DisplayName = displayName;
}
protected override Task UnloadInternal(CancellationToken token)
{
return Task.Delay(2000);
}
protected override Task RefreshInternal(CancellationToken token)
{
return Task.Delay(2000);
}
}
}
| mit | C# |
931234168d9842e5fb5f65d5bfdeecc80babee44 | Update Timber to 4.7.1 | xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents | Android/Timber/build.cake | Android/Timber/build.cake |
#load "../../common.cake"
var TARGET = Argument ("t", Argument ("target", "Default"));
var ANDROID_VERSION = "4.7.1";
var ANDROID_NUGET_VERSION = "4.7.1";
var ANDROID_URL = string.Format ("http://search.maven.org/remotecontent?filepath=com/jakewharton/timber/timber/{0}/timber-{0}.aar", ANDROID_VERSION);
var ANDROID_FILE = "jakewharton.timber.aar";
var buildSpec = new BuildSpec () {
Libs = new ISolutionBuilder [] {
new DefaultSolutionBuilder {
SolutionPath = "./source/Timber.sln",
OutputFiles = new [] {
new OutputFileCopy {
FromFile = "./source/Timber/bin/Release/Timber.dll",
}
}
}
},
Samples = new ISolutionBuilder [] {
new DefaultSolutionBuilder { SolutionPath = "./samples/TimberSample.sln" },
},
NuGets = new [] {
new NuGetInfo { NuSpec = "./nuget/Xamarin.JakeWharton.Timber.nuspec", Version = ANDROID_NUGET_VERSION },
},
};
Task ("externals")
.Does (() =>
{
if (!DirectoryExists ("./externals/"))
CreateDirectory ("./externals/");
DownloadFile (ANDROID_URL, "./externals/" + ANDROID_FILE);
});
Task ("clean").IsDependentOn ("clean-base").Does (() =>
{
DeleteFiles ("./externals/*.aar");
});
SetupXamarinBuildTasks (buildSpec, Tasks, Task);
RunTarget (TARGET);
|
#load "../../common.cake"
var TARGET = Argument ("t", Argument ("target", "Default"));
var ANDROID_VERSION = "4.6.0";
var ANDROID_NUGET_VERSION = "4.6.0";
var ANDROID_URL = string.Format ("http://search.maven.org/remotecontent?filepath=com/jakewharton/timber/timber/{0}/timber-{0}.aar", ANDROID_VERSION);
var ANDROID_FILE = "jakewharton.timber.aar";
var buildSpec = new BuildSpec () {
Libs = new ISolutionBuilder [] {
new DefaultSolutionBuilder {
SolutionPath = "./source/Timber.sln",
OutputFiles = new [] {
new OutputFileCopy {
FromFile = "./source/Timber/bin/Release/Timber.dll",
}
}
}
},
Samples = new ISolutionBuilder [] {
new DefaultSolutionBuilder { SolutionPath = "./samples/TimberSample.sln" },
},
NuGets = new [] {
new NuGetInfo { NuSpec = "./nuget/Xamarin.JakeWharton.Timber.nuspec", Version = ANDROID_NUGET_VERSION },
},
};
Task ("externals")
.Does (() =>
{
if (!DirectoryExists ("./externals/"))
CreateDirectory ("./externals/");
DownloadFile (ANDROID_URL, "./externals/" + ANDROID_FILE);
});
Task ("clean").IsDependentOn ("clean-base").Does (() =>
{
DeleteFiles ("./externals/*.aar");
});
SetupXamarinBuildTasks (buildSpec, Tasks, Task);
RunTarget (TARGET);
| mit | C# |
082fdc3896a59cc781439134e617fed90c5635ca | fix a line | SoftServeNetTeam/StartupBusinessSystem,SoftServeNetTeam/StartupBusinessSystem | Web/StartupBusinessSystem.Web/Views/Campaigns/Create.cshtml | Web/StartupBusinessSystem.Web/Views/Campaigns/Create.cshtml | @model StartupBusinessSystem.Web.ViewModels.Campaigns.CreateCampaignViewModel
@{
ViewBag.Title = "Create";
}
<h2>Add new Startup</h2>
@using (Html.BeginForm("Create", "Campaigns", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
if (!ViewData.ModelState.IsValid)
{
<div class="alert alert-danger" role="alert">
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span class="sr-only">Error:</span>
@Html.ValidationSummary(true)
</div>
}
<div class="form-group">
@Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
@Html.ValidationMessageFor(m =>m.Name)
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Description, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextAreaFor(m => m.Description, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Description)
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.GoalPrice, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.GoalPrice, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.GoalPrice)
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Shares, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Shares, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Shares)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Add Startup" />
</div>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
| @model StartupBusinessSystem.Web.ViewModels.Campaigns.CreateCampaignViewModel
@{
ViewBag.Title = "Create";
}
<h2>Add new Startup</h2>
@using (Html.BeginForm("Create", "Campaigns", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<hr />
if (!ViewData.ModelState.IsValid)
{
<div class="alert alert-danger" role="alert">
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span class="sr-only">Error:</span>
@Html.ValidationSummary(true)
</div>
}
<div class="form-group">
@Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
@Html.ValidationMessageFor(m =>m.Name)
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Description, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextAreaFor(m => m.Description, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Description)
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.GoalPrice, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.GoalPrice, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.GoalPrice)
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Shares, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Shares, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Shares)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Add Startup" />
</div>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
| mit | C# |
e9481e54e1d7b3b72e01087a7e5bcb8d0b8003f5 | Reset page number to 1 when perform a new search. Work items: 569 | jmezach/NuGet2,akrisiun/NuGet,antiufo/NuGet2,pratikkagda/nuget,alluran/node.net,themotleyfool/NuGet,themotleyfool/NuGet,rikoe/nuget,chocolatey/nuget-chocolatey,jmezach/NuGet2,rikoe/nuget,chocolatey/nuget-chocolatey,indsoft/NuGet2,chocolatey/nuget-chocolatey,antiufo/NuGet2,oliver-feng/nuget,oliver-feng/nuget,kumavis/NuGet,mono/nuget,mrward/NuGet.V2,jholovacs/NuGet,dolkensp/node.net,chester89/nugetApi,dolkensp/node.net,mrward/nuget,oliver-feng/nuget,kumavis/NuGet,oliver-feng/nuget,jmezach/NuGet2,jholovacs/NuGet,zskullz/nuget,RichiCoder1/nuget-chocolatey,xoofx/NuGet,jholovacs/NuGet,mono/nuget,xero-github/Nuget,alluran/node.net,anurse/NuGet,indsoft/NuGet2,chocolatey/nuget-chocolatey,xoofx/NuGet,OneGet/nuget,akrisiun/NuGet,GearedToWar/NuGet2,alluran/node.net,indsoft/NuGet2,ctaggart/nuget,zskullz/nuget,RichiCoder1/nuget-chocolatey,zskullz/nuget,oliver-feng/nuget,antiufo/NuGet2,RichiCoder1/nuget-chocolatey,pratikkagda/nuget,indsoft/NuGet2,rikoe/nuget,mrward/nuget,oliver-feng/nuget,jmezach/NuGet2,xoofx/NuGet,chocolatey/nuget-chocolatey,indsoft/NuGet2,themotleyfool/NuGet,jholovacs/NuGet,mrward/NuGet.V2,chester89/nugetApi,indsoft/NuGet2,OneGet/nuget,mrward/NuGet.V2,mrward/NuGet.V2,OneGet/nuget,alluran/node.net,RichiCoder1/nuget-chocolatey,mrward/nuget,anurse/NuGet,zskullz/nuget,GearedToWar/NuGet2,dolkensp/node.net,pratikkagda/nuget,mono/nuget,xoofx/NuGet,pratikkagda/nuget,OneGet/nuget,jholovacs/NuGet,pratikkagda/nuget,ctaggart/nuget,mrward/nuget,antiufo/NuGet2,RichiCoder1/nuget-chocolatey,mrward/NuGet.V2,chocolatey/nuget-chocolatey,jmezach/NuGet2,ctaggart/nuget,GearedToWar/NuGet2,pratikkagda/nuget,mrward/nuget,atheken/nuget,ctaggart/nuget,mrward/NuGet.V2,dolkensp/node.net,xoofx/NuGet,GearedToWar/NuGet2,jmezach/NuGet2,xoofx/NuGet,antiufo/NuGet2,rikoe/nuget,mrward/nuget,GearedToWar/NuGet2,GearedToWar/NuGet2,RichiCoder1/nuget-chocolatey,jholovacs/NuGet,atheken/nuget,antiufo/NuGet2,mono/nuget | src/Dialog/PackageManagerUI/BaseProvider/PackagesSearchNode.cs | src/Dialog/PackageManagerUI/BaseProvider/PackagesSearchNode.cs | using System;
using System.Linq;
using Microsoft.VisualStudio.ExtensionsExplorer;
namespace NuGet.Dialog.Providers {
internal class PackagesSearchNode : PackagesTreeNodeBase {
private string _searchText;
private readonly PackagesTreeNodeBase _baseNode;
public PackagesTreeNodeBase BaseNode {
get {
return _baseNode;
}
}
public PackagesSearchNode(PackagesProviderBase provider, IVsExtensionsTreeNode parent, PackagesTreeNodeBase baseNode, string searchText) :
base(parent, provider) {
if (baseNode == null) {
throw new ArgumentNullException("baseNode");
}
_searchText = searchText;
_baseNode = baseNode;
// Mark this node as a SearchResults node to assist navigation in ExtensionsExplorer
IsSearchResultsNode = true;
}
public override string Name {
get {
return Resources.Dialog_RootNodeSearch;
}
}
public void SetSearchText(string newSearchText) {
if (newSearchText == null) {
throw new ArgumentNullException("newSearchText");
}
if (_searchText != newSearchText) {
_searchText = newSearchText;
if (IsSelected) {
ResetQuery();
LoadPage(1);
}
}
}
public override IQueryable<IPackage> GetPackages() {
return _baseNode.GetPackages().Find(_searchText);
}
}
} | using System;
using System.Linq;
using Microsoft.VisualStudio.ExtensionsExplorer;
namespace NuGet.Dialog.Providers {
internal class PackagesSearchNode : PackagesTreeNodeBase {
private string _searchText;
private readonly PackagesTreeNodeBase _baseNode;
public PackagesTreeNodeBase BaseNode {
get {
return _baseNode;
}
}
public PackagesSearchNode(PackagesProviderBase provider, IVsExtensionsTreeNode parent, PackagesTreeNodeBase baseNode, string searchText) :
base(parent, provider) {
if (baseNode == null) {
throw new ArgumentNullException("baseNode");
}
_searchText = searchText;
_baseNode = baseNode;
// Mark this node as a SearchResults node to assist navigation in ExtensionsExplorer
IsSearchResultsNode = true;
}
public override string Name {
get {
return Resources.Dialog_RootNodeSearch;
}
}
public void SetSearchText(string newSearchText) {
if (newSearchText == null) {
throw new ArgumentNullException("newSearchText");
}
if (_searchText != newSearchText) {
_searchText = newSearchText;
if (IsSelected) {
ResetQuery();
Refresh();
}
}
}
public override IQueryable<IPackage> GetPackages() {
return _baseNode.GetPackages().Find(_searchText);
}
}
} | apache-2.0 | C# |
503225836f14e548f8f759f3e4003e206c5924e5 | Fix nullability warning | EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an | AvsAnDemo/Dictionaries.cs | AvsAnDemo/Dictionaries.cs | using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
namespace AvsAnDemo {
public static class Dictionaries {
public static IEnumerable<string> AcronymsWithUpto4Letters() {
var letters = Enumerable.Range('A', 'Z' - 'A' + 1).Select(i => (char)i).ToArray();
return new[] { 1, 2, 3, 4 }
.SelectMany(len =>
Enumerable.Repeat(letters, len)
.Aggregate(new[] { "" },
(prefixes, chars) => (
from prefix in prefixes
from suffix in chars
select prefix + suffix
).ToArray()
)
);
}
public static IEnumerable<string> SmallNumberStrings()
=> Enumerable.Range(0, 100000).Select(i => i.ToString(CultureInfo.InvariantCulture));
public static string[] LoadEnglishDictionary() {
// ReSharper disable once AssignNullToNotNullAttribute
using var stream = typeof(Dictionaries).Assembly.GetManifestResourceStream(typeof(Dictionaries), "354984si.ngl");
using var reader = new StreamReader(stream ?? throw new Exception("missing embedded 354984si.ngl"));
return reader
.ReadToEnd()
.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
}
}
}
| using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
namespace AvsAnDemo {
public static class Dictionaries {
public static IEnumerable<string> AcronymsWithUpto4Letters() {
var letters = Enumerable.Range('A', 'Z' - 'A' + 1).Select(i => (char)i).ToArray();
return new[] { 1, 2, 3, 4 }
.SelectMany(len =>
Enumerable.Repeat(letters, len)
.Aggregate(new[] { "" },
(prefixes, chars) => (
from prefix in prefixes
from suffix in chars
select prefix + suffix
).ToArray()
)
);
}
public static IEnumerable<string> SmallNumberStrings()
=> Enumerable.Range(0, 100000).Select(i => i.ToString(CultureInfo.InvariantCulture));
public static string[] LoadEnglishDictionary() {
// ReSharper disable once AssignNullToNotNullAttribute
using var stream = typeof(Dictionaries).Assembly.GetManifestResourceStream(typeof(Dictionaries), "354984si.ngl");
using var reader = new StreamReader(stream);
return reader
.ReadToEnd()
.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
}
}
}
| apache-2.0 | C# |
48157bfd23e2e57ad612582328b5feaa3a621ba2 | Add additional comparison methods for string establisher | tjb042/Establishment | Establishment/StringEstablisher.cs | Establishment/StringEstablisher.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Establishment {
public class StringEstablisher : BaseClassEstablisher<string> {
public bool IsNullOrEmpty(string value) {
if (!string.IsNullOrEmpty(value)) {
return HandleFailure(new ArgumentException("string value must be null or empty"));
}
return true;
}
public bool IsNotNullOrEmpty(string value) {
if (string.IsNullOrEmpty(value)) {
return HandleFailure(new ArgumentException("string value must not be null or empty"));
}
return true;
}
public bool IsEmpty(string value) {
if (value != string.Empty) {
return HandleFailure(new ArgumentException("string value must be empty"));
}
return true;
}
public bool IsNotEmpty(string value) {
if (value == string.Empty) {
return HandleFailure(new ArgumentException("string value must not be empty"));
}
return true;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Establishment {
public class StringEstablisher : BaseClassEstablisher<string> {
public bool IsNullOrEmpty(string value) {
if (!string.IsNullOrEmpty(value)) {
return HandleFailure(new ArgumentException("string value must be null or empty"));
}
return true;
}
public bool IsNotNullOrEmpty(string value) {
if (string.IsNullOrEmpty(value)) {
return HandleFailure(new ArgumentException("string value must not be null or empty"));
}
return true;
}
}
}
| mit | C# |
78c844e25930af377c3c28162c58551d03c374b8 | Make catch provide some HP at DrainRate=10 | UselessToucan/osu,peppy/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,smoogipooo/osu,EVAST9919/osu,NeoAdonis/osu,peppy/osu-new,2yangk23/osu,NeoAdonis/osu,2yangk23/osu,NeoAdonis/osu,peppy/osu,ZLima12/osu,ZLima12/osu,johnneijzen/osu,johnneijzen/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,ppy/osu,EVAST9919/osu,UselessToucan/osu,ppy/osu | osu.Game.Rulesets.Catch/Scoring/CatchScoreProcessor.cs | osu.Game.Rulesets.Catch/Scoring/CatchScoreProcessor.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Catch.Scoring
{
public class CatchScoreProcessor : ScoreProcessor<CatchHitObject>
{
public CatchScoreProcessor(DrawableRuleset<CatchHitObject> drawableRuleset)
: base(drawableRuleset)
{
}
private float hpDrainRate;
protected override void ApplyBeatmap(Beatmap<CatchHitObject> beatmap)
{
base.ApplyBeatmap(beatmap);
hpDrainRate = beatmap.BeatmapInfo.BaseDifficulty.DrainRate;
}
protected override double HpFactorFor(Judgement judgement, HitResult result)
{
switch (result)
{
case HitResult.Miss when judgement.IsBonus:
return 0;
case HitResult.Miss:
return hpDrainRate;
default:
return 10.2 - hpDrainRate; // Award less HP as drain rate is increased
}
}
public override HitWindows CreateHitWindows() => new CatchHitWindows();
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Catch.Scoring
{
public class CatchScoreProcessor : ScoreProcessor<CatchHitObject>
{
public CatchScoreProcessor(DrawableRuleset<CatchHitObject> drawableRuleset)
: base(drawableRuleset)
{
}
private float hpDrainRate;
protected override void ApplyBeatmap(Beatmap<CatchHitObject> beatmap)
{
base.ApplyBeatmap(beatmap);
hpDrainRate = beatmap.BeatmapInfo.BaseDifficulty.DrainRate;
}
protected override double HpFactorFor(Judgement judgement, HitResult result)
{
switch (result)
{
case HitResult.Miss when judgement.IsBonus:
return 0;
case HitResult.Miss:
return hpDrainRate;
default:
return 10 - hpDrainRate; // Award less HP as drain rate is increased
}
}
public override HitWindows CreateHitWindows() => new CatchHitWindows();
}
}
| mit | C# |
253d4a3e8e9384fc3d1fb037e9c188ebc9faf306 | Remove TralusModule from Requierd Module Types in TralusWinModule | mehrandvd/Tralus,mehrandvd/Tralus | Framework/Source/Tralus.Framework.Module.Win/TralusWinModule.cs | Framework/Source/Tralus.Framework.Module.Win/TralusWinModule.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.DC;
using DevExpress.ExpressApp.Model;
using DevExpress.ExpressApp.Model.Core;
using Tralus.Framework.BusinessModel.Utility;
namespace Tralus.Framework.Module.Win
{
public class TralusWinModule : TralusModule
{
protected TralusWinModule()
{
if (!(this is FrameworkWindowsFormsModule))
{
this.RequiredModuleTypes.Add(typeof(FrameworkWindowsFormsModule));
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.DC;
using DevExpress.ExpressApp.Model;
using DevExpress.ExpressApp.Model.Core;
using Tralus.Framework.BusinessModel.Utility;
namespace Tralus.Framework.Module.Win
{
public class TralusWinModule : TralusModule
{
protected TralusWinModule()
{
if (!(this is FrameworkWindowsFormsModule))
{
this.RequiredModuleTypes.Add(typeof(TralusModule));
this.RequiredModuleTypes.Add(typeof(FrameworkWindowsFormsModule));
}
}
}
}
| apache-2.0 | C# |
3b666596d0706c31919a36f4de41bc7f7103310c | Add PlaceId for Place Autocomplete API. | maximn/google-maps,yonglehou/google-maps,maximn/google-maps,mklimmasch/google-maps,mklimmasch/google-maps,yonglehou/google-maps | GoogleMapsApi/Entities/PlaceAutocomplete/Response/Prediction.cs | GoogleMapsApi/Entities/PlaceAutocomplete/Response/Prediction.cs | using System;
using System.Runtime.Serialization;
using GoogleMapsApi.Entities.Common;
namespace GoogleMapsApi.Entities.PlaceAutocomplete.Response
{
/// <summary>
/// When the PlaceAutocomplete service returns results from a search, it places them within a predictions array.
/// Even if the service returns no results (such as if the location is remote) it still returns an empty predictions array.
/// </summary>
[DataContract]
public class Prediction
{
/// <summary>
/// Contains the human-readable name for the returned result. For establishment results, this is usually the business name.
/// </summary>
[DataMember(Name = "description")]
public string Description { get; set; }
/// <summary>
/// Contains a unique identifier for this place. To retrieve information about this place, pass this identifier in the placeId field of
/// a Places API request.
/// </summary>
[DataMember( Name = "place_id" )]
public string PlaceId { get; set; }
/// <summary>
/// Contains a unique token that you can use to retrieve additional information about this place in a Place Details request.
/// You can store this token and use it at any time in future to refresh cached data about this place, but the same token is
/// not guaranteed to be returned for any given place across different searches.
/// </summary>
[DataMember(Name = "reference")]
[Obsolete( "Use place_id instead. See https://developers.google.com/places/documentation/search#deprecation for more information." )]
public string Reference { get; set; }
/// <summary>
/// Contains a unique stable identifier denoting this place. This identifier may not be used to retrieve information about this
/// place, but can be used to consolidate data about this place, and to verify the identity of a place across separate searches.
/// </summary>
[DataMember(Name = "id")]
[Obsolete( "Use place_id instead. See https://developers.google.com/places/documentation/search#deprecation for more information." )]
public string ID { get; set; }
/// <summary>
/// Contains an array of terms identifying each section of the returned description (a section of the description is generally
/// terminated with a comma). Each entry in the array has a value field, containing the text of the term, and an offset field,
/// defining the start position of this term in the description, measured in Unicode characters.
/// </summary>
[DataMember(Name = "terms")]
public Term[] Terms { get; set; }
/// <summary>
/// Contains an array of types that apply to this place. For example: [ "political", "locality" ] or [ "establishment", "geocode" ].
/// </summary>
[DataMember(Name = "types")]
public string[] Types { get; set; }
/// <summary>
/// Contains an offset value and a length. These describe the location of the entered term in the prediction result text, so that
/// the term can be highlighted if desired.
/// </summary>
[DataMember(Name = "matched_substrings")]
public MatchedSubstring[] MatchedSubstrings { get; set; }
}
}
| using System.Runtime.Serialization;
using GoogleMapsApi.Entities.Common;
namespace GoogleMapsApi.Entities.PlaceAutocomplete.Response
{
/// <summary>
/// When the PlaceAutocomplete service returns results from a search, it places them within a predictions array.
/// Even if the service returns no results (such as if the location is remote) it still returns an empty predictions array.
/// </summary>
[DataContract]
public class Prediction
{
/// <summary>
/// Contains the human-readable name for the returned result. For establishment results, this is usually the business name.
/// </summary>
[DataMember(Name = "description")]
public string Description { get; set; }
/// <summary>
/// Contains a unique token that you can use to retrieve additional information about this place in a Place Details request.
/// You can store this token and use it at any time in future to refresh cached data about this place, but the same token is
/// not guaranteed to be returned for any given place across different searches.
/// </summary>
[DataMember(Name = "reference")]
public string Reference { get; set; }
/// <summary>
/// Contains a unique stable identifier denoting this place. This identifier may not be used to retrieve information about this
/// place, but can be used to consolidate data about this place, and to verify the identity of a place across separate searches.
/// </summary>
[DataMember(Name = "id")]
public string ID { get; set; }
/// <summary>
/// Contains an array of terms identifying each section of the returned description (a section of the description is generally
/// terminated with a comma). Each entry in the array has a value field, containing the text of the term, and an offset field,
/// defining the start position of this term in the description, measured in Unicode characters.
/// </summary>
[DataMember(Name = "terms")]
public Term[] Terms { get; set; }
/// <summary>
/// Contains an array of types that apply to this place. For example: [ "political", "locality" ] or [ "establishment", "geocode" ].
/// </summary>
[DataMember(Name = "types")]
public string[] Types { get; set; }
/// <summary>
/// Contains an offset value and a length. These describe the location of the entered term in the prediction result text, so that
/// the term can be highlighted if desired.
/// </summary>
[DataMember( Name = "matched_substrings" )]
public MatchedSubstring[] MatchedSubstrings { get; set; }
}
}
| bsd-2-clause | C# |
dac5303a27e699889cbc8606c48d8d58fc018988 | Update AntimalwareScannerExtensions.cs | tiksn/TIKSN-Framework | TIKSN.Core/Security/Antimalware/AntimalwareScannerExtensions.cs | TIKSN.Core/Security/Antimalware/AntimalwareScannerExtensions.cs | using System.IO;
namespace TIKSN.Security.Antimalware
{
public static class AntimalwareScannerExtensions
{
public static AntimalwareScanResult ScanFile(this IAntimalwareScanner antimalwareScanner, string path)
{
var absolutePath = Path.GetFullPath(path);
var fileContent = File.ReadAllBytes(absolutePath);
return antimalwareScanner.ScanBinaryArray(fileContent, absolutePath);
}
}
}
| using System.IO;
namespace TIKSN.Security.Antimalware
{
public static class AntimalwareScannerExtensions
{
public static AntimalwareScanResult ScanFile(this IAntimalwareScanner antimalwareScanner, string path)
{
var absolutePath = Path.GetFullPath(path);
var fileContent = File.ReadAllBytes(absolutePath);
return antimalwareScanner.ScanBinaryArray(fileContent, absolutePath);
}
}
} | mit | C# |
0131fb649976dae4caa4c9b3f2c7f2236320ef75 | Extend BZip2Exception as per FxCop suggestion | McNeight/SharpZipLib | src/BZip2/BZip2Exception.cs | src/BZip2/BZip2Exception.cs | // BZip2.cs
//
// Copyright 2004 John Reilly
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
#if !COMPACT_FRAMEWORK
using System.Runtime.Serialization;
#endif
using ICSharpCode.SharpZipLib;
namespace ICSharpCode.SharpZipLib.BZip2
{
/// <summary>
/// BZip2Exception represents exceptions specific to Bzip2 algorithm
/// </summary>
#if !COMPACT_FRAMEWORK
[Serializable]
#endif
public class BZip2Exception : SharpZipBaseException
{
#if !COMPACT_FRAMEWORK
/// <summary>
/// Deserialization constructor
/// </summary>
/// <param name="info"><see cref="SerializationInfo"/> for this constructor</param>
/// <param name="context"><see cref="StreamingContext"/> for this constructor</param>
protected BZip2Exception(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
/// <summary>
/// Initialise a new instance of BZip2Exception.
/// </summary>
public BZip2Exception()
{
}
/// <summary>
/// Initialise a new instance of BZip2Exception with its message set to message.
/// </summary>
/// <param name="message">The message describing the error.</param>
public BZip2Exception(string message) : base(message)
{
}
/// <summary>
/// Initialise an instance of BZip2Exception
/// </summary>
/// <param name="message">A message describing the error.</param>
/// <param name="exception">The exception that is the cause of the current exception.</param>
public BZip2Exception(string message, Exception exception)
: base(message, exception)
{
}
}
}
| // BZip2.cs
//
// Copyright 2004 John Reilly
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
#if !COMPACT_FRAMEWORK
using System.Runtime.Serialization;
#endif
using ICSharpCode.SharpZipLib;
namespace ICSharpCode.SharpZipLib.BZip2
{
/// <summary>
/// BZip2Exception represents exceptions specific to Bzip2 algorithm
/// </summary>
#if !COMPACT_FRAMEWORK
[Serializable]
#endif
public class BZip2Exception : SharpZipBaseException
{
#if !COMPACT_FRAMEWORK
/// <summary>
/// Deserialization constructor
/// </summary>
/// <param name="info"><see cref="SerializationInfo"/> for this constructor</param>
/// <param name="context"><see cref="StreamingContext"/> for this constructor</param>
protected BZip2Exception(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
/// <summary>
/// Initialise a new instance of BZip2Exception.
/// </summary>
public BZip2Exception()
{
}
/// <summary>
/// Initialise a new instance of BZip2Exception with its message set to message.
/// </summary>
/// <param name="message">The message describing the error.</param>
public BZip2Exception(string message) : base(message)
{
}
}
}
| mit | C# |
36b5c71a817b6e9c7874f2c0c2de5509c3db2cd0 | use [ThreadStatic], drop reflection | lytico/xwt,antmicro/xwt,mono/xwt | Xwt.XamMac/Xwt.Mac/NSApplicationInitializer.cs | Xwt.XamMac/Xwt.Mac/NSApplicationInitializer.cs | //
// NSApplicationInitializer.cs
//
// Author:
// Lluis Sanchez Gual <[email protected]>
//
// Copyright (c) 2016 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using AppKit;
namespace Xwt.Mac
{
static class NSApplicationInitializer
{
[ThreadStatic]
static bool initialized;
public static void Initialize ()
{
if (!initialized) {
initialized = true;
NSApplication.IgnoreMissingAssembliesDuringRegistration = true;
NSApplication.Init ();
}
}
}
}
| //
// NSApplicationInitializer.cs
//
// Author:
// Lluis Sanchez Gual <[email protected]>
//
// Copyright (c) 2016 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using AppKit;
namespace Xwt.Mac
{
static class NSApplicationInitializer
{
public static void Initialize ()
{
var ds = System.Threading.Thread.GetNamedDataSlot ("NSApplication.Initialized");
if (System.Threading.Thread.GetData (ds) == null) {
System.Threading.Thread.SetData (ds, true);
// IgnoreMissingAssembliesDuringRegistration is only avalilable in Xamarin.Mac 3.4+
// Use reflection to not break builds with older Xamarin.Mac
var ignoreMissingAssemblies = typeof (NSApplication).GetField ("IgnoreMissingAssembliesDuringRegistration",
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
ignoreMissingAssemblies?.SetValue (null, true);
NSApplication.Init ();
}
}
}
}
| mit | C# |
9f45c54351f504c3590a6d53e9b3d9779ac420fb | Make StateMachine internal | mrahhal/Konsola | src/Konsola/StateMachine.cs | src/Konsola/StateMachine.cs | using System;
namespace Konsola
{
internal class StateMachine<T>
where T : class
{
public StateMachine(T[] data)
{
if (data == null)
{
throw new ArgumentNullException("data");
}
Data = data;
Position = -1;
}
public T[] Data { get; private set; }
public int Position { get; set; }
public bool HasNext
{
get
{
return Position + 1 < Data.Length;
}
}
public bool HasPrevious
{
get
{
return Position - 1 >= 0;
}
}
public T Current
{
get
{
if (Position >= 0 && Position < Data.Length)
{
return Data[Position];
}
return null;
}
}
public void Reset()
{
Position = -1;
}
public T PeekNext()
{
var next = Position + 1;
if (!HasNext)
{
return null;
}
return Data[next];
}
public T PeekPrevious()
{
var previous = Position - 1;
if (!HasPrevious)
{
return null;
}
return Data[previous];
}
public T Next()
{
if (!HasNext)
{
return null;
}
return Data[++Position];
}
public T Previous()
{
if (!HasPrevious)
{
return null;
}
return Data[--Position];
}
public void VisitAllNext(Func<int, T, T> visit)
{
if (visit == null)
{
throw new ArgumentNullException("visit");
}
if (!HasNext)
{
return;
}
for (int i = Position + 1; i < Data.Length; i++)
{
var currentT = Data[i];
var newT = visit(i, currentT);
if (newT != currentT)
{
Data[i] = newT;
}
}
}
public void VisitAllPrevious(Func<int, T, T> visit)
{
if (visit == null)
{
throw new ArgumentNullException("visit");
}
if (!HasPrevious)
{
return;
}
for (int i = Position - 1; i >= 0; i--)
{
var currentT = Data[i];
var newT = visit(i, currentT);
if (newT != currentT)
{
Data[i] = newT;
}
}
}
}
} | using System;
namespace Konsola
{
public class StateMachine<T>
where T : class
{
public StateMachine(T[] data)
{
if (data == null)
{
throw new ArgumentNullException("data");
}
Data = data;
Position = -1;
}
public T[] Data { get; private set; }
public int Position { get; set; }
public bool HasNext
{
get
{
return Position + 1 < Data.Length;
}
}
public bool HasPrevious
{
get
{
return Position - 1 >= 0;
}
}
public T Current
{
get
{
if (Position >= 0 && Position < Data.Length)
{
return Data[Position];
}
return null;
}
}
public void Reset()
{
Position = -1;
}
public T PeekNext()
{
var next = Position + 1;
if (!HasNext)
{
return null;
}
return Data[next];
}
public T PeekPrevious()
{
var previous = Position - 1;
if (!HasPrevious)
{
return null;
}
return Data[previous];
}
public T Next()
{
if (!HasNext)
{
return null;
}
return Data[++Position];
}
public T Previous()
{
if (!HasPrevious)
{
return null;
}
return Data[--Position];
}
public void VisitAllNext(Func<int, T, T> visit)
{
if (visit == null)
{
throw new ArgumentNullException("visit");
}
if (!HasNext)
{
return;
}
for (int i = Position + 1; i < Data.Length; i++)
{
var currentT = Data[i];
var newT = visit(i, currentT);
if (newT != currentT)
{
Data[i] = newT;
}
}
}
public void VisitAllPrevious(Func<int, T, T> visit)
{
if (visit == null)
{
throw new ArgumentNullException("visit");
}
if (!HasPrevious)
{
return;
}
for (int i = Position - 1; i >= 0; i--)
{
var currentT = Data[i];
var newT = visit(i, currentT);
if (newT != currentT)
{
Data[i] = newT;
}
}
}
}
} | mit | C# |
d80cd42d19cf7d95c1e6d6862000bb8ad08e9bc4 | Update InputGrid.cs | LANDIS-II-Foundation/Landis-Spatial-Modeling-Library | src/Landscapes/InputGrid.cs | src/Landscapes/InputGrid.cs | // Copyright 2005-2006 University of Wisconsin
// All rights reserved.
//
// Contributors:
// James Domingo, UW-Madison, Forest Landscape Ecology Lab
using Landis.SpatialModeling;
using System.Collections.Generic;
namespace Landis.Landscapes
{
/// <summary>
/// An input grid with data values.
/// </summary>
public class InputGrid<TData>
: Grid, IInputGrid<TData>
{
private IIndexableGrid<TData> data;
private Location currentLocation;
private bool disposed = false;
//---------------------------------------------------------------------
/// <summary>
/// Initializes a new instance using an indexable data grid.
/// </summary>
public InputGrid(IIndexableGrid<TData> dataGrid)
: base(dataGrid.Dimensions)
{
this.data = dataGrid;
// Initialize current location such that RowMajor.Next will return
// the upper left location (1,1).
this.currentLocation = new Location(1, 0);
}
//---------------------------------------------------------------------
/// <summary>
/// The type of data in the grid.
/// </summary>
public System.Type DataType {
get {
return typeof(TData);
}
}
//---------------------------------------------------------------------
public TData ReadValue()
{
if (disposed)
throw new System.ObjectDisposedException(GetType().FullName);
currentLocation = RowMajor.Next(currentLocation, Columns);
if (currentLocation.Row > Rows)
throw new System.IO.EndOfStreamException();
return data[currentLocation];
}
//---------------------------------------------------------------------
public void Close()
{
Dispose();
}
//---------------------------------------------------------------------
public void Dispose()
{
disposed = true;
}
}
}
| // Copyright 2005-2006 University of Wisconsin
// All rights reserved.
//
// The copyright holders license this file under the New (3-clause) BSD
// License (the "License"). You may not use this file except in
// compliance with the License. A copy of the License is available at
//
// http://www.opensource.org/licenses/BSD-3-Clause
//
// and is included in the NOTICE.txt file distributed with this work.
//
// Contributors:
// James Domingo, UW-Madison, Forest Landscape Ecology Lab
using Landis.SpatialModeling;
using System.Collections.Generic;
namespace Landis.Landscapes
{
/// <summary>
/// An input grid with data values.
/// </summary>
public class InputGrid<TData>
: Grid, IInputGrid<TData>
{
private IIndexableGrid<TData> data;
private Location currentLocation;
private bool disposed = false;
//---------------------------------------------------------------------
/// <summary>
/// Initializes a new instance using an indexable data grid.
/// </summary>
public InputGrid(IIndexableGrid<TData> dataGrid)
: base(dataGrid.Dimensions)
{
this.data = dataGrid;
// Initialize current location such that RowMajor.Next will return
// the upper left location (1,1).
this.currentLocation = new Location(1, 0);
}
//---------------------------------------------------------------------
/// <summary>
/// The type of data in the grid.
/// </summary>
public System.Type DataType {
get {
return typeof(TData);
}
}
//---------------------------------------------------------------------
public TData ReadValue()
{
if (disposed)
throw new System.ObjectDisposedException(GetType().FullName);
currentLocation = RowMajor.Next(currentLocation, Columns);
if (currentLocation.Row > Rows)
throw new System.IO.EndOfStreamException();
return data[currentLocation];
}
//---------------------------------------------------------------------
public void Close()
{
Dispose();
}
//---------------------------------------------------------------------
public void Dispose()
{
disposed = true;
}
}
}
| apache-2.0 | C# |
53f5b276b68778876fbbb69db01344cf18334295 | Clean up Paths | murador/xsp,stormleoxia/xsp,arthot/xsp,stormleoxia/xsp,stormleoxia/xsp,arthot/xsp,stormleoxia/xsp,arthot/xsp,murador/xsp,murador/xsp,arthot/xsp,murador/xsp | src/Mono.WebServer/Paths.cs | src/Mono.WebServer/Paths.cs | //
// Paths.cs
//
// Authors:
// Gonzalo Paniagua Javier ([email protected])
// Lluis Sanchez Gual ([email protected])
//
// Copyright (c) Copyright 2002-2007 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 System.Web;
using System.Web.Hosting;
namespace Mono.WebServer
{
public static class Paths
{
public static void GetPathsFromUri (IApplicationHost appHost, string verb, string uri, out string realUri, out string pathInfo)
{
// There's a hidden missing feature here... :)
realUri = uri; pathInfo = String.Empty;
string vpath = HttpRuntime.AppDomainAppVirtualPath;
int vpathLen = vpath.Length;
if (vpath [vpathLen - 1] != '/')
vpath += '/';
if (vpathLen > uri.Length)
return;
uri = uri.Substring (vpathLen);
while (uri.Length > 0 && uri [0] == '/')
uri = uri.Substring (1);
int lastSlash = uri.Length;
for (int dot = uri.LastIndexOf ('.'); dot > 0; dot = uri.LastIndexOf ('.', dot - 1)) {
int slash = uri.IndexOf ('/', dot);
if (slash == -1)
slash = lastSlash;
string partial = uri.Substring (0, slash);
lastSlash = slash;
if (!VirtualPathExists (appHost, verb, partial))
continue;
realUri = vpath + uri.Substring (0, slash);
pathInfo = uri.Substring (slash);
break;
}
}
static bool VirtualPathExists (IApplicationHost appHost, string verb, string uri)
{
if (appHost.IsHttpHandler (verb, uri))
return true;
VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;
return vpp != null && vpp.FileExists ("/" + uri);
}
}
}
| //
// Paths.cs
//
// Authors:
// Gonzalo Paniagua Javier ([email protected])
// Lluis Sanchez Gual ([email protected])
//
// Copyright (c) Copyright 2002-2007 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 System.Net;
using System.Net.Sockets;
using System.Xml;
using System.Web;
using System.Web.Hosting;
using System.Collections;
using System.Text;
using System.Threading;
using System.IO;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Collections.Generic;
namespace Mono.WebServer
{
public static class Paths
{
public static void GetPathsFromUri (IApplicationHost appHost, string verb, string uri, out string realUri, out string pathInfo)
{
// There's a hidden missing feature here... :)
realUri = uri; pathInfo = String.Empty;
string vpath = HttpRuntime.AppDomainAppVirtualPath;
int vpathLen = vpath.Length;
if (vpath [vpathLen - 1] != '/')
vpath += '/';
if (vpathLen > uri.Length)
return;
uri = uri.Substring (vpathLen);
while (uri.Length > 0 && uri [0] == '/')
uri = uri.Substring (1);
int dot, slash;
int lastSlash = uri.Length;
string partial;
for (dot = uri.LastIndexOf ('.'); dot > 0; dot = uri.LastIndexOf ('.', dot - 1)) {
slash = uri.IndexOf ('/', dot);
if (slash == -1)
slash = lastSlash;
partial = uri.Substring (0, slash);
lastSlash = slash;
if (!VirtualPathExists (appHost, verb, partial))
continue;
realUri = vpath + uri.Substring (0, slash);
pathInfo = uri.Substring (slash);
break;
}
}
static bool VirtualPathExists (IApplicationHost appHost, string verb, string uri)
{
if (appHost.IsHttpHandler (verb, uri))
return true;
VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;
if (vpp != null && vpp.FileExists ("/" + uri))
return true;
return false;
}
}
}
| mit | C# |
9b243ccc2346dfc134d6dbf62251765e3471dbc7 | Remove Hit500. | naoey/osu,smoogipoo/osu,default0/osu,peppy/osu,RedNesto/osu,UselessToucan/osu,smoogipooo/osu,naoey/osu,johnneijzen/osu,johnneijzen/osu,smoogipoo/osu,DrabWeb/osu,smoogipoo/osu,DrabWeb/osu,NeoAdonis/osu,ZLima12/osu,peppy/osu,NeoAdonis/osu,2yangk23/osu,DrabWeb/osu,EVAST9919/osu,osu-RP/osu-RP,UselessToucan/osu,NotKyon/lolisu,Drezi126/osu,EVAST9919/osu,peppy/osu-new,ppy/osu,ppy/osu,peppy/osu,2yangk23/osu,nyaamara/osu,tacchinotacchi/osu,ppy/osu,ZLima12/osu,NeoAdonis/osu,naoey/osu,theguii/osu,Nabile-Rahmani/osu,Frontear/osuKyzer,Damnae/osu,UselessToucan/osu | osu.Game.Mode.Osu/Objects/Drawables/DrawableOsuHitObject.cs | osu.Game.Mode.Osu/Objects/Drawables/DrawableOsuHitObject.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using osu.Game.Modes.Objects;
using osu.Game.Modes.Objects.Drawables;
namespace osu.Game.Modes.Osu.Objects.Drawables
{
public class DrawableOsuHitObject : DrawableHitObject
{
protected const float TIME_PREEMPT = 600;
protected const float TIME_FADEIN = 400;
protected const float TIME_FADEOUT = 500;
public DrawableOsuHitObject(OsuHitObject hitObject)
: base(hitObject)
{
}
public override JudgementInfo CreateJudgementInfo() => new OsuJudgementInfo();
protected override void UpdateState(ArmedState state)
{
if (!IsLoaded) return;
Flush(true);
UpdateInitialState();
Delay(HitObject.StartTime - Time.Current - TIME_PREEMPT + Judgement.TimeOffset, true);
UpdatePreemptState();
Delay(TIME_PREEMPT, true);
}
protected virtual void UpdatePreemptState()
{
FadeIn(TIME_FADEIN);
}
protected virtual void UpdateInitialState()
{
Alpha = 0;
}
}
public class OsuJudgementInfo : PositionalJudgementInfo
{
public OsuScoreResult Score;
public ComboResult Combo;
}
public enum ComboResult
{
[Description(@"")]
None,
[Description(@"Good")]
Good,
[Description(@"Amazing")]
Perfect
}
public enum OsuScoreResult
{
[Description(@"Miss")]
Miss,
[Description(@"50")]
Hit50,
[Description(@"100")]
Hit100,
[Description(@"300")]
Hit300,
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using osu.Game.Modes.Objects;
using osu.Game.Modes.Objects.Drawables;
namespace osu.Game.Modes.Osu.Objects.Drawables
{
public class DrawableOsuHitObject : DrawableHitObject
{
protected const float TIME_PREEMPT = 600;
protected const float TIME_FADEIN = 400;
protected const float TIME_FADEOUT = 500;
public DrawableOsuHitObject(OsuHitObject hitObject)
: base(hitObject)
{
}
public override JudgementInfo CreateJudgementInfo() => new OsuJudgementInfo();
protected override void UpdateState(ArmedState state)
{
if (!IsLoaded) return;
Flush(true);
UpdateInitialState();
Delay(HitObject.StartTime - Time.Current - TIME_PREEMPT + Judgement.TimeOffset, true);
UpdatePreemptState();
Delay(TIME_PREEMPT, true);
}
protected virtual void UpdatePreemptState()
{
FadeIn(TIME_FADEIN);
}
protected virtual void UpdateInitialState()
{
Alpha = 0;
}
}
public class OsuJudgementInfo : PositionalJudgementInfo
{
public OsuScoreResult Score;
public ComboResult Combo;
}
public enum ComboResult
{
[Description(@"")]
None,
[Description(@"Good")]
Good,
[Description(@"Amazing")]
Perfect
}
public enum OsuScoreResult
{
[Description(@"Miss")]
Miss,
[Description(@"50")]
Hit50,
[Description(@"100")]
Hit100,
[Description(@"300")]
Hit300,
[Description(@"500")]
Hit500
}
}
| mit | C# |
85f86ca094ba71c0c4c9d1e292b33ab00684b802 | Allow BaseUnit accessibility | Stratajet/UnitConversion | UnitConversion/Base/UnitFactors.cs | UnitConversion/Base/UnitFactors.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace UnitConversion.Base {
public class UnitFactors : Dictionary<UnitFactorSynonyms, double> {
public UnitFactors(string baseUnit) {
BaseUnit = baseUnit;
}
private string _baseUnit;
public string BaseUnit {
get {
return _baseUnit;
}
private set {
_baseUnit = value;
}
}
// Find the key or null for a given unit
internal UnitFactorSynonyms FindUnit(UnitFactorSynonyms synonyms) {
return this.Keys.FirstOrDefault(factor => factor.Contains(synonyms));
}
// Get the factor for a given unit
internal double FindFactor(UnitFactorSynonyms synonyms) {
var unit = this.FirstOrDefault(factor => factor.Key.Contains(synonyms));
if (unit.Key == null) {
throw new UnitNotSupportedException(synonyms.ToString());
}
return unit.Value;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace UnitConversion.Base {
public class UnitFactors : Dictionary<UnitFactorSynonyms, double> {
public UnitFactors(string baseUnit) {
BaseUnit = baseUnit;
}
protected string BaseUnit;
// Find the key or null for a given unit
internal UnitFactorSynonyms FindUnit(UnitFactorSynonyms synonyms) {
return this.Keys.FirstOrDefault(factor => factor.Contains(synonyms));
}
// Get the factor for a given unit
internal double FindFactor(UnitFactorSynonyms synonyms) {
var unit = this.FirstOrDefault(factor => factor.Key.Contains(synonyms));
if (unit.Key == null) {
throw new UnitNotSupportedException(synonyms.ToString());
}
return unit.Value;
}
}
}
| mit | C# |
76f766c6d2ebacf8a939fd8c1c4aabad3311dd31 | Remove badges from tabs | eatplayhate/versionr,eatplayhate/versionr,eatplayhate/versionr,eatplayhate/versionr,eatplayhate/versionr,eatplayhate/versionr,eatplayhate/versionr | VersionrWeb/Views/_RepoTabs.cshtml | VersionrWeb/Views/_RepoTabs.cshtml | @helper Active(string tab) {
if (tab == ViewBag.RepoTab) {
@:active
}
}
<div class="header-wrapper">
<div class="ui container"><!-- start container -->
<div class="ui vertically padded grid head"><!-- start grid -->
<div class="column"><!-- start column -->
<div class="ui header">
<div class="ui huge breadcrumb">
<i class="mega-octicon octicon-repo"></i>
@*<a href="{{AppSubUrl}}/{{.Owner.Name}}">{{.Owner.Name}}</a>
<div class="divider"> / </div>*@
<a href="/">@ViewBag.RepositoryName</a>
</div>
</div>
</div><!-- end column -->
</div><!-- end grid -->
</div><!-- end container -->
<div class="ui tabs container">
<div class="ui tabular menu navbar">
<a class="item @Active("src")" href="/src">
<i class="icon octicon octicon-code"></i> Code
</a>
<a class="item @Active("log")" href="/log"> @* TODO add branch to href *@
<i class="icon octicon octicon-history"></i> Commits
</a>
<a class="item @Active("tags")" href="/tags">
<i class="icon octicon octicon-tag"></i> Tags
</a>
</div>
</div>
<div class="ui tabs divider"></div>
</div>
| @helper Active(string tab) {
if (tab == ViewBag.RepoTab) {
@:active
}
}
<div class="header-wrapper">
<div class="ui container"><!-- start container -->
<div class="ui vertically padded grid head"><!-- start grid -->
<div class="column"><!-- start column -->
<div class="ui header">
<div class="ui huge breadcrumb">
<i class="mega-octicon octicon-repo"></i>
@*<a href="{{AppSubUrl}}/{{.Owner.Name}}">{{.Owner.Name}}</a>
<div class="divider"> / </div>*@
<a href="/">@ViewBag.RepositoryName</a>
</div>
</div>
</div><!-- end column -->
</div><!-- end grid -->
</div><!-- end container -->
<div class="ui tabs container">
<div class="ui tabular menu navbar">
<a class="item @Active("src")" href="/src">
<i class="icon octicon octicon-code"></i> Code
</a>
<a class="item @Active("log")" href="/log"> @* TODO add branch to href *@
<i class="icon octicon octicon-history"></i> Commits <span class="ui blue small label">123 @* commit count *@</span>
</a>
<a class="item @Active("tags")" href="/tags">
<i class="icon octicon octicon-tag"></i> Tags <span class="ui gray small label">0</span>
</a>
</div>
</div>
<div class="ui tabs divider"></div>
</div>
| apache-2.0 | C# |
4cef88d9724126e203611e7e774cf6581b1ae7f6 | Increment version | Abc-Arbitrage/ZeroLog | ZeroLog/Properties/AssemblyInfo.cs | ZeroLog/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ZeroLog")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ZeroLog")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("34665a87-497b-4c4e-928e-1dfbeb3f7441")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.4")]
[assembly: AssemblyFileVersion("1.0.0.4")]
[assembly:InternalsVisibleTo("ZeroLog.Tests")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ZeroLog")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ZeroLog")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("34665a87-497b-4c4e-928e-1dfbeb3f7441")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.3")]
[assembly: AssemblyFileVersion("1.0.0.3")]
[assembly:InternalsVisibleTo("ZeroLog.Tests")]
| mit | C# |
0f335da140bb6b6243ed600741b390ace42c80cd | Use JSON.NET exceptions when unable to parse | cronofy/cronofy-csharp | src/Cronofy/EventTimeConvertor.cs | src/Cronofy/EventTimeConvertor.cs | using System;
using Newtonsoft.Json;
using System.Globalization;
using Newtonsoft.Json.Linq;
namespace Cronofy
{
internal sealed class EventTimeConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return false;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.String)
{
var value = (string)reader.Value;
DateTimeOffset dtoResult;
if (DateTimeOffset.TryParseExact(value, "yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out dtoResult))
{
return new EventTime(dtoResult, "Etc/UTC");
}
Date dateResult;
if (Date.TryParse(value, out dateResult))
{
return new EventTime(dateResult, "Etc/UTC");
}
throw new JsonSerializationException("Failed to parse " + value);
}
if (reader.TokenType == JsonToken.StartObject)
{
var jobject = JObject.Load(reader);
var timeString = jobject.GetValue("time").Value<string>();
var timeZoneId = jobject.GetValue("tzid").Value<string>();
DateTimeOffset dtoResult;
if (DateTimeOffset.TryParseExact(timeString, new [] { "yyyy-MM-ddTHH:mm:ssZ", "yyyy-MM-ddTHH:mm:sszzz" }, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out dtoResult))
{
return new EventTime(dtoResult, timeZoneId);
}
Date dateResult;
if (Date.TryParse(timeString, out dateResult))
{
return new EventTime(dateResult, timeZoneId);
}
throw new JsonSerializationException("Failed to parse " + jobject);
}
throw new JsonSerializationException("Failed to parse " + reader.TokenType);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var eventTime = value as EventTime;
if (eventTime == null)
{
return;
}
writer.WriteStartObject();
writer.WritePropertyName("time");
if (eventTime.HasTime)
{
writer.WriteValue(eventTime.DateTimeOffset.ToString("u"));
}
else
{
writer.WriteValue(eventTime.Date.ToString());
}
writer.WritePropertyName("tzid");
writer.WriteValue(eventTime.TimeZoneId);
writer.WriteEndObject();
}
}
}
| using System;
using Newtonsoft.Json;
using System.Globalization;
using Newtonsoft.Json.Linq;
namespace Cronofy
{
internal sealed class EventTimeConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return false;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.String)
{
var value = (string)reader.Value;
DateTimeOffset dtoResult;
if (DateTimeOffset.TryParseExact(value, "yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out dtoResult))
{
return new EventTime(dtoResult, "Etc/UTC");
}
Date dateResult;
if (Date.TryParse(value, out dateResult))
{
return new EventTime(dateResult, "Etc/UTC");
}
throw new NotImplementedException("Failed to parse " + value);
}
if (reader.TokenType == JsonToken.StartObject)
{
var jobject = JObject.Load(reader);
var timeString = jobject.GetValue("time").Value<string>();
var timeZoneId = jobject.GetValue("tzid").Value<string>();
DateTimeOffset dtoResult;
if (DateTimeOffset.TryParseExact(timeString, new [] { "yyyy-MM-ddTHH:mm:ssZ", "yyyy-MM-ddTHH:mm:sszzz" }, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out dtoResult))
{
return new EventTime(dtoResult, timeZoneId);
}
Date dateResult;
if (Date.TryParse(timeString, out dateResult))
{
return new EventTime(dateResult, timeZoneId);
}
throw new NotImplementedException("Failed to parse " + jobject);
}
throw new NotImplementedException("Failed to parse " + reader.TokenType);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var eventTime = value as EventTime;
if (eventTime == null)
{
return;
}
writer.WriteStartObject();
writer.WritePropertyName("time");
if (eventTime.HasTime)
{
writer.WriteValue(eventTime.DateTimeOffset.ToString("u"));
}
else
{
writer.WriteValue(eventTime.Date.ToString());
}
writer.WritePropertyName("tzid");
writer.WriteValue(eventTime.TimeZoneId);
writer.WriteEndObject();
}
}
}
| mit | C# |
684981641576163db167420e177f5b7bd7cc1b1a | Check if JsonPathSettings null before returning resolver | myquay/JsonPatch | src/JsonPatch/Paths/PathHelper.cs | src/JsonPatch/Paths/PathHelper.cs | using System;
using JsonPatch.Formatting;
using JsonPatch.Paths.Components;
using JsonPatch.Paths.Resolvers;
namespace JsonPatch.Paths
{
public class PathHelper
{
internal static IPathResolver PathResolver
{
get
{
return JsonPatchFormatter.Settings == null
? JsonPatchSettings.DefaultPatchSettings().PathResolver
: JsonPatchFormatter.Settings.PathResolver;
}
}
#region Parse/Validate Paths
public static bool IsPathValid(Type entityType, string path)
{
try
{
ParsePath(path, entityType);
return true;
}
catch (JsonPatchParseException)
{
return false;
}
}
public static PathComponent[] ParsePath(string path, Type entityType)
{
return PathResolver.ParsePath(path, entityType);
}
#endregion
#region GetValueFromPath
public static object GetValueFromPath(Type entityType, string path, object entity)
{
return GetValueFromPath(entityType, ParsePath(path, entityType), entity);
}
public static object GetValueFromPath(Type entityType, PathComponent[] pathComponents, object entity)
{
return PathResolver.GetValueFromPath(entityType, pathComponents, entity);
}
#endregion
#region SetValueFromPath
public static void SetValueFromPath(Type entityType, string path, object entity, object value, JsonPatchOperationType operationType)
{
SetValueFromPath(entityType, ParsePath(path, entityType), entity, value, operationType);
}
public static void SetValueFromPath(Type entityType, PathComponent[] pathComponents, object entity, object value, JsonPatchOperationType operationType)
{
PathResolver.SetValueFromPath(entityType, pathComponents, entity, value, operationType);
}
#endregion
}
}
| using System;
using JsonPatch.Formatting;
using JsonPatch.Paths.Components;
using JsonPatch.Paths.Resolvers;
namespace JsonPatch.Paths
{
public class PathHelper
{
internal static IPathResolver PathResolver
{
get { return JsonPatchFormatter.Settings.PathResolver; }
}
#region Parse/Validate Paths
public static bool IsPathValid(Type entityType, string path)
{
try
{
ParsePath(path, entityType);
return true;
}
catch (JsonPatchParseException)
{
return false;
}
}
public static PathComponent[] ParsePath(string path, Type entityType)
{
return PathResolver.ParsePath(path, entityType);
}
#endregion
#region GetValueFromPath
public static object GetValueFromPath(Type entityType, string path, object entity)
{
return GetValueFromPath(entityType, ParsePath(path, entityType), entity);
}
public static object GetValueFromPath(Type entityType, PathComponent[] pathComponents, object entity)
{
return PathResolver.GetValueFromPath(entityType, pathComponents, entity);
}
#endregion
#region SetValueFromPath
public static void SetValueFromPath(Type entityType, string path, object entity, object value, JsonPatchOperationType operationType)
{
SetValueFromPath(entityType, ParsePath(path, entityType), entity, value, operationType);
}
public static void SetValueFromPath(Type entityType, PathComponent[] pathComponents, object entity, object value, JsonPatchOperationType operationType)
{
PathResolver.SetValueFromPath(entityType, pathComponents, entity, value, operationType);
}
#endregion
}
}
| mit | C# |
e9e76a2f3d18500f245674ca29f4bde6b7986e91 | Bump version to 0.2 | Gohla/renegadex-launcher | RXL.WPFClient/Properties/AssemblyInfo.cs | RXL.WPFClient/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RenegadeX Alternative Launcher")]
[assembly: AssemblyDescription("RenegadeX Alternative Launcher")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RXL")]
[assembly: AssemblyCopyright("Copyright © Gabriël Konat, Hans Harts 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.2.0.0")]
[assembly: AssemblyFileVersion("0.2.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RenegadeX Alternative Launcher")]
[assembly: AssemblyDescription("RenegadeX Alternative Launcher")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RXL")]
[assembly: AssemblyCopyright("Copyright © Gabriël Konat, Hans Harts 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.3.0")]
[assembly: AssemblyFileVersion("0.1.3.0")]
| mit | C# |
e2b119ce66ddde08721c2dfd817a4e3651365bb7 | Move it to the right schedule | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Jobs/JobHandler.cs | Battery-Commander.Web/Jobs/JobHandler.cs | using BatteryCommander.Web.Models;
using FluentScheduler;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Logging;
using System;
namespace BatteryCommander.Web.Jobs
{
internal static class JobHandler
{
public static void UseJobScheduler(this IApplicationBuilder app, ILoggerFactory loggerFactory)
{
var logger = loggerFactory.CreateLogger(typeof(JobHandler));
JobManager.JobStart += (job) => logger.LogInformation("{job} started", job.Name);
JobManager.JobEnd += (job) => logger.LogInformation("{job} completed in {time}", job.Name, job.Duration);
JobManager.JobException += (context) => logger.LogError(context.Exception, "{job} failed", context.Name);
JobManager.UseUtcTime();
JobManager.JobFactory = new JobFactory(app.ApplicationServices);
var registry = new Registry();
registry.Schedule<SqliteBackupJob>().ToRunEvery(1).Days().At(hours: 11, minutes: 0);
registry.Schedule<EvaluationDueReminderJob>().ToRunEvery(0).Weeks().On(DayOfWeek.Tuesday).At(hours: 13, minutes: 0);
registry.Schedule<PERSTATReportJob>().ToRunEvery(1).Days().At(hours: 6 + ExtensionMethods.EASTERN_TIME.BaseUtcOffset.Hours, minutes: 30); // 0630 EST
JobManager.Initialize(registry);
}
private class JobFactory : IJobFactory
{
private readonly IServiceProvider serviceProvider;
public JobFactory(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
}
public IJob GetJobInstance<T>() where T : IJob
{
return serviceProvider.GetService(typeof(T)) as IJob;
}
}
}
} | using BatteryCommander.Web.Models;
using FluentScheduler;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Logging;
using System;
namespace BatteryCommander.Web.Jobs
{
internal static class JobHandler
{
public static void UseJobScheduler(this IApplicationBuilder app, ILoggerFactory loggerFactory)
{
var logger = loggerFactory.CreateLogger(typeof(JobHandler));
JobManager.JobStart += (job) => logger.LogInformation("{job} started", job.Name);
JobManager.JobEnd += (job) => logger.LogInformation("{job} completed in {time}", job.Name, job.Duration);
JobManager.JobException += (context) => logger.LogError(context.Exception, "{job} failed", context.Name);
JobManager.UseUtcTime();
JobManager.JobFactory = new JobFactory(app.ApplicationServices);
var registry = new Registry();
registry.Schedule<SqliteBackupJob>().ToRunEvery(1).Days().At(hours: 11, minutes: 0);
registry.Schedule<EvaluationDueReminderJob>().ToRunEvery(0).Weeks().On(DayOfWeek.Tuesday).At(hours: 13, minutes: 0);
registry.Schedule<PERSTATReportJob>().ToRunNow();
// registry.Schedule<PERSTATReportJob>().ToRunEvery(1).Days().At(hours: 6 + ExtensionMethods.EASTERN_TIME.BaseUtcOffset.Hours, minutes: 30); // 0630 EST
JobManager.Initialize(registry);
}
private class JobFactory : IJobFactory
{
private readonly IServiceProvider serviceProvider;
public JobFactory(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
}
public IJob GetJobInstance<T>() where T : IJob
{
return serviceProvider.GetService(typeof(T)) as IJob;
}
}
}
}
| mit | C# |
e11c48ef70bf662d8e39996b4017bcc9598b39b0 | Update Polygon.cs | TeamnetGroup/cap-net,darbio/cap-net | src/CAPNet/Models/Polygon.cs | src/CAPNet/Models/Polygon.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CAPNet.Models
{
/// <summary>
///
/// </summary>
public class Polygon
{
/// <summary>
///
/// </summary>
private IEnumerable<Coordinate> coordinates;
/// <summary>
///
/// </summary>
public IEnumerable<Coordinate> Coordinates
{
get { return coordinates; }
private set { coordinates = value; }
}
/// <summary>
///
/// </summary>
/// <param name="stringRepresentation">The geographic polygon is represented by a whitespace-delimited list of [WGS 84] coordinate pairs</param>
public Polygon(string stringRepresentation)
{
var stringCoordinates = stringRepresentation.Split(' ');
coordinates = from coordinate in stringCoordinates
select new Coordinate(coordinate);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Join(" ", coordinates);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CAPNet.Models
{
/// <summary>
///
/// </summary>
public class Polygon
{
/// <summary>
///
/// </summary>
private IEnumerable<Coordinate> coordinates;
/// <summary>
///
/// </summary>
public IEnumerable<Coordinate> Coordinates
{
get { return coordinates; }
private set { coordinates = value; }
}
/// <summary>
///
/// </summary>
/// <param name="stringRepresentation">The geographic polygon is represented by a whitespace-delimited list of [WGS 84] coordinate pairs</param>
public Polygon(string stringRepresentation)
{
var stringCoordinates = stringRepresentation.Split(' ');
coordinates = from coordinate in stringCoordinates
select new Coordinate(coordinate);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Join(" ", coordinates);
}
}
}
| mit | C# |
8a34692e7c4f7ec00cefd3bb79873cb194bae71a | switch device type around to match mobile enums | bitwarden/core,bitwarden/core,bitwarden/core,bitwarden/core | src/Core/Enums/DeviceType.cs | src/Core/Enums/DeviceType.cs | namespace Bit.Core.Enums
{
public enum DeviceType : short
{
Android = 0,
iOS = 1
}
}
| namespace Bit.Core.Enums
{
public enum DeviceType : short
{
iOS = 0,
Android = 1
}
}
| agpl-3.0 | C# |
5bd9147661c4cace5dfa61bbf1756b3ac94307cf | Remove CreateCircle() - hitobjects should handle the addition of this to their hierarchy themselves. | osu-RP/osu-RP,2yangk23/osu,Frontear/osuKyzer,EVAST9919/osu,naoey/osu,RedNesto/osu,UselessToucan/osu,johnneijzen/osu,smoogipooo/osu,peppy/osu,peppy/osu-new,DrabWeb/osu,2yangk23/osu,tacchinotacchi/osu,Drezi126/osu,naoey/osu,ppy/osu,peppy/osu,naoey/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,Nabile-Rahmani/osu,UselessToucan/osu,EVAST9919/osu,smoogipoo/osu,ZLima12/osu,johnneijzen/osu,DrabWeb/osu,peppy/osu,ppy/osu,ppy/osu,smoogipoo/osu,ZLima12/osu,NeoAdonis/osu,nyaamara/osu,DrabWeb/osu,Damnae/osu,NeoAdonis/osu | osu.Game.Modes.Taiko/Objects/Drawable/DrawableTaikoHitObject.cs | osu.Game.Modes.Taiko/Objects/Drawable/DrawableTaikoHitObject.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics;
using osu.Game.Modes.Objects.Drawables;
using osu.Game.Modes.Taiko.Judgements;
namespace osu.Game.Modes.Taiko.Objects.Drawable
{
public abstract class DrawableTaikoHitObject : DrawableHitObject<TaikoHitObject, TaikoJudgement>
{
protected DrawableTaikoHitObject(TaikoHitObject hitObject)
: base(hitObject)
{
Anchor = Anchor.CentreLeft;
Origin = Anchor.Centre;
RelativePositionAxes = Axes.X;
}
protected override void LoadComplete()
{
LifetimeStart = HitObject.StartTime - HitObject.PreEmpt * 2;
LifetimeEnd = HitObject.StartTime + HitObject.PreEmpt;
base.LoadComplete();
}
protected override TaikoJudgement CreateJudgement() => new TaikoJudgement();
/// <summary>
/// Sets the scroll position of the DrawableHitObject relative to the offset between
/// a time value and the HitObject's StartTime.
/// </summary>
/// <param name="time"></param>
protected virtual void UpdateScrollPosition(double time)
{
MoveToX((float)((HitObject.StartTime - time) / HitObject.PreEmpt));
}
protected override void Update()
{
UpdateScrollPosition(Time.Current);
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics;
using osu.Game.Modes.Objects.Drawables;
using osu.Game.Modes.Taiko.Judgements;
using osu.Game.Modes.Taiko.Objects.Drawable.Pieces;
namespace osu.Game.Modes.Taiko.Objects.Drawable
{
public abstract class DrawableTaikoHitObject : DrawableHitObject<TaikoHitObject, TaikoJudgement>
{
protected DrawableTaikoHitObject(TaikoHitObject hitObject)
: base(hitObject)
{
Anchor = Anchor.CentreLeft;
Origin = Anchor.Centre;
RelativePositionAxes = Axes.X;
Children = new[]
{
CreateCircle()
};
}
protected override void LoadComplete()
{
LifetimeStart = HitObject.StartTime - HitObject.PreEmpt * 2;
LifetimeEnd = HitObject.StartTime + HitObject.PreEmpt;
base.LoadComplete();
}
protected override TaikoJudgement CreateJudgement() => new TaikoJudgement();
/// <summary>
/// Sets the scroll position of the DrawableHitObject relative to the offset between
/// a time value and the HitObject's StartTime.
/// </summary>
/// <param name="time"></param>
protected virtual void UpdateScrollPosition(double time)
{
MoveToX((float)((HitObject.StartTime - time) / HitObject.PreEmpt));
}
protected override void Update()
{
UpdateScrollPosition(Time.Current);
}
protected abstract CirclePiece CreateCircle();
}
}
| mit | C# |
82fe87132808e035f799b63b85ebcf552eef8792 | change version number | takenet/lime-csharp | src/Lime.Client.TestConsole/Properties/AssemblyInfo.cs | src/Lime.Client.TestConsole/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Lime.Client.TestConsole")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lime.Client.TestConsole")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.11.0.0")]
[assembly: AssemblyFileVersion("0.11.0.0")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Lime.Client.TestConsole")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lime.Client.TestConsole")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.10.0.0")]
[assembly: AssemblyFileVersion("0.10.0.0")]
| apache-2.0 | C# |
baef98b467e84ca78bffb468f9f134964c50b4dc | Fix naming | mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection | src/Cash-Flow-Projection/Views/Home/Index.cshtml | src/Cash-Flow-Projection/Views/Home/Index.cshtml | @model Cash_Flow_Projection.Models.Dashboard
@{
ViewData["Title"] = "Home Page";
}
@using (Html.BeginForm("Balance", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
<input type="text" name="balance" placeholder="Set Balance" />
<button type="submit">Set</button>
}
<table class="table table-striped">
@foreach (var entry in Model.Entries.OrderBy(_ => _.Date))
{
<tr>
<td>@Html.DisplayFor(_ => entry.Date)</td>
<td>@Html.DisplayFor(_ => entry.Description)</td>
<td>@Html.DisplayFor(_ => entry.Amount)</td>
<td>@Cash_Flow_Projection.Models.Balance.BalanceAsOf(Model.Entries, entry.Date)</td>
<td>
@using (Html.BeginForm("Delete", "Home", new { id = entry.id }, FormMethod.Post))
{
@Html.AntiForgeryToken()
<button type="submit">Delete</button>
}
</td>
</tr>
}
</table> | @model Cash_Flow_Projection.Models.Dashboard
@{
ViewData["Title"] = "Home Page";
}
@using (Html.BeginForm("Balance", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
<input type="text" id="balance" placeholder="Set Balance" />
<button type="submit">Set</button>
}
<table class="table table-striped">
@foreach (var entry in Model.Entries.OrderBy(_ => _.Date))
{
<tr>
<td>@Html.DisplayFor(_ => entry.Date)</td>
<td>@Html.DisplayFor(_ => entry.Description)</td>
<td>@Html.DisplayFor(_ => entry.Amount)</td>
<td>@Cash_Flow_Projection.Models.Balance.BalanceAsOf(Model.Entries, entry.Date)</td>
<td>
@using (Html.BeginForm("Delete", "Home", new { id = entry.id }, FormMethod.Post))
{
@Html.AntiForgeryToken()
<button type="submit">Delete</button>
}
</td>
</tr>
}
</table> | mit | C# |
8e356ca2b4f216559061747534d1422a542c55f5 | Fix default log level filter | mattwcole/gelf-extensions-logging | src/Gelf.Extensions.Logging/GelfLoggerOptions.cs | src/Gelf.Extensions.Logging/GelfLoggerOptions.cs | using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
namespace Gelf.Extensions.Logging
{
public class GelfLoggerOptions
{
public GelfLoggerOptions()
{
Filter = (name, level) => level >= LogLevel;
}
/// <summary>
/// GELF server host.
/// </summary>
public string Host { get; set; }
/// <summary>
/// GELF server port.
/// </summary>
public int Port { get; set; } = 12201;
/// <summary>
/// Log source name mapped to the GELF host field.
/// </summary>
public string LogSource { get; set; }
/// <summary>
/// Enable GZip message compression.
/// </summary>
public bool Compress { get; set; } = true;
/// <summary>
/// The message size in bytes under which messages will not be compressed.
/// </summary>
public int CompressionThreshold { get; set; } = 512;
/// <summary>
/// Function used to filter log events based on logger name and level. Uses <see cref="LogLevel"/> by default.
/// </summary>
public Func<string, LogLevel, bool> Filter { get; set; }
/// <summary>
/// The defualt log level.
/// </summary>
public LogLevel LogLevel { get; set; } = LogLevel.Information;
/// <summary>
/// Additional fields that will be attached to all log messages.
/// </summary>
public Dictionary<string, string> AdditionalFields { get; } = new Dictionary<string, string>();
}
}
| using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
namespace Gelf.Extensions.Logging
{
public class GelfLoggerOptions
{
public GelfLoggerOptions()
{
Filter = (name, level) => level > LogLevel;
}
/// <summary>
/// GELF server host.
/// </summary>
public string Host { get; set; }
/// <summary>
/// GELF server port.
/// </summary>
public int Port { get; set; } = 12201;
/// <summary>
/// Log source name mapped to the GELF host field.
/// </summary>
public string LogSource { get; set; }
/// <summary>
/// Enable GZip message compression.
/// </summary>
public bool Compress { get; set; } = true;
/// <summary>
/// The message size in bytes under which messages will not be compressed.
/// </summary>
public int CompressionThreshold { get; set; } = 512;
/// <summary>
/// Function used to filter log events based on logger name and level. Uses <see cref="LogLevel"/> by default.
/// </summary>
public Func<string, LogLevel, bool> Filter { get; set; }
/// <summary>
/// The defualt log level.
/// </summary>
public LogLevel LogLevel { get; set; } = LogLevel.Information;
/// <summary>
/// Additional fields that will be attached to all log messages.
/// </summary>
public Dictionary<string, string> AdditionalFields { get; } = new Dictionary<string, string>();
}
}
| mit | C# |
ab9317b5d2669d4eda964ff7062bad8da0dc074f | Remove visibility of internals for test project. | oliverzick/ImmutableUndoRedo | src/ImmutableUndoRedo/Properties/AssemblyInfo.cs | src/ImmutableUndoRedo/Properties/AssemblyInfo.cs | #region Copyright and license
// <copyright file="AssemblyInfo.cs" company="Oliver Zick">
// Copyright (c) 2015 Oliver Zick. All rights reserved.
// </copyright>
// <author>Oliver Zick</author>
// <license>
// 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.
// </license>
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("ImmutableUndoRedo")]
[assembly: AssemblyDescription("A lightweight, flexible and easy to use do/undo/redo implementation based on immutable objects for .NET.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ImmutableUndoRedo")]
[assembly: AssemblyCopyright("Copyright © 2015 Oliver Zick. All rights reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: Guid("ef605850-4540-4e3a-9e71-cc10385d94c7")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.1.1.0")] | #region Copyright and license
// <copyright file="AssemblyInfo.cs" company="Oliver Zick">
// Copyright (c) 2015 Oliver Zick. All rights reserved.
// </copyright>
// <author>Oliver Zick</author>
// <license>
// 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.
// </license>
#endregion
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("ImmutableUndoRedo")]
[assembly: AssemblyDescription("A lightweight, flexible and easy to use do/undo/redo implementation based on immutable objects for .NET.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ImmutableUndoRedo")]
[assembly: AssemblyCopyright("Copyright © 2015 Oliver Zick. All rights reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: Guid("ef605850-4540-4e3a-9e71-cc10385d94c7")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.1.1.0")]
[assembly: InternalsVisibleTo("ImmutableUndoRedo.Test")] | apache-2.0 | C# |
58808f838ae3be9776cd1b6d966ff73a08895f54 | Update AssemblyFileVersion to 1.0.1.0 | oliverzick/ImmutableUndoRedo | src/ImmutableUndoRedo/Properties/AssemblyInfo.cs | src/ImmutableUndoRedo/Properties/AssemblyInfo.cs | #region Copyright and license
// <copyright file="AssemblyInfo.cs" company="Oliver Zick">
// Copyright (c) 2015 Oliver Zick. All rights reserved.
// </copyright>
// <author>Oliver Zick</author>
// <license>
// 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.
// </license>
#endregion
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("ImmutableUndoRedo")]
[assembly: AssemblyDescription("A lightweight, flexible and easy to use do/undo/redo implementation based on immutable objects for .NET.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ImmutableUndoRedo")]
[assembly: AssemblyCopyright("Copyright © 2015 Oliver Zick. All rights reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: Guid("ef605850-4540-4e3a-9e71-cc10385d94c7")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: InternalsVisibleTo("ImmutableUndoRedo.Test")] | #region Copyright and license
// <copyright file="AssemblyInfo.cs" company="Oliver Zick">
// Copyright (c) 2015 Oliver Zick. All rights reserved.
// </copyright>
// <author>Oliver Zick</author>
// <license>
// 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.
// </license>
#endregion
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("ImmutableUndoRedo")]
[assembly: AssemblyDescription("A lightweight, flexible and easy to use do/undo/redo implementation based on immutable objects for .NET.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ImmutableUndoRedo")]
[assembly: AssemblyCopyright("Copyright © 2015 Oliver Zick. All rights reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: Guid("ef605850-4540-4e3a-9e71-cc10385d94c7")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("ImmutableUndoRedo.Test")] | apache-2.0 | C# |
9a38bdbd74d69cb51d4cf4bfc3d1fa32a4c3d5ab | Disable validation on read-only table and card views. | IntelliTect/Coalesce,IntelliTect/Coalesce,IntelliTect/Coalesce,IntelliTect/Coalesce | src/IntelliTect.Coalesce/Helpers/ScriptHelper.cs | src/IntelliTect.Coalesce/Helpers/ScriptHelper.cs | using Microsoft.AspNetCore.Html;
using System.Text;
using IntelliTect.Coalesce.TypeDefinition;
namespace IntelliTect.Coalesce.Helpers
{
public static class ScriptHelper
{
public static HtmlString StandardBinding<T>()
{
return StandardBinding(ReflectionRepository.GetClassViewModel<T>());
}
public static HtmlString StandardBinding(ClassViewModel model)
{
var html = new StringBuilder();
html.AppendLine($@"
<script>
@if (!ViewBag.Editable)
{{
@:Coalesce.GlobalConfiguration.viewModel.setupValidationAutomatically(false);
}}
var {model.ListViewModelObjectName} = new ListViewModels.{model.ListViewModelClassName}();
// Set up parent info based on the URL.
@if (ViewBag.Query != null)
{{
@:{model.ListViewModelObjectName}.queryString = ""@(ViewBag.Query)"";
}}
// Save and restore values from the URL:
var urlVariables = ['page', 'pageSize', 'search'];
$.each(urlVariables, function(){{
var param = Coalesce.Utilities.GetUrlParameter(this);
if (param) {{{model.ListViewModelObjectName}[this](param);}}
}})
{ model.ListViewModelObjectName}.isLoading.subscribe(function(){{
var newUrl = window.location.href;
$.each(urlVariables, function(){{
var param = {model.ListViewModelObjectName}[this]();
newUrl = Coalesce.Utilities.SetUrlParameter(newUrl, this, param);
}})
history.replaceState(null, document.title, newUrl);
}});
{ model.ListViewModelObjectName}.isSavingAutomatically = false;
ko.applyBindings({model.ListViewModelObjectName});
{model.ListViewModelObjectName}.isSavingAutomatically = true;
{model.ListViewModelObjectName}.includes = ""{model.ListViewModelClassName}Gen"";
{ model.ListViewModelObjectName}.load();
</script>");
return new HtmlString(html.ToString());
}
}
}
| using Microsoft.AspNetCore.Html;
using System.Text;
using IntelliTect.Coalesce.TypeDefinition;
namespace IntelliTect.Coalesce.Helpers
{
public static class ScriptHelper
{
public static HtmlString StandardBinding<T>()
{
return StandardBinding(ReflectionRepository.GetClassViewModel<T>());
}
public static HtmlString StandardBinding(ClassViewModel model)
{
var html = new StringBuilder();
html.AppendLine($@"
<script>
var {model.ListViewModelObjectName} = new ListViewModels.{model.ListViewModelClassName}();
// Set up parent info based on the URL.
@if (ViewBag.Query != null)
{{
@:{model.ListViewModelObjectName}.queryString = ""@(ViewBag.Query)"";
}}
// Save and restore values from the URL:
var urlVariables = ['page', 'pageSize', 'search'];
$.each(urlVariables, function(){{
var param = Coalesce.Utilities.GetUrlParameter(this);
if (param) {{{model.ListViewModelObjectName}[this](param);}}
}})
{ model.ListViewModelObjectName}.isLoading.subscribe(function(){{
var newUrl = window.location.href;
$.each(urlVariables, function(){{
var param = {model.ListViewModelObjectName}[this]();
newUrl = Coalesce.Utilities.SetUrlParameter(newUrl, this, param);
}})
history.replaceState(null, document.title, newUrl);
}});
{ model.ListViewModelObjectName}.isSavingAutomatically = false;
ko.applyBindings({model.ListViewModelObjectName});
{model.ListViewModelObjectName}.isSavingAutomatically = true;
{model.ListViewModelObjectName}.includes = ""{model.ListViewModelClassName}Gen"";
{ model.ListViewModelObjectName}.load();
</script>");
return new HtmlString(html.ToString());
}
}
}
| apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.