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 |
---|---|---|---|---|---|---|---|---|
74c849cf0d8afb5ef4b49033abac03eab2a88973
|
Bump version to 0.9.7
|
ar3cka/Journalist
|
src/SolutionInfo.cs
|
src/SolutionInfo.cs
|
// <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.9.7")]
[assembly: AssemblyInformationalVersionAttribute("0.9.7")]
[assembly: AssemblyFileVersionAttribute("0.9.7")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.9.7";
}
}
|
// <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.9.6")]
[assembly: AssemblyInformationalVersionAttribute("0.9.6")]
[assembly: AssemblyFileVersionAttribute("0.9.6")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.9.6";
}
}
|
apache-2.0
|
C#
|
29fed22853ea70c38f50f629db03ffc9e52c935c
|
add IDisposal class
|
keke78ui9/Mongo.Net,keke78ui9/CSharpMongo
|
CSharpMongo/Mongo.cs
|
CSharpMongo/Mongo.cs
|
using MongoDB.Driver;
using System;
using System.Configuration;
namespace CSharpMongo
{
public class Mongo : IMongo, IDisposable
{
public Mongo(string connectionName)
{
var config = ConfigurationManager.ConnectionStrings[connectionName];
if (config == null)
{
throw new Exception(connectionName + " is required for mongodb database connection.");
}
var connectionString = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
LoadDatabase(connectionString);
}
private void LoadDatabase(string connectionString)
{
Url = new MongoUrl(connectionString);
Client = new MongoClient(Url);
Database = Client.GetDatabase(Url.DatabaseName);
}
public MongoClient Client { get; private set; }
public IMongoDatabase Database { get; private set; }
public MongoUrl Url { get; private set; }
private string GetCollectionName<T>()
{
Type type = typeof(T);
return type.Name;
}
public IMongoCollection<T> CollectionName<T>() where T : TDocument
{
return Database.GetCollection<T>(GetCollectionName<T>());
}
public void Dispose()
{
Client.Cluster.Dispose();
}
}
}
|
using MongoDB.Driver;
using System;
using System.Configuration;
namespace CSharpMongo
{
public class Mongo : IMongo
{
public Mongo(string connectionName)
{
var config = ConfigurationManager.ConnectionStrings[connectionName];
if (config == null)
{
throw new Exception(connectionName + " is required for mongodb database connection.");
}
var connectionString = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
LoadDatabase(connectionString);
}
private void LoadDatabase(string connectionString)
{
Url = new MongoUrl(connectionString);
Client = new MongoClient(Url);
Database = Client.GetDatabase(Url.DatabaseName);
}
public MongoClient Client { get; private set; }
public IMongoDatabase Database { get; private set; }
public MongoUrl Url { get; private set; }
private string GetCollectionName<T>()
{
Type type = typeof(T);
return type.Name;
}
public IMongoCollection<T> CollectionName<T>() where T : TDocument
{
return Database.GetCollection<T>(GetCollectionName<T>());
}
}
}
|
mit
|
C#
|
4e7c7b26305db6fa0d9263f593791b43512396cc
|
add docs to Publisher settings
|
Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns
|
TCC.Publisher/PublisherSettings.cs
|
TCC.Publisher/PublisherSettings.cs
|
using System.Collections.Generic;
namespace TCC.Publisher
{
public class PublisherSettings
{
/// <summary>
/// Name of the repository (eg. Tera-custom-cooldowns)
/// </summary>
public string RepositoryName { get; set; }
/// <summary>
/// Username of repository owner (eg. Foglio1024)
/// </summary>
public string RepositoryOwner { get; set; }
/// <summary>
/// Path to 7z.dll (eg. C:\Program Files\7-Zip\7z.dll)
/// </summary>
public string SevenZipLibPath { get; set; }
/// <summary>
/// Path to local repository (eg. D:\Repos\TCC)
/// </summary>
public string LocalRepositoryPath { get; set; }
/// <summary>
/// Webhook used for #update channel
/// </summary>
public string DiscordWebhook { get; set; }
/// <summary>
/// Token generated from GitHub
/// </summary>
public string GithubToken { get; set; }
/// <summary>
/// Url to http activator of update_version function
/// </summary>
public string FirestoreUrl { get; set; }
/// <summary>
/// File names to not include in final zip
/// </summary>
public List<string> ExcludedFiles { get; set; }
}
}
|
using System.Collections.Generic;
namespace TCC.Publisher
{
public class PublisherSettings
{
public string RepositoryName { get; set; }
public string RepositoryOwner { get; set; }
public string SevenZipLibPath { get; set; }
public string LocalRepositoryPath { get; set; }
public string DiscordWebhook { get; set; }
public string GithubToken { get; set; }
public string FirestoreUrl { get; set; }
public List<string> ExcludedFiles { get; set; }
}
}
|
mit
|
C#
|
5f5fec0b35b6685b24c6380d8e398cb8a495007f
|
Increase precision of 'g', as requested.
|
cmdrmcdonald/EliteDangerousDataProvider
|
DataDefinitions/Body.cs
|
DataDefinitions/Body.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EddiDataDefinitions
{
/// <summary>
/// A star or planet
/// </summary>
public class Body
{
/// <summary>The ID of this body in EDDB</summary>
public long EDDBID { get; set; }
/// <summary>The name of the body</summary>
public string name { get; set; }
/// <summary>
/// Convert gravity in m/s to g
/// </summary>
public static decimal ms2g(decimal gravity)
{
return gravity / (decimal)9.80665;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EddiDataDefinitions
{
/// <summary>
/// A star or planet
/// </summary>
public class Body
{
/// <summary>The ID of this body in EDDB</summary>
public long EDDBID { get; set; }
/// <summary>The name of the body</summary>
public string name { get; set; }
/// <summary>
/// Convert gravity in m/s to g
/// </summary>
public static decimal ms2g(decimal gravity)
{
return gravity / (decimal)9.8;
}
}
}
|
apache-2.0
|
C#
|
7c117369923e39ef48b74af2bfc83e0b6acacaf3
|
Enable nullable reference checking in UserService
|
btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver
|
BTCPayServer/Services/UserService.cs
|
BTCPayServer/Services/UserService.cs
|
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using BTCPayServer.Data;
using BTCPayServer.Storage.Services;
using BTCPayServer.Services.Stores;
namespace BTCPayServer.Services
{
public class UserService
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly IAuthorizationService _authorizationService;
private readonly StoredFileRepository _storedFileRepository;
private readonly FileService _fileService;
private readonly StoreRepository _storeRepository;
public UserService(
UserManager<ApplicationUser> userManager,
IAuthorizationService authorizationService,
StoredFileRepository storedFileRepository,
FileService fileService,
StoreRepository storeRepository
)
{
_userManager = userManager;
_authorizationService = authorizationService;
_storedFileRepository = storedFileRepository;
_fileService = fileService;
_storeRepository = storeRepository;
}
public async Task DeleteUserAndAssociatedData(ApplicationUser user)
{
var userId = user.Id;
var files = await _storedFileRepository.GetFiles(new StoredFileRepository.FilesQuery()
{
UserIds = new[] { userId },
});
await Task.WhenAll(files.Select(file => _fileService.RemoveFile(file.Id, userId)));
await _userManager.DeleteAsync(user);
await _storeRepository.CleanUnreachableStores();
}
public bool IsRoleAdmin(IList<string> roles)
{
return roles.Contains(Roles.ServerAdmin, StringComparer.Ordinal);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using BTCPayServer.Data;
using BTCPayServer.Storage.Services;
using BTCPayServer.Services.Stores;
namespace BTCPayServer.Services
{
public class UserService
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly IAuthorizationService _authorizationService;
private readonly StoredFileRepository _storedFileRepository;
private readonly FileService _fileService;
private readonly StoreRepository _storeRepository;
public UserService(
UserManager<ApplicationUser> userManager,
IAuthorizationService authorizationService,
StoredFileRepository storedFileRepository,
FileService fileService,
StoreRepository storeRepository
)
{
_userManager = userManager;
_authorizationService = authorizationService;
_storedFileRepository = storedFileRepository;
_fileService = fileService;
_storeRepository = storeRepository;
}
public async Task DeleteUserAndAssociatedData(ApplicationUser user)
{
var userId = user.Id;
var files = await _storedFileRepository.GetFiles(new StoredFileRepository.FilesQuery()
{
UserIds = new[] { userId },
});
await Task.WhenAll(files.Select(file => _fileService.RemoveFile(file.Id, userId)));
await _userManager.DeleteAsync(user);
await _storeRepository.CleanUnreachableStores();
}
public bool IsRoleAdmin(IList<string> roles)
{
return roles.Contains(Roles.ServerAdmin, StringComparer.Ordinal);
}
}
}
|
mit
|
C#
|
72fc4d3d0ac705ec56951e41f5fb709d4b347af7
|
Update Step 3 - Remove integration test category.
|
dubmun/DependencyKata
|
DependencyKata.Tests/DoItAllTests.cs
|
DependencyKata.Tests/DoItAllTests.cs
|
using NSubstitute;
using NUnit.Framework;
namespace DependencyKata.Tests
{
[TestFixture]
public class DoItAllTests
{
[Test, Category("Integration")]
public void DoItAll_Does_ItAll()
{
var expected = "The passwords don't match";
var io = Substitute.For<IOutputInputAdapter>();
var logging = Substitute.For<ILogging>();
var doItAll = new DoItAll(io, logging);
var result = doItAll.Do();
Assert.AreEqual(expected, result);
}
[Test, Category("Integration")]
public void DoItAll_Does_ItAll_MatchingPasswords()
{
var expected = "Database.SaveToLog Exception:";
var io = Substitute.For<IOutputInputAdapter>();
io.GetInput().Returns("something");
var logging = new DatabaseLogging();
var doItAll = new DoItAll(io, logging);
var result = doItAll.Do();
StringAssert.Contains(expected, result);
}
[Test]
public void DoItAll_Does_ItAll_MockLogging()
{
var expected = string.Empty;
var io = Substitute.For<IOutputInputAdapter>();
io.GetInput().Returns("something");
var logging = Substitute.For<ILogging>();
var doItAll = new DoItAll(io, logging);
var result = doItAll.Do();
StringAssert.Contains(expected, result);
}
}
}
|
using NSubstitute;
using NUnit.Framework;
namespace DependencyKata.Tests
{
[TestFixture]
public class DoItAllTests
{
[Test, Category("Integration")]
public void DoItAll_Does_ItAll()
{
var expected = "The passwords don't match";
var io = Substitute.For<IOutputInputAdapter>();
var logging = Substitute.For<ILogging>();
var doItAll = new DoItAll(io, logging);
var result = doItAll.Do();
Assert.AreEqual(expected, result);
}
[Test, Category("Integration")]
public void DoItAll_Does_ItAll_MatchingPasswords()
{
var expected = "Database.SaveToLog Exception:";
var io = Substitute.For<IOutputInputAdapter>();
io.GetInput().Returns("something");
var logging = new DatabaseLogging();
var doItAll = new DoItAll(io, logging);
var result = doItAll.Do();
StringAssert.Contains(expected, result);
}
[Test, Category("Integration")]
public void DoItAll_Does_ItAll_MockLogging()
{
var expected = string.Empty;
var io = Substitute.For<IOutputInputAdapter>();
io.GetInput().Returns("something");
var logging = Substitute.For<ILogging>();
var doItAll = new DoItAll(io, logging);
var result = doItAll.Do();
StringAssert.Contains(expected, result);
}
}
}
|
mit
|
C#
|
1088d273797dc8dadd38ab5fb58bb14dc8ff8d96
|
Add ability to send array of channels to PartMessage
|
Fredi/NetIRC
|
src/NetIRC/Messages/PartMessage.cs
|
src/NetIRC/Messages/PartMessage.cs
|
using System.Collections.Generic;
namespace NetIRC.Messages
{
public class PartMessage : IRCMessage, IServerMessage, IClientMessage
{
private readonly string channels;
public string Nick { get; }
public string Channel { get; }
public PartMessage(ParsedIRCMessage parsedMessage)
{
Nick = parsedMessage.Prefix.From;
Channel = parsedMessage.Parameters[0];
}
public PartMessage(string channels)
{
this.channels = channels;
}
public PartMessage(params string[] channels)
: this(string.Join(",", channels))
{
}
public IEnumerable<string> Tokens => new[] { "PART", channels };
}
}
|
using System.Collections.Generic;
namespace NetIRC.Messages
{
public class PartMessage : IRCMessage, IServerMessage, IClientMessage
{
private string channels;
public string Nick { get; }
public string Channel { get; }
public PartMessage(ParsedIRCMessage parsedMessage)
{
Nick = parsedMessage.Prefix.From;
Channel = parsedMessage.Parameters[0];
}
public PartMessage(string channels)
{
this.channels = channels;
}
public IEnumerable<string> Tokens => new[] { "PART", channels };
}
}
|
mit
|
C#
|
b9b164116493444b2bcbe673799038579dee084d
|
Extend TriggerHelp for querying help
|
IvionSauce/MeidoBot
|
MeidoBot/Plugins/PluginExtensions.cs
|
MeidoBot/Plugins/PluginExtensions.cs
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using MeidoCommon;
namespace MeidoBot
{
public static class PluginExtensions
{
public static string Name(this IMeidoHook plugin)
{
string name = plugin.Name.Trim();
switch (name)
{
case "":
case null:
name = "Unknown";
break;
// Reserved names.
case "Main":
case "Meido":
case "Triggers":
case "Auth":
name = "_" + name;
break;
}
return name;
}
public static Dictionary<string, string> Help(this IMeidoHook plugin)
{
if (plugin.Help != null)
return plugin.Help;
return new Dictionary<string, string>();
}
public static bool Query(this TriggerHelp root, string[] fullCommand, out CommandHelp help)
{
help = null;
var cmdHelpNodes = root.Commands;
foreach (string cmdPart in fullCommand)
{
if (TryGetHelp(cmdPart, cmdHelpNodes, out help))
cmdHelpNodes = help.Subcommands;
else
{
help = null;
break;
}
}
return help != null;
}
static bool TryGetHelp(
string command,
ReadOnlyCollection<CommandHelp> searchSpace,
out CommandHelp help)
{
foreach (var cmdHelp in searchSpace)
{
if (cmdHelp.Command.Equals(command, StringComparison.Ordinal))
{
help = cmdHelp;
return true;
}
}
help = null;
return false;
}
}
}
|
using System.Collections.Generic;
using MeidoCommon;
namespace MeidoBot
{
public static class PluginExtensions
{
public static string Name(this IMeidoHook plugin)
{
string name = plugin.Name.Trim();
switch (name)
{
case "":
case null:
name = "Unknown";
break;
// Reserved names.
case "Main":
case "Meido":
case "Triggers":
case "Auth":
name = "_" + name;
break;
}
return name;
}
public static Dictionary<string, string> Help(this IMeidoHook plugin)
{
if (plugin.Help != null)
return plugin.Help;
return new Dictionary<string, string>();
}
}
}
|
bsd-2-clause
|
C#
|
9f3420ce207cc5c926798a0cd108ebc9ed4aba51
|
update server samples
|
IntelliTect/CoAP.NET,martindevans/CoAP.NET,smeshlink/CoAP.NET
|
CoAP.Server/Resources/TimeResource.cs
|
CoAP.Server/Resources/TimeResource.cs
|
using System;
using System.Collections.Generic;
using System.Text;
using CoAP.EndPoint;
using System.Threading;
namespace CoAP.Examples.Resources
{
class TimeResource : LocalResource
{
private Timer _timer;
private DateTime _now;
public TimeResource()
: base("time")
{
Title = "GET the current time";
ResourceType = "CurrentTime";
Observable = true;
_timer = new Timer(Timed, null, 0, 2000);
}
private void Timed(Object o)
{
_now = DateTime.Now;
Changed();
}
public override void DoGet(Request request)
{
request.Respond(Code.Content, _now.ToString(), MediaType.TextPlain);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using CoAP.EndPoint;
using System.Threading;
namespace CoAP.Examples.Resources
{
class TimeResource : LocalResource
{
private Timer _timer;
private DateTime _now;
public TimeResource()
: base("time")
{
Title = "GET the current time";
ResourceType = "CurrentTime";
Observable = true;
_timer = new Timer(Timed, null, 0, 2000);
}
private void Timed(Object o)
{
_now = DateTime.Now;
Changed();
}
public override void DoGet(Request request)
{
request.Respond(Code.Content, "Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!Very large string!", MediaType.TextPlain);
}
}
}
|
bsd-3-clause
|
C#
|
fa2a00b28c4ad7309bfc36454926cb683bf51aca
|
Fix AppDomain creation causing cctor executing twice.
|
Desolath/ConfuserEx3,yeaicc/ConfuserEx,engdata/ConfuserEx,Desolath/Confuserex
|
Confuser.Runtime/AntiTamper.Normal.cs
|
Confuser.Runtime/AntiTamper.Normal.cs
|
using System;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Confuser.Runtime {
internal static class AntiTamperNormal {
[DllImport("kernel32.dll")]
static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect);
static unsafe void Initialize() {
Module m = typeof(AntiTamperNormal).Module;
string n = m.FullyQualifiedName;
bool f = n.Length > 0 && n[0] == '<';
var b = (byte*)Marshal.GetHINSTANCE(m);
byte* p = b + *(uint*)(b + 0x3c);
ushort s = *(ushort*)(p + 0x6);
ushort o = *(ushort*)(p + 0x14);
uint* e = null;
uint l = 0;
var r = (uint*)(p + 0x18 + o);
uint z = (uint)Mutation.KeyI1, x = (uint)Mutation.KeyI2, c = (uint)Mutation.KeyI3, v = (uint)Mutation.KeyI4;
for (int i = 0; i < s; i++) {
uint g = (*r++) * (*r++);
if (g == (uint)Mutation.KeyI0) {
e = (uint*)(b + (f ? *(r + 3) : *(r + 1)));
l = (f ? *(r + 2) : *(r + 0)) >> 2;
}
else if (g != 0) {
var q = (uint*)(b + (f ? *(r + 3) : *(r + 1)));
uint j = *(r + 2) >> 2;
for (uint k = 0; k < j; k++) {
uint t = (z ^ (*q++)) + x + c * v;
z = x;
x = c;
x = v;
v = t;
}
}
r += 8;
}
uint[] y = new uint[0x10], d = new uint[0x10];
for (int i = 0; i < 0x10; i++) {
y[i] = v;
d[i] = x;
z = (x >> 5) | (x << 27);
x = (c >> 3) | (c << 29);
c = (v >> 7) | (v << 25);
v = (z >> 11) | (z << 21);
}
Mutation.Crypt(y, d);
uint w = 0x40;
VirtualProtect((IntPtr)e, l << 2, w, out w);
if (w == 0x40)
return;
uint h = 0;
for (uint i = 0; i < l; i++) {
*e ^= y[h & 0xf];
y[h & 0xf] = (y[h & 0xf] ^ (*e++)) + 0x3dbb2819;
h++;
}
}
}
}
|
using System;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Confuser.Runtime {
internal static class AntiTamperNormal {
[DllImport("kernel32.dll")]
static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect);
static unsafe void Initialize() {
Module m = typeof(AntiTamperNormal).Module;
string n = m.FullyQualifiedName;
bool f = n.Length > 0 && n[0] == '<';
var b = (byte*)Marshal.GetHINSTANCE(m);
byte* p = b + *(uint*)(b + 0x3c);
ushort s = *(ushort*)(p + 0x6);
ushort o = *(ushort*)(p + 0x14);
uint* e = null;
uint l = 0;
var r = (uint*)(p + 0x18 + o);
uint z = (uint)Mutation.KeyI1, x = (uint)Mutation.KeyI2, c = (uint)Mutation.KeyI3, v = (uint)Mutation.KeyI4;
for (int i = 0; i < s; i++) {
uint g = (*r++) * (*r++);
if (g == (uint)Mutation.KeyI0) {
e = (uint*)(b + (f ? *(r + 3) : *(r + 1)));
l = (f ? *(r + 2) : *(r + 0)) >> 2;
}
else if (g != 0) {
var q = (uint*)(b + (f ? *(r + 3) : *(r + 1)));
uint j = *(r + 2) >> 2;
for (uint k = 0; k < j; k++) {
uint t = (z ^ (*q++)) + x + c * v;
z = x;
x = c;
x = v;
v = t;
}
}
r += 8;
}
uint[] y = new uint[0x10], d = new uint[0x10];
for (int i = 0; i < 0x10; i++) {
y[i] = v;
d[i] = x;
z = (x >> 5) | (x << 27);
x = (c >> 3) | (c << 29);
c = (v >> 7) | (v << 25);
v = (z >> 11) | (z << 21);
}
Mutation.Crypt(y, d);
uint w = 0x40;
VirtualProtect((IntPtr)e, l << 2, w, out w);
uint h = 0;
for (uint i = 0; i < l; i++) {
*e ^= y[h & 0xf];
y[h & 0xf] = (y[h & 0xf] ^ (*e++)) + 0x3dbb2819;
h++;
}
}
}
}
|
mit
|
C#
|
22d5728049e310fb2c42fd0ec4cc7a887b71a3bc
|
comment for previous commit #433
|
samwa/loconomics,loconomics/loconomics,samwa/loconomics,loconomics/loconomics,samwa/loconomics,samwa/loconomics,loconomics/loconomics,loconomics/loconomics
|
web/api/v1/me/user-job-profile.cshtml
|
web/api/v1/me/user-job-profile.cshtml
|
@using WebMatrix.WebData;
@*
Get the list and details of job titles attached to the logged user (a service professional) and any alerts for those job titles.
The collection of job titles is called the "User Job Profile".
It allows to edit the data of each one, and special actions on each like deactive/reactive.
We allow client-only users to use the POST API, the others are restricted per method to ServiceProfessionals.
EXAMPLES {
"User Job Profile": {
"url": "/api/v1/en-US/me/user-job-profile",
"get": { },
"post": {
"jobTitleID": 106,
"intro": "Job title introduction",
"cancellationPolicyID": 1,
"instantBooking": true,
"collectPaymentAtBookMeButton": true
}
},
"User Job Profile (item -- Job Title)": {
"url": "/api/v1/en-US/me/user-job-profile/106",
"get": { },
"put": {
"intro": "Job title introduction",
"cancellationPolicyID": 1,
"instantBooking": true,
"collectPaymentAtBookMeButton": true
},
"delete": { }
},
"User Job Profile - Deactivation": {
"url": "/api/v1/en-US/me/user-job-profile/106/deactivate",
"post": { }
},
"User Job Profile - Reactivation": {
"url": "/api/v1/en-US/me/user-job-profile/106/reactivate",
"post": { }
}
}
*@
@{
// We allow client-only users to use the POST API, the others are restricted per method to ServiceProfessionals
Response.RestRequiresUser(LcData.UserInfo.UserType.User);
new RestUserJobProfile().JsonResponse(this);
}
|
@using WebMatrix.WebData;
@*
Get the list and details of job titles attached to the logged user (a service professional).
The collection of job titles is called the "User Job Profile".
It allows to edit the data of each one, and special actions on each like deactive/reactive.
We allow client-only users to use the POST API, the others are restricted per method to ServiceProfessionals.
EXAMPLES {
"User Job Profile": {
"url": "/api/v1/en-US/me/user-job-profile",
"get": { },
"post": {
"jobTitleID": 106,
"intro": "Job title introduction",
"cancellationPolicyID": 1,
"instantBooking": true,
"collectPaymentAtBookMeButton": true
}
},
"User Job Profile (item -- Job Title)": {
"url": "/api/v1/en-US/me/user-job-profile/106",
"get": { },
"put": {
"intro": "Job title introduction",
"cancellationPolicyID": 1,
"instantBooking": true,
"collectPaymentAtBookMeButton": true
},
"delete": { }
},
"User Job Profile - Deactivation": {
"url": "/api/v1/en-US/me/user-job-profile/106/deactivate",
"post": { }
},
"User Job Profile - Reactivation": {
"url": "/api/v1/en-US/me/user-job-profile/106/reactivate",
"post": { }
}
}
*@
@{
// We allow client-only users to use the POST API, the others are restricted per method to ServiceProfessionals
Response.RestRequiresUser(LcData.UserInfo.UserType.User);
new RestUserJobProfile().JsonResponse(this);
}
|
mpl-2.0
|
C#
|
e2de5d1fde687c5ecff250b4ccd0dfde8853b5e1
|
use the send irc message where applicable
|
SexyFishHorse/IrcClient4Net
|
IrcClient4Net/TwitchIrcClient.cs
|
IrcClient4Net/TwitchIrcClient.cs
|
namespace SexyFishHorse.Irc.Client
{
using System.IO;
using System.Net.Sockets;
using SexyFishHorse.Irc.Client.Configuration;
public class TwitchIrcClient : ITwitchIrcClient
{
private readonly IConfiguration configuration;
private TcpClient client;
private StreamReader inputStream;
private StreamWriter outputStream;
public TwitchIrcClient(IConfiguration configuration)
{
this.configuration = configuration;
}
public void Connect()
{
client = new TcpClient(configuration.TwitchIrcServerName, configuration.TwitchIrcPortNumber);
inputStream = new StreamReader(client.GetStream());
outputStream = new StreamWriter(client.GetStream());
outputStream.WriteLine("PASS " + configuration.TwitchIrcPassword);
outputStream.WriteLine("NICK " + configuration.TwitchIrcNickname);
outputStream.WriteLine("USER " + configuration.TwitchIrcNickname + " 8 * : " + configuration.TwitchIrcNickname);
outputStream.Flush();
}
public void JoinRoom()
{
SendIrcMessage(string.Format("JOIN #{0}", configuration.TwitchIrcNickname));
}
public void SendIrcMessage(string message)
{
outputStream.WriteLine(message);
outputStream.Flush();
}
public void SendChatMessage(string message)
{
SendIrcMessage(
string.Format(configuration.TwitchIrcPrivmsgFormat, configuration.TwitchIrcNickname, message));
}
public string ReadRawMessage()
{
return inputStream.ReadLine();
}
public void LeaveRoom()
{
SendIrcMessage(string.Format("PART #{0}", configuration.TwitchIrcNickname));
}
public void RequestMembershipCapability()
{
SendIrcMessage(string.Format("CAP REQ :{0}", configuration.TwitchIrcMembershipCapability));
}
}
}
|
namespace SexyFishHorse.Irc.Client
{
using System.IO;
using System.Net.Sockets;
using SexyFishHorse.Irc.Client.Configuration;
public class TwitchIrcClient : ITwitchIrcClient
{
private readonly IConfiguration configuration;
private TcpClient client;
private StreamReader inputStream;
private StreamWriter outputStream;
public TwitchIrcClient(IConfiguration configuration)
{
this.configuration = configuration;
}
public void Connect()
{
client = new TcpClient(configuration.TwitchIrcServerName, configuration.TwitchIrcPortNumber);
inputStream = new StreamReader(client.GetStream());
outputStream = new StreamWriter(client.GetStream());
outputStream.WriteLine("PASS " + configuration.TwitchIrcPassword);
outputStream.WriteLine("NICK " + configuration.TwitchIrcNickname);
outputStream.WriteLine("USER " + configuration.TwitchIrcNickname + " 8 * : " + configuration.TwitchIrcNickname);
outputStream.Flush();
}
public void JoinRoom()
{
outputStream.WriteLine("JOIN #" + configuration.TwitchIrcNickname);
outputStream.Flush();
}
public void SendIrcMessage(string message)
{
outputStream.WriteLine(message);
outputStream.Flush();
}
public void SendChatMessage(string message)
{
SendIrcMessage(
string.Format(configuration.TwitchIrcPrivmsgFormat, configuration.TwitchIrcNickname, message));
}
public string ReadRawMessage()
{
return inputStream.ReadLine();
}
public void LeaveRoom()
{
SendIrcMessage(string.Format("PART #{0}", configuration.TwitchIrcNickname));
}
public void RequestMembershipCapability()
{
SendIrcMessage(string.Format("CAP REQ :{0}", configuration.TwitchIrcMembershipCapability));
}
}
}
|
mit
|
C#
|
ba974268d8bfdebcd7ea0f3b1125728104bf864a
|
Add user32 function in winutilities
|
CindyB/sloth
|
Sloth/Sloth/Core/WinUtilities.cs
|
Sloth/Sloth/Core/WinUtilities.cs
|
using Sloth.Interfaces.Core;
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Sloth.Core
{
public class WinUtilities : IWinUtilities
{
public IntPtr FindControlHandle(IntPtr windowsHandle, string controlName)
{
throw new NotImplementedException();
}
public IntPtr FindWindowsHandle(string className,string windowsName)
{
throw new NotImplementedException();
}
public string GetClassName(IntPtr windowsHandle)
{
throw new NotImplementedException();
}
public string GetWindowText(IntPtr windowsHandle)
{
throw new NotImplementedException();
}
public void SendMessage(IntPtr windowsHandle, IntPtr controlHandle, ISlothEvent slothEvent)
{
throw new NotImplementedException();
}
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
[DllImport("user32.dll")]
static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}
}
|
using Sloth.Interfaces.Core;
using System;
namespace Sloth.Core
{
public class WinUtilities : IWinUtilities
{
public IntPtr FindControlHandle(IntPtr windowsHandle, string controlName)
{
throw new NotImplementedException();
}
public IntPtr FindWindowsHandle(string className,string windowsName)
{
throw new NotImplementedException();
}
public string GetClassName(IntPtr windowsHandle)
{
throw new NotImplementedException();
}
public string GetWindowText(IntPtr windowsHandle)
{
throw new NotImplementedException();
}
public void SendMessage(IntPtr windowsHandle, IntPtr controlHandle, ISlothEvent slothEvent)
{
throw new NotImplementedException();
}
}
}
|
mit
|
C#
|
32adab462e96748a1048b1d7fafe9619072b7cd6
|
Remove unused using statements
|
whampson/cascara,whampson/bft-spec
|
Src/WHampson.Bft/TemplateFile.cs
|
Src/WHampson.Bft/TemplateFile.cs
|
#region License
/* Copyright (c) 2017 Wes Hampson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#endregion
using System.Xml;
using System.Xml.Linq;
namespace WHampson.Bft
{
public sealed class TemplateFile
{
private static XDocument OpenXmlFile(string path)
{
try
{
return XDocument.Load(path, LoadOptions.SetLineInfo);
}
catch (XmlException e)
{
throw new TemplateException(e.Message, e);
}
}
private XDocument doc;
public TemplateFile(string path)
{
doc = OpenXmlFile(path);
}
public T Process<T>(string filePath)
{
TemplateProcessor processor = new TemplateProcessor(doc);
return processor.Process<T>(filePath);
}
public string this[string key]
{
// Get template metadata (Root element attribute values)
get
{
XAttribute attr = doc.Root.Attribute(key);
return (attr != null) ? attr.Value : null;
}
}
}
}
|
#region License
/* Copyright (c) 2017 Wes Hampson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
namespace WHampson.Bft
{
public sealed class TemplateFile
{
private static XDocument OpenXmlFile(string path)
{
try
{
return XDocument.Load(path, LoadOptions.SetLineInfo);
}
catch (XmlException e)
{
throw new TemplateException(e.Message, e);
}
}
private XDocument doc;
public TemplateFile(string path)
{
doc = OpenXmlFile(path);
}
public T Process<T>(string filePath)
{
TemplateProcessor processor = new TemplateProcessor(doc);
return processor.Process<T>(filePath);
}
public string this[string key]
{
// Get template metadata (Root element attribute values)
get
{
XAttribute attr = doc.Root.Attribute(key);
return (attr != null) ? attr.Value : null;
}
}
}
}
|
mit
|
C#
|
33c3efd06434da41b7be214331ff9010434970a2
|
Change pen color.
|
eylvisaker/AgateLib
|
Tools/FontCreator/frmViewFont.cs
|
Tools/FontCreator/frmViewFont.cs
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using ERY.AgateLib.BitmapFont;
using ERY.AgateLib.WinForms;
namespace FontCreator
{
public partial class frmViewFont : Form
{
public frmViewFont()
{
InitializeComponent();
}
Image image;
FontMetrics font;
internal DialogResult ShowDialog(IWin32Window owner, string tempImage, string tempXml)
{
image = new Bitmap(tempImage);
font = new FontMetrics();
font.Load(tempXml);
foreach (char key in font.Keys)
{
lstItems.Items.Add(key);
}
return ShowDialog(owner);
}
private void pctImage_Paint(object sender, PaintEventArgs e)
{
e.Graphics.FillRectangle(Brushes.DarkRed, new Rectangle(0,0,image.Width, image.Height));
e.Graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height));
if (lstItems.SelectedIndex != -1)
{
char glyph = (char)lstItems.SelectedItem;
GlyphMetrics metric = font[glyph];
Color clr = Color.FromArgb(128, Color.Blue);
using (Pen p = new Pen(clr))
{
e.Graphics.DrawRectangle(p, FormsInterop.ConvertRectangle(metric.SourceRect));
}
}
}
private void lstItems_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstItems.SelectedItem == null)
{
properties.SelectedObject = null;
}
else
{
properties.SelectedObject = font[(char)lstItems.SelectedItem];
}
pctImage.Invalidate();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using ERY.AgateLib.BitmapFont;
using ERY.AgateLib.WinForms;
namespace FontCreator
{
public partial class frmViewFont : Form
{
public frmViewFont()
{
InitializeComponent();
}
Image image;
FontMetrics font;
internal DialogResult ShowDialog(IWin32Window owner, string tempImage, string tempXml)
{
image = new Bitmap(tempImage);
font = new FontMetrics();
font.Load(tempXml);
foreach (char key in font.Keys)
{
lstItems.Items.Add(key);
}
return ShowDialog(owner);
}
private void pctImage_Paint(object sender, PaintEventArgs e)
{
e.Graphics.FillRectangle(Brushes.DarkRed, new Rectangle(0,0,image.Width, image.Height));
e.Graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height));
if (lstItems.SelectedIndex != -1)
{
char glyph = (char)lstItems.SelectedItem;
GlyphMetrics metric = font[glyph];
e.Graphics.DrawRectangle(Pens.Blue, FormsInterop.ConvertRectangle(metric.SourceRect));
}
}
private void lstItems_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstItems.SelectedItem == null)
{
properties.SelectedObject = null;
}
else
{
properties.SelectedObject = font[(char)lstItems.SelectedItem];
}
pctImage.Invalidate();
}
}
}
|
mit
|
C#
|
dc5cfa810a23b9ed6a4f242e89b9763942df202a
|
Add wrapper function for PathCanonicalize.
|
mcneel/RhinoCycles
|
Core/RcCore.cs
|
Core/RcCore.cs
|
/**
Copyright 2014-2017 Robert McNeel and Associates
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**/
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace RhinoCyclesCore.Core
{
public sealed class RcCore
{
#region helper functions to get relative path between two paths
private const int FileAttributeDirectory = 0x10;
[DllImport("shlwapi.dll", SetLastError = true)]
private static extern int PathRelativePathTo(StringBuilder pszPath,
string pszFrom, int dwAttrFrom, string pszTo, int dwAttrTo);
public static string GetRelativePath(string fromPath, string toPath)
{
var path = new StringBuilder(1024);
if (PathRelativePathTo(path,
fromPath, FileAttributeDirectory,
toPath, FileAttributeDirectory) == 0)
{
throw new ArgumentException("Paths must have a common prefix");
}
return path.ToString();
}
[DllImport("shlwapi.dll", SetLastError = true)]
private static extern int PathCanonicalize(StringBuilder pszDest,
string pszSrc);
public static string GetCanonicalizedPath(string original)
{
var path = new StringBuilder(1024);
if (PathCanonicalize(path, original) == 0)
{
throw new ArgumentException($"Invalid original path: '{original}'");
}
return path.ToString();
}
#endregion
public void TriggerInitialisationCompleted(object sender)
{
InitialisationCompleted?.Invoke(sender, EventArgs.Empty);
}
/// <summary>
/// Event signalling that CCSycles initialisation has been completed.
/// </summary>
public event EventHandler InitialisationCompleted;
/// <summary>
/// Flag to keep track of CSycles initialisation
/// </summary>
public bool Initialised { get; set; }
public bool AppInitialised { get; set; }
/// <summary>
/// Get the path used to look up .cubins (absolute)
/// </summary>
public string KernelPath { get; set; }
/// <summary>
/// Get the path where runtime created data like compiled kernels and BVH caches are stored.
/// </summary>
public string DataUserPath { get; set; }
/// <summary>
/// Get the path used to look up .cubins (relative)
/// </summary>
public string KernelPathRelative { get; set; }
public string PluginPath { get; set; }
public string AppPath { get; set; }
public EngineSettings EngineSettings => _engineSettings;
private readonly EngineSettings _engineSettings;
private RcCore() {
AppInitialised = false;
if(_engineSettings == null)
_engineSettings = new EngineSettings();
}
public static RcCore It { get; } = new RcCore();
}
}
|
/**
Copyright 2014-2017 Robert McNeel and Associates
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**/
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace RhinoCyclesCore.Core
{
public sealed class RcCore
{
#region helper functions to get relative path between two paths
private const int FileAttributeDirectory = 0x10;
public static string GetRelativePath(string fromPath, string toPath)
{
var path = new StringBuilder();
if (PathRelativePathTo(path,
fromPath, FileAttributeDirectory,
toPath, FileAttributeDirectory) == 0)
{
throw new ArgumentException("Paths must have a common prefix");
}
return path.ToString();
}
[DllImport("shlwapi.dll", SetLastError = true)]
private static extern int PathRelativePathTo(StringBuilder pszPath,
string pszFrom, int dwAttrFrom, string pszTo, int dwAttrTo);
#endregion
public void TriggerInitialisationCompleted(object sender)
{
InitialisationCompleted?.Invoke(sender, EventArgs.Empty);
}
/// <summary>
/// Event signalling that CCSycles initialisation has been completed.
/// </summary>
public event EventHandler InitialisationCompleted;
/// <summary>
/// Flag to keep track of CSycles initialisation
/// </summary>
public bool Initialised { get; set; }
public bool AppInitialised { get; set; }
/// <summary>
/// Get the path used to look up .cubins (absolute)
/// </summary>
public string KernelPath { get; set; }
/// <summary>
/// Get the path where runtime created data like compiled kernels and BVH caches are stored.
/// </summary>
public string DataUserPath { get; set; }
/// <summary>
/// Get the path used to look up .cubins (relative)
/// </summary>
public string KernelPathRelative { get; set; }
public string PluginPath { get; set; }
public string AppPath { get; set; }
public EngineSettings EngineSettings => _engineSettings;
private readonly EngineSettings _engineSettings;
private RcCore() {
AppInitialised = false;
if(_engineSettings == null)
_engineSettings = new EngineSettings();
}
public static RcCore It { get; } = new RcCore();
}
}
|
apache-2.0
|
C#
|
1f1a15b5614fc2c239f5fc9793824975f740bdda
|
Update for cli start command on Ubuntu
|
WorkplaceX/Framework,WorkplaceX/Framework,WorkplaceX/Framework,WorkplaceX/Framework,WorkplaceX/Framework
|
Framework.Cli/Command/CommandStart.cs
|
Framework.Cli/Command/CommandStart.cs
|
namespace Framework.Cli.Command
{
using System.Runtime.InteropServices;
/// <summary>
/// Cli start command.
/// </summary>
public class CommandStart : CommandBase
{
public CommandStart(AppCli appCli)
: base(appCli, "start", "Start server and open browser")
{
}
protected internal override void Execute()
{
CommandBuild.InitConfigWebServer(AppCli); // Copy ConnectionString from ConfigCli.json to ConfigWebServer.json.
string folderName = UtilFramework.FolderName + @"Application.Server/";
UtilCli.DotNet(folderName, "build");
UtilCli.DotNet(folderName, "run --no-build", false);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
UtilCli.OpenWebBrowser("http://localhost:50919/"); // For port setting see also: Application.Server\Properties\launchSettings.json (applicationUrl, sslPort)
}
}
}
}
|
namespace Framework.Cli.Command
{
/// <summary>
/// Cli start command.
/// </summary>
public class CommandStart : CommandBase
{
public CommandStart(AppCli appCli)
: base(appCli, "start", "Start server and open browser")
{
}
protected internal override void Execute()
{
CommandBuild.InitConfigWebServer(AppCli); // Copy ConnectionString from ConfigCli.json to ConfigWebServer.json.
string folderName = UtilFramework.FolderName + @"Application.Server/";
UtilCli.DotNet(folderName, "build");
UtilCli.DotNet(folderName, "run --no-build", false);
UtilCli.OpenWebBrowser("http://localhost:50919/"); // For port setting see also: Application.Server\Properties\launchSettings.json (applicationUrl, sslPort)
}
}
}
|
mit
|
C#
|
48f49d5105f4bdeeca7f9c55120812c49b6e637b
|
Fix ci error
|
gmich/Gem
|
Gem.Infrastructure/DisposableEntry.cs
|
Gem.Infrastructure/DisposableEntry.cs
|
using System;
using System.Collections.Generic;
namespace Gem.Infrastructure
{
/// <summary>
/// Helper class for disposable collection entries.
/// Disposing removes the entry from the list
/// <remarks>Not thread safe</remarks>
/// </summary>
/// <typeparam name="TEntry">The IList's generic type</typeparam>
public sealed class DisposableEntry<TEntry> : IDisposable
{
private IList<TEntry> registered;
private TEntry current;
internal DisposableEntry(IList<TEntry> registered, TEntry current)
{
this.registered = registered;
this.current = current;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private bool isDisposed = false;
private void Dispose(bool disposing)
{
if (disposing && !isDisposed)
{
if (registered.Contains(current))
registered.Remove(current);
isDisposed = true;
}
}
}
/// <summary>
/// Factory for creating disposable entries
/// </summary>
public static class Disposable
{
public static DisposableEntry<TEntry> Create<TEntry>(IList<TEntry> registered, TEntry current)
{
return new DisposableEntry<TEntry>(registered, current);
}
public static IDisposable CreateDummy()
{
return new DummyDisposable();
}
}
public class DummyDisposable : IDisposable
{
public void Dispose()
{
return;
}
}
}
|
using System;
using System.Collections.Generic;
namespace Gem.Infrastructure
{
/// <summary>
/// Helper class for disposable collection entries.
/// Disposing removes the entry from the list
/// <remarks>Not thread safe</remarks>
/// </summary>
/// <typeparam name="TEntry">The IList's generic type</typeparam>
public sealed class DisposableEntry<TEntry> : IDisposable
{
private IList<TEntry> registered;
private TEntry current;
internal DisposableEntry(IList<TEntry> registered, TEntry current)
{
this.registered = registered;
this.current = current;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private bool isDisposed = false;
private void Dispose(bool disposing)
{
if (disposing && !isDisposed)
{
if (registered.Contains(current))
registered.Remove(current);
isDisposed = true;
}
}
}
/// <summary>
/// Factory for creating disposable entries
/// </summary>
public static class Disposable
{
public static DisposableEntry<TEntry> Create<TEntry>(IList<TEntry> registered, TEntry current)
{
return new DisposableEntry<TEntry>(registered, current);
}
public static IDisposable CreateDummy()
{
return new DummyDisposable();
}
}
public class DummyDisposable : IDisposable
{
public void Dispose()
{
List<string> mylist = null;
string someEntry;
mylist.Add(someEntry);
var dis= Disposable.Create(mylist, someEntry);
return;
}
}
}
|
mit
|
C#
|
57cc1642d45f39c10af0de17b8ee87c175866c23
|
Add comments to PersonDto.
|
harrison314/MapperPerformace
|
MapperPerformace/Testing/PersonDto.cs
|
MapperPerformace/Testing/PersonDto.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MapperPerformace.Testing
{
/// <summary>
/// Dto reprints <see cref="MapperPerformace.Ef.Person"/>
/// </summary>
public class PersonDto
{
public int BusinessEntityID
{
get;
set;
}
public string PersonType
{
get;
set;
}
public string Title
{
get;
set;
}
public string FirstName
{
get;
set;
}
public string MiddleName
{
get;
set;
}
public string LastName
{
get;
set;
}
public DateTime? EmployeeBrithDate
{
get;
set;
}
public string EmployeeGender
{
get;
set;
}
public List<string> TelephoneNumbers
{
get;
set;
}
public List<EmailDto> Emails
{
get;
set;
}
/// <summary>
/// Initializes a new instance of the <see cref="PersonDto"/> class.
/// </summary>
public PersonDto()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MapperPerformace.Testing
{
public class PersonDto
{
public int BusinessEntityID
{
get;
set;
}
public string PersonType
{
get;
set;
}
public string Title
{
get;
set;
}
public string FirstName
{
get;
set;
}
public string MiddleName
{
get;
set;
}
public string LastName
{
get;
set;
}
public DateTime? EmployeeBrithDate
{
get;
set;
}
public string EmployeeGender
{
get;
set;
}
public List<string> TelephoneNumbers
{
get;
set;
}
public List<EmailDto> Emails
{
get;
set;
}
public PersonDto()
{
}
}
}
|
mit
|
C#
|
fb435c8ef4f92af1f895b94412d4699a24d56483
|
fix on small screens total score doesn't line up right
|
CecilCable/Ingress-ScoreKeeper,CecilCable/Ingress-ScoreKeeper,CecilCable/Ingress-ScoreKeeper,CecilCable/Ingress-ScoreKeeper
|
Upchurch.Ingress/Views/Home/OverallScore.cshtml
|
Upchurch.Ingress/Views/Home/OverallScore.cshtml
|
<div class="jumbotron">
<div class="row">
<div class="col-md-4">
Resistance
<br />
{{overallScore.ResistanceScore | number}}
</div>
<div class="col-md-8">
Enlightened
<br />
{{overallScore.EnlightenedScore | number}}
</div>
</div>
</div>
|
<div class="jumbotron">
<div class="row">
<div class="col-md-4">
Resistance
</div>
<div class="col-md-8">
Enlightened
</div>
<div class="col-md-4">
{{overallScore.ResistanceScore | number}}
</div>
<div class="col-md-4">
{{overallScore.EnlightenedScore | number}}
</div>
</div>
</div>
|
mit
|
C#
|
b33f0cec88f8bbe70dfaf4c466dfb70824f83af6
|
fix nuget versioning
|
FantasticFiasco/mvvm-dialogs
|
build.cake
|
build.cake
|
#load "build/utils.cake"
//////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
//////////////////////////////////////////////////////////////////////
// VARIABLES
//////////////////////////////////////////////////////////////////////
var solution = new FilePath("./MvvmDialogs.sln");
//////////////////////////////////////////////////////////////////////
// TASKS
//////////////////////////////////////////////////////////////////////
Task("Clean")
.Description("Clean all files")
.Does(() =>
{
CleanDirectories("./**/bin");
CleanDirectories("./**/obj");
});
Task("Restore")
.Description("Restore NuGet packages")
.IsDependentOn("Clean")
.Does(() =>
{
NuGetRestore(solution);
});
Task("Build")
.Description("Build the solution")
.IsDependentOn("Restore")
.Does(() =>
{
MSBuild(solution, settings => settings
.SetConfiguration(configuration)
.SetMaxCpuCount(0)); // Enable parallel build
});
Task("Pack")
.Description("Create NuGet package")
.IsDependentOn("Build")
.Does(() =>
{
var version = GetAssemblyVersion("./Directory.Build.props");
var isTag = EnvironmentVariable("APPVEYOR_REPO_TAG");
// Unless this is a tag, this is a pre-release
if (isTag != "true")
{
var sha = EnvironmentVariable("APPVEYOR_REPO_COMMIT");
version += $"-sha-{sha}";
}
NuGetPack(
"./MvvmDialogs.nuspec",
new NuGetPackSettings
{
Version = version,
Symbols = true
});
});
//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("Pack");
//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////
RunTarget(target);
|
#load "build/utils.cake"
//////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
//////////////////////////////////////////////////////////////////////
// VARIABLES
//////////////////////////////////////////////////////////////////////
var solution = new FilePath("./MvvmDialogs.sln");
//////////////////////////////////////////////////////////////////////
// TASKS
//////////////////////////////////////////////////////////////////////
Task("Clean")
.Description("Clean all files")
.Does(() =>
{
CleanDirectories("./**/bin");
CleanDirectories("./**/obj");
});
Task("Restore")
.Description("Restore NuGet packages")
.IsDependentOn("Clean")
.Does(() =>
{
NuGetRestore(solution);
});
Task("Build")
.Description("Build the solution")
.IsDependentOn("Restore")
.Does(() =>
{
MSBuild(solution, settings => settings
.SetConfiguration(configuration)
.SetMaxCpuCount(0)); // Enable parallel build
});
Task("Pack")
.Description("Create NuGet package")
.IsDependentOn("Build")
.Does(() =>
{
var version = GetAssemblyVersion("./Directory.Build.props");
var branch = EnvironmentVariable("APPVEYOR_REPO_BRANCH");
// Unless on master, this is a pre-release
if (branch != "master")
{
var sha = EnvironmentVariable("APPVEYOR_REPO_COMMIT");
version += $"-sha-{sha}";
}
NuGetPack(
"./MvvmDialogs.nuspec",
new NuGetPackSettings
{
Version = version,
Symbols = true
});
});
//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("Pack");
//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////
RunTarget(target);
|
apache-2.0
|
C#
|
d595860d7acea34d5cb7584f3a3f53edbf7108cf
|
Clean up build script
|
robertcoltheart/Deploy
|
build.cake
|
build.cake
|
#tool "nuget:?package=GitVersion.CommandLine&version=3.6.1"
#tool "nuget:?package=NUnit.ConsoleRunner&version=3.4.1"
//////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var nugetApiKey = Argument("nugetapikey", EnvironmentVariable("NUGET_API_KEY"));
//////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
//////////////////////////////////////////////////////////////////////
var version = "1.0.0";
var artifacts = Directory("./artifacts");
var solution = File("./src/Deploy.sln");
//////////////////////////////////////////////////////////////////////
// TASKS
//////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() =>
{
CleanDirectories("./src/**/bin");
CleanDirectories("./src/**/obj");
if (DirectoryExists(artifacts))
DeleteDirectory(artifacts, true);
});
Task("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
NuGetRestore(solution);
});
Task("Versioning")
.IsDependentOn("Clean")
.WithCriteria(() => !BuildSystem.IsLocalBuild)
.Does(() =>
{
GitVersion(new GitVersionSettings
{
OutputType = GitVersionOutput.BuildServer
});
var result = GitVersion(new GitVersionSettings
{
UpdateAssemblyInfo = true
});
version = result.NuGetVersion;
});
Task("Build")
.IsDependentOn("Versioning")
.IsDependentOn("Restore")
.Does(() =>
{
CreateDirectory(artifacts);
DotNetBuild(solution, x =>
{
x.SetConfiguration("Release");
x.WithProperty("GenerateDocumentation", "true");
});
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
var testResults = artifacts + File("TestResults.xml");
NUnit3("./src/**/bin/**/Release/*.Tests.dll", new NUnit3Settings
{
Results = testResults
});
if (BuildSystem.IsRunningOnAppVeyor)
AppVeyor.UploadTestResults(testResults, AppVeyorTestResultsType.NUnit3);
});
Task("Package")
.IsDependentOn("Build")
.IsDependentOn("Test")
.Does(() =>
{
NuGetPack("./build/Deploy.nuspec", new NuGetPackSettings
{
Version = version,
BasePath = "./src",
OutputDirectory = artifacts
});
});
Task("Publish")
.IsDependentOn("Package")
.Does(() =>
{
var package = "./artifacts/Deploy." + version + ".nupkg";
NuGetPush(package, new NuGetPushSettings
{
ApiKey = nugetApiKey
});
});
//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("Package");
//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////
RunTarget(target);
|
#addin "nuget:?package=Cake.DocFx&version=0.1.6"
#addin "nuget:?package=Cake.ReSharperReports&version=0.3.1"
#tool "nuget:?package=GitVersion.CommandLine&version=3.6.1"
#tool "nuget:?package=NUnit.ConsoleRunner&version=3.4.1"
//////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var nugetApiKey = Argument("nugetapikey", EnvironmentVariable("NUGET_API_KEY"));
//////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
//////////////////////////////////////////////////////////////////////
var version = "1.0.0";
var artifacts = Directory("./artifacts");
var solution = File("./src/Deploy.sln");
//////////////////////////////////////////////////////////////////////
// TASKS
//////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() =>
{
CleanDirectories("./src/**/bin");
CleanDirectories("./src/**/obj");
if (DirectoryExists(artifacts))
DeleteDirectory(artifacts, true);
});
Task("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
NuGetRestore(solution);
});
Task("Versioning")
.IsDependentOn("Clean")
.WithCriteria(() => !BuildSystem.IsLocalBuild)
.Does(() =>
{
GitVersion(new GitVersionSettings
{
OutputType = GitVersionOutput.BuildServer
});
var result = GitVersion(new GitVersionSettings
{
UpdateAssemblyInfo = true
});
version = result.NuGetVersion;
});
Task("Build")
.IsDependentOn("Versioning")
.IsDependentOn("Restore")
.Does(() =>
{
CreateDirectory(artifacts);
DotNetBuild(solution, x =>
{
x.SetConfiguration("Release");
x.WithProperty("GenerateDocumentation", "true");
});
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
var testResults = artifacts + File("TestResults.xml");
NUnit3("./src/**/bin/**/Release/*.Tests.dll", new NUnit3Settings
{
Results = testResults
});
if (BuildSystem.IsRunningOnAppVeyor)
AppVeyor.UploadTestResults(testResults, AppVeyorTestResultsType.NUnit3);
});
Task("Package")
.IsDependentOn("Build")
.IsDependentOn("Test")
.Does(() =>
{
NuGetPack("./build/Deploy.nuspec", new NuGetPackSettings
{
Version = version,
BasePath = "./src",
OutputDirectory = artifacts
});
});
Task("Publish")
.IsDependentOn("Package")
.Does(() =>
{
var package = "./artifacts/Deploy." + version + ".nupkg";
NuGetPush(package, new NuGetPushSettings
{
ApiKey = nugetApiKey
});
});
//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("Package");
//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////
RunTarget(target);
|
mit
|
C#
|
1c3220765369ab9ae9c9ed4aedcd61388aa7ab9f
|
Add basic subjects tab
|
victoria92/university-program-generator,victoria92/university-program-generator
|
UniProgramGen/Data/Subject.cs
|
UniProgramGen/Data/Subject.cs
|
using System.Collections.Generic;
namespace UniProgramGen.Data
{
public class Subject
{
public List<RoomType> roomTypes { get; internal set; }
public List<Teacher> teachers { get; internal set; }
public string name { get; internal set; }
public uint duration { get; internal set; }
public string Name
{
get { return name; }
}
public Subject(List<RoomType> roomTypes, List<Teacher> teachers, string name, uint duration)
{
this.roomTypes = roomTypes;
this.teachers = teachers;
this.name = name;
this.duration = duration;
}
}
}
|
using System.Collections.Generic;
namespace UniProgramGen.Data
{
public class Subject
{
public List<RoomType> roomTypes { get; internal set; }
public List<Teacher> teachers { get; internal set; }
public string name { get; internal set; }
public uint duration { get; internal set; }
public Subject(List<RoomType> roomTypes, List<Teacher> teachers, string name, uint duration)
{
this.roomTypes = roomTypes;
this.teachers = teachers;
this.name = name;
this.duration = duration;
}
}
}
|
bsd-2-clause
|
C#
|
8f209336e72c196da18a6b568884cd69f7a13a26
|
Fix AudioFormat.GetBytesPerSample
|
ermau/Gablarski,ermau/Gablarski
|
src/Gablarski/Audio/AudioExtensions.cs
|
src/Gablarski/Audio/AudioExtensions.cs
|
// Copyright (c) 2011, Eric Maupin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with
// or without modification, are permitted provided that
// the following conditions are met:
//
// - Redistributions of source code must retain the above
// copyright notice, this list of conditions and the
// following disclaimer.
//
// - Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// - Neither the name of Gablarski nor the names of its
// contributors may be used to endorse or promote products
// or services derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
// AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Gablarski.Audio
{
public static class AudioExtensions
{
public static int GetBytesPerSample (this AudioFormat self)
{
return (self.BitsPerSample * self.Channels) / 8;
}
public static int GetBytes (this AudioFormat self, int samples)
{
return self.GetBytesPerSample () * samples;
}
public static int GetSamplesPerSecond (this AudioFormat self)
{
return self.SampleRate * self.Channels;
}
}
}
|
// Copyright (c) 2011, Eric Maupin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with
// or without modification, are permitted provided that
// the following conditions are met:
//
// - Redistributions of source code must retain the above
// copyright notice, this list of conditions and the
// following disclaimer.
//
// - Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// - Neither the name of Gablarski nor the names of its
// contributors may be used to endorse or promote products
// or services derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
// AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Gablarski.Audio
{
public static class AudioExtensions
{
public static int GetBytesPerSample (this AudioFormat self)
{
return self.BitsPerSample * self.Channels;
}
public static int GetBytes (this AudioFormat self, int samples)
{
return self.GetBytesPerSample () * samples;
}
public static int GetSamplesPerSecond (this AudioFormat self)
{
return self.SampleRate * self.Channels;
}
}
}
|
bsd-3-clause
|
C#
|
239d6433a13ffa5a92907a307ef979072be9d60e
|
Update CopyHelper.cs
|
github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity
|
src/GitHub.Api/Installer/CopyHelper.cs
|
src/GitHub.Api/Installer/CopyHelper.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GitHub.Logging;
namespace GitHub.Unity
{
public static class CopyHelper
{
private static readonly ILogging Logger = LogHelper.GetLogger(typeof(CopyHelper));
public static void Copy(NPath fromPath, NPath toPath)
{
Logger.Trace("Copying from {0} to {1}", fromPath, toPath);
try
{
CopyFolder(fromPath, toPath);
}
catch (Exception ex1)
{
Logger.Warning(ex1, "Error copying.");
try
{
CopyFolderContents(fromPath, toPath);
}
catch (Exception ex2)
{
Logger.Error(ex2, "Error copying contents.");
throw;
}
}
finally
{
fromPath.DeleteIfExists();
}
}
public static void CopyFolder(NPath fromPath, NPath toPath)
{
Logger.Trace("CopyFolder from {0} to {1}", fromPath, toPath);
toPath.DeleteIfExists();
toPath.EnsureParentDirectoryExists();
fromPath.Move(toPath);
}
public static void CopyFolderContents(NPath fromPath, NPath toPath)
{
Logger.Trace("CopyFolderContents from {0} to {1}", fromPath, toPath);
toPath.DeleteContents();
fromPath.MoveFiles(toPath, true);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GitHub.Logging;
namespace GitHub.Unity
{
public static class CopyHelper
{
private static readonly ILogging Logger = LogHelper.GetLogger(typeof(CopyHelper));
public static void Copy(NPath fromPath, NPath toPath)
{
Logger.Trace("Copying from {0} to {1}", fromPath, toPath);
try
{
CopyFolder(fromPath, toPath);
}
catch (Exception ex1)
{
Logger.Warning(ex1, "Error copying.");
try
{
CopyFolderContents(fromPath, toPath);
}
catch (Exception ex2)
{
Logger.Error(ex2, "Error copying contents.");
throw;
}
}
finally
{
fromPath.DeleteIfExists();
}
}
public static void CopyFolder(NPath fromPath, NPath toPath)
{
Logger.Trace("CopyFolder from {0} to {1}", fromPath, toPath);
toPath.DeleteIfExists();
toPath.EnsureParentDirectoryExists();
fromPath.Move(toPath);
}
public static void CopyFolderContents(NPath fromPath, NPath toPath)
{
Logger.Trace("CopyFolder Contents from {0} to {1}", fromPath, toPath);
toPath.DeleteContents();
fromPath.MoveFiles(toPath, true);
}
}
}
|
mit
|
C#
|
b46c5d5e15bdc6e4babd5194e0a1723d3e9cfc46
|
Correct the docs on ISession.IsAvailable #27733 (#36301)
|
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
|
src/Http/Http.Features/src/ISession.cs
|
src/Http/Http.Features/src/ISession.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Http
{
/// <summary>
/// Stores user data while the user browses a web application. Session state uses a store maintained by the application
/// to persist data across requests from a client. The session data is backed by a cache and considered ephemeral data.
/// </summary>
public interface ISession
{
/// <summary>
/// Indicates whether the current session loaded successfully. Accessing this property before the session is loaded will cause it to be loaded inline.
/// </summary>
bool IsAvailable { get; }
/// <summary>
/// A unique identifier for the current session. This is not the same as the session cookie
/// since the cookie lifetime may not be the same as the session entry lifetime in the data store.
/// </summary>
string Id { get; }
/// <summary>
/// Enumerates all the keys, if any.
/// </summary>
IEnumerable<string> Keys { get; }
/// <summary>
/// Load the session from the data store. This may throw if the data store is unavailable.
/// </summary>
/// <returns></returns>
Task LoadAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Store the session in the data store. This may throw if the data store is unavailable.
/// </summary>
/// <returns></returns>
Task CommitAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieve the value of the given key, if present.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns>The retrieved value.</returns>
bool TryGetValue(string key, [NotNullWhen(true)] out byte[]? value);
/// <summary>
/// Set the given key and value in the current session. This will throw if the session
/// was not established prior to sending the response.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
void Set(string key, byte[] value);
/// <summary>
/// Remove the given key from the session if present.
/// </summary>
/// <param name="key"></param>
void Remove(string key);
/// <summary>
/// Remove all entries from the current session, if any.
/// The session cookie is not removed.
/// </summary>
void Clear();
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Http
{
/// <summary>
/// Stores user data while the user browses a web application. Session state uses a store maintained by the application
/// to persist data across requests from a client. The session data is backed by a cache and considered ephemeral data.
/// </summary>
public interface ISession
{
/// <summary>
/// Indicate whether the current session has loaded.
/// </summary>
bool IsAvailable { get; }
/// <summary>
/// A unique identifier for the current session. This is not the same as the session cookie
/// since the cookie lifetime may not be the same as the session entry lifetime in the data store.
/// </summary>
string Id { get; }
/// <summary>
/// Enumerates all the keys, if any.
/// </summary>
IEnumerable<string> Keys { get; }
/// <summary>
/// Load the session from the data store. This may throw if the data store is unavailable.
/// </summary>
/// <returns></returns>
Task LoadAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Store the session in the data store. This may throw if the data store is unavailable.
/// </summary>
/// <returns></returns>
Task CommitAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieve the value of the given key, if present.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns>The retrieved value.</returns>
bool TryGetValue(string key, [NotNullWhen(true)] out byte[]? value);
/// <summary>
/// Set the given key and value in the current session. This will throw if the session
/// was not established prior to sending the response.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
void Set(string key, byte[] value);
/// <summary>
/// Remove the given key from the session if present.
/// </summary>
/// <param name="key"></param>
void Remove(string key);
/// <summary>
/// Remove all entries from the current session, if any.
/// The session cookie is not removed.
/// </summary>
void Clear();
}
}
|
apache-2.0
|
C#
|
b2a659d20fcd5e2c2befce488ab0137e26166ce4
|
Update the AntShellDemo to the new API.
|
antmicro/AntShell
|
AntShellDemo/AntCalc.cs
|
AntShellDemo/AntCalc.cs
|
/*
Copyright (c) 2013 Ant Micro <www.antmicro.com>
Authors:
* Mateusz Holenko (mholenko@antmicro.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 AntShell;
using System.IO;
using AntShell.Terminal;
namespace AntShellDemo
{
public class AntCalc
{
private Shell shell;
public AntCalc(Stream stream)
{
var sett = new ShellSettings {
NormalPrompt = new Prompt("ant-calc ", ConsoleColor.DarkBlue),
BannerProvider = () => "Welcome to AntCalc - AntShell Demo!"
};
var io = new IOProvider { Backend = new StreamIOSource(stream) };
shell = new Shell(io, null, sett);
shell.RegisterCommand(new AddCommand());
shell.RegisterCommand(new AskCommand());
shell.RegisterCommand(new PrintCommand());
}
public void Start()
{
shell.Start();
}
}
}
|
/*
Copyright (c) 2013 Ant Micro <www.antmicro.com>
Authors:
* Mateusz Holenko (mholenko@antmicro.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 AntShell;
using System.IO;
using AntShell.Terminal;
namespace AntShellDemo
{
public class AntCalc
{
private Shell shell;
public AntCalc(Stream stream)
{
var sett = new ShellSettings {
NormalPrompt = new Prompt("ant-calc ", ConsoleColor.DarkBlue),
Banner = "Welcome to AntCalc - AntShell Demo!"
};
shell = new Shell(new DetachableIO(new StreamIOSource(stream)), null, sett);
shell.RegisterCommand(new AddCommand());
shell.RegisterCommand(new AskCommand());
shell.RegisterCommand(new PrintCommand());
}
public void Start()
{
shell.Start();
}
}
}
|
apache-2.0
|
C#
|
e63393c1996c40ad7c9bd420d061963ef5596d88
|
Create project and editor explicitly
|
Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
|
Core2D.Sample/Program.cs
|
Core2D.Sample/Program.cs
|
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dependencies;
namespace Core2D.Sample
{
class Program
{
static void Main(string[] args)
{
CreateSampleProject();
}
static EditorContext CreateContext()
{
var context = new EditorContext()
{
View = null,
Renderers = null,
ProjectFactory = new ProjectFactory(),
TextClipboard = null,
Serializer = new NewtonsoftSerializer(),
PdfWriter = null,
DxfWriter = null,
CsvReader = null,
CsvWriter = null
};
var project = context.ProjectFactory.GetProject();
context.Editor = Editor.Create(project);
context.New();
return context;
}
static void CreateSampleProject()
{
try
{
var context = CreateContext();
var factory = new ShapeFactory(context);
factory.Line(30, 30, 60, 30);
factory.Text(30, 30, 60, 60, "Sample");
context.Save("sample.project");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
Console.ReadKey(true);
}
}
}
}
|
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dependencies;
namespace Core2D.Sample
{
class Program
{
static void Main(string[] args)
{
CreateSampleProject();
}
static EditorContext CreateContext()
{
var context = new EditorContext()
{
View = null,
Renderers = null,
ProjectFactory = new ProjectFactory(),
TextClipboard = null,
Serializer = new NewtonsoftSerializer(),
PdfWriter = null,
DxfWriter = null,
CsvReader = null,
CsvWriter = null
};
context.InitializeEditor();
context.InitializeCommands();
context.New();
return context;
}
static void CreateSampleProject()
{
try
{
var context = CreateContext();
var factory = new ShapeFactory(context);
factory.Line(30, 30, 60, 30);
factory.Text(30, 30, 60, 60, "Sample");
context.Save("sample.project");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
Console.ReadKey(true);
}
}
}
}
|
mit
|
C#
|
15128f71aae67374c34a8a0b6ca247b1873924fd
|
Update Program.cs
|
SteveAndrews/EmptyFolderDeleter
|
EmptyFolderDeleter/Program.cs
|
EmptyFolderDeleter/Program.cs
|
using System;
using System.IO;
using System.Linq;
namespace EmptyFolderDeleter
{
public class Program
{
private static string rootPath = @"C:\ReplaceWithDirectoryPath\";
public static void Main(string[] args)
{
RecurseDirectory(rootPath);
Console.WriteLine();
Console.WriteLine("Done");
Console.ReadKey();
}
private static void RecurseDirectory(string path)
{
try
{
var folders = Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly);
foreach (var folder in folders)
{
RecurseDirectory(folder);
}
var results = Directory.GetDirectories(path).Any() || Directory.GetFiles(path).Any();
if (!results && GetDirectorySize(path) == 0)
{
Directory.Delete(path, false);
Console.WriteLine("Deleted: {0}", path);
}
}
catch (Exception)
{
}
}
private static long GetDirectorySize(string path)
{
var files = Directory.GetFiles(path, "*.*");
long size = 0;
foreach (var name in files)
{
var info = new FileInfo(name);
size += info.Length;
}
return size;
}
}
}
|
using System;
using System.IO;
using System.Linq;
namespace EmptyFolderDeleter
{
public class Program
{
private static string rootPath = @"C:\Users\stevanich\";
public static void Main(string[] args)
{
RecurseDirectory(rootPath);
Console.WriteLine();
Console.WriteLine("Done");
Console.ReadKey();
}
private static void RecurseDirectory(string path)
{
try
{
var folders = Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly);
foreach (var folder in folders)
{
RecurseDirectory(folder);
}
var results = Directory.GetDirectories(path).Any() || Directory.GetFiles(path).Any();
if (!results && GetDirectorySize(path) == 0)
{
Directory.Delete(path, false);
Console.WriteLine("Deleted: {0}", path);
}
}
catch (Exception)
{
}
}
private static long GetDirectorySize(string path)
{
var files = Directory.GetFiles(path, "*.*");
long size = 0;
foreach (var name in files)
{
var info = new FileInfo(name);
size += info.Length;
}
return size;
}
}
}
|
mit
|
C#
|
4d3baafe06f345cf97cd98c4b1bbd496af1c1cc2
|
Remove unneeded member variable
|
TheEadie/LazyLibrary,TheEadie/LazyStorage,TheEadie/LazyStorage
|
LazyStorage/StorageFactory.cs
|
LazyStorage/StorageFactory.cs
|
using LazyStorage.InMemory;
using LazyStorage.Xml;
namespace LazyStorage
{
public class StorageFactory
{
public IStorage GetInMemoryStorage()
{
return new InMemoryStorage();
}
public IStorage GetXmlStorage(string storageFolder)
{
return new XmlStorage(storageFolder);
}
}
}
|
using LazyStorage.InMemory;
using LazyStorage.Xml;
namespace LazyStorage
{
public class StorageFactory
{
private IStorage m_Store;
public IStorage GetInMemoryStorage()
{
return m_Store = new InMemoryStorage();
}
public IStorage GetXmlStorage(string storageFolder)
{
return new XmlStorage(storageFolder);
}
}
}
|
mit
|
C#
|
4ee162fbc0292ef70bdb5bcfd78f048e89c28c60
|
Update Test
|
arduosoft/wlog,arduosoft/wlog
|
Wlog.Test/Tests/Repository.cs
|
Wlog.Test/Tests/Repository.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wlog.Library.BLL.Reporitories;
using Xunit;
namespace Wlog.Test.Tests
{
public class Repository
{
[Fact]
public void InitRepo()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wlog.Library.BLL.Reporitories;
using Xunit;
namespace Wlog.Test.Tests
{
public class Repository
{
[Fact]
public void InitRepo()
{
RepositoryContext.Current.Users.GetById(new Guid(""));
}
}
}
|
lgpl-2.1
|
C#
|
e8537d34af2037c6a6381f44c1a8b7d8025556a1
|
Change messages attribute to type "object"
|
goshippo/shippo-csharp-client
|
Shippo/BatchShipment.cs
|
Shippo/BatchShipment.cs
|
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Shippo
{
[JsonObject (MemberSerialization.OptIn)]
public class BatchShipment : ShippoId
{
[JsonProperty (PropertyName = "object_status")]
public string ObjectStatus;
[JsonProperty (PropertyName = "carrier_account")]
public string CarrierAccount;
[JsonProperty (PropertyName = "servicelevel_token")]
public string ServicelevelToken;
[JsonProperty (PropertyName = "shipment")]
public Object Shipment;
[JsonProperty (PropertyName = "transaction")]
public string Transaction;
[JsonProperty (PropertyName = "messages")]
public object Messages;
[JsonProperty (PropertyName = "metadata")]
public string Metadata;
public override string ToString ()
{
return string.Format ("[BatchShipment: ObjectStatus={0}, CarrierAccount={1}, ServicelevelToken={2}, " +
"Shipment={3}, Transaction={4}, Messages={5}, Metadata={6}]", ObjectStatus,
CarrierAccount, ServicelevelToken, Shipment, Transaction, Messages, Metadata);
}
}
}
|
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Shippo
{
[JsonObject (MemberSerialization.OptIn)]
public class BatchShipment : ShippoId
{
[JsonProperty (PropertyName = "object_status")]
public string ObjectStatus;
[JsonProperty (PropertyName = "carrier_account")]
public string CarrierAccount;
[JsonProperty (PropertyName = "servicelevel_token")]
public string ServicelevelToken;
[JsonProperty (PropertyName = "shipment")]
public Object Shipment;
[JsonProperty (PropertyName = "transaction")]
public string Transaction;
[JsonProperty (PropertyName = "messages")]
public List<String> Messages;
[JsonProperty (PropertyName = "metadata")]
public string Metadata;
public override string ToString ()
{
return string.Format ("[BatchShipment: ObjectStatus={0}, CarrierAccount={1}, ServicelevelToken={2}, " +
"Shipment={3}, Transaction={4}, Messages={5}, Metadata={6}]", ObjectStatus,
CarrierAccount, ServicelevelToken, Shipment, Transaction, Messages, Metadata);
}
}
}
|
apache-2.0
|
C#
|
f18816a2040d17225f61f8f1da5cb530eb51313e
|
Use new expressions
|
steamcore/TinyIpc
|
test/TinyIpc.Benchmarks/Benchmark.cs
|
test/TinyIpc.Benchmarks/Benchmark.cs
|
using System.Text;
using BenchmarkDotNet.Attributes;
using TinyIpc.IO;
using TinyIpc.Messaging;
namespace TinyIpc.Benchmarks;
[MemoryDiagnoser]
public class Benchmark : IDisposable
{
private readonly byte[] message = Encoding.UTF8.GetBytes("Lorem ipsum dolor sit amet.");
private readonly TinyMessageBus messagebusWithRealFile = new("benchmark", TimeSpan.Zero);
private readonly TinyMessageBus messagebusWithFakeFile = new(new FakeMemoryMappedFile(100_000), true, TimeSpan.Zero);
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
messagebusWithRealFile.Dispose();
messagebusWithFakeFile.Dispose();
}
}
[Benchmark]
public Task PublishRealFile()
{
return messagebusWithRealFile.PublishAsync(message);
}
[Benchmark]
public Task PublishFakeFile()
{
return messagebusWithFakeFile.PublishAsync(message);
}
}
internal sealed class FakeMemoryMappedFile : ITinyMemoryMappedFile, IDisposable
{
private readonly MemoryStream memoryStream;
private readonly MemoryStream writeStream;
public long MaxFileSize { get; }
public event EventHandler? FileUpdated;
public FakeMemoryMappedFile(int maxFileSize)
{
MaxFileSize = maxFileSize;
memoryStream = new MemoryStream(maxFileSize);
writeStream = new MemoryStream(maxFileSize);
}
public void Dispose()
{
memoryStream.Dispose();
writeStream.Dispose();
}
public int GetFileSize()
{
return (int)memoryStream.Length;
}
public T Read<T>(Func<MemoryStream, T> readData)
{
memoryStream.Seek(0, SeekOrigin.Begin);
return readData(memoryStream);
}
public void ReadWrite(Action<MemoryStream, MemoryStream> updateFunc)
{
memoryStream.Seek(0, SeekOrigin.Begin);
writeStream.SetLength(0);
updateFunc(memoryStream, writeStream);
memoryStream.SetLength(0);
writeStream.Seek(0, SeekOrigin.Begin);
writeStream.CopyTo(memoryStream);
FileUpdated?.Invoke(this, EventArgs.Empty);
}
public void Write(MemoryStream data)
{
memoryStream.SetLength(0);
data.CopyTo(memoryStream);
FileUpdated?.Invoke(this, EventArgs.Empty);
}
}
|
using System.Text;
using BenchmarkDotNet.Attributes;
using TinyIpc.IO;
using TinyIpc.Messaging;
namespace TinyIpc.Benchmarks;
[MemoryDiagnoser]
public class Benchmark : IDisposable
{
private readonly byte[] message = Encoding.UTF8.GetBytes("Lorem ipsum dolor sit amet.");
private readonly TinyMessageBus messagebusWithRealFile = new TinyMessageBus("benchmark", TimeSpan.Zero);
private readonly TinyMessageBus messagebusWithFakeFile = new TinyMessageBus(new FakeMemoryMappedFile(100_000), true, TimeSpan.Zero);
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
messagebusWithRealFile.Dispose();
messagebusWithFakeFile.Dispose();
}
}
[Benchmark]
public Task PublishRealFile()
{
return messagebusWithRealFile.PublishAsync(message);
}
[Benchmark]
public Task PublishFakeFile()
{
return messagebusWithFakeFile.PublishAsync(message);
}
}
internal sealed class FakeMemoryMappedFile : ITinyMemoryMappedFile, IDisposable
{
private readonly MemoryStream memoryStream;
private readonly MemoryStream writeStream;
public long MaxFileSize { get; }
public event EventHandler? FileUpdated;
public FakeMemoryMappedFile(int maxFileSize)
{
MaxFileSize = maxFileSize;
memoryStream = new MemoryStream(maxFileSize);
writeStream = new MemoryStream(maxFileSize);
}
public void Dispose()
{
memoryStream.Dispose();
writeStream.Dispose();
}
public int GetFileSize()
{
return (int)memoryStream.Length;
}
public T Read<T>(Func<MemoryStream, T> readData)
{
memoryStream.Seek(0, SeekOrigin.Begin);
return readData(memoryStream);
}
public void ReadWrite(Action<MemoryStream, MemoryStream> updateFunc)
{
memoryStream.Seek(0, SeekOrigin.Begin);
writeStream.SetLength(0);
updateFunc(memoryStream, writeStream);
memoryStream.SetLength(0);
writeStream.Seek(0, SeekOrigin.Begin);
writeStream.CopyTo(memoryStream);
FileUpdated?.Invoke(this, EventArgs.Empty);
}
public void Write(MemoryStream data)
{
memoryStream.SetLength(0);
data.CopyTo(memoryStream);
FileUpdated?.Invoke(this, EventArgs.Empty);
}
}
|
mit
|
C#
|
077be5a5603d058ba582e9ae8a6d5e5e2a366d32
|
remove summary for atom feed
|
bapt/cplanet
|
samples/cplanet-atom.cs
|
samples/cplanet-atom.cs
|
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title type="text"><?cs var:CPlanet.Name ?></title>
<subtitle type="text"><?cs var:CPlanet.Description ?></subtitle>
<id><?cs var:CPlanet.URL ?>/</id>
<link rel="self" type="text/xml" href="<?cs var:CPlanet.URL ?>/cplanet.atom" />
<link rel="alternate" type="text/html" href="<?cs var:CPlanet.URL ?>" />
<updated><?cs var:CPlanet.GenerationDate ?></updated>
<author><name><?cs var:CPlanet.Name ?></name></author>
<generator uri="http://wiki.github.com/bapt/CPlanet" version="<?cs var:CPlanet.Version ?>">CPlanet</generator>
<?cs each:post = CPlanet.Posts ?>
<entry>
<title type="text"><?cs var:post.FeedName ?> >> <?cs var:post.Title ?></title>
<?cs if:post.Author ?><author><name> <?cs var:post.Author ?></name></author> <?cs /if ?>
<content type="html"><![CDATA[<?cs var:post.Description ?>]]></content>
<?cs each:tags = post.Tags ?><category term="<?cs var:tags.Tag ?>" /><?cs /each ?>
<id><?cs var:post.Link ?></id>
<link rel="alternate" href="<?cs var:post.Link ?>" />
<published><?cs var:post.Date ?></published>
</entry>
<?cs /each ?>
</feed>
|
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title type="text"><?cs var:CPlanet.Name ?></title>
<subtitle type="text"><?cs var:CPlanet.Description ?></subtitle>
<id><?cs var:CPlanet.URL ?>/</id>
<link rel="self" type="text/xml" href="<?cs var:CPlanet.URL ?>/cplanet.atom" />
<link rel="alternate" type="text/html" href="<?cs var:CPlanet.URL ?>" />
<updated><?cs var:CPlanet.GenerationDate ?></updated>
<author><name><?cs var:CPlanet.Name ?></name></author>
<generator uri="http://wiki.github.com/bapt/CPlanet" version="<?cs var:CPlanet.Version ?>">CPlanet</generator>
<?cs each:post = CPlanet.Posts ?>
<entry>
<title type="text"><?cs var:post.FeedName ?> >> <?cs var:post.Title ?></title>
<summary type="text">None Currently</summary>
<?cs if:post.Author ?><author><name> <?cs var:post.Author ?></name></author> <?cs /if ?>
<content type="html"><![CDATA[<?cs var:post.Description ?>]]></content>
<?cs each:tags = post.Tags ?><category term="<?cs var:tags.Tag ?>" /><?cs /each ?>
<id><?cs var:post.Link ?></id>
<link rel="alternate" href="<?cs var:post.Link ?>" />
<published><?cs var:post.Date ?></published>
</entry>
<?cs /each ?>
</feed>
|
bsd-2-clause
|
C#
|
a92252bee3a99d77832b173396ef8cf297fdc3f6
|
optimize red
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Gui/Converters/MoneyBrushConverter.cs
|
WalletWasabi.Gui/Converters/MoneyBrushConverter.cs
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Avalonia.Data.Converters;
using Avalonia.Media;
using AvalonStudio.Extensibility.Theme;
using NBitcoin;
using WalletWasabi.Models;
namespace WalletWasabi.Gui.Converters
{
public class MoneyBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var money = decimal.Parse((string)value);
return money < 0 ? Brushes.IndianRed : Brushes.Green;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Avalonia.Data.Converters;
using Avalonia.Media;
using AvalonStudio.Extensibility.Theme;
using NBitcoin;
using WalletWasabi.Models;
namespace WalletWasabi.Gui.Converters
{
public class MoneyBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var money = decimal.Parse((string)value);
return money < 0 ? Brushes.Red : Brushes.Green;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
}
|
mit
|
C#
|
edc4867c54cf8b97f76df1d0cff3dfd76d7d10f7
|
Divide by zero error
|
1game/1game-csharp
|
Playtomic/PlayerLevel.cs
|
Playtomic/PlayerLevel.cs
|
using System;
using System.Collections;
namespace Playtomic
{
public class PlayerLevel : Hashtable
{
public PlayerLevel()
{
}
public PlayerLevel(IDictionary data)
{
foreach(string x in data.Keys)
{
if(x == "date")
{
var d = new DateTime(1970, 1, 1, 0, 0, 0);
date = d.AddSeconds ((double)data[x]);
}
else
{
this[x] = data[x];
}
}
}
public string levelid
{
get { return GetString ("levelid"); }
set { SetProperty ("levelid", value); }
}
public string source
{
get { return GetString ("source"); }
set { SetProperty ("source", value); }
}
public string playerid
{
get { return GetString ("playerid"); }
set { SetProperty ("playerid", value); }
}
public string playername
{
get { return GetString ("playername"); }
set { SetProperty ("playername", value); }
}
public string name
{
get { return GetString ("name"); }
set { SetProperty ("name", value); }
}
public string data
{
get { return GetString ("data"); }
set { SetProperty ("data", value); }
}
public long votes
{
get { return GetLong("votes"); }
}
public long score
{
get { return GetLong ("score"); }
}
public double rating
{
get {
var s = score;
var v = votes;
if (s == 0 || v == 0) {
return 0;
}
return s / v;
}
}
public DateTime date
{
get { return ContainsKey ("date") ? (DateTime) this["date"] : DateTime.Now; }
set { SetProperty ("date", value); }
}
public string rdate
{
get { return GetString ("rdate"); }
set { SetProperty ("rdate", value); }
}
public Hashtable fields
{
get { return ContainsKey ("fields") ? (Hashtable)this["fields"] : new Hashtable(); }
set { SetProperty ("fields", value); }
}
private long GetLong(string s)
{
return ContainsKey (s) ? (Int64) this[s] : 0L;
}
private string GetString(string s)
{
return ContainsKey (s) ? this[s].ToString () : null;
}
private void SetProperty(string key, object value)
{
if(ContainsKey(key))
{
this[key] = value;
}
else
{
Add(key, value);
}
}
}
}
|
using System;
using System.Collections;
namespace Playtomic
{
public class PlayerLevel : Hashtable
{
public PlayerLevel()
{
}
public PlayerLevel(IDictionary data)
{
foreach(string x in data.Keys)
{
if(x == "date")
{
var d = new DateTime(1970, 1, 1, 0, 0, 0);
date = d.AddSeconds ((double)data[x]);
}
else
{
this[x] = data[x];
}
}
}
public string levelid
{
get { return GetString ("levelid"); }
set { SetProperty ("levelid", value); }
}
public string source
{
get { return GetString ("source"); }
set { SetProperty ("source", value); }
}
public string playerid
{
get { return GetString ("playerid"); }
set { SetProperty ("playerid", value); }
}
public string playername
{
get { return GetString ("playername"); }
set { SetProperty ("playername", value); }
}
public string name
{
get { return GetString ("name"); }
set { SetProperty ("name", value); }
}
public string data
{
get { return GetString ("data"); }
set { SetProperty ("data", value); }
}
public long votes
{
get { return GetLong("votes"); }
set { SetProperty ("votes", value); }
}
public long plays
{
get { return GetLong ("plays"); }
set { SetProperty ("plays", value); }
}
public double rating
{
get { return score / votes; }
}
public long score
{
get { return GetLong ("score"); }
set { SetProperty ("score", value); }
}
public DateTime date
{
get { return ContainsKey ("date") ? (DateTime) this["date"] : DateTime.Now; }
set { SetProperty ("date", value); }
}
public string rdate
{
get { return GetString ("rdate"); }
set { SetProperty ("rdate", value); }
}
public Hashtable fields
{
get { return ContainsKey ("fields") ? (Hashtable)this["fields"] : new Hashtable(); }
set { SetProperty ("fields", value); }
}
private long GetLong(string s)
{
return ContainsKey (s) ? (Int64) this[s] : 0L;
}
private string GetString(string s)
{
return ContainsKey (s) ? this[s].ToString () : null;
}
private void SetProperty(string key, object value)
{
if(ContainsKey(key))
{
this[key] = value;
}
else
{
Add(key, value);
}
}
}
}
|
mit
|
C#
|
a6d9adb5bff9d790342bed1413b1afab1fb36b53
|
Adjust timing ratio to prevent occasional failing
|
Fody/FodyAddinSamples,Fody/FodyAddinSamples
|
ThrottleSample/Sample.cs
|
ThrottleSample/Sample.cs
|
using System;
using System.Threading;
using System.Windows.Threading;
using Throttle;
using Xunit;
using TomsToolbox.Desktop;
public class ThrottleSample
{
int throttledCalls;
[Fact]
public void Run()
{
var dispatcher = Dispatcher.CurrentDispatcher;
dispatcher.BeginInvoke(() =>
{
ThrottledMethod();
Delay(5);
ThrottledMethod();
Delay(5);
ThrottledMethod();
Delay(5);
ThrottledMethod();
Delay(5);
ThrottledMethod();
Delay(5);
Assert.Equal(0, throttledCalls);
Delay(200);
Assert.Equal(1, throttledCalls);
dispatcher.BeginInvokeShutdown(DispatcherPriority.ApplicationIdle);
});
Dispatcher.Run();
}
static void Delay(int timeSpan)
{
var frame = new DispatcherFrame();
var timer = new DispatcherTimer(TimeSpan.FromMilliseconds(timeSpan), DispatcherPriority.Normal, (sender, args) => frame.Continue = false, Dispatcher.CurrentDispatcher);
timer.Start();
Dispatcher.PushFrame(frame);
}
[Throttled(typeof(TomsToolbox.Desktop.Throttle), 100)]
void ThrottledMethod()
{
Interlocked.Increment(ref throttledCalls);
}
}
|
using System;
using System.Threading;
using System.Windows.Threading;
using Throttle;
using Xunit;
using TomsToolbox.Desktop;
public class ThrottleSample
{
int throttledCalls;
[Fact]
public void Run()
{
var dispatcher = Dispatcher.CurrentDispatcher;
dispatcher.BeginInvoke(() =>
{
ThrottledMethod();
Delay(5);
ThrottledMethod();
Delay(5);
ThrottledMethod();
Delay(5);
ThrottledMethod();
Delay(5);
ThrottledMethod();
Delay(5);
Assert.Equal(0, throttledCalls);
Delay(20);
Assert.Equal(1, throttledCalls);
dispatcher.BeginInvokeShutdown(DispatcherPriority.ApplicationIdle);
});
Dispatcher.Run();
}
static void Delay(int timeSpan)
{
var frame = new DispatcherFrame();
var timer = new DispatcherTimer(TimeSpan.FromMilliseconds(timeSpan), DispatcherPriority.Normal, (sender, args) => frame.Continue = false, Dispatcher.CurrentDispatcher);
timer.Start();
Dispatcher.PushFrame(frame);
}
[Throttled(typeof(TomsToolbox.Desktop.Throttle), 10)]
void ThrottledMethod()
{
Interlocked.Increment(ref throttledCalls);
}
}
|
mit
|
C#
|
2bb674bb0ae06cd624c03564a8606983dbed0b3e
|
Fix line endings.
|
OSVR/OSVR-Unity,DuFF14/OSVR-Unity,grobm/OSVR-Unity,grobm/OSVR-Unity,JeroMiya/OSVR-Unity
|
Managed-OSVR/ExampleClients/TrackerCallback/Properties/AssemblyInfo.cs
|
Managed-OSVR/ExampleClients/TrackerCallback/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Managed-OSVR Tracker Callback Example")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany("Sensics, Inc.")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright("Copyright © 2014 Sensics, Inc.")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.0.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
[assembly: AssemblyFileVersionAttribute("1.0.0.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Managed-OSVR Tracker Callback Example")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany("Sensics, Inc.")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright("Copyright © 2014 Sensics, Inc.")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.0.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
[assembly: AssemblyFileVersionAttribute("1.0.0.0")]
|
apache-2.0
|
C#
|
acb73b172f344e1dcbb10cb4c14d02bcf5a012a9
|
Change default ships
|
BeefEX/ships
|
Ships-Common/Ship.cs
|
Ships-Common/Ship.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Ships_Common {
public class Ship {
public static class Parts {
public static char[,] PART_EXPLODED = {{'\\', '#', '/'}, {'@', '#', '@'}, {'/', '@', '\\'}};
}
public static Dictionary<string, Ship> defaultShips = new Dictionary<string, Ship> {
{"SHIP_SMALL", new Ship(default(Vector2), new[] {new Vector2()})},
{"SHIP_NORMAL", new Ship(default(Vector2), new[] {new Vector2(), new Vector2(0, -1)})},
{"SHIP_BIG", new Ship(default(Vector2), new[] {new Vector2(0, 1), new Vector2(), new Vector2(0, -1)})},
{"SHIP_HUGE", new Ship(default(Vector2), new[] {new Vector2(0, 1), new Vector2(), new Vector2(0, -1), new Vector2(0, -2)})}
};
public Vector2[] shape { get; private set; }
public bool[] hits { get; private set; }
public Vector2 position;
protected Ship(Vector2 position, Vector2[] shape) {
this.position = position;
this.shape = shape;
hits = new bool[this.shape.Length];
}
public bool isHit(Vector2 pos) {
bool hit = checkShape(pos);
if (hit) {
int index = 0;
for (int i = 0; i < shape.Length; i++) {
if (Equals(shape[i], position - pos)) {
index = i;
break;
}
}
hits[index] = true;
}
return hit;
}
public bool checkShape(Vector2 pos) {
return shape.Contains(pos - position);
}
public Ship Instantiate(Vector2 pos) {
return new Ship(pos, shape);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Ships_Common {
public class Ship {
public static class Parts {
public static char[,] PART_EXPLODED = {{'\\', '#', '/'}, {'@', '#', '@'}, {'/', '@', '\\'}};
}
public static Ship SHIP_SMALL = new Ship(default(Vector2), new[] { new Vector2(0, 0) });
public static Ship SHIP_NORMAL = new Ship(default(Vector2), new[] { new Vector2(0, 0), new Vector2(0, -1) });
public static Ship SHIP_BIG = new Ship(default(Vector2), new[] { new Vector2(0, 1), new Vector2(0, 0), new Vector2(0, -1) });
public static Ship SHIP_PLANE = new Ship(default(Vector2), new[] { new Vector2(0, 1), new Vector2(0, 0), new Vector2(0, -1), new Vector2(1, 0) });
public Vector2[] shape { get; private set; }
public bool[] hits { get; private set; }
public Vector2 position;
protected Ship(Vector2 position, Vector2[] shape) {
this.position = position;
this.shape = shape;
hits = new bool[this.shape.Length];
}
public bool isHit(Vector2 pos) {
bool hit = checkShape(pos);
if (hit) {
int index = 0;
for (int i = 0; i < shape.Length; i++) {
if (Equals(shape[i], position - pos)) {
index = i;
break;
}
}
hits[index] = true;
}
return hit;
}
public bool checkShape(Vector2 pos) {
return shape.Contains(pos - position);
}
public Ship Instantiate(Vector2 pos) {
return new Ship(pos, shape);
}
}
}
|
mit
|
C#
|
80e7e473470bef732381c782b412e6925c8bab2d
|
Remove random SoftPwm test code
|
treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk
|
NET/Demos/Console/Blink/Program.cs
|
NET/Demos/Console/Blink/Program.cs
|
using System;
using Treehopper;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Collections.Generic;
using System.Threading;
namespace Blink
{
/// <summary>
/// This demo blinks the built-in LED using async programming.
/// </summary>
class Program
{
static TreehopperUsb Board;
static void Main(string[] args)
{
// We can't do async calls from the Console's Main() function, so we run all our code in a separate async method.
RunBlink().Wait();
}
static async Task RunBlink()
{
while (true)
{
Console.Write("Waiting for board...");
// Get a reference to the first TreehopperUsb board connected. This will await indefinitely until a board is connected.
Board = await ConnectionService.Instance.GetFirstDeviceAsync();
Console.WriteLine("Found board: " + Board);
Console.WriteLine("Version: " + Board.Version);
// You must explicitly connect to a board before communicating with it
await Board.ConnectAsync();
Console.WriteLine("Start blinking. Press any key to stop.");
while (Board.IsConnected && !Console.KeyAvailable)
{
// toggle the LED.
Board.Led = !Board.Led;
await Task.Delay(100);
}
}
}
}
}
|
using System;
using Treehopper;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Collections.Generic;
using System.Threading;
namespace Blink
{
/// <summary>
/// This demo blinks the built-in LED using async programming.
/// </summary>
class Program
{
static TreehopperUsb Board;
static void Main(string[] args)
{
// We can't do async calls from the Console's Main() function, so we run all our code in a separate async method.
RunBlink().Wait();
}
static async Task RunBlink()
{
while (true)
{
Console.Write("Waiting for board...");
// Get a reference to the first TreehopperUsb board connected. This will await indefinitely until a board is connected.
Board = await ConnectionService.Instance.GetFirstDeviceAsync();
Console.WriteLine("Found board: " + Board);
Console.WriteLine("Version: " + Board.Version);
// You must explicitly connect to a board before communicating with it
await Board.ConnectAsync();
Board.Pins[0].SoftPwm.Enabled = true;
Board.Pins[0].SoftPwm.DutyCycle = 0.5;
Console.WriteLine("Start blinking. Press any key to stop.");
while (Board.IsConnected && !Console.KeyAvailable)
{
// toggle the LED.
Board.Led = !Board.Led;
await Task.Delay(100);
}
}
}
}
}
|
mit
|
C#
|
fe748ce1d1869d783e348aa083fa7c94d46affce
|
Add Comment C#2.0 point_07 restricting-accessor-accessibility
|
m2wasabi/CSharpYuRuFuWaHandson
|
CS2_07_restricting-accessor-accessibility/Program.cs
|
CS2_07_restricting-accessor-accessibility/Program.cs
|
using System;
namespace CS2_07_restricting_accessor_accessibility
{
class Program
{
/// <summary>プロパティの get/set 個別のアクセスレベル</summary>
/// <remarks>プロパティの get アクセサーと set で異なるアクセス レベルを設定できる。
/// https://docs.microsoft.com/ja-jp/dotnet/csharp/programming-guide/nullable-types/
/// </remarks>
static void Main(string[] args)
{
A a = new A();
// a.PropertyA = 1; <- これはできない
a.SetPropertyA(10);
int propertyValue = a.PropertyA;
Console.WriteLine(propertyValue); // 10
Console.ReadKey();
}
}
class A
{
public int PropertyA { get; private set; }
public void SetPropertyA(int value) { PropertyA = value; }
}
}
|
using System;
namespace CS2_07_restricting_accessor_accessibility
{
class Program
{
static void Main(string[] args)
{
A a = new A();
// a.PropertyA = 1; <- これはできない
a.SetPropertyA(10);
int propertyValue = a.PropertyA;
Console.WriteLine(propertyValue); // 10
Console.ReadKey();
}
}
class A
{
public int PropertyA { get; private set; }
public void SetPropertyA(int value) { PropertyA = value; }
}
}
|
mit
|
C#
|
7b7da43fd819830151aa70b9e4dc951d835d19de
|
Update comments in RemoteAuthenticationOptions
|
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
|
src/Microsoft.AspNetCore.Authentication/RemoteAuthenticationOptions.cs
|
src/Microsoft.AspNetCore.Authentication/RemoteAuthenticationOptions.cs
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authentication;
namespace Microsoft.AspNetCore.Builder
{
/// <summary>
/// Contains the options used by the <see cref="RemoteAuthenticationHandler{T}"/>.
/// </summary>
public class RemoteAuthenticationOptions : AuthenticationOptions
{
/// <summary>
/// Gets or sets timeout value in milliseconds for back channel communications with the remote identity provider.
/// </summary>
/// <value>
/// The back channel timeout.
/// </value>
public TimeSpan BackchannelTimeout { get; set; } = TimeSpan.FromSeconds(60);
/// <summary>
/// The HttpMessageHandler used to communicate with remote identity provider.
/// This cannot be set at the same time as BackchannelCertificateValidator unless the value
/// can be downcast to a WebRequestHandler.
/// </summary>
public HttpMessageHandler BackchannelHttpHandler { get; set; }
/// <summary>
/// The request path within the application's base path where the user-agent will be returned.
/// The middleware will process this request when it arrives.
/// </summary>
public PathString CallbackPath { get; set; }
/// <summary>
/// Gets or sets the authentication scheme corresponding to the middleware
/// responsible of persisting user's identity after a successful authentication.
/// This value typically corresponds to a cookie middleware registered in the Startup class.
/// When omitted, <see cref="SharedAuthenticationOptions.SignInScheme"/> is used as a fallback value.
/// </summary>
public string SignInScheme { get; set; }
/// <summary>
/// Get or sets the text that the user can display on a sign in user interface.
/// </summary>
public string DisplayName
{
get { return Description.DisplayName; }
set { Description.DisplayName = value; }
}
/// <summary>
/// Gets or sets the time limit for completing the authentication flow (15 minutes by default).
/// </summary>
public TimeSpan RemoteAuthenticationTimeout { get; set; } = TimeSpan.FromMinutes(15);
public IRemoteAuthenticationEvents Events = new RemoteAuthenticationEvents();
/// <summary>
/// Defines whether access and refresh tokens should be stored in the
/// <see cref="Http.Authentication.AuthenticationProperties"/> after a successful authorization.
/// This property is set to <c>false</c> by default to reduce
/// the size of the final authentication cookie.
/// </summary>
public bool SaveTokens { get; set; }
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authentication;
namespace Microsoft.AspNetCore.Builder
{
/// <summary>
/// Contains the options used by the <see cref="RemoteAuthenticationHandler{T}"/>.
/// </summary>
public class RemoteAuthenticationOptions : AuthenticationOptions
{
/// <summary>
/// Gets or sets timeout value in milliseconds for back channel communications with the remote provider.
/// </summary>
/// <value>
/// The back channel timeout.
/// </value>
public TimeSpan BackchannelTimeout { get; set; } = TimeSpan.FromSeconds(60);
/// <summary>
/// The HttpMessageHandler used to communicate with Twitter.
/// This cannot be set at the same time as BackchannelCertificateValidator unless the value
/// can be downcast to a WebRequestHandler.
/// </summary>
public HttpMessageHandler BackchannelHttpHandler { get; set; }
/// <summary>
/// The request path within the application's base path where the user-agent will be returned.
/// The middleware will process this request when it arrives.
/// </summary>
public PathString CallbackPath { get; set; }
/// <summary>
/// Gets or sets the authentication scheme corresponding to the middleware
/// responsible of persisting user's identity after a successful authentication.
/// This value typically corresponds to a cookie middleware registered in the Startup class.
/// When omitted, <see cref="SharedAuthenticationOptions.SignInScheme"/> is used as a fallback value.
/// </summary>
public string SignInScheme { get; set; }
/// <summary>
/// Get or sets the text that the user can display on a sign in user interface.
/// </summary>
public string DisplayName
{
get { return Description.DisplayName; }
set { Description.DisplayName = value; }
}
/// <summary>
/// Gets or sets the time limit for completing the authentication flow (15 minutes by default).
/// </summary>
public TimeSpan RemoteAuthenticationTimeout { get; set; } = TimeSpan.FromMinutes(15);
public IRemoteAuthenticationEvents Events = new RemoteAuthenticationEvents();
/// <summary>
/// Defines whether access and refresh tokens should be stored in the
/// <see cref="Http.Authentication.AuthenticationProperties"/> after a successful authorization.
/// This property is set to <c>false</c> by default to reduce
/// the size of the final authentication cookie.
/// </summary>
public bool SaveTokens { get; set; }
}
}
|
apache-2.0
|
C#
|
26b7aaa76ea8c53e8f0aafc796c12652f3a2eee6
|
Fix Navigation link on acl
|
dfensgmbh/biz.dfch.CS.Appclusive.UI,dfensgmbh/biz.dfch.CS.Appclusive.UI,dfch/biz.dfch.CS.Appclusive.UI,dfch/biz.dfch.CS.Appclusive.UI,dfch/biz.dfch.CS.Appclusive.UI
|
src/biz.dfch.CS.Appclusive.UI/Views/Shared/DisplayTemplates/Acl.cshtml
|
src/biz.dfch.CS.Appclusive.UI/Views/Shared/DisplayTemplates/Acl.cshtml
|
@model biz.dfch.CS.Appclusive.UI.Models.Core.Acl
@using biz.dfch.CS.Appclusive.UI.App_LocalResources
@if (Model != null && !string.IsNullOrEmpty(Model.Name))
{
if (biz.dfch.CS.Appclusive.UI.Navigation.PermissionDecisions.Current.HasPermission(Model.GetType(), "CanRead"))
{
string id = (string)ViewContext.Controller.ControllerContext.RouteData.Values["id"];
string action = (string)ViewContext.Controller.ControllerContext.RouteData.Values["action"];
string controller = (string)ViewContext.Controller.ControllerContext.RouteData.Values["controller"];
@Html.ActionLink(Model.Name, "Details", "Acls", new { id = Model.Id, rId = id, rAction = action, rController = controller }, null)
}
else
{
@Html.DisplayFor(model => model.Name)
}
}
|
@model biz.dfch.CS.Appclusive.UI.Models.Core.Acl
@using biz.dfch.CS.Appclusive.UI.App_LocalResources
@if (Model != null && !string.IsNullOrEmpty(Model.Name))
{
if (biz.dfch.CS.Appclusive.UI.Navigation.PermissionDecisions.Current.HasPermission(Model.GetType(), "CanRead"))
{
string id = (string)ViewContext.Controller.ControllerContext.RouteData.Values["id"];
string action = (string)ViewContext.Controller.ControllerContext.RouteData.Values["action"];
string controller = (string)ViewContext.Controller.ControllerContext.RouteData.Values["controller"];
@Html.ActionLink(Model.Name, "ItemDetails", "Acls", new { id = Model.Id, rId = id, rAction = action, rController = controller }, null)
}
else
{
@Html.DisplayFor(model => model.Name)
}
}
|
apache-2.0
|
C#
|
bb4b9f84040af3fdd43111a50e90bd92e6be5cd4
|
Remove drop menus from main menu
|
michaelp0730/MichaelsMusic,michaelp0730/MichaelsMusic,michaelp0730/MichaelsMusic
|
MichaelsMusic/Views/Shared/Components/_Header.cshtml
|
MichaelsMusic/Views/Shared/Components/_Header.cshtml
|
<header class="main-header">
<div class="row">
<div class="column">
<ul class="menu">
<li class="mobile-expand" id="mobile-expand">
<a href="#">
<i class="fa fa-align-justify"></i>
</a>
</li>
<li class="branding">@Html.ActionLink("Michael's Music", "Index", "Home")</li>
<li>
<a href="/guitars/">Guitars</a>
</li>
<li>
<a href="#">Amps</a>
</li>
<li>
<a href="#">Pedals</a>
</li>
<li>
@Html.ActionLink("About", "About", "Home")
</li>
</ul>
</div>
</div>
</header>
|
<header class="main-header">
<div class="row">
<div class="column">
<ul class="menu">
<li class="mobile-expand" id="mobile-expand">
<a href="#">
<i class="fa fa-align-justify"></i>
</a>
</li>
<li class="branding">@Html.ActionLink("Michael's Music", "Index", "Home")</li>
<li class="has-submenu">
<a href="#">Guitars</a>
<ul class="submenu" data-submenu>
<li><a href="/guitars/">All Guitars</a></li>
<li><a href="#">Guitars by Brand</a></li>
</ul>
</li>
<li class="has-submenu">
<a href="#">Amps</a>
<ul class="submenu" data-submenu>
<li><a href="#">All Amps</a></li>
<li><a href="#">Amps by Brand</a></li>
</ul>
</li>
<li class="has-submenu">
<a href="#">Pedals</a>
<ul class="submenu" data-submenu>
<li><a href="#">All Pedals</a></li>
<li><a href="#">Pedals by Brand</a></li>
</ul>
</li>
<li>
@Html.ActionLink("About", "About", "Home")
</li>
</ul>
</div>
</div>
</header>
|
mit
|
C#
|
fe6644a5adff9d230d8344d78c84d1344cef7162
|
make PropertiesProvider test pass
|
jagt/fullserializer,shadowmint/fullserializer,shadowmint/fullserializer,Ksubaka/fullserializer,jacobdufault/fullserializer,Ksubaka/fullserializer,jagt/fullserializer,jagt/fullserializer,nuverian/fullserializer,jacobdufault/fullserializer,shadowmint/fullserializer,jacobdufault/fullserializer,Ksubaka/fullserializer
|
Testing/RuntimeTests/Providers/PropertiesProvider.cs
|
Testing/RuntimeTests/Providers/PropertiesProvider.cs
|
using System;
using System.Collections.Generic;
using UnityEngine;
public class PropertiesProvider : TestProvider<object> {
public struct PublicGetPublicSet {
public PublicGetPublicSet(int value) : this() { Value = value; }
public int Value { get; set; }
}
public struct PrivateGetPublicSet {
public PrivateGetPublicSet(int value) : this() { Value = value; }
[SerializeField]
public int Value { private get; set; }
public static bool Compare(PrivateGetPublicSet a, PrivateGetPublicSet b) {
return a.Value == b.Value;
}
}
public struct PublicGetPrivateSet {
public PublicGetPrivateSet(int value) : this() { Value = value; }
public int Value { get; private set; }
}
public struct PrivateGetPrivateSet {
public PrivateGetPrivateSet(int value) : this() { Value = value; }
private int Value { get; set; }
public bool Verify() {
if (Value != 0) {
throw new Exception("Private autoproperty was deserialized");
}
return true;
}
}
public override bool Compare(object before, object after) {
if (before is PublicGetPublicSet) {
var beforeA = (PublicGetPublicSet)before;
var afterA = (PublicGetPublicSet)after;
return beforeA.Value == afterA.Value;
}
if (before is PrivateGetPublicSet) {
var beforeA = (PrivateGetPublicSet)before;
var afterA = (PrivateGetPublicSet)after;
return PrivateGetPublicSet.Compare(beforeA, afterA);
}
if (before is PublicGetPrivateSet) {
var beforeA = (PublicGetPrivateSet)before;
var afterA = (PublicGetPrivateSet)after;
return beforeA.Value == afterA.Value;
}
if (after is PrivateGetPrivateSet) {
return ((PrivateGetPrivateSet)after).Verify();
}
throw new Exception("Unknown type");
}
public override IEnumerable<object> GetValues() {
for (int i = -1; i <= 1; ++i) {
yield return new PublicGetPublicSet(i);
yield return new PrivateGetPublicSet(i);
yield return new PublicGetPrivateSet(i);
yield return new PrivateGetPrivateSet(i);
}
}
}
|
using System;
using System.Collections.Generic;
public class PropertiesProvider : TestProvider<object> {
public struct PublicGetPublicSet {
public PublicGetPublicSet(int value) : this() { Value = value; }
public int Value { get; set; }
}
public struct PrivateGetPublicSet {
public PrivateGetPublicSet(int value) : this() { Value = value; }
public int Value { private get; set; }
public static bool Compare(PrivateGetPublicSet a, PrivateGetPublicSet b) {
return a.Value == b.Value;
}
}
public struct PublicGetPrivateSet {
public PublicGetPrivateSet(int value) : this() { Value = value; }
public int Value { get; private set; }
}
public struct PrivateGetPrivateSet {
public PrivateGetPrivateSet(int value) : this() { Value = value; }
private int Value { get; set; }
public bool Verify() {
if (Value != 0) {
throw new Exception("Private autoproperty was deserialized");
}
return true;
}
}
public override bool Compare(object before, object after) {
if (before is PublicGetPublicSet) {
var beforeA = (PublicGetPublicSet)before;
var afterA = (PublicGetPublicSet)after;
return beforeA.Value == afterA.Value;
}
if (before is PrivateGetPublicSet) {
var beforeA = (PrivateGetPublicSet)before;
var afterA = (PrivateGetPublicSet)after;
return PrivateGetPublicSet.Compare(beforeA, afterA);
}
if (before is PublicGetPrivateSet) {
var beforeA = (PublicGetPrivateSet)before;
var afterA = (PublicGetPrivateSet)after;
return beforeA.Value == afterA.Value;
}
if (after is PrivateGetPrivateSet) {
return ((PrivateGetPrivateSet)after).Verify();
}
throw new Exception("Unknown type");
}
public override IEnumerable<object> GetValues() {
for (int i = -1; i <= 1; ++i) {
yield return new PublicGetPublicSet(i);
yield return new PrivateGetPublicSet(i);
yield return new PublicGetPrivateSet(i);
yield return new PrivateGetPrivateSet(i);
}
}
}
|
mit
|
C#
|
d8212808381f686d630daa11c54e6f03bd754174
|
fix merge conflict.
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Fluent/ViewModels/AddWallet/TermsAndConditionsViewModel.cs
|
WalletWasabi.Fluent/ViewModels/AddWallet/TermsAndConditionsViewModel.cs
|
using System.Reactive.Linq;
using System.Windows.Input;
using ReactiveUI;
using WalletWasabi.Fluent.ViewModels.Navigation;
using WalletWasabi.Services;
namespace WalletWasabi.Fluent.ViewModels.AddWallet
{
[NavigationMetaData(Title = "Welcome to Wasabi Wallet")]
public partial class TermsAndConditionsViewModel : RoutableViewModel
{
[AutoNotify] private bool _isAgreed;
public TermsAndConditionsViewModel(LegalChecker legalChecker, RoutableViewModel next)
{
ViewTermsCommand = ReactiveCommand.Create(
() =>
{
if (legalChecker.TryGetNewLegalDocs(out _))
{
var legalDocs = new LegalDocumentsViewModel(legalChecker);
Navigate().To(legalDocs);
}
});
NextCommand = ReactiveCommand.CreateFromTask(
async () =>
{
await legalChecker.AgreeAsync();
Navigate().To(next, NavigationMode.Clear);
},
this.WhenAnyValue(x => x.IsAgreed).ObserveOn(RxApp.MainThreadScheduler));
}
public ICommand ViewTermsCommand { get; }
}
}
|
using System.Reactive.Linq;
using System.Windows.Input;
using ReactiveUI;
using WalletWasabi.Fluent.ViewModels.Navigation;
using WalletWasabi.Services;
namespace WalletWasabi.Fluent.ViewModels.AddWallet
{
[NavigationMetaData(Title = "Welcome to Wasabi Wallet")]
public partial class TermsAndConditionsViewModel : RoutableViewModel
{
[AutoNotify] private bool _isAgreed;
public TermsAndConditionsViewModel(LegalChecker legalChecker, RoutableViewModel next)
{
Title = "Welcome to Wasabi Wallet";
Navigate().To(legalDocs);
ViewTermsCommand = ReactiveCommand.Create(
() =>
{
if (legalChecker.TryGetNewLegalDocs(out _))
{
var legalDocs = new LegalDocumentsViewModel(legalChecker);
Navigate().To(legalDocs);
}
});
NextCommand = ReactiveCommand.CreateFromTask(
async () =>
{
await legalChecker.AgreeAsync();
Navigate().To(next, NavigationMode.Clear);
},
this.WhenAnyValue(x => x.IsAgreed).ObserveOn(RxApp.MainThreadScheduler));
}
public ICommand ViewTermsCommand { get; }
}
}
|
mit
|
C#
|
bd4c8e3cc2aa150a13a3e499cde417589495f497
|
Add jitter to head movement of faking avatar even when there's no speaker. Fix #45
|
Nagasaki45/UnsocialVR,Nagasaki45/UnsocialVR
|
Assets/Scripts/Faking/LookAtSpeaker.cs
|
Assets/Scripts/Faking/LookAtSpeaker.cs
|
using UnityEngine;
public class LookAtSpeaker : MonoBehaviour {
public bool active = false;
public float speed;
public float jitterFreq;
public float jitterLerp;
public float jitterScale;
public float blankGazeDistance;
private Transform myTransform;
private Vector3 randomValue;
private Vector3 randomTarget;
void Start()
{
myTransform = GetComponent<Transform>();
InvokeRepeating("Repeatedly", 0, 1 / jitterFreq);
}
void Repeatedly()
{
randomTarget = Random.insideUnitSphere;
}
void Update()
{
if (active)
{
randomValue = Vector3.Lerp(randomValue, randomTarget, Time.deltaTime * jitterLerp);
GameObject speaker = PlayerTalking.speaker;
Vector3 target;
if (speaker != null)
{
target = speaker.transform.Find("HeadController").position;
}
else
{
target = myTransform.position + myTransform.forward * blankGazeDistance;
}
SlowlyRotateTowards(target);
}
}
void SlowlyRotateTowards(Vector3 target)
{
Vector3 direction = (target - myTransform.position + randomValue * jitterScale).normalized;
Quaternion lookRotation = Quaternion.LookRotation(direction);
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, lookRotation, Time.deltaTime * speed);
}
}
|
using UnityEngine;
public class LookAtSpeaker : MonoBehaviour {
public bool active = false;
public float speed;
public float jitterFreq;
public float jitterLerp;
public float jitterScale;
private Transform myTransform;
private Vector3 randomValue;
private Vector3 randomTarget;
void Start()
{
myTransform = GetComponent<Transform>();
InvokeRepeating("Repeatedly", 0, 1 / jitterFreq);
}
void Repeatedly()
{
randomTarget = Random.insideUnitSphere;
}
void Update()
{
if (active)
{
randomValue = Vector3.Lerp(randomValue, randomTarget, Time.deltaTime * jitterLerp);
GameObject speaker = PlayerTalking.speaker;
if (speaker != null)
{
Transform speakerHead = speaker.transform.Find("HeadController");
SlowlyRotateTowards(speakerHead);
}
}
}
void SlowlyRotateTowards(Transform target)
{
Vector3 direction = (target.position - myTransform.position + randomValue * jitterScale).normalized;
Quaternion lookRotation = Quaternion.LookRotation(direction);
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, lookRotation, Time.deltaTime * speed);
}
}
|
mit
|
C#
|
3761e9eb48a8c542f142684a1993997bac4cffc5
|
create files for import into ArangoDB Layer Collection.
|
johnvcoleman/Harlow,layeredio/Harlow
|
Harlow/HarlowConsoleTestbed/Program.cs
|
Harlow/HarlowConsoleTestbed/Program.cs
|
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Harlow;
using Newtonsoft.Json;
namespace HarlowConsoleTestbed {
class Program {
static void Main(string[] args)
{
try{
Console.WriteLine("Starting Harlow interactions.");
string shapeFile = @"D:\Data\geo\tiger\TIGER2016\STATE\tl_2016_us_state.shp";
ShapeFileReader reader = new ShapeFileReader(shapeFile);
reader.RequiredPrecision = 6;
reader.LoadFile();
using( StreamWriter sw = new StreamWriter(@"C:\Projects\Layered.io\Data\JSON\HarlowFeatures\us_states_features_temp.txt")){
// sw.WriteLine("[");
foreach (var f in reader.Features) {
string json = JsonConvert.SerializeObject(f);
// var fe = JsonConvert.DeserializeObject<VectorShape>(json);
sw.WriteLine(json);
// sw.WriteLine(",");
}
// sw.WriteLine("]");
}
} finally {
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
}
|
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Harlow;
using Newtonsoft.Json;
namespace HarlowConsoleTestbed {
class Program {
static void Main(string[] args)
{
try{
Console.WriteLine("Starting Harlow interactions.");
string shapeFile = @"D:\Data\geo\tiger\TIGER2016\AREALM\tl_2016_02_arealm.shp";
ShapeFileReader reader = new ShapeFileReader(shapeFile);
reader.RequiredPrecision = 6;
reader.LoadFile();
using( StreamWriter sw = new StreamWriter(@"C:\Projects\Layered.io\Data\JSON\HarlowFeatures\us_AreaLandmarks_02_features.json")){
sw.WriteLine("[");
foreach (var f in reader.Features) {
sw.Write(JsonConvert.SerializeObject(f));
sw.WriteLine(",");
}
sw.WriteLine("]");
}
} finally {
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
}
|
mit
|
C#
|
1d830061096de3427cd7db80126281a2c1b1d833
|
Update FuncOfTaskWhichThrowsDirectlyScenario.cs
|
JoeMighty/shouldly
|
src/Shouldly.Tests/ShouldThrow/FuncOfTaskWhichThrowsDirectlyScenario.cs
|
src/Shouldly.Tests/ShouldThrow/FuncOfTaskWhichThrowsDirectlyScenario.cs
|
using System;
using System.Threading.Tasks;
using Xunit;
namespace Shouldly.Tests.ShouldThrow
{
public class FuncOfTaskWhichThrowsDirectlyScenario
{
[Fact]
public void ShouldPass()
{
// ReSharper disable once RedundantDelegateCreation
var task = new Func<Task>(() => { throw new InvalidOperationException(); });
task.ShouldThrow<InvalidOperationException>();
}
[Fact]
public void ShouldPass_ExceptionTypePassedIn()
{
// ReSharper disable once RedundantDelegateCreation
var task = new Func<Task>(() => { throw new InvalidOperationException(); });
task.ShouldThrow(typeof(InvalidOperationException));
}
[Fact]
public void ShouldPassTimeoutException()
{
var task = new Func<Task>(() => { throw new TimeoutException(); });
task.ShouldThrow<TimeoutException>();
}
[Fact]
public void ShouldPassTimeoutException_ExceptionTypePassedIn()
{
var task = new Func<Task>(() => { throw new TimeoutException(); });
task.ShouldThrow(typeof(TimeoutException));
}
[Fact]
public async Task ShouldPassTimeoutExceptionAsync()
{
var task = new Func<Task>(async () => { await Task.FromException(new TimeoutException()); });
await Task.FromResult(task.ShouldThrow<TimeoutException>());
}
[Fact]
public async Task ShouldPassTimeoutExceptionAsync_ExceptionTypePassedIn()
{
var task = new Func<Task>(async () => { await Task.FromException(new TimeoutException()); });
await Task.FromResult(task.ShouldThrow(typeof(TimeoutException)));
}
}
}
|
using System;
using System.Threading.Tasks;
using Xunit;
namespace Shouldly.Tests.ShouldThrow
{
public class FuncOfTaskWhichThrowsDirectlyScenario
{
[Fact]
public void ShouldPass()
{
// ReSharper disable once RedundantDelegateCreation
var task = new Func<Task>(() => { throw new InvalidOperationException(); });
task.ShouldThrow<InvalidOperationException>();
}
[Fact]
public void ShouldPass_ExceptionTypePassedIn()
{
// ReSharper disable once RedundantDelegateCreation
var task = new Func<Task>(() => { throw new InvalidOperationException(); });
task.ShouldThrow(typeof(InvalidOperationException));
}
[Fact]
public void ShouldPassTimeoutException()
{
var task = new Func<Task>(() => { throw new TimeoutException(); });
task.ShouldThrow<TimeoutException>();
}
[Fact]
public void ShouldPassTimeoutException_ExceptionTypePassedIn()
{
var task = new Func<Task>(() => { throw new TimeoutException(); });
task.ShouldThrow(typeof(TimeoutException));
}
[Fact]
public async Task ShouldPassTimeoutExceptionAsync()
{
var task = new Func<Task>(async () => { await Task.FromException(new TimeoutException()); });
await Task.FromResult(task.ShouldThrow<TimeoutException>());
}
[Fact]
public async Task ShouldPassTimeoutExceptionAsync_ExceptionTypePassedIn()
{
var task = new Func<Task>(async () => { await Task.FromException(new TimeoutException()); });
await Task.FromResult(task.ShouldThrow(typeof(TimeoutException)));
}
}
}
|
bsd-3-clause
|
C#
|
375c5c0f9893ccee32c3fa80b0ce6cb0dda12557
|
fix missed script register
|
ziyasal/AspNet.Mvc.ConfigurationExporter,ziyasal/AspNet.Mvc.ConfigurationExporter
|
src/AspNet.Mvc.ConfigurationExporter.WebSite/Views/Shared/_Layout.cshtml
|
src/AspNet.Mvc.ConfigurationExporter.WebSite/Views/Shared/_Layout.cshtml
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
</ul>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
</div>
<script type="text/javascript" src="~/configr"></script>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", false)
</body>
</html>
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
</ul>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", false)
</body>
</html>
|
mit
|
C#
|
a11a600cf5cf2752d4cd1370350d872315cb133e
|
Clean up file
|
gordonwatts/IndicoInterface.NET
|
IndicoInterface.NET/DateTimeUtils.cs
|
IndicoInterface.NET/DateTimeUtils.cs
|
using System;
namespace IndicoInterface.NET
{
public static class DateTimeUtils
{
/// <summary>
/// Return the date time as the number of seconds since Jan 1, 1970.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static int AsSecondsFromUnixEpoch(this DateTime dt)
{
if (dt.Kind == DateTimeKind.Unspecified)
throw new ArgumentException("Don't know how to shift timezones for an unspecified DateTime kind!");
// We have to deal with time zones here.
var dtUtc = dt;
if (dt.Kind == DateTimeKind.Local)
{
var offset = TimeZoneInfo.Local.GetUtcOffset(dt);
dtUtc = new DateTime(dt.Ticks, DateTimeKind.Utc) - offset;
}
var ts = dtUtc - new DateTime(1970, 1, 1, 0, 0, 0);
return (int)ts.TotalSeconds;
}
}
}
|
using System;
namespace IndicoInterface.NET
{
public static class DateTimeUtils
{
/// <summary>
/// Return the date time as the number of seconds since Jan 1, 1970.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static int AsSecondsFromUnixEpoch(this DateTime dt)
{
if (dt.Kind == DateTimeKind.Unspecified)
throw new ArgumentException("Don't know how to shift timezones for an unspecified DateTime kind!");
// We have to deal with time zones here.
var dtUtc = dt;
if (dt.Kind == DateTimeKind.Local)
{
var offset = TimeZoneInfo.Local.GetUtcOffset(dt);
dtUtc = new DateTime(dt.Ticks, DateTimeKind.Utc) - offset;
}
var ts = dtUtc - new DateTime(1970, 1, 1, 0, 0, 0);
return (int)ts.TotalSeconds;
}
}
}
#if false
var dt = DateTime.UtcNow;
Console.WriteLine(dt.ToLocalTime());
var tz = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
var utcOffset = new DateTimeOffset(dt, TimeSpan.Zero);
Console.WriteLine(utcOffset.ToOffset(tz.GetUtcOffset(utcOffset)));
#endif
|
mit
|
C#
|
bac1771f6b8c116552d220ef4091111f32658bc6
|
Add comment
|
mattherman/MbDotNet,mattherman/MbDotNet
|
MbDotNet.Acceptance.Tests/Program.cs
|
MbDotNet.Acceptance.Tests/Program.cs
|
using System;
using MbDotNet;
using System.Collections.Generic;
namespace MbDotNet.Acceptance.Tests
{
public class Program
{
private static int _passed = 0;
private static int _failed = 0;
private static int _skipped = 0;
public static void Main()
{
var tests = new List<Type>
{
typeof(AcceptanceTests.CanNotGetImposterThatDoesNotExist),
typeof(AcceptanceTests.CanCreateAndGetHttpImposter),
typeof(AcceptanceTests.CanCreateAndGetHttpsImposter),
typeof(AcceptanceTests.CanCreateAndGetTcpImposter),
typeof(AcceptanceTests.CanDeleteImposter),
typeof(AcceptanceTests.CanVerifyCallsOnImposter),
typeof(AcceptanceTests.CanCreateAndGetHttpImposterWithNoPort)
};
var runner = new AcceptanceTestRunner(tests, OnTestPassing, OnTestFailing, OnTestSkipped);
runner.Execute();
Console.WriteLine("\nFINISHED {0} passed, {1} failed, {2} skipped", _passed, _failed, _skipped);
// Return an exit code of 1 if any tests failed
if (_failed > 0)
{
Environment.Exit(1);
}
}
public static void OnTestPassing(string testName, long elapsed)
{
Console.WriteLine("PASS {0} ({1}ms)", testName, elapsed);
_passed++;
}
public static void OnTestFailing(string testName, long elapsed, Exception ex)
{
Console.WriteLine("FAIL {0} ({1}ms)\n\t=> {2}", testName, elapsed, ex.Message);
_failed++;
}
public static void OnTestSkipped(string testName, string reason)
{
Console.WriteLine("SKIP {0} [{1}]", testName, reason);
_skipped++;
}
}
}
|
using System;
using MbDotNet;
using System.Collections.Generic;
namespace MbDotNet.Acceptance.Tests
{
public class Program
{
private static int _passed = 0;
private static int _failed = 0;
private static int _skipped = 0;
public static void Main()
{
var tests = new List<Type>
{
typeof(AcceptanceTests.CanNotGetImposterThatDoesNotExist),
typeof(AcceptanceTests.CanCreateAndGetHttpImposter),
typeof(AcceptanceTests.CanCreateAndGetHttpsImposter),
typeof(AcceptanceTests.CanCreateAndGetTcpImposter),
typeof(AcceptanceTests.CanDeleteImposter),
typeof(AcceptanceTests.CanVerifyCallsOnImposter),
typeof(AcceptanceTests.CanCreateAndGetHttpImposterWithNoPort)
};
var runner = new AcceptanceTestRunner(tests, OnTestPassing, OnTestFailing, OnTestSkipped);
runner.Execute();
Console.WriteLine("\nFINISHED {0} passed, {1} failed, {2} skipped", _passed, _failed, _skipped);
if (_failed > 0)
{
Environment.Exit(1);
}
}
public static void OnTestPassing(string testName, long elapsed)
{
Console.WriteLine("PASS {0} ({1}ms)", testName, elapsed);
_passed++;
}
public static void OnTestFailing(string testName, long elapsed, Exception ex)
{
Console.WriteLine("FAIL {0} ({1}ms)\n\t=> {2}", testName, elapsed, ex.Message);
_failed++;
}
public static void OnTestSkipped(string testName, string reason)
{
Console.WriteLine("SKIP {0} [{1}]", testName, reason);
_skipped++;
}
}
}
|
mit
|
C#
|
fe60e590c7cf16b3f3e015221aaf58a696e01c42
|
Add ShowId to TvEpisode
|
LordMike/TMDbLib
|
TMDbLib/Objects/TvShows/TvEpisode.cs
|
TMDbLib/Objects/TvShows/TvEpisode.cs
|
using System;
using System.Collections.Generic;
using TMDbLib.Objects.General;
namespace TMDbLib.Objects.TvShows
{
public class TvEpisode
{
/// <summary>
/// Object Id, will only be populated when explicitly getting episode details
/// </summary>
public int? Id { get; set; }
public int? ShowId { get; set; }
/// <summary>
/// Will only be populated when explicitly getting an episode
/// </summary>
public int? SeasonNumber { get; set; }
public int EpisodeNumber { get; set; }
public DateTime AirDate { get; set; }
public string Name { get; set; }
public string Overview { get; set; }
public string StillPath { get; set; }
public string ProductionCode { get; set; } // TODO check type, was null in the apiary
public double VoteAverage { get; set; }
public int VoteCount { get; set; }
public List<Crew> Crew { get; set; }
public List<Cast> GuestStars { get; set; }
public Credits Credits { get; set; }
public ExternalIds ExternalIds { get; set; }
public StillImages Images { get; set; }
public ResultContainer<Video> Videos { get; set; }
public AccountState AccountStates { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Lists;
namespace TMDbLib.Objects.TvShows
{
public class TvEpisode
{
/// <summary>
/// Object Id, will only be populated when explicitly getting episode details
/// </summary>
public int? Id { get; set; }
/// <summary>
/// Will only be populated when explicitly getting an episode
/// </summary>
public int? SeasonNumber { get; set; }
public int EpisodeNumber { get; set; }
public DateTime AirDate { get; set; }
public string Name { get; set; }
public string Overview { get; set; }
public string StillPath { get; set; }
public string ProductionCode { get; set; } // TODO check type, was null in the apiary
public double VoteAverage { get; set; }
public int VoteCount { get; set; }
public List<Crew> Crew { get; set; }
public List<Cast> GuestStars { get; set; }
public Credits Credits { get; set; }
public ExternalIds ExternalIds { get; set; }
public StillImages Images { get; set; }
public ResultContainer<Video> Videos { get; set; }
public AccountState AccountStates { get; set; }
}
}
|
mit
|
C#
|
e2f032c8f4847b7372e5ec8c19f7a2a18ba3f8a4
|
Update version to 1.0.0-alpha5
|
bungeemonkee/Utilitron
|
Utilitron/Properties/AssemblyInfo.cs
|
Utilitron/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Resources;
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("Utilitron")]
[assembly: AssemblyDescription("Basic .NET utilities.")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyCompany("David love")]
[assembly: AssemblyProduct("Utilitron")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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("089b3411-e1ca-4812-8daa-92d332f72408")]
// Version information for an assembly consists of the following four values.
// We will increase these values in the following way:
// Major Version : Increased when there is a release that breaks a public api
// Minor Version : Increased for each non-api-breaking release
// Build Number : 0 for alpha versions, 1 for beta versions, 2 for release candidates, 3 for releases
// Revision : Always 0 for release versions, always 1+ for alpha, beta, rc versions to indicate the alpha/beta/rc number
[assembly: AssemblyVersion("1.0.0.5")]
[assembly: AssemblyFileVersion("1.0.0.5")]
// This version number will roughly follow semantic versioning : http://semver.org
// The first three numbers will always match the first the numbers of the version above.
[assembly: AssemblyInformationalVersion("1.0.0-alpha5")]
|
using System.Reflection;
using System.Resources;
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("Utilitron")]
[assembly: AssemblyDescription("Basic .NET utilities.")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyCompany("David love")]
[assembly: AssemblyProduct("Utilitron")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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("089b3411-e1ca-4812-8daa-92d332f72408")]
// Version information for an assembly consists of the following four values.
// We will increase these values in the following way:
// Major Version : Increased when there is a release that breaks a public api
// Minor Version : Increased for each non-api-breaking release
// Build Number : 0 for alpha versions, 1 for beta versions, 2 for release candidates, 3 for releases
// Revision : Always 0 for release versions, always 1+ for alpha, beta, rc versions to indicate the alpha/beta/rc number
[assembly: AssemblyVersion("1.0.0.4")]
[assembly: AssemblyFileVersion("1.0.0.4")]
// This version number will roughly follow semantic versioning : http://semver.org
// The first three numbers will always match the first the numbers of the version above.
[assembly: AssemblyInformationalVersion("1.0.0-alpha4")]
|
mit
|
C#
|
a42bc03b497806c0af01b4db113b9089db0d4966
|
Update Index.cshtml
|
johnnyreilly/jQuery.Validation.Unobtrusive.Native,johnnyreilly/jQuery.Validation.Unobtrusive.Native,johnnyreilly/jQuery.Validation.Unobtrusive.Native,senzacionale/jQuery.Validation.Unobtrusive.Native
|
jVUNDemo/Views/Home/Index.cshtml
|
jVUNDemo/Views/Home/Index.cshtml
|
@section metatags{
<meta name="Description" content="Provides MVC HTML helper extensions that marry jQuery Validation's native unobtrusive support for validation driven by HTML 5 data attributes with MVC's ability to generate data attributes from Model metadata. With this in place you can use jQuery Validation as it is - you don't need jquery.validate.unobtrusive.js.">
}
<h3>What is jQuery Validation Unobtrusive Native?</h3>
<p>jQuery Validation Unobtrusive Native is a collection of ASP.Net MVC HTML helper extensions. These make use of jQuery Validation's native support for validation driven by HTML 5 data attributes. Microsoft shipped <a href="http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html" target="_blank">jquery.validate.unobtrusive.js</a> back with MVC 3. It provided a way to apply data model validations to the client side using a combination of jQuery Validation and HTML 5 data attributes (that's the "unobtrusive" part).</p>
<p>The principal of this was and is fantastic. But since that time the jQuery Validation project has implemented its own support for driving validation unobtrusively (which shipped with <a href="http://jquery.bassistance.de/validate/changelog.txt" target="_blank">jQuery Validation 1.11.0</a>). The main advantages of using the native support over jquery.validate.unobtrusive.js are:</p>
<ol>
<li>Dynamically created form elements are parsed automatically. jquery.validate.unobtrusive.js does not support this whilst jQuery Validation does.<br />
@Html.ActionLink("See a demo", "Dynamic", "AdvancedDemo")<br /><br /></li>
<li>jquery.validate.unobtrusive.js restricts how you use jQuery Validation. If you want to use showErrors or something similar then you may find that you need to go native (or at least you may find that significantly easier than working with the jquery.validate.unobtrusive.js defaults)...<br />
@Html.ActionLink("See a demo", "Tooltip", "AdvancedDemo")<br /><br /></li>
<li>Send less code to your browser, make your browser to do less work, get a performance benefit (though in all honesty you'd probably have to be the Flash to actually notice the difference...)</li>
</ol>
<p>This project intends to be a bridge between MVC's inbuilt support for driving validation from data attributes and jQuery Validation's native support for the same. This is achieved by hooking into the MVC data attribute creation mechanism and using it to generate the data attributes used by jQuery Validation.</p>
<h4>Future Plans</h4>
<p>So far the basic set of the HtmlHelpers and their associated unobtrusive mappings have been implemented. If any have been missed then let me know. As time goes by I intend to:</p>
<ul>
<li>fill in any missing gaps there may be</li>
<li>maintain MVC 3, 4, 5 (and when the time comes 6+) versions of this on Nuget</li>
<li>get the unit test coverage to a good level and (most importantly)</li>
<li>create some really useful demos and documentation.</li>
</ul>
<p>Help is appreciated so feel free to pitch in! You can find the project on <a href="http://github.com/johnnyreilly/jQuery.Validation.Unobtrusive.Native" target="_blank">GitHub</a>...</p>
|
@section metatags{
<meta name="Description" content="Provides MVC HTML helper extensions that marry jQuery Validation's native unobtrusive support for validation driven by HTML 5 data attributes with MVC's ability to generate data attributes from Model metadata. With this in place you can use jQuery Validation as it is - you don't need jquery.validate.unobtrusive.js. Which is nice">
}
<h3>What is jQuery Validation Unobtrusive Native?</h3>
<p>jQuery Validation Unobtrusive Native is a collection of ASP.Net MVC HTML helper extensions. These make use of jQuery Validation's native support for validation driven by HTML 5 data attributes. Microsoft shipped <a href="http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html" target="_blank">jquery.validate.unobtrusive.js</a> back with MVC 3. It provided a way to apply data model validations to the client side using a combination of jQuery Validation and HTML 5 data attributes (that's the "unobtrusive" part).</p>
<p>The principal of this was and is fantastic. But since that time the jQuery Validation project has implemented its own support for driving validation unobtrusively (which shipped with <a href="http://jquery.bassistance.de/validate/changelog.txt" target="_blank">jQuery Validation 1.11.0</a>). The main advantages of using the native support over jquery.validate.unobtrusive.js are:</p>
<ol>
<li>Dynamically created form elements are parsed automatically. jquery.validate.unobtrusive.js does not support this whilst jQuery Validation does.<br />
@Html.ActionLink("See a demo", "Dynamic", "AdvancedDemo")<br /><br /></li>
<li>jquery.validate.unobtrusive.js restricts how you use jQuery Validation. If you want to use showErrors or something similar then you may find that you need to go native (or at least you may find that significantly easier than working with the jquery.validate.unobtrusive.js defaults)...<br />
@Html.ActionLink("See a demo", "Tooltip", "AdvancedDemo")<br /><br /></li>
<li>Send less code to your browser, make your browser to do less work, get a performance benefit (though in all honesty you'd probably have to be the Flash to actually notice the difference...)</li>
</ol>
<p>This project intends to be a bridge between MVC's inbuilt support for driving validation from data attributes and jQuery Validation's native support for the same. This is achieved by hooking into the MVC data attribute creation mechanism and using it to generate the data attributes used by jQuery Validation.</p>
<h4>Future Plans</h4>
<p>So far the basic set of the HtmlHelpers and their associated unobtrusive mappings have been implemented. If any have been missed then let me know. As time goes by I intend to:</p>
<ul>
<li>fill in any missing gaps there may be</li>
<li>maintain MVC 3, 4, 5 (and when the time comes 6+) versions of this on Nuget</li>
<li>get the unit test coverage to a good level and (most importantly)</li>
<li>create some really useful demos and documentation.</li>
</ul>
<p>Help is appreciated so feel free to pitch in! You can find the project on <a href="http://github.com/johnnyreilly/jQuery.Validation.Unobtrusive.Native" target="_blank">GitHub</a>...</p>
|
mit
|
C#
|
b1b19ebe490368cbdfb2c953390ac896e59ed782
|
Update EngineInfo
|
Vorlias/Andromeda
|
System/EngineInfo.cs
|
System/EngineInfo.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Andromeda.System
{
public static class EngineInfo
{
const int DATE = 180104;
const int MAJOR = 0;
const int MINOR = 500;
const int REVISION = 0;
const int FULL = (MAJOR * 10000) + (MINOR * 100) + REVISION;
public static string String
{
get
{
return string.Format("{0}.{1}.{2}", MAJOR, MINOR, REVISION);
}
}
public static string FullString
{
get
{
return string.Format("{0}.{1}.{2}.{3}", MAJOR, MINOR, REVISION, DATE);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Andromeda.System
{
public static class EngineInfo
{
const int DATE = 171214;
const int MAJOR = 0;
const int MINOR = 400;
const int REVISION = 0;
const int FULL = (MAJOR * 10000) + (MINOR * 100) + REVISION;
public static string String
{
get
{
return string.Format("{0}.{1}.{2}", MAJOR, MINOR, REVISION);
}
}
public static string FullString
{
get
{
return string.Format("{0}.{1}.{2}.{3}", MAJOR, MINOR, REVISION, DATE);
}
}
}
}
|
mit
|
C#
|
d244ef040fb564c24a503288f4c571ad12c79233
|
add SendEvent to QueryService (#3)
|
NickRimmer/ApiAi
|
ApiAi/QueryService.cs
|
ApiAi/QueryService.cs
|
//
// Copyright (c) 2017 Nick Rimmer. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using ApiAi.Internal.Attributes;
using ApiAi.Internal.Models;
using ApiAi.Internal.Models.Requests;
using ApiAi.Internal.Models.Responses;
using ApiAi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ApiAi
{
/// <summary>
/// The query endpoint is used to process natural language in the form of text.
/// </summary>
public static class QueryService
{
/// <summary>
/// Takes natural language text and information as query parameters.
/// </summary>
/// <param name="config">Agent connection configuration</param>
/// <param name="message">Natural language text to be processed. Query length should not exceed 256 characters.</param>
/// <returns></returns>
public static QueryResponseModel SendRequest(ConfigModel config, string message)
{
var requestData = new QueryRequestJsonModel
{
Query = message,
SessionId = (config.SessionId ?? Guid.NewGuid()).ToString(),
Lang = config.Language.GetAlternativeString()
};
var result = Internal.RequestHelper.Send<QueryRequestJsonModel, QueryResponseJsonModel>
(requestData, Internal.Enums.ActionsEnum.Query, System.Net.Http.HttpMethod.Post, config);
return new QueryResponseModel(result);
}
public static QueryResponseModel SendEvent(ConfigModel config, string eventName)
{
var requestData = new QueryRequestJsonModel
{
SessionId = (config.SessionId ?? Guid.NewGuid()).ToString(),
Lang = config.Language.GetAlternativeString(),
Event = new EventJsonModel
{
Name = eventName
}
};
var result = Internal.RequestHelper.Send<QueryRequestJsonModel, QueryResponseJsonModel>
(requestData, Internal.Enums.ActionsEnum.Query, System.Net.Http.HttpMethod.Post, config);
return new QueryResponseModel(result);
}
}
}
|
//
// Copyright (c) 2017 Nick Rimmer. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using ApiAi.Internal.Attributes;
using ApiAi.Internal.Models;
using ApiAi.Internal.Models.Requests;
using ApiAi.Internal.Models.Responses;
using ApiAi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ApiAi
{
/// <summary>
/// The query endpoint is used to process natural language in the form of text.
/// </summary>
public static class QueryService
{
/// <summary>
/// Takes natural language text and information as query parameters.
/// </summary>
/// <param name="config">Agent connection configuration</param>
/// <param name="message">Natural language text to be processed. Query length should not exceed 256 characters.</param>
/// <returns></returns>
public static QueryResponseModel SendRequest(ConfigModel config, string message)
{
var requestData = new QueryRequestJsonModel
{
Query = message,
SessionId = (config.SessionId ?? Guid.NewGuid()).ToString(),
Lang = config.Language.GetAlternativeString()
};
var result = Internal.RequestHelper.Send<QueryRequestJsonModel, QueryResponseJsonModel>
(requestData, Internal.Enums.ActionsEnum.Query, System.Net.Http.HttpMethod.Post, config);
return new QueryResponseModel(result);
}
}
}
|
mit
|
C#
|
0c1e23cd27ec81303bb1013ada6f0ce49b4cb66a
|
Remove unnecessary IFormattable constraint from IEnumerable.StringJoin
|
orbitalgames/collections-extensions
|
IEnumerableExtensions.cs
|
IEnumerableExtensions.cs
|
/*
The MIT License (MIT)
Copyright (c) 2015 Orbital Games, LLC.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System.Collections.Generic;
using System.Linq;
using System;
namespace OrbitalGames.Collections
{
/// <summary>
/// Extension methods for System.IEnumerable
/// </summary>
public static class IEnumerableExtensions
{
/// <summary>
/// Joins the string representations of each element of the given IEnumerable using a given separator string.
/// </summary>
/// <param name="source">IEnumerable to join</param>
/// <param name="separator">String to use as a separator</param>
/// <exception cref="System.ArgumentException">Thrown when <paramref name="source" /> is null</exception>
/// <returns>Joined string</returns>
public static string StringJoin<TSource>(this IEnumerable<TSource> source, string separator)
{
if (source == null)
{
throw new ArgumentException("source is null", "source");
}
return string.Join(separator, source.Select<TSource, string>(x => x.ToString()).ToArray());
}
}
}
|
/*
The MIT License (MIT)
Copyright (c) 2015 Orbital Games, LLC.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System.Collections.Generic;
using System.Linq;
using System;
namespace OrbitalGames.Collections
{
/// <summary>
/// Extension methods for System.IEnumerable
/// </summary>
public static class IEnumerableExtensions
{
/// <summary>
/// Joins the string representations of each element of the given IEnumerable using a given separator string.
/// </summary>
/// <param name="source">IEnumerable to join</param>
/// <param name="separator">String to use as a separator</param>
/// <exception cref="System.ArgumentException">Thrown when <paramref name="source" /> is null</exception>
/// <returns>Joined string</returns>
public static string StringJoin<TSource>(this IEnumerable<TSource> source, string separator) where TSource : IFormattable
{
if (source == null)
{
throw new ArgumentException("source is null", "source");
}
return string.Join(separator, source.Select<TSource, string>(x => x.ToString()).ToArray());
}
}
}
|
mit
|
C#
|
b08bb6f08b076621f987c54f0b6b7c551cdb11e2
|
Kill dead code.
|
arlobelshee/Minions,Minions/Minions,Minions/Minions,arlobelshee/Minions
|
src/Fools/Recognizing/BlockFinder.cs
|
src/Fools/Recognizing/BlockFinder.cs
|
using System.Collections.Generic;
using System.Linq;
using Fools.Ast;
using Fools.Tokenization;
namespace Fools.Recognizing
{
public class BlockFinder : Transformation<INode, INode>
{
private static readonly IdentifierToken Colon = new IdentifierToken(":");
private readonly Stack<Block> _currentBlocks = new Stack<Block>();
public override void OnNext(INode value)
{
HandleLine((Line) value);
}
public override void OnCompleted()
{
EndBlockIfNeeded(0);
base.OnCompleted();
}
private void HandleLine(Line value)
{
EndBlockIfNeeded(value.IndentationLevel);
if(value.Contents.Last() == Colon)
AddBlock(new Block(value.Contents.Take(value.Contents.Count - 1)));
else
AddStatementToCurrentBlock(new UnrecognizedStatement(value.Contents));
}
private void AddStatementToCurrentBlock(UnrecognizedStatement statement)
{
if(_currentBlocks.Count == 0)
SendNext(statement);
else
_currentBlocks.Peek().AddStatement(statement);
}
private void EndBlockIfNeeded(int newIndentationLevel)
{
if(newIndentationLevel >= _currentBlocks.Count || _currentBlocks.Count == 0) return;
while (_currentBlocks.Count > 1) _currentBlocks.Pop();
SendNext(_currentBlocks.Pop());
}
private void AddBlock(Block block)
{
if(_currentBlocks.Count > 0) _currentBlocks.Peek().AddStatement(block);
_currentBlocks.Push(block);
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Fools.Ast;
using Fools.Tokenization;
namespace Fools.Recognizing
{
public class BlockFinder : Transformation<INode, INode>
{
private static readonly IdentifierToken Colon = new IdentifierToken(":");
private readonly Stack<Block> _currentBlocks = new Stack<Block>();
public override void OnNext(INode value)
{
HandleLine((Line) value);
}
public override void OnCompleted()
{
EndBlockIfNeeded(0);
base.OnCompleted();
}
private void HandleLine(Line value)
{
EndBlockIfNeeded(value.IndentationLevel);
if(value.Contents.Last() == Colon)
AddBlock(new Block(value.Contents.Take(value.Contents.Count - 1)));
else
AddStatementToCurrentBlock(new UnrecognizedStatement(value.Contents), value.IndentationLevel);
}
private void AddStatementToCurrentBlock(UnrecognizedStatement statement, int indentationLevel)
{
if(_currentBlocks.Count == 0)
SendNext(statement);
else
_currentBlocks.Peek().AddStatement(statement);
}
private void EndBlockIfNeeded(int newIndentationLevel)
{
if(newIndentationLevel >= _currentBlocks.Count || _currentBlocks.Count == 0) return;
while (_currentBlocks.Count > 1) _currentBlocks.Pop();
SendNext(_currentBlocks.Pop());
}
private void AddBlock(Block block)
{
if(_currentBlocks.Count > 0) _currentBlocks.Peek().AddStatement(block);
_currentBlocks.Push(block);
}
}
}
|
bsd-3-clause
|
C#
|
ed4ac2c9c1c0f3f28c8929c040be83c058cc5a76
|
add stylecop suggestions
|
carterjones/pe-analyzer,carterjones/pe-analyzer
|
PEAnalyzer/Extensions.cs
|
PEAnalyzer/Extensions.cs
|
namespace PEAnalyzer
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// <summary>
/// A collection of miscellaneous extension methods.
/// </summary>
internal static class Extensions
{
/// <summary>
/// Get a hexidecimal address representation of a 32-bit address value.
/// </summary>
/// <param name="value">the address value</param>
/// <returns>a hexidecimal address representation of a 32-bit address value</returns>
public static string ToAddressString32(this ulong value)
{
return "0x" + new IntPtr((long)value).ToString("x").PadLeft(8, '0');
}
/// <summary>
/// Get a hexidecimal address representation of a 64-bit address value.
/// </summary>
/// <param name="value">the address value</param>
/// <returns>a hexidecimal address representation of a 64-bit address value</returns>
public static string ToAddressString64(this ulong value)
{
return "0x" + new IntPtr((long)value).ToString("x").PadLeft(16, '0');
}
}
}
|
namespace PEAnalyzer
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
internal static class Extensions
{
public static string ToAddressString32(this ulong value)
{
return "0x" + new IntPtr((long)value).ToString("x").PadLeft(8, '0');
}
public static string ToAddressString64(this ulong value)
{
return "0x" + new IntPtr((long)value).ToString("x").PadLeft(16, '0');
}
}
}
|
bsd-2-clause
|
C#
|
9a8f59ab5088a8e937178cfa153959f27c97305f
|
Add debug-upgrade CL command
|
Cyberboss/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server,tgstation/tgstation-server,Cyberboss/tgstation-server
|
TGCommandLine/Program.cs
|
TGCommandLine/Program.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using TGServiceInterface;
namespace TGCommandLine
{
class Program
{
static ExitCode RunCommandLine(IList<string> argsAsList)
{
var res = Server.VerifyConnection();
if (res != null)
{
Console.WriteLine("Unable to connect to service: " + res);
return ExitCode.ConnectionError;
}
try
{
return new CLICommand().DoRun(argsAsList);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.ToString());
return ExitCode.ConnectionError;
};
}
public static string ReadLineSecure()
{
string result = "";
while (true)
{
ConsoleKeyInfo i = Console.ReadKey(true);
if (i.Key == ConsoleKey.Enter)
{
break;
}
else if (i.Key == ConsoleKey.Backspace)
{
if (result.Length > 0)
{
result = result.Substring(0, result.Length - 1);
Console.Write("\b \b");
}
}
else
{
result += i.KeyChar;
Console.Write("*");
}
}
return result;
}
static int Main(string[] args)
{
Command.OutputProcVar.Value = Console.WriteLine;
if (args.Length != 0)
return (int)RunCommandLine(new List<string>(args));
//interactive mode
while (true)
{
Console.Write("Enter command: ");
var NextCommand = Console.ReadLine();
switch (NextCommand.ToLower())
{
case "quit":
case "exit":
return (int)ExitCode.Normal;
#if DEBUG
case "debug-upgrade":
Server.GetComponent<ITGSService>().PrepareForUpdate();
return (int)ExitCode.Normal;
#endif
default:
//linq voodoo to get quoted strings
var formattedCommand = NextCommand.Split('"')
.Select((element, index) => index % 2 == 0 // If even index
? element.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) // Split the item
: new string[] { element }) // Keep the entire item
.SelectMany(element => element).ToList();
formattedCommand = formattedCommand.Select(x => x.Trim()).ToList();
formattedCommand.Remove("");
RunCommandLine(formattedCommand);
break;
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using TGServiceInterface;
namespace TGCommandLine
{
class Program
{
static ExitCode RunCommandLine(IList<string> argsAsList)
{
var res = Server.VerifyConnection();
if (res != null)
{
Console.WriteLine("Unable to connect to service: " + res);
return ExitCode.ConnectionError;
}
try
{
return new CLICommand().DoRun(argsAsList);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.ToString());
return ExitCode.ConnectionError;
};
}
public static string ReadLineSecure()
{
string result = "";
while (true)
{
ConsoleKeyInfo i = Console.ReadKey(true);
if (i.Key == ConsoleKey.Enter)
{
break;
}
else if (i.Key == ConsoleKey.Backspace)
{
if (result.Length > 0)
{
result = result.Substring(0, result.Length - 1);
Console.Write("\b \b");
}
}
else
{
result += i.KeyChar;
Console.Write("*");
}
}
return result;
}
static int Main(string[] args)
{
Command.OutputProcVar.Value = Console.WriteLine;
if (args.Length != 0)
return (int)RunCommandLine(new List<string>(args));
//interactive mode
while (true)
{
Console.Write("Enter command: ");
var NextCommand = Console.ReadLine();
switch (NextCommand.ToLower())
{
case "quit":
case "exit":
return (int)ExitCode.Normal;
default:
//linq voodoo to get quoted strings
var formattedCommand = NextCommand.Split('"')
.Select((element, index) => index % 2 == 0 // If even index
? element.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) // Split the item
: new string[] { element }) // Keep the entire item
.SelectMany(element => element).ToList();
formattedCommand = formattedCommand.Select(x => x.Trim()).ToList();
formattedCommand.Remove("");
RunCommandLine(formattedCommand);
break;
}
}
}
}
}
|
agpl-3.0
|
C#
|
598b04a37b490b28349c6705895a03babfee11fa
|
update version
|
danelkhen/corex
|
src/corex/Properties/AssemblyInfo.cs
|
src/corex/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("corex")]
[assembly: AssemblyDescription(".NET Core Extensions")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Dan-el Khen")]
[assembly: AssemblyProduct("corex")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5c1cae89-8692-45df-a771-58bf1bf87039")]
// 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.2.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("corex")]
[assembly: AssemblyDescription(".NET Core Extensions")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Dan-el Khen")]
[assembly: AssemblyProduct("corex")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5c1cae89-8692-45df-a771-58bf1bf87039")]
// 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#
|
de741e1598119f50f21316b213f924d1207486f4
|
Add missing close tag
|
CollActionteam/CollAction,CollActionteam/CollAction,CollActionteam/CollAction,CollActionteam/CollAction,CollActionteam/CollAction
|
CollAction/Views/Projects/Embed.cshtml
|
CollAction/Views/Projects/Embed.cshtml
|
@model int
@{
Layout = "_EmbeddedLayout";
ViewData["Title"] = "Embedded Project";
}
<div id="embedded-project" data-project-id="@Model"></div>
|
@model int
@{
Layout = "_EmbeddedLayout";
ViewData["Title"] = "Embedded Project";
}
<div id="embedded-project" data-project-id="@Model"><div>
|
agpl-3.0
|
C#
|
14e86c2cd5f4841200b8122d4702d46e72eec1e1
|
Enable Shift+R to reset prefs in development builds
|
NitorInc/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare,Barleytree/NitoriWare
|
Assets/Scripts/Global/GameController.cs
|
Assets/Scripts/Global/GameController.cs
|
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Events;
using System.Collections;
public class GameController : MonoBehaviour
{
public static GameController instance;
#pragma warning disable 0649
[SerializeField]
private bool disableCursor;
[SerializeField]
private MicrogameCollection _microgameCollection;
[SerializeField]
private SceneShifter _sceneShifter;
[SerializeField]
private Sprite[] controlSprites;
[SerializeField]
private UnityEvent onSceneLoad;
#pragma warning restore 0649
private string startScene;
public MicrogameCollection microgameCollection
{
get { return _microgameCollection; }
}
public SceneShifter sceneShifter
{
get { return _sceneShifter; }
}
void Awake()
{
if (instance != null)
{
Destroy(gameObject);
return;
}
startScene = gameObject.scene.name;
DontDestroyOnLoad(transform.gameObject);
instance = this;
Cursor.visible = !disableCursor;
Cursor.lockState = CursorLockMode.Confined;
Application.targetFrameRate = 60;
forceResolutionAspect();
AudioListener.pause = false;
SceneManager.sceneLoaded += onSceneLoaded;
}
void forceResolutionAspect()
{
int height = Screen.currentResolution.height;
if (!MathHelper.Approximately((float)height, (float) Screen.currentResolution.width * 3f / 4f, .01f))
Screen.SetResolution((int)((float)Screen.currentResolution.width * 3f / 4f), height, Screen.fullScreen);
}
private void Update()
{
//Debug features
if (Debug.isDebugBuild)
{
//Shift+R to reset all prefs
if ((Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) && Input.GetKeyDown(KeyCode.R))
PlayerPrefs.DeleteAll();
}
}
void onSceneLoaded(Scene scene, LoadSceneMode mode)
{
if (PauseManager.exitedWhilePaused)
{
AudioListener.pause = false;
Time.timeScale = 1f;
PauseManager.exitedWhilePaused = false;
Cursor.visible = true;
}
onSceneLoad.Invoke();
}
public Sprite getControlSprite(MicrogameTraits.ControlScheme controlScheme)
{
return controlSprites[(int)controlScheme];
}
public string getStartScene()
{
return startScene;
}
}
|
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Events;
using System.Collections;
public class GameController : MonoBehaviour
{
public static GameController instance;
#pragma warning disable 0649
[SerializeField]
private bool disableCursor;
[SerializeField]
private MicrogameCollection _microgameCollection;
[SerializeField]
private SceneShifter _sceneShifter;
[SerializeField]
private Sprite[] controlSprites;
[SerializeField]
private UnityEvent onSceneLoad;
#pragma warning restore 0649
private string startScene;
public MicrogameCollection microgameCollection
{
get { return _microgameCollection; }
}
public SceneShifter sceneShifter
{
get { return _sceneShifter; }
}
void Awake()
{
if (instance != null)
{
Destroy(gameObject);
return;
}
startScene = gameObject.scene.name;
DontDestroyOnLoad(transform.gameObject);
instance = this;
Cursor.visible = !disableCursor;
Cursor.lockState = CursorLockMode.Confined;
Application.targetFrameRate = 60;
forceResolutionAspect();
AudioListener.pause = false;
SceneManager.sceneLoaded += onSceneLoaded;
}
void forceResolutionAspect()
{
int height = Screen.currentResolution.height;
if (!MathHelper.Approximately((float)height, (float) Screen.currentResolution.width * 3f / 4f, .01f))
Screen.SetResolution((int)((float)Screen.currentResolution.width * 3f / 4f), height, Screen.fullScreen);
}
//private void Update()
//{
// if (Input.GetKeyDown(KeyCode.G))
// PlayerPrefs.DeleteAll();
//}
void onSceneLoaded(Scene scene, LoadSceneMode mode)
{
if (PauseManager.exitedWhilePaused)
{
AudioListener.pause = false;
Time.timeScale = 1f;
PauseManager.exitedWhilePaused = false;
Cursor.visible = true;
}
onSceneLoad.Invoke();
}
public Sprite getControlSprite(MicrogameTraits.ControlScheme controlScheme)
{
return controlSprites[(int)controlScheme];
}
public string getStartScene()
{
return startScene;
}
}
|
mit
|
C#
|
354ee81ff5151e38270147f2ba4b78b89fef05f0
|
Update to v0.2.0.0
|
codeite/WebApiProblem
|
WebApiProblem/Properties/AssemblyInfo.cs
|
WebApiProblem/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("WebApiProblem")]
[assembly: AssemblyDescription("A small framework for turning exceptions into good Rest responses in WebApi. Based on the IETF draft at http://tools.ietf.org/html/draft-nottingham-http-problem-03")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Codeite Ltd")]
[assembly: AssemblyProduct("WebApiProblem")]
[assembly: AssemblyCopyright("Copyright © Codeite Ltd 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fa049d81-8b88-46b7-843a-0272e537ce24")]
// 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.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("WebApiProblem")]
[assembly: AssemblyDescription("A small framework for turning exceptions into good Rest responses in WebApi. Based on the IETF draft at http://tools.ietf.org/html/draft-nottingham-http-problem-03")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Codeite Ltd")]
[assembly: AssemblyProduct("WebApiProblem")]
[assembly: AssemblyCopyright("Copyright © Codeite Ltd 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fa049d81-8b88-46b7-843a-0272e537ce24")]
// 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.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
|
mit
|
C#
|
00cdd985f6932fce3d827d030aa638e5fa75836e
|
bump version for release
|
barnhill/barcodelib,barnhill/barcodelib,bbarnhill/barcodelib
|
BarcodeLib/Properties/AssemblyInfo.cs
|
BarcodeLib/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("BarcodeLib")]
[assembly: AssemblyDescription("Barcode Image Generation Library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Barnhill Software")]
[assembly: AssemblyProduct("BarcodeLib")]
[assembly: AssemblyCopyright("Copyright © Brad Barnhill 2007-present")]
[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("6b4a01ba-c67e-443d-813f-24c0c0f39a02")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.23")]
[assembly: AssemblyFileVersion("1.0.0.23")]
|
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("BarcodeLib")]
[assembly: AssemblyDescription("Barcode Image Generation Library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Barnhill Software")]
[assembly: AssemblyProduct("BarcodeLib")]
[assembly: AssemblyCopyright("Copyright © Brad Barnhill 2007-present")]
[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("6b4a01ba-c67e-443d-813f-24c0c0f39a02")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.22")]
[assembly: AssemblyFileVersion("1.0.0.22")]
|
apache-2.0
|
C#
|
b772407c81e37387730a648bf86060878a40f516
|
Implement vmdscale command
|
paralleltree/Scallion.Tools
|
vmdscale/Program.cs
|
vmdscale/Program.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text.RegularExpressions;
using System.Numerics;
using NDesk.Options;
using Scallion.Tools.Essentials;
using Scallion.DomainModels;
namespace Scallion.Tools.VmdScale
{
class Program : Runner
{
public override string Description
{
get { return "モーションファイルをスケーリングし出力します。\nデフォルトではファイル名に倍率を付加して出力します。"; }
}
public override string ArgumentFormat
{
get { return "[OPTION]... [INPUT] [OUTPUT]"; }
}
ExecutionParameter Parameter = new ExecutionParameter();
static void Main(string[] args)
{
Runner.Execute(() => new Program(args));
}
private Program(string[] args)
{
var opt = new OptionSet()
{
{ "?|h|help", "ヘルプを表示し、終了します。", _ => Parameter.ShowHelp = _ != null },
{ "s=|scale=", "スケーリングの倍率を指定します。", (float f) => Parameter.ScaleFactor = f }
};
var files = opt.Parse(args);
if (Parameter.ShowHelp || files.Count != 2)
{
if (args.Length > 0 && !Parameter.ShowHelp)
{
throw new MissingArgumentException("実行には2つのファイルの指定が必要です。");
}
PrintHelp(opt);
Environment.Exit(Parameter.ShowHelp ? 0 : 1);
}
Parameter.InputFile = files[0];
Parameter.OutputFile = files[1];
}
public override void Run()
{
var input = new Motion().Load(Parameter.InputFile);
foreach (var bone in input.Bones)
foreach (var keyframe in bone.KeyFrames)
keyframe.Position = keyframe.Position.ScaleVector3(Parameter.ScaleFactor);
foreach (var keyframe in input.Camera.KeyFrames)
keyframe.Position = keyframe.Position.ScaleVector3(Parameter.ScaleFactor);
if (File.Exists(Parameter.OutputFile))
{
while (true)
{
Console.Write("出力ファイルを上書きしますか? (y/N) > ");
string res = Console.ReadLine();
if (res == "" || Regex.IsMatch(res, "^(y|n)$", RegexOptions.IgnoreCase))
{
if (res.ToLower() == "y") break;
else return;
}
}
}
input.Save(Parameter.OutputFile);
}
}
class ExecutionParameter
{
public bool ShowHelp { get; set; }
public string InputFile { get; set; }
public string OutputFile { get; set; }
public float ScaleFactor { get; set; } = 1.0f;
}
static class Extensions
{
public static Vector3 ScaleVector3(this Vector3 src, float scale)
{
return new Vector3(src.X * scale, src.Y * scale, src.Z * scale);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Scallion.Tools.VmdScale
{
class Program
{
static void Main(string[] args)
{
}
}
}
|
mit
|
C#
|
f533260ae62988793ad6d74fac32429da96c50fe
|
make Ord<T> be an IComparer<T>
|
StanJav/language-ext,louthy/language-ext
|
LanguageExt.Core/TypeClasses/Ord/Ord.cs
|
LanguageExt.Core/TypeClasses/Ord/Ord.cs
|
using LanguageExt.Attributes;
using System.Diagnostics.Contracts;
namespace LanguageExt.TypeClasses
{
[Typeclass("Ord*")]
public interface Ord<A> : Eq<A>, System.Collections.Generic.IComparer<A>
{
/// <summary>
/// Compare two values
/// </summary>
/// <param name="x">Left hand side of the compare operation</param>
/// <param name="y">Right hand side of the compare operation</param>
/// <returns>
/// if x greater than y : 1
///
/// if x less than y : -1
///
/// if x equals y : 0
/// </returns>
[Pure]
int Compare(A x, A y);
}
}
|
using LanguageExt.Attributes;
using System.Diagnostics.Contracts;
namespace LanguageExt.TypeClasses
{
[Typeclass("Ord*")]
public interface Ord<A> : Eq<A>
{
/// <summary>
/// Compare two values
/// </summary>
/// <param name="x">Left hand side of the compare operation</param>
/// <param name="y">Right hand side of the compare operation</param>
/// <returns>
/// if x greater than y : 1
///
/// if x less than y : -1
///
/// if x equals y : 0
/// </returns>
[Pure]
int Compare(A x, A y);
}
}
|
mit
|
C#
|
894a1dea82ff171e6c39b6378cff2f7ce146ce51
|
add get metod
|
nudyk/NudykBot,nudyk/NudykBot
|
BotNudyk/BotNudyk/Controllers/MessagesController.cs
|
BotNudyk/BotNudyk/Controllers/MessagesController.cs
|
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using Microsoft.Bot.Connector;
using Microsoft.Bot.Connector.Utilities;
using Newtonsoft.Json;
namespace BotNudyk
{
[BotAuthentication]
public class MessagesController : ApiController
{
/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>
public async Task<Message> Post([FromBody]Message message)
{
if (message.Type == "Message")
{
// calculate something for us to return
int length = (message.Text ?? string.Empty).Length;
// return our reply to the user
return message.CreateReplyMessage($"You sent {length} characters");
}
else
{
return HandleSystemMessage(message);
}
}
[AllowAnonymous]
public async Task<bool> Get()
{
return true;
}
private Message HandleSystemMessage(Message message)
{
if (message.Type == "Ping")
{
Message reply = message.CreateReplyMessage();
reply.Type = "Ping";
return reply;
}
else if (message.Type == "DeleteUserData")
{
// Implement user deletion here
// If we handle user deletion, return a real message
}
else if (message.Type == "BotAddedToConversation")
{
}
else if (message.Type == "BotRemovedFromConversation")
{
}
else if (message.Type == "UserAddedToConversation")
{
}
else if (message.Type == "UserRemovedFromConversation")
{
}
else if (message.Type == "EndOfConversation")
{
}
return null;
}
}
}
|
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using Microsoft.Bot.Connector;
using Microsoft.Bot.Connector.Utilities;
using Newtonsoft.Json;
namespace BotNudyk
{
[BotAuthentication]
public class MessagesController : ApiController
{
/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>
public async Task<Message> Post([FromBody]Message message)
{
if (message.Type == "Message")
{
// calculate something for us to return
int length = (message.Text ?? string.Empty).Length;
// return our reply to the user
return message.CreateReplyMessage($"You sent {length} characters");
}
else
{
return HandleSystemMessage(message);
}
}
private Message HandleSystemMessage(Message message)
{
if (message.Type == "Ping")
{
Message reply = message.CreateReplyMessage();
reply.Type = "Ping";
return reply;
}
else if (message.Type == "DeleteUserData")
{
// Implement user deletion here
// If we handle user deletion, return a real message
}
else if (message.Type == "BotAddedToConversation")
{
}
else if (message.Type == "BotRemovedFromConversation")
{
}
else if (message.Type == "UserAddedToConversation")
{
}
else if (message.Type == "UserRemovedFromConversation")
{
}
else if (message.Type == "EndOfConversation")
{
}
return null;
}
}
}
|
mit
|
C#
|
ecad7e7084005e150afaede93b046803060362c9
|
Change Assembly version to 2.3.
|
transistor1/dockpanelsuite,15070217668/dockpanelsuite,thijse/dockpanelsuite,Romout/dockpanelsuite,angelapper/dockpanelsuite,15070217668/dockpanelsuite,joelbyren/dockpanelsuite,RadarNyan/dockpanelsuite,compborg/dockpanelsuite,jorik041/dockpanelsuite,xo-energy/dockpanelsuite,ArsenShnurkov/dockpanelsuite,rohitlodha/dockpanelsuite,modulexcite/O2_Fork_dockpanelsuite,dockpanelsuite/dockpanelsuite,elnomade/dockpanelsuite,shintadono/dockpanelsuite
|
WinFormsUI/Properties/AssemblyInfo.cs
|
WinFormsUI/Properties/AssemblyInfo.cs
|
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
[assembly: AssemblyTitle("DockPanel Suite for .Net 2.0")]
[assembly: AssemblyDescription(".Net Docking Library for Windows Forms")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Weifen Luo")]
[assembly: AssemblyProduct("DockPanel Suite")]
[assembly: AssemblyCopyright("Copyright © Weifen Luo 2007")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: Guid("9d690ef9-ce19-4c69-874c-e24d8eb36aff")]
[assembly: AssemblyVersion("2.3.*")]
[assembly: AssemblyFileVersion("2.3.0.0")]
[module: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "namespace", Target = "WeifenLuo.WinFormsUI.Docking", MessageId = "Weifen")]
[module: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "namespace", Target = "WeifenLuo.WinFormsUI.Docking", MessageId = "Luo")]
[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Weifen")]
[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Luo")]
[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Dockable")]
|
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
[assembly: AssemblyTitle("DockPanel Suite for .Net 2.0")]
[assembly: AssemblyDescription(".Net Docking Library for Windows Forms")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Weifen Luo")]
[assembly: AssemblyProduct("DockPanel Suite")]
[assembly: AssemblyCopyright("Copyright © Weifen Luo 2007")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: Guid("9d690ef9-ce19-4c69-874c-e24d8eb36aff")]
[assembly: AssemblyVersion("2.2.*")]
[assembly: AssemblyFileVersion("2.2.0.0")]
[module: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "namespace", Target = "WeifenLuo.WinFormsUI.Docking", MessageId = "Weifen")]
[module: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "namespace", Target = "WeifenLuo.WinFormsUI.Docking", MessageId = "Luo")]
[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Weifen")]
[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Luo")]
[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Dockable")]
|
mit
|
C#
|
a6996ee8027c4a9afe2fcbe2815c6e7122dbccdb
|
Support for Split Payment. Closes #1.
|
sirmmo/FatturaElettronicaPA,FatturaElettronicaPA/FatturaElettronicaPA
|
Validators/FEsigibilitaIVAValidator.cs
|
Validators/FEsigibilitaIVAValidator.cs
|
using BusinessObjects.Validators;
namespace FatturaElettronicaPA.Validators
{
/// <summary>
/// Validates FatturaElettronicaBody.DatiGenerali.DatiBeniServizi.DatiRiepilogo.EsigibilitaIVA.
/// </summary>
public class FEsigibilitaIVAValidator : DomainValidator
{
private const string BrokenDescription = "Valori ammessi [I] immediata, [D] differita, [S] scissione dei pagamenti.";
/// <summary>
/// Validates FatturaElettronicaBody.DatiGenerali.DatiBeniServizi.DatiRiepilogo.EsigibilitaIVA.
/// </summary>
public FEsigibilitaIVAValidator() : this(null, BrokenDescription) { }
public FEsigibilitaIVAValidator(string propertyName) : this(propertyName, BrokenDescription) { }
public FEsigibilitaIVAValidator(string propertyName, string description) : base(propertyName, description)
{
Domain = new[] { "I", "D", "S" };
}
}
}
|
using BusinessObjects.Validators;
namespace FatturaElettronicaPA.Validators
{
/// <summary>
/// Validates FatturaElettronicaBody.DatiGenerali.DatiBeniServizi.DatiRiepilogo.EsigibilitaIVA.
/// </summary>
public class FEsigibilitaIVAValidator : DomainValidator
{
private const string BrokenDescription = "Valori ammessi [I] immediata, [D] differita.";
/// <summary>
/// Validates FatturaElettronicaBody.DatiGenerali.DatiBeniServizi.DatiRiepilogo.EsigibilitaIVA.
/// </summary>
public FEsigibilitaIVAValidator() : this(null, BrokenDescription) { }
public FEsigibilitaIVAValidator(string propertyName) : this(propertyName, BrokenDescription) { }
public FEsigibilitaIVAValidator(string propertyName, string description) : base(propertyName, description)
{
Domain = new[] { "I", "D" };
}
}
}
|
bsd-3-clause
|
C#
|
c2abce22f55bcfa77707da72d61891ee4e6a2e3f
|
Fix wrong guard expression
|
evicertia/HermaFx,evicertia/HermaFx,evicertia/HermaFx
|
HermaFx.Foundation/DesignPatterns/EnhancedEnumType.cs
|
HermaFx.Foundation/DesignPatterns/EnhancedEnumType.cs
|
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Reflection;
namespace HermaFx.DesignPatterns
{
[Serializable]
public abstract class EnhancedEnumType<L, T> : ReadOnlyCollection<T>, IEnhancedEnumTypeDescriptor<T>
where L : EnhancedEnumType<L, T>
{
#region Fields
private static T[] _entries = GetFields<L>();
#endregion
#region .ctors
static EnhancedEnumType()
{
Guard.Against<InvalidOperationException>(_entries.Length == 0, "EnhancedEnumType {0} has no elements?!", typeof(L).Name);
}
public EnhancedEnumType(Func<T, object> memberKeyGetter)
: this(memberKeyGetter, null)
{
}
public EnhancedEnumType(Func<T, object> memberKeyGetter, Func<T, object, bool> memberKeyMatcher)
: base(_entries)
{
MemberKeyGetter = memberKeyGetter;
MemberKeyMatcher = memberKeyMatcher ?? ((x, value) => memberKeyGetter(x) == value);
MemberType = memberKeyGetter(_entries.First()).GetType();
Guard.Against<InvalidOperationException>(
_entries.Count() != _entries.Select(x => MemberKeyGetter(x)).Distinct().Count(),
"One or more EnhancedEnum members have duplicated keys"
);
}
#endregion
#region static helper methods..
private static T[] GetFields<W>()
where W : ReadOnlyCollection<T>
{
// Fill _entries list..
var type = typeof(W);
var bflags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static;
var fields = type.FindMembers(MemberTypes.Field, bflags, null, null);
return fields.OfType<FieldInfo>()
.Select(x => x.GetValue(null))
.OfType<T>()
.ToArray();
}
#endregion
#region IEnhancedEnumTypeDescriptor<T> Members
public Type MemberType { get; private set; }
public Func<T, object> MemberKeyGetter { get; private set; }
public Func<T, object, bool> MemberKeyMatcher { get; private set; }
#endregion
}
public interface IEnhancedEnumTypeDescriptor<T>
{
Type MemberType { get; }
Func<T, object> MemberKeyGetter { get; }
Func<T, object, bool> MemberKeyMatcher { get; }
}
}
|
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Reflection;
namespace HermaFx.DesignPatterns
{
[Serializable]
public abstract class EnhancedEnumType<L, T> : ReadOnlyCollection<T>, IEnhancedEnumTypeDescriptor<T>
where L : EnhancedEnumType<L, T>
{
#region Fields
private static T[] _entries = GetFields<L>();
#endregion
#region .ctors
static EnhancedEnumType()
{
Guard.Against<InvalidOperationException>(_entries.Length == 0, "EnhancedEnumType {0} has no elements?!", typeof(L).Name);
}
public EnhancedEnumType(Func<T, object> memberKeyGetter)
: this(memberKeyGetter, null)
{
}
public EnhancedEnumType(Func<T, object> memberKeyGetter, Func<T, object, bool> memberKeyMatcher)
: base(_entries)
{
MemberKeyGetter = memberKeyGetter;
MemberKeyMatcher = memberKeyMatcher ?? ((x, value) => memberKeyGetter(x) == value);
MemberType = memberKeyGetter(_entries.First()).GetType();
Guard.Against<InvalidOperationException>(
_entries.Count() == _entries.Select(x => MemberKeyGetter(x)).Distinct().Count(),
"One or more EnhancedEnum members have duplicated keys"
);
}
#endregion
#region static helper methods..
private static T[] GetFields<W>()
where W : ReadOnlyCollection<T>
{
// Fill _entries list..
var type = typeof(W);
var bflags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static;
var fields = type.FindMembers(MemberTypes.Field, bflags, null, null);
return fields.OfType<FieldInfo>()
.Select(x => x.GetValue(null))
.OfType<T>()
.ToArray();
}
#endregion
#region IEnhancedEnumTypeDescriptor<T> Members
public Type MemberType { get; private set; }
public Func<T, object> MemberKeyGetter { get; private set; }
public Func<T, object, bool> MemberKeyMatcher { get; private set; }
#endregion
}
public interface IEnhancedEnumTypeDescriptor<T>
{
Type MemberType { get; }
Func<T, object> MemberKeyGetter { get; }
Func<T, object, bool> MemberKeyMatcher { get; }
}
}
|
mit
|
C#
|
8f297e7f69cb4c4865f03bfa0c9a3a11bb59558a
|
bump version to 1.5.11
|
martin2250/OpenCNCPilot
|
OpenCNCPilot/Properties/AssemblyInfo.cs
|
OpenCNCPilot/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("OpenCNCPilot")]
[assembly: AssemblyDescription("GCode Sender and AutoLeveller")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("martin2250")]
[assembly: AssemblyProduct("OpenCNCPilot")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.5.11.0")]
[assembly: AssemblyFileVersion("1.5.11.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("OpenCNCPilot")]
[assembly: AssemblyDescription("GCode Sender and AutoLeveller")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("martin2250")]
[assembly: AssemblyProduct("OpenCNCPilot")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.5.10.0")]
[assembly: AssemblyFileVersion("1.5.10.0")]
|
mit
|
C#
|
067a211b08e83844119d435a15f9fb35c9c82f8a
|
Build and publish nuget package.
|
rlyczynski/XSerializer,QuickenLoans/XSerializer
|
XSerializer/Properties/AssemblyInfo.cs
|
XSerializer/Properties/AssemblyInfo.cs
|
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XSerializer")]
[assembly: AssemblyDescription("A .NET XML serializer that serializes and deserializes anything.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Quicken Loans")]
[assembly: AssemblyProduct("XSerializer")]
[assembly: AssemblyCopyright("Copyright © Quicken Loans 2013-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)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5aeaebd0-35de-424c-baa9-ba6d65fa3409")]
[assembly: CLSCompliant(true)]
// 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.0.0")]
[assembly: AssemblyFileVersion("0.2.4")]
[assembly: AssemblyInformationalVersion("0.2.4")]
[assembly: InternalsVisibleTo("XSerializer.Tests")]
[assembly: InternalsVisibleTo("XSerializer.PerformanceTests")]
|
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XSerializer")]
[assembly: AssemblyDescription("A .NET XML serializer that serializes and deserializes anything.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Quicken Loans")]
[assembly: AssemblyProduct("XSerializer")]
[assembly: AssemblyCopyright("Copyright © Quicken Loans 2013-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)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5aeaebd0-35de-424c-baa9-ba6d65fa3409")]
[assembly: CLSCompliant(true)]
// 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.0.0")]
[assembly: AssemblyFileVersion("0.2.3")]
[assembly: AssemblyInformationalVersion("0.2.3")]
[assembly: InternalsVisibleTo("XSerializer.Tests")]
[assembly: InternalsVisibleTo("XSerializer.PerformanceTests")]
|
mit
|
C#
|
dd4a4f790df3b546731ed1dd39da1f7bad960f63
|
Add unit test for implicit Guid construction
|
OlsonDev/YeamulNet
|
Yeamul.Test/Test_Node_Implicit_Ctor.cs
|
Yeamul.Test/Test_Node_Implicit_Ctor.cs
|
using System;
using NUnit.Framework;
namespace Yeamul {
[TestFixture]
public class Test_Node_Implicit_Ctor {
[Test]
public void CanConstructImplicitlyFromBoolean() {
Node node = true;
AssertNodeIsDefinedScalar(node);
Assert.That(node.IsBoolean);
AssertNodeHasTypes(node, NodeType.Scalar, ScalarType.Boolean, NumberType.NotANumber, MapType.NotApplicable);
}
[Test]
public void CanConstructImplicitlyFromInt16() {
Node node = Int16.MaxValue;
AssertNodeIsDefinedScalarNumber(node);
AssertNodeHasTypes(node, NodeType.Scalar, ScalarType.Number, NumberType.Int16, MapType.NotApplicable);
}
[Test]
public void CanConstructImplicitlyFromInt32() {
Node node = Int32.MaxValue;
AssertNodeIsDefinedScalarNumber(node);
AssertNodeHasTypes(node, NodeType.Scalar, ScalarType.Number, NumberType.Int32, MapType.NotApplicable);
}
[Test]
public void CanConstructImplicitlyFromInt64() {
Node node = Int64.MaxValue;
AssertNodeIsDefinedScalarNumber(node);
AssertNodeHasTypes(node, NodeType.Scalar, ScalarType.Number, NumberType.Int64, MapType.NotApplicable);
}
[Test]
public void CanConstructImplicitlyFromUInt16() {
Node node = UInt16.MaxValue;
AssertNodeIsDefinedScalarNumber(node);
AssertNodeHasTypes(node, NodeType.Scalar, ScalarType.Number, NumberType.UInt16, MapType.NotApplicable);
}
[Test]
public void CanConstructImplicitlyFromUInt32() {
Node node = UInt32.MaxValue;
AssertNodeIsDefinedScalarNumber(node);
AssertNodeHasTypes(node, NodeType.Scalar, ScalarType.Number, NumberType.UInt32, MapType.NotApplicable);
}
[Test]
public void CanConstructImplicitlyFromUInt64() {
Node node = UInt64.MaxValue;
AssertNodeIsDefinedScalarNumber(node);
AssertNodeHasTypes(node, NodeType.Scalar, ScalarType.Number, NumberType.UInt64, MapType.NotApplicable);
}
[Test]
public void CanConstructImplicitlyFromGuid() {
Node node = Guid.NewGuid();
AssertNodeIsDefinedScalarNumber(node);
AssertNodeHasTypes(node, NodeType.Scalar, ScalarType.Number, NumberType.Guid, MapType.NotApplicable);
}
private static void AssertNodeIsDefinedScalar(Node node) {
Assert.That(node.IsDefined);
Assert.That(node.IsScalar);
}
private static void AssertNodeIsDefinedScalarNumber(Node node) {
AssertNodeIsDefinedScalar(node);
Assert.That(node.IsNumber);
}
private void AssertNodeHasTypes(Node node, NodeType nodeType, ScalarType scalarType, NumberType numberType, MapType mapType) {
Assert.AreEqual(node.NodeType, nodeType);
Assert.AreEqual(node.ScalarType, scalarType);
Assert.AreEqual(node.NumberType, numberType);
Assert.AreEqual(node.MapType, mapType);
}
}
}
|
using System;
using NUnit.Framework;
namespace Yeamul {
[TestFixture]
public class Test_Node_Implicit_Ctor {
[Test]
public void CanConstructImplicitlyFromBoolean() {
Node node = true;
AssertNodeIsDefinedScalar(node);
Assert.That(node.IsBoolean);
AssertNodeHasTypes(node, NodeType.Scalar, ScalarType.Boolean, NumberType.NotANumber, MapType.NotApplicable);
}
[Test]
public void CanConstructImplicitlyFromInt16() {
Node node = Int16.MaxValue;
AssertNodeIsDefinedScalarNumber(node);
AssertNodeHasTypes(node, NodeType.Scalar, ScalarType.Number, NumberType.Int16, MapType.NotApplicable);
}
[Test]
public void CanConstructImplicitlyFromInt32() {
Node node = Int32.MaxValue;
AssertNodeIsDefinedScalarNumber(node);
AssertNodeHasTypes(node, NodeType.Scalar, ScalarType.Number, NumberType.Int32, MapType.NotApplicable);
}
[Test]
public void CanConstructImplicitlyFromInt64() {
Node node = Int64.MaxValue;
AssertNodeIsDefinedScalarNumber(node);
AssertNodeHasTypes(node, NodeType.Scalar, ScalarType.Number, NumberType.Int64, MapType.NotApplicable);
}
[Test]
public void CanConstructImplicitlyFromUInt16() {
Node node = UInt16.MaxValue;
AssertNodeIsDefinedScalarNumber(node);
AssertNodeHasTypes(node, NodeType.Scalar, ScalarType.Number, NumberType.UInt16, MapType.NotApplicable);
}
[Test]
public void CanConstructImplicitlyFromUInt32() {
Node node = UInt32.MaxValue;
AssertNodeIsDefinedScalarNumber(node);
AssertNodeHasTypes(node, NodeType.Scalar, ScalarType.Number, NumberType.UInt32, MapType.NotApplicable);
}
[Test]
public void CanConstructImplicitlyFromUInt64() {
Node node = UInt64.MaxValue;
AssertNodeIsDefinedScalarNumber(node);
AssertNodeHasTypes(node, NodeType.Scalar, ScalarType.Number, NumberType.UInt64, MapType.NotApplicable);
}
private static void AssertNodeIsDefinedScalar(Node node) {
Assert.That(node.IsDefined);
Assert.That(node.IsScalar);
}
private static void AssertNodeIsDefinedScalarNumber(Node node) {
AssertNodeIsDefinedScalar(node);
Assert.That(node.IsNumber);
}
private void AssertNodeHasTypes(Node node, NodeType nodeType, ScalarType scalarType, NumberType numberType, MapType mapType) {
Assert.AreEqual(node.NodeType, nodeType);
Assert.AreEqual(node.ScalarType, scalarType);
Assert.AreEqual(node.NumberType, numberType);
Assert.AreEqual(node.MapType, mapType);
}
}
}
|
mit
|
C#
|
e0a700d9e39625eb274f1e974c7726c4805b705f
|
bump version
|
Fody/PropertyChanged,user1568891/PropertyChanged,0x53A/PropertyChanged
|
CommonAssemblyInfo.cs
|
CommonAssemblyInfo.cs
|
using System.Reflection;
[assembly: AssemblyTitle("PropertyChanged")]
[assembly: AssemblyProduct("PropertyChanged")]
[assembly: AssemblyCompany("Simon Cropp and Contributors")]
[assembly: AssemblyDescription("Fody add-in for injecting INotifyPropertyChanged code into properties.")]
[assembly: AssemblyVersion("1.48.4")]
[assembly: AssemblyFileVersion("1.48.4")]
|
using System.Reflection;
[assembly: AssemblyTitle("PropertyChanged")]
[assembly: AssemblyProduct("PropertyChanged")]
[assembly: AssemblyCompany("Simon Cropp and Contributors")]
[assembly: AssemblyDescription("Fody add-in for injecting INotifyPropertyChanged code into properties.")]
[assembly: AssemblyVersion("1.48.3")]
[assembly: AssemblyFileVersion("1.48.3")]
|
mit
|
C#
|
f28834e2963cf0b02c3eed812d99a1e4519afd32
|
Fix GraphQL type error
|
ASP-NET-Core-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate,ASP-NET-Core-Boilerplate/Templates,ASP-NET-MVC-Boilerplate/Templates,ASP-NET-MVC-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate,RehanSaeed/ASP.NET-MVC-Boilerplate,ASP-NET-Core-Boilerplate/Templates
|
Source/Content/GraphQLTemplate/Types/HumanObject.cs
|
Source/Content/GraphQLTemplate/Types/HumanObject.cs
|
namespace GraphQLTemplate.Types
{
using System.Collections.Generic;
#if (Authorization)
using GraphQL.Authorization;
#endif
using GraphQL.Types;
using GraphQLTemplate.Constants;
using GraphQLTemplate.Models;
using GraphQLTemplate.Repositories;
public class HumanObject : ObjectGraphType<Human>
{
public HumanObject(IHumanRepository humanRepository)
{
this.Name = "Human";
this.Description = "A humanoid creature from the Star Wars universe.";
#if (Authorization)
// this.AuthorizeWith(AuthorizationPolicyName.Admin); // To require authorization for all fields in this type.
#endif
this.Field(x => x.Id, type: typeof(NonNullGraphType<IdGraphType>))
.Description("The unique identifier of the human.");
this.Field(x => x.Name)
.Description("The name of the human.");
this.Field(x => x.DateOfBirth)
#if (Authorization)
.AuthorizeWith(AuthorizationPolicyName.Admin) // Require authorization to access the date of birth field.
#endif
.Description("The humans date of birth.");
this.Field(x => x.HomePlanet, nullable: true)
.Description("The home planet of the human.");
this.Field(x => x.AppearsIn, type: typeof(ListGraphType<EpisodeEnumeration>))
.Description("Which movie they appear in.");
this.FieldAsync<ListGraphType<CharacterInterface>, List<Character>>(
nameof(Human.Friends),
"The friends of the character, or an empty list if they have none.",
resolve: context => humanRepository.GetFriends(context.Source, context.CancellationToken));
this.Interface<CharacterInterface>();
}
}
}
|
namespace GraphQLTemplate.Types
{
using System.Collections.Generic;
#if (Authorization)
using GraphQL.Authorization;
#endif
using GraphQL.Types;
using GraphQLTemplate.Constants;
using GraphQLTemplate.Models;
using GraphQLTemplate.Repositories;
public class HumanObject : ObjectGraphType<Human>
{
public HumanObject(IHumanRepository humanRepository)
{
this.Name = "Human";
this.Description = "A humanoid creature from the Star Wars universe.";
#if (Authorization)
// this.AuthorizeWith(AuthorizationPolicyName.Admin); // To require authorization for all fields in this type.
#endif
this.Field(x => x.Id, type: typeof(IdGraphType))
.Description("The unique identifier of the human.");
this.Field(x => x.Name)
.Description("The name of the human.");
this.Field(x => x.DateOfBirth)
#if (Authorization)
.AuthorizeWith(AuthorizationPolicyName.Admin) // Require authorization to access the date of birth field.
#endif
.Description("The humans date of birth.");
this.Field(x => x.HomePlanet, nullable: true)
.Description("The home planet of the human.");
this.Field(x => x.AppearsIn, type: typeof(ListGraphType<EpisodeEnumeration>))
.Description("Which movie they appear in.");
this.FieldAsync<ListGraphType<CharacterInterface>, List<Character>>(
nameof(Human.Friends),
"The friends of the character, or an empty list if they have none.",
resolve: context => humanRepository.GetFriends(context.Source, context.CancellationToken));
this.Interface<CharacterInterface>();
}
}
}
|
mit
|
C#
|
bd75a2f43aaa42d0e063a8226bfac5badd8ebc97
|
Make sure playerComp is in the node lookup list
|
Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder
|
PathfinderAPI/BaseGameFixes/Performance/NodeLookup.cs
|
PathfinderAPI/BaseGameFixes/Performance/NodeLookup.cs
|
using System.Collections.Generic;
using Hacknet;
using HarmonyLib;
using Pathfinder.Event;
using Pathfinder.Event.Loading;
using Pathfinder.Util;
namespace Pathfinder.BaseGameFixes.Performance
{
[HarmonyPatch]
internal static class NodeLookup
{
[HarmonyPostfix]
[HarmonyPatch(typeof(List<Computer>), nameof(List<Computer>.Add))]
[HarmonyPatch(typeof(List<Computer>), nameof(List<Computer>.Insert))]
internal static void AddComputerReference(List<Computer> __instance, Computer item)
{
if (object.ReferenceEquals(__instance, OS.currentInstance?.netMap?.nodes))
{
ComputerLookup.PopulateLookups(item);
}
}
[HarmonyPrefix]
[HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.findComp))]
internal static bool ModifyComputerLoaderLookup(out Computer __result, string target)
{
__result = ComputerLookup.FindById(target);
return false;
}
[HarmonyPrefix]
[HarmonyPatch(typeof(Programs), nameof(Programs.getComputer))]
internal static bool ModifyProgramsLookup(out Computer __result, string ip_Or_ID_or_Name)
{
__result = ComputerLookup.Find(ip_Or_ID_or_Name);
return false;
}
[HarmonyPostfix]
[HarmonyPatch(typeof(OS), nameof(OS.quitGame))]
internal static void ClearOnQuitGame()
{
ComputerLookup.ClearLookups();
}
}
}
|
using System.Collections.Generic;
using Hacknet;
using HarmonyLib;
using Pathfinder.Event;
using Pathfinder.Event.Loading;
using Pathfinder.Util;
namespace Pathfinder.BaseGameFixes.Performance
{
[HarmonyPatch]
internal static class NodeLookup
{
[HarmonyPostfix]
[HarmonyPatch(typeof(List<Computer>), nameof(List<Computer>.Add))]
internal static void AddComputerReference(List<Computer> __instance, Computer item)
{
if (object.ReferenceEquals(__instance, OS.currentInstance?.netMap?.nodes))
{
ComputerLookup.PopulateLookups(item);
}
}
[HarmonyPrefix]
[HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.findComp))]
internal static bool ModifyComputerLoaderLookup(out Computer __result, string target)
{
__result = ComputerLookup.FindById(target);
return false;
}
[HarmonyPrefix]
[HarmonyPatch(typeof(Programs), nameof(Programs.getComputer))]
internal static bool ModifyProgramsLookup(out Computer __result, string ip_Or_ID_or_Name)
{
__result = ComputerLookup.Find(ip_Or_ID_or_Name);
return false;
}
[HarmonyPostfix]
[HarmonyPatch(typeof(OS), nameof(OS.quitGame))]
internal static void ClearOnQuitGame()
{
ComputerLookup.ClearLookups();
}
}
}
|
mit
|
C#
|
151d717005bfe5e9d452c0148afcc6eee2e813d7
|
Add GetEndpointData manual test to ConsoleAppTester
|
AshleyPoole/ssllabs-api-wrapper
|
SSLLWrapper.ConsoleAppTester/Program.cs
|
SSLLWrapper.ConsoleAppTester/Program.cs
|
using System;
using System.Linq;
namespace SSLLWrapper.ConsoleAppTester
{
class Program
{
private const string ApiUrl = "https://api.dev.ssllabs.com/api/fa78d5a4";
static readonly ApiService ApiService = new ApiService(ApiUrl);
static void Main(string[] args)
{
//AnalyzeTester();
//InfoTester();
GetEndpointData();
}
static void InfoTester()
{
var info = ApiService.Info();
Console.WriteLine("Has Error Occoured: {0}", info.HasErrorOccurred);
Console.WriteLine("Status Code: {0}", info.Headers.statusCode);
Console.WriteLine("Engine Version: {0}", info.engineVersion);
Console.WriteLine("Online: {0}", info.Online);
Console.ReadLine();
}
static void AnalyzeTester()
{
var analyze = ApiService.Analyze("http://www.ashleypoole.co.uk");
Console.WriteLine("Has Error Occoured: {0}", analyze.HasErrorOccurred);
Console.WriteLine("Status Code: {0}", analyze.Headers.statusCode);
Console.WriteLine("Status: {0}", analyze.status);
Console.ReadLine();
}
static void GetEndpointData()
{
var endpointDataModel = ApiService.GetEndpointData("http://www.ashleypoole.co.uk", "104.28.6.2");
Console.WriteLine("Has Error Occoured: {0}", endpointDataModel.HasErrorOccurred);
Console.WriteLine("Status Code: {0}", endpointDataModel.Headers.statusCode);
Console.WriteLine("IP Adress: {0}", endpointDataModel.ipAddress);
Console.WriteLine("Grade: {0}", endpointDataModel.grade);
Console.WriteLine("Status Message: {0}", endpointDataModel.statusMessage);
Console.ReadLine();
}
}
}
|
using System;
using System.Linq;
namespace SSLLWrapper.ConsoleAppTester
{
class Program
{
private const string apiUrl = "https://api.dev.ssllabs.com/api/fa78d5a4";
static void Main(string[] args)
{
AnalyzeTester();
}
static void AnalyzeTester()
{
var apiService = new ApiService(apiUrl);
var analyze = apiService.Analyze("http://www.ashleypoole.co.uk");
Console.WriteLine("Has Error Occoured: {0}", analyze.HasErrorOccurred);
Console.WriteLine("Status Code: {0}", analyze.Headers.statusCode);
Console.WriteLine("Status: {0}", analyze.status);
Console.ReadLine();
}
}
}
|
mit
|
C#
|
545f166856f626d332e28c9fbbf1d0db767f01e5
|
Make reference type
|
CamTechConsultants/CvsntGitImporter
|
Revision.cs
|
Revision.cs
|
/*
* John Hall <john.hall@xjtag.com>
* Copyright (c) Midas Yellow Ltd. All rights reserved.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace CvsGitConverter
{
/// <summary>
/// Represents a CVS revision number.
/// </summary>
class Revision
{
private string m_value;
public static Revision Empty = new Revision("");
/// <summary>
/// Initializes a new instance of the <see cref="Revision"/> struct.
/// </summary>
/// <exception cref="ArgumentException">if the revision string is invalid</exception>
public Revision(string value)
{
if (value.Length > 0 && !Regex.IsMatch(value, @"\d+(\.\d+){1,}"))
throw new ArgumentException(String.Format("Invalid revision format: '{0}'", value));
m_value = value;
}
/// <summary>
/// Split the revision up into parts.
/// </summary>
public IEnumerable<int> Parts
{
get { return m_value.Split('.').Select(p => int.Parse(p)); }
}
public override string ToString()
{
return m_value;
}
public static bool operator==(Revision a, string b)
{
return a.m_value == b;
}
public static bool operator !=(Revision a, string b)
{
return a.m_value != b;
}
public override bool Equals(object obj)
{
if (obj is string)
return m_value == (string)obj;
else if (obj is Revision)
return m_value == ((Revision)obj).m_value;
else
return false;
}
public override int GetHashCode()
{
return m_value.GetHashCode();
}
}
}
|
/*
* John Hall <john.hall@xjtag.com>
* Copyright (c) Midas Yellow Ltd. All rights reserved.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace CvsGitConverter
{
/// <summary>
/// Represents a CVS revision number.
/// </summary>
struct Revision
{
private string m_value;
public static Revision Empty = new Revision("");
/// <summary>
/// Initializes a new instance of the <see cref="Revision"/> struct.
/// </summary>
/// <exception cref="ArgumentException">if the revision string is invalid</exception>
public Revision(string value)
{
if (value.Length > 0 && !Regex.IsMatch(value, @"\d+(\.\d+){1,}"))
throw new ArgumentException(String.Format("Invalid revision format: '{0}'", value));
m_value = value;
}
/// <summary>
/// Split the revision up into parts.
/// </summary>
public IEnumerable<int> Parts
{
get { return m_value.Split('.').Select(p => int.Parse(p)); }
}
public override string ToString()
{
return m_value;
}
public static bool operator==(Revision a, string b)
{
return a.m_value == b;
}
public static bool operator !=(Revision a, string b)
{
return a.m_value != b;
}
public override bool Equals(object obj)
{
if (obj is string)
return m_value == (string)obj;
else if (obj is Revision)
return m_value == ((Revision)obj).m_value;
else
return false;
}
public override int GetHashCode()
{
return m_value.GetHashCode();
}
}
}
|
mit
|
C#
|
e31104dc7da75dab3a01920bd52366fd991c1843
|
Use element type name for variable names
|
zatherz/MonoMod,0x0ade/MonoMod,AngelDE98/MonoMod
|
MonoMod/DebugIL/DebugILGeneratorExt.cs
|
MonoMod/DebugIL/DebugILGeneratorExt.cs
|
using Mono.Cecil;
using Mono.Cecil.Cil;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace MonoMod.DebugIL {
public static class DebugILGeneratorExt {
public readonly static Type t_MetadataType = typeof(MetadataType);
public static ScopeDebugInformation GetOrAddScope(this MethodDebugInformation mdi) {
if (mdi.Scope != null)
return mdi.Scope;
return mdi.Scope = new ScopeDebugInformation(
mdi.Method.Body.Instructions[0],
mdi.Method.Body.Instructions[mdi.Method.Body.Instructions.Count - 1]
);
}
public static string GenerateVariableName(this VariableDefinition @var, MethodDefinition method = null, int i = -1) {
TypeReference type = @var.VariableType;
while (type is TypeSpecification)
type = ((TypeSpecification) type).ElementType;
string name = type.Name;
if (type.MetadataType == MetadataType.Boolean)
name = "flag";
else if (type.IsPrimitive)
name = Enum.GetName(t_MetadataType, type.MetadataType);
name = name.Substring(0, 1).ToLowerInvariant() + name.Substring(1);
if (method == null)
return i < 0 ? name : (name + i);
// Check for usage as loop counter or similar?
return i < 0 ? name : (name + i);
}
}
}
|
using Mono.Cecil;
using Mono.Cecil.Cil;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace MonoMod.DebugIL {
public static class DebugILGeneratorExt {
public readonly static Type t_MetadataType = typeof(MetadataType);
public static ScopeDebugInformation GetOrAddScope(this MethodDebugInformation mdi) {
if (mdi.Scope != null)
return mdi.Scope;
return mdi.Scope = new ScopeDebugInformation(
mdi.Method.Body.Instructions[0],
mdi.Method.Body.Instructions[mdi.Method.Body.Instructions.Count - 1]
);
}
public static string GenerateVariableName(this VariableDefinition @var, MethodDefinition method = null, int i = -1) {
TypeReference type = @var.VariableType;
string name = type.Name;
if (type.MetadataType == MetadataType.Boolean)
name = "flag";
else if (type.IsPrimitive)
name = Enum.GetName(t_MetadataType, type.MetadataType);
name = name.Substring(0, 1).ToLowerInvariant() + name.Substring(1);
if (method == null)
return i < 0 ? name : (name + i);
// Check for usage as loop counter or similar?
return i < 0 ? name : (name + i);
}
}
}
|
mit
|
C#
|
a3906a72db7dfe40b0dd0df5eabc50648b895046
|
Fix board size updater not running
|
thijser/ARGAME,thijser/ARGAME,thijser/ARGAME
|
ARGame/Assets/Scripts/Core/BoardResizer.cs
|
ARGame/Assets/Scripts/Core/BoardResizer.cs
|
//----------------------------------------------------------------------------
// <copyright file="BoardResizer.cs" company="Delft University of Technology">
// Copyright 2015, Delft University of Technology
//
// This software is licensed under the terms of the MIT License.
// A copy of the license should be included with this software. If not,
// see http://opensource.org/licenses/MIT for the full license.
// </copyright>
//----------------------------------------------------------------------------
namespace Core
{
using System.Collections;
using Network;
using UnityEngine;
/// <summary>
/// Resizes the board when a level serverUpdate is received with a new board size.
/// </summary>
public class BoardResizer : MonoBehaviour
{
/// <summary>
/// Updates the board size with the size in the argument.
/// </summary>
/// <param name="level">The level update.</param>
public void OnLevelUpdate(LevelUpdate level)
{
Debug.Log("Applying Board Size: " + level.Size);
this.StartCoroutine(this.UpdateBoardSize(level.Size));
}
/// <summary>
/// Updates the size of the playing board.
/// </summary>
/// <param name="size">The new board size.</param>
/// <returns>True if the board size was updated, false if no board was found.</returns>
public IEnumerator UpdateBoardSize(Vector2 size)
{
yield return new WaitForFixedUpdate();
Transform board = this.GetComponentInChildren<Board>().transform.parent;
if (board != null)
{
board.gameObject.SetActive(true);
Vector3 scale = new Vector3(-size.x, board.localScale.y, size.y);
board.localScale = scale;
}
else
{
Debug.LogError("no board found");
}
}
}
}
|
//----------------------------------------------------------------------------
// <copyright file="BoardResizer.cs" company="Delft University of Technology">
// Copyright 2015, Delft University of Technology
//
// This software is licensed under the terms of the MIT License.
// A copy of the license should be included with this software. If not,
// see http://opensource.org/licenses/MIT for the full license.
// </copyright>
//----------------------------------------------------------------------------
namespace Core
{
using System.Collections;
using Network;
using UnityEngine;
/// <summary>
/// Resizes the board when a level serverUpdate is received with a new board size.
/// </summary>
public class BoardResizer : MonoBehaviour
{
/// <summary>
/// Updates the board size with the size in the argument.
/// </summary>
/// <param name="level">The level update.</param>
public void OnLevelUpdate(LevelUpdate level)
{
Debug.Log("Applying Board Size: " + level.Size);
this.StartCoroutine(this.UpdateBoardSize(level.Size));
}
/// <summary>
/// Updates the size of the playing board.
/// </summary>
/// <param name="size">The new board size.</param>
/// <returns>True if the board size was updated, false if no board was found.</returns>
public IEnumerator UpdateBoardSize(Vector2 size)
{
yield return new WaitForEndOfFrame();
Transform board = this.GetComponentInChildren<Board>().transform.parent;
if (board != null)
{
board.gameObject.SetActive(true);
Vector3 scale = new Vector3(-size.x, board.localScale.y, size.y);
board.localScale = scale;
}
else
{
Debug.LogError("no board found");
}
}
}
}
|
mit
|
C#
|
28c49e91b6ff633214f5702dd66d45d20833cdc2
|
Use actual StarDate
|
dannydwarren/Cortana-Location-UWP,dannydwarren/Cortana-Location-UWP
|
dev/Cortana_Location/ComputerAssistant.UI/Models/DateTimeStampedBindable.cs
|
dev/Cortana_Location/ComputerAssistant.UI/Models/DateTimeStampedBindable.cs
|
using System;
namespace ComputerAssistant.UI.Models
{
public class DateTimeStampedBindable : Bindable
{
public DateTimeStampedBindable()
{
StarDate = DateTime.UtcNow;
}
public DateTime StarDate { get; set; }
public string StardateString => $"{StarDate.ToStarDate()}";
public string CurrentDateString => StarDate.ToLocalTime().ToString("yyyy-MM-DD HH:mm:ss:ff tt zzz");
}
public static class Extensions
{
/// <summary>
/// StarDate by ballance on GitHub: https://github.com/ballance/StarDate
/// https://github.com/ballance/StarDate/blob/master/Ballance.StarDate/StarDateConverter.cs</summary>
/// <param name="earthDateTime"></param>
/// <returns></returns>
public static double ToStarDate(this DateTime earthDateTime)
{
var starDateOrigin = new DateTime(2318, 7, 5, 12, 0, 0);
var earthToStarDateDiff = earthDateTime - starDateOrigin;
var millisecondConversion = earthToStarDateDiff.TotalMilliseconds / (34367056.4);
var starDate = Math.Floor(millisecondConversion * 100) / 100;
return Math.Round(starDate, 2, MidpointRounding.AwayFromZero);
}
}
}
|
using System;
namespace ComputerAssistant.UI.Models
{
public class DateTimeStampedBindable : Bindable
{
public DateTimeStampedBindable()
{
StarDate = DateTime.UtcNow;
}
public DateTime StarDate { get; set; }
public string StardateString => $"{StarDate.ToString( "yyyy" )}.{StarDate.DayOfYear}{StarDate.ToString( "HHmmssff" )}";
public string CurrentDateString => StarDate.ToLocalTime().ToString( "yyyy-MM-DD HH:mm:ss:ff tt zzz" );
}
}
|
mit
|
C#
|
9e044514f27bb53f44f36fe439cfbeb9db163191
|
Change the content for COVID banner
|
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
|
src/SFA.DAS.EmployerAccounts.Web/Views/Shared/_COVID19GuidanceBanner.cshtml
|
src/SFA.DAS.EmployerAccounts.Web/Views/Shared/_COVID19GuidanceBanner.cshtml
|
@if (ViewBag.UseCDN ?? false)
{
<div class="das-notification">
<h3 class="das-notification__heading">
Coronavirus (COVID-19): <a href="https://www.gov.uk/government/publications/coronavirus-covid-19-apprenticeship-programme-response/coronavirus-covid-19-guidance-for-apprentices-employers-training-providers-end-point-assessment-organisations-and-external-quality-assurance-pro" target="_blank">read our guidance</a> on the changes we're making to apprenticeships and <a href="https://help.apprenticeships.education.gov.uk/hc/en-gb/articles/360009509360-Pause-or-stop-an-apprenticeship" target="_blank">find out how you can pause your apprenticeships</a>.
</h3>
</div>
}
else
{
<div class="info-summary">
<h2 class="heading-small">
Coronavirus (COVID-19): <a href="https://www.gov.uk/government/publications/coronavirus-covid-19-apprenticeship-programme-response/coronavirus-covid-19-guidance-for-apprentices-employers-training-providers-end-point-assessment-organisations-and-external-quality-assurance-pro" target="_blank">read our guidance</a> on the changes we're making to apprenticeships and <a href="https://help.apprenticeships.education.gov.uk/hc/en-gb/articles/360009509360-Pause-or-stop-an-apprenticeship" target="_blank">find out how you can pause your apprenticeships</a>.
</h2>
</div>
}
|
@if (ViewBag.UseCDN ?? false)
{
<div class="das-notification">
<h3 class="das-notification__heading">New employer agreement</h3>
<p class="das-notification__body">From 14 April 2020, you must accept a new employer agreement to:</p>
<ul class="govuk-list govuk-list--bullet">
<li>access apprenticeship funding for new apprentices</li>
<li>approve any changes in your account</li>
</ul>
<p class="das-notification__body">
Coronavirus (COVID-19): <a href="https://www.gov.uk/government/publications/coronavirus-covid-19-apprenticeship-programme-response/coronavirus-covid-19-guidance-for-apprentices-employers-training-providers-end-point-assessment-organisations-and-external-quality-assurance-pro" target="_blank">read our guidance</a> on the changes we're making to apprenticeships and <a href="https://help.apprenticeships.education.gov.uk/hc/en-gb/articles/360009509360-Pause-or-stop-an-apprenticeship" target="_blank">find out how you can pause your own apprentices</a>.
</p>
</div>
}
else
{
<div class="info-summary">
<h2 class="heading-small">New employer agreement</h2>
<p>From 14 April 2020, you must accept a new employer agreement to:</p>
<ul class="list list-bullet list-standard-margin">
<li>access apprenticeship funding for new apprentices</li>
<li>approve any changes in your account</li>
</ul>
<p>
Coronavirus (COVID-19): <a href="https://www.gov.uk/government/publications/coronavirus-covid-19-apprenticeship-programme-response/coronavirus-covid-19-guidance-for-apprentices-employers-training-providers-end-point-assessment-organisations-and-external-quality-assurance-pro" target="_blank">read our guidance</a> on the changes we're making to apprenticeships and <a href="https://help.apprenticeships.education.gov.uk/hc/en-gb/articles/360009509360-Pause-or-stop-an-apprenticeship" target="_blank">find out how you can pause your own apprentices</a>.
</p>
</div>
}
|
mit
|
C#
|
67f6d8231b9b36d8c40ece543fc5c94a65fd3af4
|
Fix GetStocks by reading the response in the proper format.
|
leddt/Stockfighter
|
Stockfighter/Venue.cs
|
Stockfighter/Venue.cs
|
using System.Threading.Tasks;
using Stockfighter.Helpers;
namespace Stockfighter
{
public class Venue
{
public string Symbol { get; private set; }
public Venue(string symbol)
{
Symbol = symbol;
}
public async Task<bool> IsUp()
{
using (var client = new Client())
{
try
{
var response = await client.Get<Heartbeat>($"venues/{Symbol}/heartbeat");
return response.ok;
}
catch
{
return false;
}
}
}
public async Task<Stock[]> GetStocks()
{
using (var client = new Client())
{
var response = await client.Get<StocksResponse>($"venues/{Symbol}/stocks");
foreach (var stock in response.symbols)
stock.Venue = Symbol;
return response.symbols;
}
}
private class Heartbeat
{
public bool ok { get; set; }
public string venue { get; set; }
}
private class StocksResponse
{
public bool ok { get; set; }
public Stock[] symbols { get; set; }
}
}
}
|
using System.Threading.Tasks;
using Stockfighter.Helpers;
namespace Stockfighter
{
public class Venue
{
public string Symbol { get; private set; }
public Venue(string symbol)
{
Symbol = symbol;
}
public async Task<bool> IsUp()
{
using (var client = new Client())
{
try
{
var response = await client.Get<Heartbeat>($"venues/{Symbol}/heartbeat");
return response.ok;
}
catch
{
return false;
}
}
}
public async Task<Stock[]> GetStocks()
{
using (var client = new Client())
{
var stocks = await client.Get<Stock[]>($"venues/{Symbol}/stocks");
foreach (var stock in stocks)
stock.Venue = Symbol;
return stocks;
}
}
private class Heartbeat
{
public bool ok { get; set; }
public string venue { get; set; }
}
}
}
|
mit
|
C#
|
8625dc127743c0bbd0b06da956abffffa451e783
|
Fix PrototypeDerived.Has returning void
|
copygirl/EntitySystem
|
src/EntitySystem/Components/PrototypeDerived.cs
|
src/EntitySystem/Components/PrototypeDerived.cs
|
using System.Collections;
using System.Collections.Generic;
namespace EntitySystem.Components
{
public class PrototypeDerived : IComponent, IEnumerable<Entity>
{
readonly HashSet<Entity> _derivatives = new HashSet<Entity>();
public bool Has(Entity entity) => _derivatives.Contains(entity);
public void Add(Entity entity) => _derivatives.Add(entity);
public void Remove(Entity entity) => _derivatives.Remove(entity);
public void Clear() => _derivatives.Clear();
public IEnumerator<Entity> GetEnumerator() => _derivatives.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => _derivatives.GetEnumerator();
}
}
|
using System.Collections;
using System.Collections.Generic;
namespace EntitySystem.Components
{
public class PrototypeDerived : IComponent, IEnumerable<Entity>
{
readonly HashSet<Entity> _derivatives = new HashSet<Entity>();
public void Has(Entity entity) => _derivatives.Contains(entity);
public void Add(Entity entity) => _derivatives.Add(entity);
public void Remove(Entity entity) => _derivatives.Remove(entity);
public void Clear() => _derivatives.Clear();
public IEnumerator<Entity> GetEnumerator() => _derivatives.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => _derivatives.GetEnumerator();
}
}
|
mit
|
C#
|
6586c921f0ca944865f0fe74976a72ac9fa56158
|
Fix compiler error introduced by merge conflict
|
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
|
build/tasks/ProjectModel/ProjectInfo.cs
|
build/tasks/ProjectModel/ProjectInfo.cs
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
namespace RepoTasks.ProjectModel
{
internal class ProjectInfo
{
public ProjectInfo(string fullPath,
IReadOnlyList<ProjectFrameworkInfo> frameworks,
IReadOnlyList<DotNetCliReferenceInfo> tools,
bool isPackable,
string packageId,
string packageVersion)
{
if (!Path.IsPathRooted(fullPath))
{
throw new ArgumentException("Path must be absolute", nameof(fullPath));
}
Frameworks = frameworks ?? throw new ArgumentNullException(nameof(frameworks));
Tools = tools ?? throw new ArgumentNullException(nameof(tools));
FullPath = fullPath;
FileName = Path.GetFileName(fullPath);
Directory = Path.GetDirectoryName(FullPath);
IsPackable = isPackable;
PackageId = packageId;
PackageVersion = packageVersion;
}
public string FullPath { get; }
public string FileName { get; }
public string Directory { get; }
public string PackageId { get; }
public string PackageVersion { get; }
public bool IsPackable { get; }
public SolutionInfo SolutionInfo { get; set; }
public IReadOnlyList<ProjectFrameworkInfo> Frameworks { get; }
public IReadOnlyList<DotNetCliReferenceInfo> Tools { get; }
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
namespace RepoTasks.ProjectModel
{
internal class ProjectInfo
{
public ProjectInfo(string fullPath,
IReadOnlyList<ProjectFrameworkInfo> frameworks,
IReadOnlyList<DotNetCliReferenceInfo> tools,
bool isPackable,
string packageId,
string packageVersion)
{
if (!Path.IsPathRooted(fullPath))
{
throw new ArgumentException("Path must be absolute", nameof(fullPath));
}
Frameworks = frameworks ?? throw new ArgumentNullException(nameof(frameworks));
Tools = tools ?? throw new ArgumentNullException(nameof(tools));
FullPath = fullPath;
FileName = Path.GetFileName(fullPath);
Directory = Path.GetDirectoryName(FullPath);
IsPackable = isPackable;
PackageId = packageId;
PackageVersion = packageVersion;
}
public string FullPath { get; }
public string FileName { get; }
public string Directory { get; }
public string PackageId { get; }
public string PackageVersion { get; }
public bool IsPackable { get; }
public SolutionInfo SolutionInfo { get; set; }
public IReadOnlyList<ProjectFrameworkInfo> Frameworks { get; }
public IReadOnlyList<DotNetCliReferenceInfo> Tools { get; }
public SolutionInfo SolutionInfo { get; internal set; }
}
}
|
apache-2.0
|
C#
|
eb31c8a785d5522519d9bbf5d8043bcf6469a24d
|
Fix issue with tests where settings were not being injected into test class and causing a null error at runtime. Now uses parent settings class. Also changed one expected test return type to reflect change in Google data.
|
chadly/Geocoding.net
|
test/Geocoding.Tests/GoogleAsyncGeocoderTest.cs
|
test/Geocoding.Tests/GoogleAsyncGeocoderTest.cs
|
using System;
using System.Linq;
using System.Threading.Tasks;
using Geocoding.Google;
using Xunit;
namespace Geocoding.Tests
{
[Collection("Settings")]
public class GoogleAsyncGeocoderTest : AsyncGeocoderTest
{
GoogleGeocoder geoCoder;
protected override IGeocoder CreateAsyncGeocoder()
{
string apiKey = settings.GoogleApiKey;
if (String.IsNullOrEmpty(apiKey))
{
geoCoder = new GoogleGeocoder();
}
else
{
geoCoder = new GoogleGeocoder(apiKey);
}
return geoCoder;
}
[Theory]
[InlineData("United States", GoogleAddressType.Country)]
[InlineData("Illinois, US", GoogleAddressType.AdministrativeAreaLevel1)]
[InlineData("New York, New York", GoogleAddressType.Locality)]
[InlineData("90210, US", GoogleAddressType.PostalCode)]
[InlineData("1600 pennsylvania ave washington dc", GoogleAddressType.Establishment)]
public async Task CanParseAddressTypes(string address, GoogleAddressType type)
{
var result = await geoCoder.GeocodeAsync(address);
GoogleAddress[] addresses = result.ToArray();
Assert.Equal(type, addresses[0].Type);
}
}
}
|
using System;
using System.Linq;
using System.Threading.Tasks;
using Geocoding.Google;
using Xunit;
namespace Geocoding.Tests
{
[Collection("Settings")]
public class GoogleAsyncGeocoderTest : AsyncGeocoderTest
{
readonly SettingsFixture settings;
GoogleGeocoder geoCoder;
public GoogleAsyncGeocoderTest(SettingsFixture settings)
{
this.settings = settings;
}
protected override IGeocoder CreateAsyncGeocoder()
{
string apiKey = settings.GoogleApiKey;
if (String.IsNullOrEmpty(apiKey))
{
geoCoder = new GoogleGeocoder();
}
else
{
geoCoder = new GoogleGeocoder(apiKey);
}
return geoCoder;
}
[Theory]
[InlineData("United States", GoogleAddressType.Country)]
[InlineData("Illinois, US", GoogleAddressType.AdministrativeAreaLevel1)]
[InlineData("New York, New York", GoogleAddressType.Locality)]
[InlineData("90210, US", GoogleAddressType.PostalCode)]
[InlineData("1600 pennsylvania ave washington dc", GoogleAddressType.StreetAddress)]
public async Task CanParseAddressTypes(string address, GoogleAddressType type)
{
var result = await geoCoder.GeocodeAsync(address);
GoogleAddress[] addresses = result.ToArray();
Assert.Equal(type, addresses[0].Type);
}
}
}
|
mit
|
C#
|
78598bed11e5dbadbf08d358a3d0945530fd8b66
|
Use FormatMessageHandler instead of eagerly formatting.
|
Stift/NuGet.Lucene,googol/NuGet.Lucene,themotleyfool/NuGet.Lucene
|
source/NuGet.Lucene.Web/UnhandledExceptionLogger.cs
|
source/NuGet.Lucene.Web/UnhandledExceptionLogger.cs
|
using System;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using Common.Logging;
namespace NuGet.Lucene.Web
{
public static class UnhandledExceptionLogger
{
internal static readonly ILog Log = LogManager.GetLogger(typeof(UnhandledExceptionLogger));
public static void LogException(Exception exception)
{
LogException(exception, m => m("Unhandled exception: {0}: {1}", exception.GetType(), exception.Message));
}
public static void LogException(Exception exception, Action<FormatMessageHandler> formatMessageCallback)
{
var log = GetLogSeverityDelegate(exception);
log(formatMessageCallback, exception.StackTrace != null ? exception : null);
}
private static Action<Action<FormatMessageHandler>, Exception> GetLogSeverityDelegate(Exception exception)
{
if (exception is HttpRequestValidationException || exception is ViewStateException)
{
return Log.Warn;
}
if (exception is TaskCanceledException || exception is OperationCanceledException)
{
return Log.Info;
}
var httpError = exception as HttpException;
if (httpError != null && (httpError.ErrorCode == unchecked((int)0x80070057) || httpError.ErrorCode == unchecked((int)0x800704CD)))
{
// "The remote host closed the connection."
return Log.Debug;
}
if (httpError != null && (httpError.GetHttpCode() < 500))
{
return Log.Info;
}
return Log.Error;
}
}
}
|
using System;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using Common.Logging;
namespace NuGet.Lucene.Web
{
public static class UnhandledExceptionLogger
{
internal static readonly ILog Log = LogManager.GetLogger(typeof(UnhandledExceptionLogger));
public static void LogException(Exception exception)
{
LogException(exception, string.Format("Unhandled exception: {0}: {1}", exception.GetType(), exception.Message));
}
public static void LogException(Exception exception, string message)
{
var log = GetLogSeverityDelegate(exception);
log(m => m(message), exception.StackTrace != null ? exception : null);
}
private static Action<Action<FormatMessageHandler>, Exception> GetLogSeverityDelegate(Exception exception)
{
if (exception is HttpRequestValidationException || exception is ViewStateException)
{
return Log.Warn;
}
if (exception is TaskCanceledException || exception is OperationCanceledException)
{
return Log.Info;
}
var httpError = exception as HttpException;
if (httpError != null && (httpError.ErrorCode == unchecked((int)0x80070057) || httpError.ErrorCode == unchecked((int)0x800704CD)))
{
// "The remote host closed the connection."
return Log.Debug;
}
if (httpError != null && (httpError.GetHttpCode() < 500))
{
return Log.Info;
}
return Log.Error;
}
}
}
|
apache-2.0
|
C#
|
276943f4ab9d5b62cab3f81f6bdac5513f30a288
|
Update message converter to access context
|
zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype
|
src/Glimpse.Common/Broker/DefaultMessageConverter.cs
|
src/Glimpse.Common/Broker/DefaultMessageConverter.cs
|
using Newtonsoft.Json;
using System;
using System.Globalization;
using System.IO;
using System.Text;
namespace Glimpse
{
public class DefaultMessageConverter : IMessageConverter
{
private readonly JsonSerializer _jsonSerializer;
private readonly IServiceProvider _serviceProvider;
public DefaultMessageConverter(JsonSerializer jsonSerializer, IServiceProvider serviceProvider)
{
_jsonSerializer = jsonSerializer;
_serviceProvider = serviceProvider;
}
public IMessageEnvelope ConvertMessage(IMessage message)
{
//var context = (MessageContext)_serviceProvider.GetService(typeof(MessageContext));
var newMessage = new MessageEnvelope();
newMessage.Type = message.GetType().FullName;
newMessage.Payload = Serialize(message);
//newMessage.Context = context;
return newMessage;
}
protected string Serialize(object data)
{
// Brought across from - https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/JsonConvert.cs#L635
var stringBuilder = new StringBuilder(256);
using (var stringWriter = new StringWriter(stringBuilder, CultureInfo.InvariantCulture))
using (var jsonWriter = new JsonTextWriter(stringWriter))
{
_jsonSerializer.Serialize(jsonWriter, data, data.GetType());
return stringWriter.ToString();
}
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Globalization;
using System.IO;
using System.Text;
namespace Glimpse
{
public class DefaultMessageConverter : IMessageConverter
{
private readonly JsonSerializer _jsonSerializer;
public DefaultMessageConverter(JsonSerializer jsonSerializer)
{
_jsonSerializer = jsonSerializer;
}
public IMessageEnvelope ConvertMessage(IMessage message)
{
var newMessage = new MessageEnvelope();
newMessage.Type = message.GetType().FullName;
newMessage.Payload = Serialize(message);
return newMessage;
}
protected string Serialize(object data)
{
// Brought across from - https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/JsonConvert.cs#L635
var stringBuilder = new StringBuilder(256);
using (var stringWriter = new StringWriter(stringBuilder, CultureInfo.InvariantCulture))
using (var jsonWriter = new JsonTextWriter(stringWriter))
{
_jsonSerializer.Serialize(jsonWriter, data, data.GetType());
return stringWriter.ToString();
}
}
}
}
|
mit
|
C#
|
bba9d2e51a7ef5e29dc04f75b1b3faf9a696fc41
|
Fix failing unittest
|
ikkentim/SampSharp,ikkentim/SampSharp,ikkentim/SampSharp
|
src/SampSharp.Core.UnitTests/Hosting/InteropTests.cs
|
src/SampSharp.Core.UnitTests/Hosting/InteropTests.cs
|
// SampSharp
// Copyright 2022 Tim Potze
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Runtime.InteropServices;
using System.Text;
using Moq;
using SampSharp.Core.Hosting;
using SampSharp.Core.UnitTests.TestHelpers;
using Shouldly;
using Xunit;
namespace SampSharp.Core.UnitTests.Hosting;
public unsafe class InteropTests
{
private static string? _printfFormat;
private static string? _printfMessage;
[UnmanagedCallersOnly]
static void PrintfUnmanaged(byte* format, byte* message)
{
_printfFormat = new string((sbyte*)format);
_printfMessage = new string((sbyte*)message);
}
[Theory]
[InlineData("test message")]
[InlineData("")]
[InlineData(" %s %d test ")]
public void Print_should_invoke_correct_api(string message)
{
// arrange
_printfFormat = null;
_printfMessage = null;
var pluginData = new InteropStructs.PluginDataRw { Logprintf = &PrintfUnmanaged };
var api = new InteropStructs.SampSharpApiRw
{
Size = (uint)sizeof(InteropStructs.SampSharpApiRw),
PluginData = &pluginData
};
using var gmScope = new GameModeClientScope(Mock.Of<IGameModeClient>(x => x.Encoding == Encoding.ASCII));
using var apiScope = new ApiScope(&api);
// act
Interop.Print(message);
// assert
_printfFormat.ShouldBe("%s");
_printfMessage.ShouldBe(message);
}
}
|
// SampSharp
// Copyright 2022 Tim Potze
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Runtime.InteropServices;
using Moq;
using SampSharp.Core.Hosting;
using SampSharp.Core.UnitTests.TestHelpers;
using Shouldly;
using Xunit;
namespace SampSharp.Core.UnitTests.Hosting;
public unsafe class InteropTests
{
private static string? _printfFormat;
private static string? _printfMessage;
[UnmanagedCallersOnly]
static void PrintfUnmanaged(byte* format, byte* message)
{
_printfFormat = new string((sbyte*)format);
_printfMessage = new string((sbyte*)message);
}
[Theory]
[InlineData("test message")]
[InlineData("")]
[InlineData(" %s %d test ")]
public void Print_should_invoke_correct_api(string message)
{
// arrange
_printfFormat = null;
_printfMessage = null;
var pluginData = new InteropStructs.PluginDataRw { Logprintf = &PrintfUnmanaged };
var api = new InteropStructs.SampSharpApiRw
{
Size = (uint)sizeof(InteropStructs.SampSharpApiRw),
PluginData = &pluginData
};
using var gmScope = new GameModeClientScope(Mock.Of<IGameModeClient>());
using var apiScope = new ApiScope(&api);
// act
Interop.Print(message);
// assert
_printfFormat.ShouldBe("%s");
_printfMessage.ShouldBe(message);
}
}
|
apache-2.0
|
C#
|
269d833e266f3f0633511e39a039daa0a4d6ad10
|
Fix misspelled ConventionTemplateAttribute::otherTemplateName property
|
DejanMilicic/n2cms,SntsDev/n2cms,nicklv/n2cms,VoidPointerAB/n2cms,bussemac/n2cms,bussemac/n2cms,bussemac/n2cms,nicklv/n2cms,nicklv/n2cms,SntsDev/n2cms,nicklv/n2cms,EzyWebwerkstaden/n2cms,nicklv/n2cms,bussemac/n2cms,DejanMilicic/n2cms,SntsDev/n2cms,VoidPointerAB/n2cms,SntsDev/n2cms,VoidPointerAB/n2cms,nimore/n2cms,nimore/n2cms,n2cms/n2cms,nimore/n2cms,DejanMilicic/n2cms,DejanMilicic/n2cms,n2cms/n2cms,nimore/n2cms,bussemac/n2cms,EzyWebwerkstaden/n2cms,VoidPointerAB/n2cms,EzyWebwerkstaden/n2cms,n2cms/n2cms,EzyWebwerkstaden/n2cms,n2cms/n2cms,EzyWebwerkstaden/n2cms
|
src/Framework/N2/Web/ConventionTemplateAttribute.cs
|
src/Framework/N2/Web/ConventionTemplateAttribute.cs
|
using System;
namespace N2.Web
{
/// <summary>
/// Tells the system to look for the ASPX template associated with the
/// attribute content item in the default location. This is typically
/// "~/UI/Views/" or the location defined by any [ConventionTemplateDirectory]
/// attribute in the same assembly.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class ConventionTemplateAttribute : Attribute, IPathFinder
{
readonly string otherTemplateName;
public ConventionTemplateAttribute()
{
}
/// <summary>
/// Uses the provided template name instead of the class name to
/// find the template's location.
/// </summary>
/// <param name="otherTemplateName">The name used to find the template.</param>
public ConventionTemplateAttribute(string otherTemplateName)
{
this.otherTemplateName = otherTemplateName;
}
#region IPathFinder Members
public PathData GetPath(ContentItem item, string remainingUrl)
{
if(string.IsNullOrEmpty(remainingUrl))
{
Type itemType = item.GetContentType();
string virtualDirectory = ConventionTemplateDirectoryAttribute.GetDirectory(itemType);
string templateName = otherTemplateName ?? itemType.Name;
return new PathData(item, virtualDirectory + templateName + ".aspx");
}
return null;
}
#endregion
}
}
|
using System;
namespace N2.Web
{
/// <summary>
/// Tells the system to look for the ASPX template associated with the
/// attribute content item in the default location. This is typically
/// "~/UI/Views/" or the location defined by any [ConventionTemplateDirectory]
/// attribute in the same assembly.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class ConventionTemplateAttribute : Attribute, IPathFinder
{
readonly string otherTemplateName;
public ConventionTemplateAttribute()
{
}
/// <summary>
/// Uses the provided template name instead of the class name to
/// find the template's location.
/// </summary>
/// <param name="otherTemlpateName">The name used to find the template.</param>
public ConventionTemplateAttribute(string otherTemlpateName)
{
this.otherTemplateName = otherTemlpateName;
}
#region IPathFinder Members
public PathData GetPath(ContentItem item, string remainingUrl)
{
if(string.IsNullOrEmpty(remainingUrl))
{
Type itemType = item.GetContentType();
string virtualDirectory = ConventionTemplateDirectoryAttribute.GetDirectory(itemType);
string templateName = otherTemplateName ?? itemType.Name;
return new PathData(item, virtualDirectory + templateName + ".aspx");
}
return null;
}
#endregion
}
}
|
lgpl-2.1
|
C#
|
b58bb3cbbdc0cce3e2f49d699cf9c2005c21f460
|
add missing model: NuGetPackageSymbols
|
lvermeulen/ProGet.Net
|
src/ProGet.Net/Native/Models/NuGetPackageSymbols.cs
|
src/ProGet.Net/Native/Models/NuGetPackageSymbols.cs
|
// ReSharper disable InconsistentNaming
namespace ProGet.Net.Native.Models
{
public class NuGetPackageSymbols
{
public int Feed_Id { get; set; }
public byte[] Symbol_Id { get; set; }
public string SymbolFileName_Text { get; set; }
public int Symbol_Age { get; set; }
public string Package_Id { get; set; }
public string Package_Version_Text { get; set; }
public string Package_SymbolFilePath_Text { get; set; }
}
}
|
namespace ProGet.Net.Native.Models
{
public class NuGetPackageSymbols
{
}
}
|
mit
|
C#
|
bca8e66494a7f0993f57a77c522180a9e5c5d7f1
|
fix setter and readonly
|
dfch/biz.dfch.CS.System.Utilities
|
src/biz.dfch.CS.System.Utilities/Logging/LogBase.cs
|
src/biz.dfch.CS.System.Utilities/Logging/LogBase.cs
|
/**
* Copyright 2014-2015 d-fens GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
namespace biz.dfch.CS.Utilities.Logging
{
public class LogBase
{
private static log4net.ILog _log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected static log4net.ILog log
{
get
{
return _log;
}
private set
{
_log = value;
}
}
public static void WriteException(string message, Exception ex)
{
if (log.IsErrorEnabled)
{
log.ErrorFormat("{0}@{1}: '{2}'\r\n[{3}]\r\n{4}", ex.GetType().Name, ex.Source, message, ex.Message, ex.StackTrace);
}
}
}
}
|
/**
* Copyright 2014-2015 d-fens GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
namespace biz.dfch.CS.Utilities.Logging
{
public class LogBase
{
private static readonly log4net.ILog _log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected static log4net.ILog log
{
get
{
return _log;
}
private set
{
_log = value;
}
}
public static void WriteException(string message, Exception ex)
{
if (log.IsErrorEnabled)
{
log.ErrorFormat("{0}@{1}: '{2}'\r\n[{3}]\r\n{4}", ex.GetType().Name, ex.Source, message, ex.Message, ex.StackTrace);
}
}
}
}
|
apache-2.0
|
C#
|
da614b9d9680cfda303cb00823a2f994221ec2ef
|
Add missing file header
|
vladikk/NLog,kevindaub/NLog,FeodorFitsner/NLog,pwelter34/NLog,NLog/NLog,rajk987/NLog,kevindaub/NLog,BrandonLegault/NLog,vbfox/NLog,BrandonLegault/NLog,AqlaSolutions/NLog-Unity3D,fringebits/NLog,littlesmilelove/NLog,zbrad/NLog,snakefoot/NLog,campbeb/NLog,AndreGleichner/NLog,RichiCoder1/NLog,Niklas-Peter/NLog,BrandonLegault/NLog,ie-zero/NLog,mikkelxn/NLog,czema/NLog,ie-zero/NLog,tetrodoxin/NLog,BrutalCode/NLog,nazim9214/NLog,MartinTherriault/NLog,littlesmilelove/NLog,rajk987/NLog,czema/NLog,rajeshgande/NLog,ilya-g/NLog,AqlaSolutions/NLog-Unity3D,babymechanic/NLog,tohosnet/NLog,ArsenShnurkov/NLog,breyed/NLog,vladikk/NLog,RRUZ/NLog,thomkinson/NLog,BrandonLegault/NLog,UgurAldanmaz/NLog,thomkinson/NLog,MartinTherriault/NLog,mikkelxn/NLog,MoaidHathot/NLog,RRUZ/NLog,fringebits/NLog,czema/NLog,AqlaSolutions/NLog-Unity3D,hubo0831/NLog,vbfox/NLog,campbeb/NLog,michaeljbaird/NLog,AqlaSolutions/NLog-Unity3D,MoaidHathot/NLog,babymechanic/NLog,breyed/NLog,tohosnet/NLog,matteobruni/NLog,bjornbouetsmith/NLog,fringebits/NLog,rajk987/NLog,czema/NLog,FeodorFitsner/NLog,hubo0831/NLog,luigiberrettini/NLog,ArsenShnurkov/NLog,bhaeussermann/NLog,zbrad/NLog,mikkelxn/NLog,304NotModified/NLog,michaeljbaird/NLog,thomkinson/NLog,RichiCoder1/NLog,tetrodoxin/NLog,tmusico/NLog,matteobruni/NLog,vladikk/NLog,ilya-g/NLog,AndreGleichner/NLog,ajayanandgit/NLog,rajk987/NLog,UgurAldanmaz/NLog,BrutalCode/NLog,bryjamus/NLog,fringebits/NLog,rajeshgande/NLog,Niklas-Peter/NLog,luigiberrettini/NLog,thomkinson/NLog,ajayanandgit/NLog,nazim9214/NLog,mikkelxn/NLog,bryjamus/NLog,bhaeussermann/NLog,pwelter34/NLog,bjornbouetsmith/NLog,tmusico/NLog,vladikk/NLog,sean-gilliam/NLog
|
tests/NLog.UnitTests/Targets/EventLogTargetTests.cs
|
tests/NLog.UnitTests/Targets/EventLogTargetTests.cs
|
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !SILVERLIGHT && !MONO
namespace NLog.UnitTests.Targets
{
using System.Diagnostics;
using NLog.Config;
using NLog.Targets;
using System;
using System.Linq;
using Xunit;
public class EventLogTargetTests : NLogTestBase
{
[Fact]
public void WriteEventLogEntry()
{
var target = new EventLogTarget();
//The Log to write to is intentionally lower case!!
target.Log = "application";
SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
var logger = LogManager.GetLogger("WriteEventLogEntry");
var el = new EventLog(target.Log);
var latestEntryTime = el.Entries.Cast<EventLogEntry>().Max(n => n.TimeWritten);
var testValue = Guid.NewGuid();
logger.Debug(testValue.ToString());
var entryExists = (from entry in el.Entries.Cast<EventLogEntry>()
where entry.TimeWritten >= latestEntryTime
&& entry.Message.Contains(testValue.ToString())
select entry).Any();
Assert.True(entryExists);
}
}
}
#endif
|
#if !SILVERLIGHT && !MONO
namespace NLog.UnitTests.Targets
{
using System.Diagnostics;
using NLog.Config;
using NLog.Targets;
using System;
using System.Linq;
using Xunit;
public class EventLogTargetTests : NLogTestBase
{
[Fact]
public void WriteEventLogEntry()
{
var target = new EventLogTarget();
//The Log to write to is intentionally lower case!!
target.Log = "application";
SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
var logger = LogManager.GetLogger("WriteEventLogEntry");
var el = new EventLog(target.Log);
var latestEntryTime = el.Entries.Cast<EventLogEntry>().Max(n => n.TimeWritten);
var testValue = Guid.NewGuid();
logger.Debug(testValue.ToString());
var entryExists = (from entry in el.Entries.Cast<EventLogEntry>()
where entry.TimeWritten >= latestEntryTime
&& entry.Message.Contains(testValue.ToString())
select entry).Any();
Assert.True(entryExists);
}
}
}
#endif
|
bsd-3-clause
|
C#
|
d51d61054b0ec2f15ea9d3df8327809f7e94cb9d
|
Update code
|
sakapon/Samples-2017
|
AzureFunctionsSample/GetRandomNumber-Webhook/run.csx
|
AzureFunctionsSample/GetRandomNumber-Webhook/run.csx
|
using System.Net;
static readonly Random random = new Random();
public static async Task<object> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info($"Webhook was triggered!");
var n = random.Next(1, 10000);
return req.CreateResponse(HttpStatusCode.OK, new { n });
}
|
#r "Newtonsoft.Json"
using System;
using System.Net;
using Newtonsoft.Json;
static readonly Random random = new Random();
public static async Task<object> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info($"Webhook was triggered!");
var n = random.Next(1, 10000);
return req.CreateResponse(HttpStatusCode.OK, new {
n
});
}
|
mit
|
C#
|
0ca361a78a3cd5e82427da69729904f76fa341e0
|
Make HttpClientHandler wiping more conservative. Fixes #1484
|
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
|
samples/MonoSanityClient/Examples.cs
|
samples/MonoSanityClient/Examples.cs
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using WebAssembly.JSInterop;
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Net.Http;
namespace MonoSanityClient
{
public static class Examples
{
public static string AddNumbers(int a, int b)
=> (a + b).ToString();
public static string RepeatString(string str, int count)
{
var result = new StringBuilder();
for (var i = 0; i < count; i++)
{
result.Append(str);
}
return result.ToString();
}
public static void TriggerException(string message)
{
throw new InvalidOperationException(message);
}
public static void InvokeWipedMethod()
{
new HttpClientHandler().Dispose();
}
public static string EvaluateJavaScript(string expression)
{
var result = InternalCalls.InvokeJSUnmarshalled<string, string, object, object>(out var exceptionMessage, "evaluateJsExpression", expression, null, null);
if (exceptionMessage != null)
{
return $".NET got exception: {exceptionMessage}";
}
return $".NET received: {(result ?? "(NULL)")}";
}
public static string CallJsNoBoxing(int numberA, int numberB)
{
// For tests that call this method, we'll exercise the 'BlazorInvokeJS' code path
// since that doesn't box the params
var result = InternalCalls.InvokeJSUnmarshalled<int, int, object, int>(out var exceptionMessage, "divideNumbersUnmarshalled", numberA, numberB, null);
if (exceptionMessage != null)
{
return $".NET got exception: {exceptionMessage}";
}
return $".NET received: {result}";
}
public static string GetRuntimeInformation()
=> $"OSDescription: '{RuntimeInformation.OSDescription}';"
+ $" OSArchitecture: '{RuntimeInformation.OSArchitecture}';"
+ $" IsOSPlatform(WEBASSEMBLY): '{RuntimeInformation.IsOSPlatform(OSPlatform.Create("WEBASSEMBLY"))}'";
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using WebAssembly.JSInterop;
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Net.Http;
namespace MonoSanityClient
{
public static class Examples
{
public static string AddNumbers(int a, int b)
=> (a + b).ToString();
public static string RepeatString(string str, int count)
{
var result = new StringBuilder();
for (var i = 0; i < count; i++)
{
result.Append(str);
}
return result.ToString();
}
public static void TriggerException(string message)
{
throw new InvalidOperationException(message);
}
public static void InvokeWipedMethod()
{
new HttpClientHandler();
}
public static string EvaluateJavaScript(string expression)
{
var result = InternalCalls.InvokeJSUnmarshalled<string, string, object, object>(out var exceptionMessage, "evaluateJsExpression", expression, null, null);
if (exceptionMessage != null)
{
return $".NET got exception: {exceptionMessage}";
}
return $".NET received: {(result ?? "(NULL)")}";
}
public static string CallJsNoBoxing(int numberA, int numberB)
{
// For tests that call this method, we'll exercise the 'BlazorInvokeJS' code path
// since that doesn't box the params
var result = InternalCalls.InvokeJSUnmarshalled<int, int, object, int>(out var exceptionMessage, "divideNumbersUnmarshalled", numberA, numberB, null);
if (exceptionMessage != null)
{
return $".NET got exception: {exceptionMessage}";
}
return $".NET received: {result}";
}
public static string GetRuntimeInformation()
=> $"OSDescription: '{RuntimeInformation.OSDescription}';"
+ $" OSArchitecture: '{RuntimeInformation.OSArchitecture}';"
+ $" IsOSPlatform(WEBASSEMBLY): '{RuntimeInformation.IsOSPlatform(OSPlatform.Create("WEBASSEMBLY"))}'";
}
}
|
apache-2.0
|
C#
|
eb363810abc8e05219d4bf0e315936c4157b8f02
|
Update ComponentManager.Set
|
copygirl/EntitySystem
|
src/EntitySystem/ComponentManager.cs
|
src/EntitySystem/ComponentManager.cs
|
using System;
using System.Collections.Generic;
using System.Reflection;
using EntitySystem.Collections;
using EntitySystem.Storage;
using EntitySystem.Utility;
namespace EntitySystem
{
public class ComponentManager
{
readonly TypedCollection<object> _typeHandlers = new TypedCollection<object>();
readonly GenericComponentMap _defaultMap = new GenericComponentMap();
public EntityManager Entities { get; }
public event Action<Entity, IComponent> Added;
public event Action<Entity, IComponent> Removed;
internal ComponentManager(EntityManager entities)
{
Entities = entities;
Entities.Removed += _defaultMap.RemoveAll; // This might be slow..?
}
public ComponentsOfType<T> OfType<T>() where T : IComponent =>
_typeHandlers.GetOrAdd<ComponentsOfType<T>>(() => {
var type = typeof(T).GetTypeInfo();
if (type.IsInterface || type.IsAbstract)
throw new InvalidOperationException(
$"{ typeof(T) } is not a concrete component type");
return new ComponentsOfType<T>(this);
});
public Option<T> Get<T>(Entity entity) where T : IComponent
{
if (!Entities.Has(entity)) throw new EntityNonExistantException(Entities, entity);
return _defaultMap.Get<T>(entity);
}
public Option<T> Set<T>(Entity entity, Option<T> valueOption) where T : IComponent
{
if (!Entities.Has(entity)) throw new EntityNonExistantException(Entities, entity);
T value;
var hasValue = valueOption.TryGet(out value);
T previous;
var hasPrevious = _defaultMap.Set<T>(entity, valueOption).TryGet(out previous);
if (hasValue) {
if (!hasPrevious) {
OfType<T>().RaiseAdded(entity, value);
Added?.Invoke(entity, value);
}
} else if (hasPrevious) {
OfType<T>().RaiseRemoved(entity, previous);
Removed?.Invoke(entity, previous);
}
return previous;
}
public IEnumerable<IComponent> GetAll(Entity entity)
{
if (!Entities.Has(entity)) throw new EntityNonExistantException(Entities, entity);
return _defaultMap.GetAll(entity);
}
public class ComponentsOfType<T> where T : IComponent
{
readonly ComponentManager _manager;
public event Action<Entity, T> Added;
public event Action<Entity, T> Removed;
// Add Changed event? It's possible. Unsure if needed.
// Depends on how large the overhead for it would be.
// Can be overridden by using a custom storage handler in the future.
public IEnumerable<Tuple<Entity, T>> Entries =>
_manager._defaultMap.Entries<T>();
internal ComponentsOfType(ComponentManager manager) { _manager = manager; }
internal void RaiseAdded(Entity entity, T component) => Added?.Invoke(entity, component);
internal void RaiseRemoved(Entity entity, T component) => Removed?.Invoke(entity, component);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Reflection;
using EntitySystem.Collections;
using EntitySystem.Storage;
using EntitySystem.Utility;
namespace EntitySystem
{
public class ComponentManager
{
readonly TypedCollection<object> _typeHandlers = new TypedCollection<object>();
readonly GenericComponentMap _defaultMap = new GenericComponentMap();
public EntityManager Entities { get; }
public event Action<Entity, IComponent> Added;
public event Action<Entity, IComponent> Removed;
internal ComponentManager(EntityManager entities)
{
Entities = entities;
Entities.Removed += _defaultMap.RemoveAll; // This might be slow..?
}
public ComponentsOfType<T> OfType<T>() where T : IComponent =>
_typeHandlers.GetOrAdd<ComponentsOfType<T>>(() => {
var type = typeof(T).GetTypeInfo();
if (type.IsInterface || type.IsAbstract)
throw new InvalidOperationException(
$"{ typeof(T) } is not a concrete component type");
return new ComponentsOfType<T>(this);
});
public Option<T> Get<T>(Entity entity) where T : IComponent
{
if (!Entities.Has(entity)) throw new EntityNonExistantException(Entities, entity);
return _defaultMap.Get<T>(entity);
}
public Option<T> Set<T>(Entity entity, Option<T> value) where T : IComponent
{
if (!Entities.Has(entity)) throw new EntityNonExistantException(Entities, entity);
var previous = _defaultMap.Set<T>(entity, value);
if (value.HasValue) {
if (!previous.HasValue) {
OfType<T>().RaiseAdded(entity, value.Value);
Added?.Invoke(entity, value.Value);
}
} else if (previous.HasValue) {
OfType<T>().RaiseRemoved(entity, previous.Value);
Removed?.Invoke(entity, previous.Value);
}
return previous;
}
public IEnumerable<IComponent> GetAll(Entity entity)
{
if (!Entities.Has(entity)) throw new EntityNonExistantException(Entities, entity);
return _defaultMap.GetAll(entity);
}
public class ComponentsOfType<T> where T : IComponent
{
readonly ComponentManager _manager;
public event Action<Entity, T> Added;
public event Action<Entity, T> Removed;
// Add Changed event? It's possible. Unsure if needed.
// Depends on how large the overhead for it would be.
// Can be overridden by using a custom storage handler in the future.
public IEnumerable<Tuple<Entity, T>> Entries =>
_manager._defaultMap.Entries<T>();
internal ComponentsOfType(ComponentManager manager) { _manager = manager; }
internal void RaiseAdded(Entity entity, T component) => Added?.Invoke(entity, component);
internal void RaiseRemoved(Entity entity, T component) => Removed?.Invoke(entity, component);
}
}
}
|
mit
|
C#
|
f2ca52fe975e5906070411feb33317db536116f0
|
Clean up IRequestBroker
|
murador/xsp,stormleoxia/xsp,arthot/xsp,murador/xsp,murador/xsp,stormleoxia/xsp,arthot/xsp,stormleoxia/xsp,murador/xsp,stormleoxia/xsp,arthot/xsp,arthot/xsp
|
src/Mono.WebServer/IRequestBroker.cs
|
src/Mono.WebServer/IRequestBroker.cs
|
//
// Mono.WebServer.IRequestBroker
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// Documentation:
// Brian Nickel
//
// (C) 2003 Ximian, Inc (http://www.ximian.com)
// (C) Copyright 2004-2010 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.
//
namespace Mono.WebServer
{
public interface IRequestBroker
{
}
}
|
//
// Mono.WebServer.IRequestBroker
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// Documentation:
// Brian Nickel
//
// (C) 2003 Ximian, Inc (http://www.ximian.com)
// (C) Copyright 2004-2010 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;
namespace Mono.WebServer
{
public interface IRequestBroker
{
}
}
|
mit
|
C#
|
0d500de983a5b506be0df2203cca5ac6b1575d89
|
Fix issue #2 (build error in sample project)
|
weltkante/managed-lzma,weltkante/managed-lzma,weltkante/managed-lzma
|
sandbox-7z/Program.cs
|
sandbox-7z/Program.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using ManagedLzma.LZMA.Master.SevenZip;
namespace sandbox_7z
{
static class Program
{
class Password: master._7zip.Legacy.IPasswordProvider
{
string _pw;
public Password(string pw)
{
_pw = pw;
}
string master._7zip.Legacy.IPasswordProvider.CryptoGetTextPassword()
{
return _pw;
}
}
[STAThread]
static void Main()
{
Directory.CreateDirectory("_test");
using(var stream = new FileStream(@"_test\test.7z", FileMode.Create, FileAccess.ReadWrite, FileShare.Delete))
{
var writer = new ArchiveWriter(stream);
writer.ConnectEncoder(new ArchiveWriter.Lzma2Encoder(null));
string path = Path.GetDirectoryName(typeof(Program).Assembly.Location);
var directory = new DirectoryInfo(path);
foreach(string filename in Directory.EnumerateFiles(path))
writer.WriteFile(directory, new FileInfo(filename));
writer.WriteFinalHeader();
}
{
var db = new master._7zip.Legacy.CArchiveDatabaseEx();
var x = new master._7zip.Legacy.ArchiveReader();
x.Open(new FileStream(@"_test\test.7z", FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete));
x.ReadDatabase(db, null);
db.Fill();
x.Extract(db, null, null);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using ManagedLzma.LZMA.Master.SevenZip;
namespace sandbox_7z
{
static class Program
{
class Password: master._7zip.Legacy.IPasswordProvider
{
string _pw;
public Password(string pw)
{
_pw = pw;
}
string master._7zip.Legacy.IPasswordProvider.CryptoGetTextPassword()
{
return _pw;
}
}
[STAThread]
static void Main()
{
Directory.CreateDirectory("_test");
using(var stream = new FileStream(@"_test\test.7z", FileMode.Create, FileAccess.ReadWrite, FileShare.Delete))
{
var writer = new ArchiveWriter(stream);
writer.InitializeLzma2Encoder();
string path = Path.GetDirectoryName(typeof(Program).Assembly.Location);
var directory = new DirectoryInfo(path);
foreach(string filename in Directory.EnumerateFiles(path))
writer.WriteFile(directory, new FileInfo(filename));
writer.WriteFinalHeader();
}
{
var db = new master._7zip.Legacy.CArchiveDatabaseEx();
var x = new master._7zip.Legacy.ArchiveReader();
x.Open(new FileStream(@"_test\test.7z", FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete));
x.ReadDatabase(db, null);
db.Fill();
x.Extract(db, null, null);
}
}
}
}
|
mit
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.