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 |
---|---|---|---|---|---|---|---|---|
771c7ce73d9a805a9d2105c665147a768c38b726
|
Use DownloadFlakyString with Coinbase
|
IWBWbiz/MultiMiner,nwoolls/MultiMiner,nwoolls/MultiMiner,IWBWbiz/MultiMiner
|
MultiMiner.Coinbase/ApiContext.cs
|
MultiMiner.Coinbase/ApiContext.cs
|
using MultiMiner.ExchangeApi;
using MultiMiner.ExchangeApi.Data;
using MultiMiner.Utility.Net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace MultiMiner.Coinbase
{
public class ApiContext : IApiContext
{
public IEnumerable<ExchangeInformation> GetExchangeInformation()
{
ApiWebClient webClient = new ApiWebClient();
string response = webClient.DownloadFlakyString(new Uri(GetApiUrl()));
Data.SellPrices sellPrices = JsonConvert.DeserializeObject<Data.SellPrices>(response);
List<ExchangeInformation> results = new List<ExchangeInformation>();
results.Add(new ExchangeInformation()
{
SourceCurrency = "BTC",
TargetCurrency = "USD",
TargetSymbol = "$",
ExchangeRate = sellPrices.Subtotal.Amount
});
return results;
}
public string GetInfoUrl()
{
return "https://coinbase.com";
}
public string GetApiUrl()
{
return "https://coinbase.com/api/v1/prices/sell";
}
public string GetApiName()
{
return "Coinbase";
}
}
}
|
using MultiMiner.ExchangeApi;
using MultiMiner.ExchangeApi.Data;
using MultiMiner.Utility.Net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
namespace MultiMiner.Coinbase
{
public class ApiContext : IApiContext
{
public IEnumerable<ExchangeInformation> GetExchangeInformation()
{
WebClient webClient = new ApiWebClient();
string response = webClient.DownloadString(new Uri(GetApiUrl()));
Data.SellPrices sellPrices = JsonConvert.DeserializeObject<Data.SellPrices>(response);
List<ExchangeInformation> results = new List<ExchangeInformation>();
results.Add(new ExchangeInformation()
{
SourceCurrency = "BTC",
TargetCurrency = "USD",
TargetSymbol = "$",
ExchangeRate = sellPrices.Subtotal.Amount
});
return results;
}
public string GetInfoUrl()
{
return "https://coinbase.com";
}
public string GetApiUrl()
{
return "https://coinbase.com/api/v1/prices/sell";
}
public string GetApiName()
{
return "Coinbase";
}
}
}
|
mit
|
C#
|
f644376d528a95164ece3debe949e66e261b02cf
|
Remove suppress attribute
|
mminns/octokit.net,cH40z-Lord/octokit.net,Sarmad93/octokit.net,devkhan/octokit.net,ivandrofly/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,rlugojr/octokit.net,SmithAndr/octokit.net,khellang/octokit.net,gdziadkiewicz/octokit.net,octokit-net-test-org/octokit.net,SLdragon1989/octokit.net,naveensrinivasan/octokit.net,shana/octokit.net,takumikub/octokit.net,hahmed/octokit.net,geek0r/octokit.net,alfhenrik/octokit.net,ivandrofly/octokit.net,octokit-net-test/octokit.net,shiftkey/octokit.net,shiftkey-tester/octokit.net,forki/octokit.net,gabrielweyer/octokit.net,magoswiat/octokit.net,kolbasov/octokit.net,michaKFromParis/octokit.net,hahmed/octokit.net,dampir/octokit.net,octokit-net-test-org/octokit.net,gabrielweyer/octokit.net,ChrisMissal/octokit.net,editor-tools/octokit.net,chunkychode/octokit.net,dampir/octokit.net,dlsteuer/octokit.net,chunkychode/octokit.net,mminns/octokit.net,Sarmad93/octokit.net,gdziadkiewicz/octokit.net,fake-organization/octokit.net,eriawan/octokit.net,rlugojr/octokit.net,khellang/octokit.net,adamralph/octokit.net,SamTheDev/octokit.net,shiftkey-tester/octokit.net,shana/octokit.net,devkhan/octokit.net,kdolan/octokit.net,M-Zuber/octokit.net,TattsGroup/octokit.net,brramos/octokit.net,editor-tools/octokit.net,SamTheDev/octokit.net,Red-Folder/octokit.net,nsnnnnrn/octokit.net,thedillonb/octokit.net,thedillonb/octokit.net,fffej/octokit.net,darrelmiller/octokit.net,alfhenrik/octokit.net,daukantas/octokit.net,TattsGroup/octokit.net,hitesh97/octokit.net,eriawan/octokit.net,bslliw/octokit.net,octokit/octokit.net,M-Zuber/octokit.net,SmithAndr/octokit.net,shiftkey/octokit.net,octokit/octokit.net,nsrnnnnn/octokit.net,shiftkey-tester-org-blah-blah/octokit.net
|
Octokit/Models/Request/NewGist.cs
|
Octokit/Models/Request/NewGist.cs
|
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Octokit
{
public class NewGist
{
public NewGist()
{
Files = new Dictionary<string, string>();
}
/// <summary>
/// The description of the gist.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Indicates whether the gist is public
/// </summary>
public bool Public { get; set; }
/// <summary>
/// Files that make up this gist using the key as Filename
/// and value as Content
/// </summary>
public IDictionary<string, string> Files { get; private set; }
}
}
|
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Octokit
{
public class NewGist
{
public NewGist()
{
Files = new Dictionary<string, string>();
}
/// <summary>
/// The description of the gist.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Indicates whether the gist is public
/// </summary>
public bool Public { get; set; }
/// <summary>
/// Files that make up this gist using the key as Filename
/// and value as Content
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public IDictionary<string, string> Files { get; set; }
}
}
|
mit
|
C#
|
efd4ca654a0d9b2d43e81561ab3e19f5af45224f
|
Debug output adding
|
adamjez/CVaS,adamjez/CVaS,adamjez/CVaS
|
src/CVaS.Web/Controllers/AlgoController.cs
|
src/CVaS.Web/Controllers/AlgoController.cs
|
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CVaS.BL.Repositories;
using CVaS.BL.Services.Process;
using CVaS.DAL.Model;
using CVaS.Web.Models;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
namespace CVaS.Web.Controllers
{
[Route("[controller]")]
public class AlgoController : ApiController
{
private readonly ILogger<AlgoController> logger;
private readonly AlgorithmRepository repository;
private readonly IFileProvider fileProvider;
private readonly IProcessService processService;
public AlgoController(ILogger<AlgoController> logger, AlgorithmRepository repository, IFileProvider fileProvider, IProcessService processService)
{
this.logger = logger;
this.repository = repository;
this.fileProvider = fileProvider;
this.processService = processService;
}
[HttpPost("{codeName}")]
public async Task<IActionResult> Process(string codeName, [FromBody] AlgorithmOptions options)
{
var algorithm = await repository.GetByCodeName(codeName);
if (algorithm == null)
{
return NotFound("Given algorithm codeName doesn't exists");
}
var algoDir = fileProvider.GetDirectoryContents("Algorithms" + Path.PathSeparator + codeName);
if (algoDir == null)
{
return NotFound("Given algorithm execution file doesn't exists (1)");
}
var file = algoDir.FirstOrDefault(f => f.Name == algorithm.FilePath);
if (file == null)
{
return NotFound($"Given algorithm execution file doesn't exists ({algorithm.FilePath})");
}
var result = processService.Run(file.PhysicalPath, options.Arguments);
return Ok(new AlgorithmResult
{
Title = algorithm.Title,
Arguments = options.Arguments,
Result = result
});
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CVaS.BL.Repositories;
using CVaS.BL.Services.Process;
using CVaS.DAL.Model;
using CVaS.Web.Models;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
namespace CVaS.Web.Controllers
{
[Route("[controller]")]
public class AlgoController : ApiController
{
private readonly ILogger<AlgoController> logger;
private readonly AlgorithmRepository repository;
private readonly IFileProvider fileProvider;
private readonly IProcessService processService;
public AlgoController(ILogger<AlgoController> logger, AlgorithmRepository repository, IFileProvider fileProvider, IProcessService processService)
{
this.logger = logger;
this.repository = repository;
this.fileProvider = fileProvider;
this.processService = processService;
}
[HttpPost("{codeName}")]
public async Task<IActionResult> Process(string codeName, [FromBody] AlgorithmOptions options)
{
var algorithm = await repository.GetByCodeName(codeName);
if (algorithm == null)
{
return NotFound("Given algorithm codeName doesn't exists");
}
var algoDir = fileProvider.GetDirectoryContents("Algorithms" + Path.PathSeparator + codeName);
if (algoDir == null)
{
return NotFound("Given algorithm execution file doesn't exists (1)");
}
var file = algoDir.FirstOrDefault(f => f.Name == algorithm.FilePath);
if (file == null)
{
return NotFound("Given algorithm execution file doesn't exists (2)");
}
var result = processService.Run(file.PhysicalPath, options.Arguments);
return Ok(new AlgorithmResult
{
Title = algorithm.Title,
Arguments = options.Arguments,
Result = result
});
}
}
}
|
mit
|
C#
|
f95e023e0d8a44255ea4650fb0ddc606ec1129f5
|
Undo Windows Changed UI thread dispatcher #166
|
AndreiMisiukevich/FFImageLoading,molinch/FFImageLoading,daniel-luberda/FFImageLoading,luberda-molinet/FFImageLoading
|
source/FFImageLoading.Windows/Helpers/MainThreadDispatcher.cs
|
source/FFImageLoading.Windows/Helpers/MainThreadDispatcher.cs
|
using System;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.UI.Core;
namespace FFImageLoading.Helpers
{
public class MainThreadDispatcher : IMainThreadDispatcher
{
static MainThreadDispatcher instance;
public static MainThreadDispatcher Instance
{
get
{
if (instance == null)
instance = new MainThreadDispatcher();
return instance;
}
}
public async void Post(Action action)
{
if (action == null)
return;
// already in UI thread:
if (CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess)
{
action();
}
// not in UI thread, ensuring UI thread:
else
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => action());
//await CoreApplication.GetCurrentView().Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => action());
}
}
public Task PostAsync(Action action)
{
var tcs = new TaskCompletionSource<object>();
Post(() => {
try
{
action();
tcs.SetResult(string.Empty);
}
catch (Exception ex)
{
tcs.SetException(ex);
}
});
return tcs.Task;
}
}
}
|
using System;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.UI.Core;
namespace FFImageLoading.Helpers
{
public class MainThreadDispatcher : IMainThreadDispatcher
{
static MainThreadDispatcher instance;
public static MainThreadDispatcher Instance
{
get
{
if (instance == null)
instance = new MainThreadDispatcher();
return instance;
}
}
public async void Post(Action action)
{
if (action == null)
return;
// already in UI thread:
if (CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess)
{
action();
}
// not in UI thread, ensuring UI thread:
else
{
await CoreApplication.GetCurrentView().Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => action());
}
}
public Task PostAsync(Action action)
{
var tcs = new TaskCompletionSource<object>();
Post(() => {
try
{
action();
tcs.SetResult(string.Empty);
}
catch (Exception ex)
{
tcs.SetException(ex);
}
});
return tcs.Task;
}
}
}
|
mit
|
C#
|
3a161df910cfa7410dc19edd13e2daf09363277a
|
Fix test naming convention for NoError
|
LeandroMBarreto/MlIB.Reply,LeandroMBarreto/lib-Reply
|
source/MlIB.Reply.Tests.Unit/Features/static_Reply_NoError.cs
|
source/MlIB.Reply.Tests.Unit/Features/static_Reply_NoError.cs
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MlIB.Reply.Tests.Unit.Features
{
[TestClass]
public class static_Reply_NoError
{
// UNIT UNDER TEST:
//public static Reply<T> NoError<T>(T value)
//I:value nullString
//O:has no error
//O:nullString as value
[TestMethod]
public void static_Reply_NoError_value_nullString()
{
var result = M.Reply.NoError<string>(null);
Assert.IsFalse(result.HasError, "WHY HAS ERROR??");
Assert.AreEqual(null, result.Value, "WHY NOT EXPECTED VALUE??");
}
//I:value emptyString
//O:has no error
//O:emptyString as value
[TestMethod]
public void static_Reply_NoError_value_emptyString()
{
var result = M.Reply.NoError(string.Empty);
Assert.IsFalse(result.HasError, "WHY HAS ERROR??");
Assert.AreEqual(string.Empty, result.Value, "WHY NOT EXPECTED VALUE??");
}
//I:value ok
//O:has no error
//O:expected value is set
[TestMethod]
public void static_Reply_NoError_value_ok()
{
var value = "ANY VALUE";
var result = M.Reply.NoError(value);
Assert.IsFalse(result.HasError, "WHY HAS ERROR??");
Assert.AreEqual(value, result.Value, "WHY NOT EXPECTED VALUE??");
}
//I:value exception
//O:has no error
//O:exception as value
[TestMethod]
public void static_Reply_NoError_value_exception()
{
var result = M.Reply.NoError(Stubs.Common.EXCEPTION);
Assert.IsFalse(result.HasError, "WHY HAS ERROR??");
Assert.AreEqual(Stubs.Common.EXCEPTION, result.Value, "WHY NOT EXPECTED VALUE??");
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MlIB.Reply.Tests.Unit.Features
{
[TestClass]
public class static_Reply_NoError
{
// UNIT UNDER TEST:
//public static Reply<T> NoError<T>(T value)
//I:value nullString
//O:has no error
//O:nullString as value
[TestMethod]
public void Reply_NoError_value_nullString()
{
var result = M.Reply.NoError<string>(null);
Assert.IsFalse(result.HasError, "WHY HAS ERROR??");
Assert.AreEqual(null, result.Value, "WHY NOT EXPECTED VALUE??");
}
//I:value emptyString
//O:has no error
//O:emptyString as value
[TestMethod]
public void Reply_NoError_value_emptyString()
{
var result = M.Reply.NoError(string.Empty);
Assert.IsFalse(result.HasError, "WHY HAS ERROR??");
Assert.AreEqual(string.Empty, result.Value, "WHY NOT EXPECTED VALUE??");
}
//I:value ok
//O:has no error
//O:expected value is set
[TestMethod]
public void Reply_NoError_value_ok()
{
var value = "ANY VALUE";
var result = M.Reply.NoError(value);
Assert.IsFalse(result.HasError, "WHY HAS ERROR??");
Assert.AreEqual(value, result.Value, "WHY NOT EXPECTED VALUE??");
}
//I:value exception
//O:has no error
//O:exception as value
[TestMethod]
public void Reply_NoError_value_exception()
{
var result = M.Reply.NoError(Stubs.Common.EXCEPTION);
Assert.IsFalse(result.HasError, "WHY HAS ERROR??");
Assert.AreEqual(Stubs.Common.EXCEPTION, result.Value, "WHY NOT EXPECTED VALUE??");
}
}
}
|
mit
|
C#
|
8888d1f701cc28e37a0d815611cba0cb722b66f4
|
Update for KSP 1.4
|
DMagic1/DMModuleScienceAnimateGeneric
|
Source/Properties/AssemblyInfo.cs
|
Source/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("DMModuleScienceAnimateGeneric")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DMModuleScienceAnimateGeneric")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("148cb195-6345-4253-809b-f3d61338b45b")]
[assembly: AssemblyVersion("0.20.0.0")]
[assembly: AssemblyFileVersion("0.20.0.0")]
[assembly: KSPAssembly("DMModuleScienceAnimateGeneric", 0, 20)]
|
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("DMModuleScienceAnimateGeneric")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DMModuleScienceAnimateGeneric")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("148cb195-6345-4253-809b-f3d61338b45b")]
[assembly: AssemblyVersion("0.19.0.0")]
[assembly: AssemblyFileVersion("0.19.0.0")]
[assembly: KSPAssembly("DMModuleScienceAnimateGeneric", 0, 19)]
|
bsd-2-clause
|
C#
|
026c4601330a594c9c368629254c27e750a5c68a
|
Add formatToSqlParams param to GetOrCreateUserQuery
|
ITCompaniet/ITCO-SBO-Addon-Framework
|
src/ITCO.SboAddon.Framework/Extensions/UserQueryExtensions.cs
|
src/ITCO.SboAddon.Framework/Extensions/UserQueryExtensions.cs
|
using System.Linq;
using System.Text.RegularExpressions;
using ITCO.SboAddon.Framework.Helpers;
using SAPbobsCOM;
namespace ITCO.SboAddon.Framework.Extensions
{
public static class UserQueryExtensions
{
/// <summary>
/// Get or create User Query
/// </summary>
/// <param name="company">Company Object</param>
/// <param name="userQueryName">User Query Name</param>
/// <param name="userQueryDefaultQuery">Query</param>
/// <param name="formatToSqlParams">Replace [%0] to @p0</param>
/// <returns></returns>
public static string GetOrCreateUserQuery(this Company company, string userQueryName, string userQueryDefaultQuery, bool formatToSqlParams = false)
{
var userQuery = userQueryDefaultQuery;
using (var userQueryObject = new SboRecordsetQuery<UserQueries>(
$"SELECT [IntrnalKey] FROM [OUQR] WHERE [QName] = '{userQueryName}'", BoObjectTypes.oUserQueries))
{
if (userQueryObject.Count == 0)
{
userQueryObject.BusinessObject.QueryDescription = userQueryName;
userQueryObject.BusinessObject.Query = userQueryDefaultQuery;
userQueryObject.BusinessObject.QueryCategory = -1;
var response = userQueryObject.BusinessObject.Add();
ErrorHelper.HandleErrorWithException(response, $"Could not create User Query '{userQueryName}'");
}
else
{
userQuery = userQueryObject.Result.First().Query;
}
}
if (formatToSqlParams)
userQuery = Regex.Replace(userQuery, @"\[%([0-9])\]", "@p$1");
return userQuery;
}
}
}
|
using System.Linq;
using ITCO.SboAddon.Framework.Helpers;
using SAPbobsCOM;
namespace ITCO.SboAddon.Framework.Extensions
{
public static class UserQueryExtensions
{
public static string GetOrCreateUserQuery(this Company company, string userQueryName, string userQueryDefaultQuery)
{
using (var userQuery = new SboRecordsetQuery<UserQueries>(
$"SELECT [IntrnalKey] FROM [OUQR] WHERE [QName] = '{userQueryName}'", BoObjectTypes.oUserQueries))
{
if (userQuery.Count == 0)
{
userQuery.BusinessObject.QueryDescription = userQueryName;
userQuery.BusinessObject.Query = userQueryDefaultQuery;
userQuery.BusinessObject.QueryCategory = -1;
var response = userQuery.BusinessObject.Add();
ErrorHelper.HandleErrorWithException(response, $"Could not create User Query '{userQueryName}'");
return userQueryDefaultQuery;
}
return userQuery.Result.First().Query;
}
}
}
}
|
mit
|
C#
|
f07be8a89a055602ab193bb4c77391b9af850b7c
|
Fix Orchestration tests
|
quartz-software/kephas,quartz-software/kephas
|
src/Tests/Kephas.Orchestration.Tests/OrchestrationTestBase.cs
|
src/Tests/Kephas.Orchestration.Tests/OrchestrationTestBase.cs
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="OrchestrationTestBase.cs" company="Kephas Software SRL">
// Copyright (c) Kephas Software SRL. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
// Implements the orchestration test base class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Kephas.Orchestration.Tests
{
using System.Collections.Generic;
using System.Reflection;
using Kephas.Commands;
using Kephas.Messaging;
using Kephas.Testing.Application;
using NUnit.Framework;
[TestFixture]
public class OrchestrationTestBase : ApplicationTestBase
{
public override IEnumerable<Assembly> GetDefaultConventionAssemblies()
{
var assemblies = new List<Assembly>(base.GetDefaultConventionAssemblies())
{
typeof(IMessageProcessor).Assembly,
typeof(IOrchestrationManager).Assembly,
typeof(ICommandProcessor).Assembly,
};
return assemblies;
}
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="OrchestrationTestBase.cs" company="Kephas Software SRL">
// Copyright (c) Kephas Software SRL. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
// Implements the orchestration test base class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Kephas.Orchestration.Tests
{
using System.Collections.Generic;
using System.Reflection;
using Kephas.Messaging;
using Kephas.Testing.Application;
using NUnit.Framework;
[TestFixture]
public class OrchestrationTestBase : ApplicationTestBase
{
public override IEnumerable<Assembly> GetDefaultConventionAssemblies()
{
var assemblies = new List<Assembly>(base.GetDefaultConventionAssemblies())
{
typeof(IMessageProcessor).Assembly,
typeof(IOrchestrationManager).Assembly,
};
return assemblies;
}
}
}
|
mit
|
C#
|
cbe6936e9f207874d269e9023aa14555a4228de3
|
Update version
|
lukakama/rimworld-mod-real-fow
|
Properties/AssemblyInfo.cs
|
Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
// Le informazioni generali relative a un assembly sono controllate dal seguente
// set di attributi. Modificare i valori di questi attributi per modificare le informazioni
// associate a un assembly.
[assembly: AssemblyTitle("RimWorldRealFoWMod")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RimWorldRealFoWMod")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Se si imposta ComVisible su false, i tipi in questo assembly non saranno visibili
// ai componenti COM. Se è necessario accedere a un tipo in questo assembly da
// COM, impostare su true l'attributo ComVisible per tale tipo.
[assembly: ComVisible(false)]
// Se il progetto viene esposto a COM, il GUID seguente verrà utilizzato come ID della libreria dei tipi
[assembly: Guid("9e008b68-2b98-4ac2-9c65-832d13f94746")]
// Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori:
//
// Versione principale
// Versione secondaria
// Numero di build
// Revisione
//
// È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build
// usando l'asterisco '*' come illustrato di seguito:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.24.0")]
[assembly: AssemblyFileVersion("0.1.24.0")]
|
using System.Reflection;
using System.Runtime.InteropServices;
// Le informazioni generali relative a un assembly sono controllate dal seguente
// set di attributi. Modificare i valori di questi attributi per modificare le informazioni
// associate a un assembly.
[assembly: AssemblyTitle("RimWorldRealFoWMod")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RimWorldRealFoWMod")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Se si imposta ComVisible su false, i tipi in questo assembly non saranno visibili
// ai componenti COM. Se è necessario accedere a un tipo in questo assembly da
// COM, impostare su true l'attributo ComVisible per tale tipo.
[assembly: ComVisible(false)]
// Se il progetto viene esposto a COM, il GUID seguente verrà utilizzato come ID della libreria dei tipi
[assembly: Guid("9e008b68-2b98-4ac2-9c65-832d13f94746")]
// Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori:
//
// Versione principale
// Versione secondaria
// Numero di build
// Revisione
//
// È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build
// usando l'asterisco '*' come illustrato di seguito:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.23.0")]
[assembly: AssemblyFileVersion("0.1.23.0")]
|
apache-2.0
|
C#
|
040bac28fec8a2af635a1b3f303072d8f5fd982f
|
Update KSP version to 1.1.2
|
agufranov/ksp-advanced-flybywire,agufranov/ksp-advanced-flybywire
|
Properties/AssemblyInfo.cs
|
Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// 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("KSPAdvancedFlyByWire")]
[assembly: AssemblyDescription("Input mod for Kerbal Space Program")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Alexander \"nlight\" Dzhoganov (alexander.dzhoganov@gmail.com)")]
[assembly: AssemblyProduct("KSPAdvancedFlyByWire")]
[assembly: AssemblyCopyright("Copyright © Alexander Dzhoganov 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("c749b9c9-cbf8-4782-a73c-bd17e631c366")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.2.0")]
[assembly: AssemblyFileVersion("1.1.2.0")]
[assembly: NeutralResourcesLanguageAttribute("")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// 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("KSPAdvancedFlyByWire")]
[assembly: AssemblyDescription("Input mod for Kerbal Space Program")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Alexander \"nlight\" Dzhoganov (alexander.dzhoganov@gmail.com)")]
[assembly: AssemblyProduct("KSPAdvancedFlyByWire")]
[assembly: AssemblyCopyright("Copyright © Alexander Dzhoganov 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("c749b9c9-cbf8-4782-a73c-bd17e631c366")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: NeutralResourcesLanguageAttribute("")]
|
mit
|
C#
|
1e927dc0a7ab022bc6ecbd53134d2b2c738b6ba5
|
update date
|
Microsoft/vscode-mono-debug,Microsoft/vscode-mono-debug
|
Properties/AssemblyInfo.cs
|
Properties/AssemblyInfo.cs
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
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("mono-debug")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Visual Studio Code")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
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("mono-debug")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Visual Studio Code")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
|
mit
|
C#
|
cc0ecae67705ae7a3c80e442426a8e7ef32c41dc
|
Fix Silverlight build error
|
MindTouch/NServiceKit,nataren/NServiceKit,ZocDoc/ServiceStack,timba/NServiceKit,timba/NServiceKit,MindTouch/NServiceKit,NServiceKit/NServiceKit,timba/NServiceKit,MindTouch/NServiceKit,ZocDoc/ServiceStack,timba/NServiceKit,NServiceKit/NServiceKit,MindTouch/NServiceKit,NServiceKit/NServiceKit,ZocDoc/ServiceStack,nataren/NServiceKit,nataren/NServiceKit,NServiceKit/NServiceKit,ZocDoc/ServiceStack,nataren/NServiceKit
|
src/ServiceStack.Common/Utils/FuncUtils.cs
|
src/ServiceStack.Common/Utils/FuncUtils.cs
|
using System;
using ServiceStack.Logging;
namespace ServiceStack.Common.Utils
{
public static class FuncUtils
{
private static readonly ILog Log = LogManager.GetLogger(typeof(FuncUtils));
/// <summary>
/// Invokes the action provided and returns true if no excpetion was thrown.
/// Otherwise logs the exception and returns false if an exception was thrown.
/// </summary>
/// <param name="action">The action.</param>
/// <returns></returns>
public static bool TryExec(Action action)
{
try
{
action();
return true;
}
catch (Exception ex)
{
Log.Error(ex.Message, ex);
}
return false;
}
public static T TryExec<T>(Func<T> func)
{
return TryExec(func, default(T));
}
public static T TryExec<T>(Func<T> func, T defaultValue)
{
try
{
return func();
}
catch (Exception ex)
{
Log.Error(ex.Message, ex);
}
return default(T);
}
#if !SILVERLIGHT //No Stopwatch
public static void WaitWhile(Func<bool> condition, int millisecondTimeout, int millsecondPollPeriod = 10)
{
var timer = System.Diagnostics.Stopwatch.StartNew();
while (condition())
{
System.Threading.Thread.Sleep(millsecondPollPeriod);
if (timer.ElapsedMilliseconds > millisecondTimeout)
throw new TimeoutException("Timed out waiting for condition function.");
}
}
#endif
}
}
|
using System;
using ServiceStack.Logging;
namespace ServiceStack.Common.Utils
{
public static class FuncUtils
{
private static readonly ILog Log = LogManager.GetLogger(typeof(FuncUtils));
/// <summary>
/// Invokes the action provided and returns true if no excpetion was thrown.
/// Otherwise logs the exception and returns false if an exception was thrown.
/// </summary>
/// <param name="action">The action.</param>
/// <returns></returns>
public static bool TryExec(Action action)
{
try
{
action();
return true;
}
catch (Exception ex)
{
Log.Error(ex.Message, ex);
}
return false;
}
public static T TryExec<T>(Func<T> func)
{
return TryExec(func, default(T));
}
public static T TryExec<T>(Func<T> func, T defaultValue)
{
try
{
return func();
}
catch (Exception ex)
{
Log.Error(ex.Message, ex);
}
return default(T);
}
public static void WaitWhile(Func<bool> condition, int millisecondTimeout, int millsecondPollPeriod = 10)
{
var timer = System.Diagnostics.Stopwatch.StartNew();
while (condition())
{
System.Threading.Thread.Sleep(millsecondPollPeriod);
if (timer.ElapsedMilliseconds > millisecondTimeout)
throw new TimeoutException("Timed out waiting for condition function.");
}
}
}
}
|
bsd-3-clause
|
C#
|
500e16f3a57d28b3e387425de8e14bf72b02488a
|
Update SolutionProjectExtractorTests.cs
|
ParticularLabs/SetStartupProjects
|
src/Tests/SolutionProjectExtractorTests.cs
|
src/Tests/SolutionProjectExtractorTests.cs
|
using SetStartupProjects;
using VerifyXunit;
using Xunit;
[UsesVerify]
public class SolutionProjectExtractorTests
{
[Fact]
public Task GetAllProjectFiles()
{
var allProjectFiles = SolutionProjectExtractor.GetAllProjectFiles("SampleSolution.txt");
return Verify(allProjectFiles);
}
}
|
using SetStartupProjects;
using VerifyXunit;
using Xunit;
[UsesVerify]
public class SolutionProjectExtractorTests
{
[Fact]
public Task GetAllProjectFiles()
{
var allProjectFiles = SolutionProjectExtractor.GetAllProjectFiles("SampleSolution.txt");
return Verifier.Verify(allProjectFiles);
}
}
|
mit
|
C#
|
7052fb7d67fab67fd4a804e3b655eec934612ff9
|
Remove extra loadImage callback until we discuss it
|
Excel-DNA/Samples
|
Ribbon/RibbonController.cs
|
Ribbon/RibbonController.cs
|
using System.Runtime.InteropServices;
using System.Windows.Forms;
using ExcelDna.Integration.CustomUI;
namespace Ribbon
{
[ComVisible(true)]
public class RibbonController : ExcelRibbon
{
public override string GetCustomUI(string RibbonID)
{
return @"
<customUI xmlns='http://schemas.microsoft.com/office/2006/01/customui'>
<ribbon>
<tabs>
<tab id='tab1' label='My Tab'>
<group id='group1' label='My Group'>
<button id='button1' label='My Button' onAction='OnButtonPressed'/>
</group >
</tab>
</tabs>
</ribbon>
</customUI>";
}
public void OnButtonPressed(IRibbonControl control)
{
MessageBox.Show("Hello from control " + control.Id);
DataWriter.WriteData();
}
}
}
|
using System.Runtime.InteropServices;
using System.Windows.Forms;
using ExcelDna.Integration.CustomUI;
namespace Ribbon
{
[ComVisible(true)]
public class RibbonController : ExcelRibbon
{
public override string GetCustomUI(string RibbonID)
{
return @"
<customUI xmlns='http://schemas.microsoft.com/office/2006/01/customui' loadImage='LoadImage'>
<ribbon>
<tabs>
<tab id='tab1' label='My Tab'>
<group id='group1' label='My Group'>
<button id='button1' label='My Button' onAction='OnButtonPressed'/>
</group >
</tab>
</tabs>
</ribbon>
</customUI>";
}
public void OnButtonPressed(IRibbonControl control)
{
MessageBox.Show("Hello from control " + control.Id);
DataWriter.WriteData();
}
}
}
|
mit
|
C#
|
b87ca9c0b1a8fe57d8aacaf06052988b3cba42d3
|
Remove substatus field from test since SHIPPO_TRANIST DOES NOT CONTAIN SUBSTATUS
|
goshippo/shippo-csharp-client
|
ShippoTesting/TrackTest.cs
|
ShippoTesting/TrackTest.cs
|
using NUnit.Framework;
using System;
using System.Collections;
using Shippo;
namespace ShippoTesting
{
[TestFixture]
public class TrackTest : ShippoTest
{
private static readonly String TRACKING_NO = "SHIPPO_TRANSIT";
private static readonly String CARRIER = "shippo";
[Test]
public void TestValidGetStatus()
{
Track track = getAPIResource().RetrieveTracking(CARRIER, TRACKING_NO);
Assert.AreEqual(TRACKING_NO, track.TrackingNumber);
Assert.IsNotNull(track.TrackingStatus);
Assert.IsNotNull(track.TrackingHistory);
}
[Test]
public void TestInvalidGetStatus()
{
Assert.That(() => getAPIResource().RetrieveTracking(CARRIER, "INVALID_ID"),
Throws.TypeOf<ShippoException>());
}
[Test]
public void TestValidRegisterWebhook()
{
Track track = getAPIResource().RetrieveTracking(CARRIER, TRACKING_NO);
Hashtable parameters = new Hashtable();
parameters.Add("carrier", CARRIER);
parameters.Add("tracking_number", track.TrackingNumber);
Track register = getAPIResource().RegisterTrackingWebhook(parameters);
Assert.IsNotNull(register.TrackingNumber);
Assert.IsNotNull(register.TrackingHistory);
}
[Test]
public void TestInvalidRegisterWebhook()
{
Hashtable parameters = new Hashtable();
parameters.Add("carrier", CARRIER);
parameters.Add("tracking_number", "INVALID_ID");
Assert.That(() => getAPIResource().RegisterTrackingWebhook(parameters),
Throws.TypeOf<ShippoException>());
}
}
}
|
using NUnit.Framework;
using System;
using System.Collections;
using Shippo;
namespace ShippoTesting
{
[TestFixture]
public class TrackTest : ShippoTest
{
private static readonly String TRACKING_NO = "SHIPPO_TRANSIT";
private static readonly String CARRIER = "shippo";
[Test]
public void TestValidGetStatus()
{
Track track = getAPIResource().RetrieveTracking(CARRIER, TRACKING_NO);
Assert.AreEqual(TRACKING_NO, track.TrackingNumber);
Assert.IsNotNull(track.TrackingStatus);
Assert.IsNotNull(track?.TrackingStatus.Substatus);
Assert.IsNotNull(track.TrackingHistory);
}
[Test]
public void TestInvalidGetStatus()
{
Assert.That(() => getAPIResource().RetrieveTracking(CARRIER, "INVALID_ID"),
Throws.TypeOf<ShippoException>());
}
[Test]
public void TestValidRegisterWebhook()
{
Track track = getAPIResource().RetrieveTracking(CARRIER, TRACKING_NO);
Hashtable parameters = new Hashtable();
parameters.Add("carrier", CARRIER);
parameters.Add("tracking_number", track.TrackingNumber);
Track register = getAPIResource().RegisterTrackingWebhook(parameters);
Assert.IsNotNull(register.TrackingNumber);
Assert.IsNotNull(register.TrackingHistory);
}
[Test]
public void TestInvalidRegisterWebhook()
{
Hashtable parameters = new Hashtable();
parameters.Add("carrier", CARRIER);
parameters.Add("tracking_number", "INVALID_ID");
Assert.That(() => getAPIResource().RegisterTrackingWebhook(parameters),
Throws.TypeOf<ShippoException>());
}
}
}
|
apache-2.0
|
C#
|
8e7e6a4bec2f6b9284293d21f72ded8aeb3d31b8
|
Make explicit DLR lookups
|
RonnChyran/snowflake,SnowflakePowered/snowflake,SnowflakePowered/snowflake,faint32/snowflake-1,faint32/snowflake-1,SnowflakePowered/snowflake,faint32/snowflake-1,RonnChyran/snowflake,RonnChyran/snowflake
|
Snowflake/Game/GameInfo.cs
|
Snowflake/Game/GameInfo.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Snowflake.Information.MediaStore;
using Snowflake.Information;
using Snowflake.Utility;
namespace Snowflake.Game
{
public class GameInfo : Info, IGameInfo
{
public string UUID { get; private set; }
public string FileName { get; private set; }
public string CRC32 { get; private set; }
public GameInfo(string platformId, string name, IMediaStore mediaStore, IDictionary<string, string> metadata, string uuid, string fileName, string crc32)
: base(platformId, name, mediaStore, metadata)
{
this.UUID = uuid;
this.FileName = fileName;
this.CRC32 = crc32;
}
public GameInfo(string platformId, string name, IMediaStore mediaStore, IDictionary<string, string> metadata, string uuid, string fileName)
: this(platformId, name, mediaStore, metadata, uuid, fileName, FileHash.GetCRC32(fileName)) { }
public static IGameInfo FromJson(dynamic json)
{
var metadata = json.Metadata.ToObject<IDictionary<string, string>>();
string mediaStoreKey = json.MediaStore.MediaStoreKey;
var mediastore = new FileMediaStore(mediaStoreKey);
string platformId = json.PlatformID;
string name = json.Name;
string uuid = json.UUID;
string fileName = json.FileName;
string crc32 = json.CRC32;
return new GameInfo(platformId, name, mediastore, metadata, uuid, fileName, crc32);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Snowflake.Information.MediaStore;
using Snowflake.Information;
using Snowflake.Utility;
namespace Snowflake.Game
{
public class GameInfo : Info, IGameInfo
{
public string UUID { get; private set; }
public string FileName { get; private set; }
public string CRC32 { get; private set; }
public GameInfo(string platformId, string name, IMediaStore mediaStore, IDictionary<string, string> metadata, string uuid, string fileName, string crc32)
: base(platformId, name, mediaStore, metadata)
{
this.UUID = uuid;
this.FileName = fileName;
this.CRC32 = crc32;
}
public GameInfo(string platformId, string name, IMediaStore mediaStore, IDictionary<string, string> metadata, string uuid, string fileName)
: this(platformId, name, mediaStore, metadata, uuid, fileName, FileHash.GetCRC32(fileName)) { }
public static IGameInfo FromJson(dynamic json)
{
var metadata = json.Metadata.ToObject<IDictionary<string, string>>();
var mediastore = new FileMediaStore(json.MediaStore.MediaStoreKey);
return new GameInfo(json.PlatformID, json.Name, mediastore, metadata, json.UUID, json.FileName, json.CRC32);
}
}
}
|
mpl-2.0
|
C#
|
c28b1cfd75f5184a89a019350619ac55333beabb
|
Throw error on Insert/Remove IGluon while ticking/updating
|
tainicom/Aether
|
Source/Core/GluonPlasma.cs
|
Source/Core/GluonPlasma.cs
|
#region License
// Copyright 2015 Kastellanos Nikolaos
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using Microsoft.Xna.Framework;
using tainicom.Aether.Elementary;
using tainicom.Aether.Elementary.Gluon;
using tainicom.Aether.Engine.Data;
namespace tainicom.Aether.Core
{
public class GluonPlasma: BasePlasma, ITickable
{
EnabledList<IAether> _enabledParticles;
private bool isEnumerating = false;
public GluonPlasma()
{
_enabledParticles = new EnabledList<IAether>();
}
public void Tick(GameTime gameTime)
{
_enabledParticles.Process();
isEnumerating = true;
foreach (IGluon item in _enabledParticles)
{
item.Tick(gameTime);
}
isEnumerating = false;
return;
}
protected override void InsertItem(int index, IAether item)
{
if (isEnumerating)
throw new InvalidOperationException("Can't modify collection inside Tick() method.");
base.InsertItem(index, item);
_enabledParticles.Add(item);
return;
}
protected override void RemoveItem(int index)
{
if (isEnumerating)
throw new InvalidOperationException("Can't modify collection inside Tick() method.");
IAether item = this[index];
if (_enabledParticles.Contains(item)) _enabledParticles.Remove(item);
base.RemoveItem(index);
}
public void Enable(IGluon item)
{
_enabledParticles.Enable(item);
}
public void Disable(IGluon item)
{
_enabledParticles.Disable(item);
}
}
}
|
#region License
// Copyright 2015 Kastellanos Nikolaos
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using Microsoft.Xna.Framework;
using tainicom.Aether.Elementary;
using tainicom.Aether.Elementary.Gluon;
using tainicom.Aether.Engine.Data;
namespace tainicom.Aether.Core
{
public class GluonPlasma: BasePlasma, ITickable
{
EnabledList<IAether> _enabledParticles;
public GluonPlasma()
{
_enabledParticles = new EnabledList<IAether>();
}
public void Tick(GameTime gameTime)
{
_enabledParticles.Process();
foreach (IGluon item in _enabledParticles)
{
item.Tick(gameTime);
}
return;
}
protected override void InsertItem(int index, IAether item)
{
base.InsertItem(index, item);
_enabledParticles.Add(item);
return;
}
protected override void RemoveItem(int index)
{
IAether item = this[index];
if (_enabledParticles.Contains(item)) _enabledParticles.Remove(item);
base.RemoveItem(index);
}
public void Enable(IGluon item)
{
_enabledParticles.Enable(item);
}
public void Disable(IGluon item)
{
_enabledParticles.Disable(item);
}
}
}
|
apache-2.0
|
C#
|
931dfb600f0feb943dc68d090840bcf22c8d89ae
|
increment patch version,
|
jwChung/Experimentalism,jwChung/Experimentalism
|
build/CommonAssemblyInfo.cs
|
build/CommonAssemblyInfo.cs
|
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.15.1")]
[assembly: AssemblyInformationalVersion("0.15.1")]
/*
* Version 0.15.1
*
* - [FIX] Improves performance for creating test commands in
* `BaseFirstClassTheoremAttribute`.
*
* - [FIX] Fixes an exception thrown when creating test data in
* `BaseTheoremAttribute`.
*/
|
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.15.0")]
[assembly: AssemblyInformationalVersion("0.15.0")]
/*
* Version 0.15.1
*
* - [FIX] Improves performance for creating test commands in
* `BaseFirstClassTheoremAttribute`.
*
* - [FIX] Fixes an exception thrown when creating test data in
* `BaseTheoremAttribute`.
*/
|
mit
|
C#
|
10c4e54e72427e39cbdd919b3bf8ed1e46bb2caa
|
Add proper repo
|
Frozenfire92/UnityScripts
|
Scripts/TimeColor.cs
|
Scripts/TimeColor.cs
|
/* TimeColor.cs
*
* Author: Joel Kuntz - github.com/Frozenfire92/UnityScripts
* Started: December 19 2014
* Updated: December 20 2014
* License: Public Domain
*
* Attach this script to a Unity 4.6 UI/Text object.
* It will update the text with the time and hex value
* afterwards it updates the main cameras background color to match it.
*
* Inspired by http://whatcolourisit.scn9a.org/
* HexToColor from http://wiki.unity3d.com/index.php?title=HexConverter
*/
using UnityEngine;
using UnityEngine.UI;
using System;
public class TimeColor : MonoBehaviour {
private DateTime time;
private Camera cam;
private Text textObj;
private string doubleZero = "00";
private string hex;
private Color32 color;
private bool toggleText = true;
void Start()
{
// Set references
cam = Camera.main;
textObj = gameObject.GetComponent<Text>();
}
void Update ()
{
// Get current time
time = DateTime.Now;
// Reset and build hex string
hex = "";
// Hour
if (time.Hour == 0) hex += doubleZero;
else if (time.Hour > 0 && time.Hour < 10) hex += ("0" + time.Hour);
else hex += time.Hour;
// Minute
if (time.Minute == 0) hex += doubleZero;
else if (time.Minute > 0 && time.Minute < 10) hex += ("0" + time.Minute);
else hex += time.Minute;
// Second
if (time.Second == 0) hex += doubleZero;
else if (time.Second > 0 && time.Second < 10) hex += ("0" + time.Second);
else hex += time.Second;
// Get color, update text & camera
color = HexToColor(hex);
textObj.text = (toggleText) ? hex.Substring(0,2) + ":" + hex.Substring(2,2) + ":" + hex.Substring(4,2) + "\n#" + hex;
cam.backgroundColor = color;
}
// For UI to toggle the text on/off while maintaining camera color change
public void ToggleText ()
{
toggleText = !toggleText;
}
// Converts a string hex color ("123456") to Unity Color
private Color32 HexToColor(string HexVal)
{
// Convert each set of 2 digits to its corresponding byte value
byte R = byte.Parse(HexVal.Substring(0,2), System.Globalization.NumberStyles.HexNumber);
byte G = byte.Parse(HexVal.Substring(2,2), System.Globalization.NumberStyles.HexNumber);
byte B = byte.Parse(HexVal.Substring(4,2), System.Globalization.NumberStyles.HexNumber);
return new Color32(R, G, B, 255);
}
}
|
/* TimeColor.cs
*
* Author: Joel Kuntz - github.com/Frozenfire92
* Started: December 19 2014
* Updated: December 20 2014
* License: Public Domain
*
* Attach this script to a Unity 4.6 UI/Text object.
* It will update the text with the time and hex value
* afterwards it updates the main cameras background color to match it.
*
* Inspired by http://whatcolourisit.scn9a.org/
* HexToColor from http://wiki.unity3d.com/index.php?title=HexConverter
*/
using UnityEngine;
using UnityEngine.UI;
using System;
public class TimeColor : MonoBehaviour {
private DateTime time;
private Camera cam;
private Text textObj;
private string doubleZero = "00";
private string hex;
private Color32 color;
private bool toggleText = true;
void Start()
{
// Set references
cam = Camera.main;
textObj = gameObject.GetComponent<Text>();
}
void Update ()
{
// Get current time
time = DateTime.Now;
// Reset and build hex string
hex = "";
// Hour
if (time.Hour == 0) hex += doubleZero;
else if (time.Hour > 0 && time.Hour < 10) hex += ("0" + time.Hour);
else hex += time.Hour;
// Minute
if (time.Minute == 0) hex += doubleZero;
else if (time.Minute > 0 && time.Minute < 10) hex += ("0" + time.Minute);
else hex += time.Minute;
// Second
if (time.Second == 0) hex += doubleZero;
else if (time.Second > 0 && time.Second < 10) hex += ("0" + time.Second);
else hex += time.Second;
// Get color, update text & camera
color = HexToColor(hex);
textObj.text = (toggleText) ? hex.Substring(0,2) + ":" + hex.Substring(2,2) + ":" + hex.Substring(4,2) + "\n#" + hex;
cam.backgroundColor = color;
}
// For UI to toggle the text on/off while maintaining camera color change
public void ToggleText ()
{
toggleText = !toggleText;
}
// Converts a string hex color ("123456") to Unity Color
private Color32 HexToColor(string HexVal)
{
// Convert each set of 2 digits to its corresponding byte value
byte R = byte.Parse(HexVal.Substring(0,2), System.Globalization.NumberStyles.HexNumber);
byte G = byte.Parse(HexVal.Substring(2,2), System.Globalization.NumberStyles.HexNumber);
byte B = byte.Parse(HexVal.Substring(4,2), System.Globalization.NumberStyles.HexNumber);
return new Color32(R, G, B, 255);
}
}
|
unlicense
|
C#
|
96f782e75a65e61f6f54c8bf225cf3ffe8b5b816
|
fix object reference issue maybe?
|
smoogipoo/osu,peppy/osu,peppy/osu,Frontear/osuKyzer,NeoAdonis/osu,peppy/osu-new,ZLima12/osu,EVAST9919/osu,smoogipooo/osu,NeoAdonis/osu,naoey/osu,UselessToucan/osu,peppy/osu,johnneijzen/osu,naoey/osu,smoogipoo/osu,EVAST9919/osu,ppy/osu,UselessToucan/osu,DrabWeb/osu,UselessToucan/osu,smoogipoo/osu,naoey/osu,DrabWeb/osu,2yangk23/osu,ppy/osu,ZLima12/osu,johnneijzen/osu,DrabWeb/osu,NeoAdonis/osu,Nabile-Rahmani/osu,ppy/osu,2yangk23/osu
|
osu.Game/Overlays/BeatmapSet/HeaderButton.cs
|
osu.Game/Overlays/BeatmapSet/HeaderButton.cs
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics;
using osu.Game.Graphics.UserInterface;
using osu.Game.Graphics.Backgrounds;
using osu.Game.Graphics.Containers;
using osu.Framework.Audio;
using osu.Framework.Allocation;
namespace osu.Game.Overlays.BeatmapSet
{
public class HeaderButton : OsuButton
{
private readonly Container content;
protected override Container<Drawable> Content => content;
public HeaderButton()
{
Height = 0;
RelativeSizeAxes = Axes.Y;
AddInternal(content = new Container
{
RelativeSizeAxes = Axes.Both
});
}
[BackgroundDependencyLoader]
private void load(OsuColour colours, AudioManager audio)
{
Masking = true;
CornerRadius = 3;
BackgroundColour = OsuColour.FromHex(@"094c5f");
this.Triangles.ColourLight = OsuColour.FromHex(@"0f7c9b");
this.Triangles.ColourDark = OsuColour.FromHex(@"094c5f");
this.Triangles.TriangleScale = 1.5f;
}
}
}
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics;
using osu.Game.Graphics.UserInterface;
using osu.Game.Graphics.Backgrounds;
using osu.Game.Graphics.Containers;
using osu.Framework.Audio;
using osu.Framework.Allocation;
namespace osu.Game.Overlays.BeatmapSet
{
public class HeaderButton : OsuButton
{
private readonly Container content;
protected override Container<Drawable> Content => content;
public HeaderButton()
{
Height = 0;
RelativeSizeAxes = Axes.Y;
AddInternal(content = new Container
{
RelativeSizeAxes = Axes.Both
});
}
[BackgroundDependencyLoader]
private void load(OsuColour colours, AudioManager audio)
{
Masking = true;
CornerRadius = 3;
BackgroundColour = OsuColour.FromHex(@"094c5f");
Triangles.ColourLight = OsuColour.FromHex(@"0f7c9b");
Triangles.ColourDark = OsuColour.FromHex(@"094c5f");
Triangles.TriangleScale = 1.5f;
}
}
}
|
mit
|
C#
|
b2e99cd52e23506eda60e8b644c149876eda0f46
|
Fix unit test
|
stwalkerster/eyeinthesky,stwalkerster/eyeinthesky,stwalkerster/eyeinthesky
|
EyeInTheSky/Services/ConfigFactoryBase.cs
|
EyeInTheSky/Services/ConfigFactoryBase.cs
|
namespace EyeInTheSky.Services
{
using System;
using System.Globalization;
using System.Xml;
using Castle.Core.Logging;
public abstract class ConfigFactoryBase
{
public ConfigFactoryBase(ILogger logger)
{
this.Logger = logger;
}
protected ILogger Logger { get; private set; }
internal DateTime ParseDate(string flagName, string input, string propName)
{
DateTime result;
try
{
result = XmlConvert.ToDateTime(input, XmlDateTimeSerializationMode.Utc);
}
catch (FormatException ex)
{
this.Logger.WarnFormat("Unknown date format in item '{0}' {2}: {1}", flagName, input, propName);
if (!DateTime.TryParse(input, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out result))
{
var err = string.Format("Failed date parse for item '{0}' {2}: {1}", flagName, input, propName);
this.Logger.Error(err);
throw new FormatException(err, ex);
}
}
return result;
}
}
}
|
namespace EyeInTheSky.Services
{
using System;
using System.Globalization;
using System.Xml;
using Castle.Core.Logging;
public abstract class ConfigFactoryBase
{
public ConfigFactoryBase(ILogger logger)
{
this.Logger = logger;
}
protected ILogger Logger { get; private set; }
internal DateTime ParseDate(string flagName, string input, string propName)
{
DateTime result;
try
{
result = XmlConvert.ToDateTime(input, XmlDateTimeSerializationMode.Utc);
}
catch (FormatException ex)
{
this.Logger.WarnFormat("Unknown date format in item '{0}' {2}: {1}", flagName, input, propName);
if (!DateTime.TryParse(input, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out result))
{
var err = string.Format("Failed date parse for item '{0}' {2}: {1}", flagName, input, propName);
this.Logger.Error(err);
throw new FormatException(err, ex);
}
}
return result;
}
}
}
|
mit
|
C#
|
4d92eebac43843a2cab257074f4afa8777ce8ce4
|
Add Azure File Storage code
|
A51UK/File-Repository
|
File-Repository/Azure/AzureFileStorage.cs
|
File-Repository/Azure/AzureFileStorage.cs
|
/*
* Copyright 2017 Criag Lee Mark Adams
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.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.File;
using System.Threading.Tasks;
namespace File_Repository
{
public class AzureFileStorage : StorageBase
{
public override async Task<FileData> GetAsync(FileGetOptions fileGetOptions)
{
FileData file = new FileData();
CloudStorageAccount storageAccount = Authorized(fileGetOptions);
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
CloudFileShare fileshare = fileClient.GetShareReference(fileGetOptions.Folder);
if (fileshare.ExistsAsync().Result)
{
CloudFileDirectory cFileDir = fileshare.GetRootDirectoryReference();
CloudFile cFile = cFileDir.GetFileReference(fileGetOptions.Key);
if(cFile.ExistsAsync().Result)
{
await cFile.DownloadToStreamAsync(file.Stream);
}
}
file.Type = "Azure File Storage";
return file;
}
public override async Task<string> SaveAsync(FileSetOptions fileSetOptions)
{
FileData file = new FileData();
CloudStorageAccount storageAccount = Authorized(fileSetOptions);
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
CloudFileShare fileshare = fileClient.GetShareReference(fileSetOptions.Folder);
await fileshare.CreateIfNotExistsAsync();
CloudFileDirectory cFileDir = fileshare.GetRootDirectoryReference();
await cFileDir.CreateIfNotExistsAsync();
CloudFile cFile = cFileDir.GetFileReference(fileSetOptions.Key);
await cFile.UploadFromStreamAsync(fileSetOptions._stream);
return fileSetOptions.Key;
}
private CloudStorageAccount Authorized(dynamic secureOptions)
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(secureOptions.ConfigurationString);
return storageAccount;
}
}
}
|
/*
* Copyright 2017 Criag Lee Mark Adams
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.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.WindowsAzure.Storage;
using System.Threading.Tasks;
namespace File_Repository
{
public class AzureFileStorage : StorageBase
{
public override Task<FileData> GetAsync(FileGetOptions fileGetOptions)
{
throw new NotImplementedException();
}
public override Task<string> SaveAsync(FileSetOptions fileSetOptions)
{
throw new NotImplementedException();
}
}
}
|
apache-2.0
|
C#
|
5781b45b3903393570025c567a7071446b08f9f5
|
Set TimeRate after mod application
|
smoogipooo/osu,DrabWeb/osu,UselessToucan/osu,johnneijzen/osu,Drezi126/osu,ppy/osu,UselessToucan/osu,EVAST9919/osu,NeoAdonis/osu,ZLima12/osu,DrabWeb/osu,ZLima12/osu,ppy/osu,Nabile-Rahmani/osu,NeoAdonis/osu,naoey/osu,DrabWeb/osu,peppy/osu,naoey/osu,EVAST9919/osu,johnneijzen/osu,smoogipoo/osu,naoey/osu,2yangk23/osu,UselessToucan/osu,smoogipoo/osu,2yangk23/osu,Frontear/osuKyzer,ppy/osu,peppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu-new,smoogipoo/osu
|
osu.Game/Beatmaps/DifficultyCalculator.cs
|
osu.Game/Beatmaps/DifficultyCalculator.cs
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Objects;
using System.Collections.Generic;
using osu.Game.Rulesets.Mods;
using osu.Framework.Timing;
using System.Linq;
using osu.Framework.Extensions.IEnumerableExtensions;
namespace osu.Game.Beatmaps
{
public abstract class DifficultyCalculator
{
protected double TimeRate = 1;
public abstract double Calculate(Dictionary<string, string> categoryDifficulty = null);
}
public abstract class DifficultyCalculator<T> : DifficultyCalculator where T : HitObject
{
protected readonly Beatmap Beatmap;
protected readonly Mod[] Mods;
protected List<T> Objects;
protected DifficultyCalculator(Beatmap beatmap)
: this(beatmap, null)
{
}
protected DifficultyCalculator(Beatmap beatmap, Mod[] mods)
{
Beatmap = beatmap;
Mods = mods ?? new Mod[0];
Objects = CreateBeatmapConverter().Convert(beatmap).HitObjects;
foreach (var h in Objects)
h.ApplyDefaults(beatmap.ControlPointInfo, beatmap.BeatmapInfo.BaseDifficulty);
ApplyMods(mods);
PreprocessHitObjects();
}
protected virtual void ApplyMods(Mod[] mods)
{
var clock = new StopwatchClock();
mods.OfType<IApplicableToClock>().ForEach(m => m.ApplyToClock(clock));
TimeRate = clock.Rate;
foreach (var mod in mods.OfType<IApplicableToHitObject<T>>())
foreach (var obj in Objects)
mod.ApplyToHitObject(obj);
}
protected virtual void PreprocessHitObjects()
{
}
protected abstract BeatmapConverter<T> CreateBeatmapConverter();
}
}
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Objects;
using System.Collections.Generic;
using osu.Game.Rulesets.Mods;
using osu.Framework.Timing;
using System.Linq;
using osu.Framework.Extensions.IEnumerableExtensions;
namespace osu.Game.Beatmaps
{
public abstract class DifficultyCalculator
{
protected double TimeRate = 1;
public abstract double Calculate(Dictionary<string, string> categoryDifficulty = null);
}
public abstract class DifficultyCalculator<T> : DifficultyCalculator where T : HitObject
{
protected readonly Beatmap Beatmap;
protected readonly Mod[] Mods;
protected List<T> Objects;
protected DifficultyCalculator(Beatmap beatmap)
: this(beatmap, null)
{
}
protected DifficultyCalculator(Beatmap beatmap, Mod[] mods)
{
Beatmap = beatmap;
Mods = mods ?? new Mod[0];
Objects = CreateBeatmapConverter().Convert(beatmap).HitObjects;
foreach (var h in Objects)
h.ApplyDefaults(beatmap.ControlPointInfo, beatmap.BeatmapInfo.BaseDifficulty);
ApplyMods(mods);
PreprocessHitObjects();
}
protected virtual void ApplyMods(Mod[] mods)
{
var clock = new StopwatchClock();
mods.OfType<IApplicableToClock>().ForEach(m => m.ApplyToClock(clock));
foreach (var mod in mods.OfType<IApplicableToHitObject<T>>())
foreach (var obj in Objects)
mod.ApplyToHitObject(obj);
TimeRate = clock.Rate;
}
protected virtual void PreprocessHitObjects()
{
}
protected abstract BeatmapConverter<T> CreateBeatmapConverter();
}
}
|
mit
|
C#
|
13018bd92059d19452c654982bb35b994722ef26
|
Update NativeShareTest.cs
|
yasirkula/UnityNativeShare
|
NativeShareDemo/Assets/NativeShareTest.cs
|
NativeShareDemo/Assets/NativeShareTest.cs
|
using System.Collections;
using System.IO;
using UnityEngine;
public class NativeShareTest : MonoBehaviour
{
void Update()
{
transform.Rotate( 0, 90 * Time.deltaTime, 0 );
if( Input.GetMouseButtonDown( 0 ) )
StartCoroutine( TakeSSAndShare() );
}
private IEnumerator TakeSSAndShare()
{
yield return new WaitForEndOfFrame();
Texture2D ss = new Texture2D( Screen.width, Screen.height, TextureFormat.RGB24, false );
ss.ReadPixels( new Rect( 0, 0, Screen.width, Screen.height ), 0, 0 );
ss.Apply();
string filePath = Path.Combine( Application.persistentDataPath, "shared img.png" );
File.WriteAllBytes( filePath, ss.EncodeToPNG() );
NativeShare.Share( filePath, "Subject here (optional)", "Message here (optional)", true, "nativeshare.test" );
}
}
|
using System.Collections;
using System.IO;
using UnityEngine;
public class NativeShareTest : MonoBehaviour
{
void Update()
{
transform.Rotate( 0, 90 * Time.deltaTime, 0 );
if( Input.GetMouseButtonDown( 0 ) )
StartCoroutine( TakeSSAndShare() );
}
private IEnumerator TakeSSAndShare()
{
yield return new WaitForEndOfFrame();
Texture2D ss = new Texture2D( Screen.width, Screen.height, TextureFormat.RGB24, false );
ss.ReadPixels( new Rect( 0, 0, Screen.width, Screen.height ), 0, 0 );
ss.Apply();
string filePath = Path.Combine( Application.persistentDataPath, "shared img.png" );
File.WriteAllBytes( filePath, ss.EncodeToPNG() );
NativeShare.Share( filePath, true, "nativeshare.test" );
}
}
|
mit
|
C#
|
de70260b292de04d1bf936418ee9eb71f254124f
|
Remove trailing newline.
|
jagrem/msg
|
Msg.Core.Specs/Transport/Connections/Tcp/TcpConnectionSpecs.cs
|
Msg.Core.Specs/Transport/Connections/Tcp/TcpConnectionSpecs.cs
|
using NUnit.Framework;
using System.Threading.Tasks;
using Msg.Core.Transport.Connections.Tcp;
using FluentAssertions;
namespace Msg.Core.Specs.Transport.Connections.Tcp
{
[TestFixture]
public class TcpConnectionSpecs
{
[Test]
public async Task Given_a_Tcp_server_When_sending_bytes_Then_the_server_receives_the_bytes()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var server = new TcpServer ();
await server.StartAsync ();
var connection = new TcpConnection ();
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
await connection.SendAsync (new byte[] { 1, 2, 3, 4 });
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
var result = await server.GetReceivedBytes ();
result.Should ().BeEquivalentTo (new byte[] { 1, 2, 3, 4 });
}
}
}
|
using NUnit.Framework;
using System.Threading.Tasks;
using Msg.Core.Transport.Connections.Tcp;
using FluentAssertions;
namespace Msg.Core.Specs.Transport.Connections.Tcp
{
[TestFixture]
public class TcpConnectionSpecs
{
[Test]
public async Task Given_a_Tcp_server_When_sending_bytes_Then_the_server_receives_the_bytes()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var server = new TcpServer ();
await server.StartAsync ();
var connection = new TcpConnection ();
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
await connection.SendAsync (new byte[] { 1, 2, 3, 4 });
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
var result = await server.GetReceivedBytes ();
result.Should ().BeEquivalentTo (new byte[] { 1, 2, 3, 4 });
}
}
}
|
apache-2.0
|
C#
|
5670d1882dcd0abfa37fd9f4fe72f0b370718f75
|
fix assembly info
|
paymill/paymill-net,paymill/paymill-net
|
PaymillWrapper/Properties/AssemblyInfo.cs
|
PaymillWrapper/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// La información general sobre un ensamblado se controla mediante el siguiente
// conjunto de atributos. Cambie estos atributos para modificar la información
// asociada con un ensamblado.
[assembly: AssemblyTitle("PaymillWrapper")]
[assembly: AssemblyDescription("Wrapper for the PAYMILL API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("www.paymill.com")]
[assembly: AssemblyProduct("PaymillWrapper")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Si establece ComVisible como false, los tipos de este ensamblado no estarán visibles
// para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde
// COM, establezca el atributo ComVisible como true en este tipo.
[assembly: ComVisible(false)]
// El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM
[assembly: Guid("054f8db0-d3f0-489c-8b29-a5b2944540d0")]
// La información de versión de un ensamblado consta de los cuatro valores siguientes:
//
// Versión principal
// Versión secundaria
// Número de compilación
// Revisión
//
// Puede especificar todos los valores o establecer como predeterminados los números de compilación y de revisión
// mediante el carácter '*', como se muestra a continuación:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.1.2")]
[assembly: AssemblyFileVersion("0.1.1.2")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// La información general sobre un ensamblado se controla mediante el siguiente
// conjunto de atributos. Cambie estos atributos para modificar la información
// asociada con un ensamblado.
[assembly: AssemblyTitle("PaymillWrapperNET")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("www.javiercantos.net")]
[assembly: AssemblyProduct("PaymillWrapperNET")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Si establece ComVisible como false, los tipos de este ensamblado no estarán visibles
// para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde
// COM, establezca el atributo ComVisible como true en este tipo.
[assembly: ComVisible(false)]
// El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM
[assembly: Guid("054f8db0-d3f0-489c-8b29-a5b2944540d0")]
// La información de versión de un ensamblado consta de los cuatro valores siguientes:
//
// Versión principal
// Versión secundaria
// Número de compilación
// Revisión
//
// Puede especificar todos los valores o establecer como predeterminados los números de compilación y de revisión
// mediante el carácter '*', como se muestra a continuación:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.2")]
[assembly: AssemblyFileVersion("0.1.0.2")]
|
mit
|
C#
|
105eb6883255abba44d38e2a782b4dabe3741f6c
|
Update GrabDesktop.cs
|
UnityCommunity/UnityLibrary
|
Scripts/Helpers/Screenshot/GrabDesktop.cs
|
Scripts/Helpers/Screenshot/GrabDesktop.cs
|
using UnityEngine;
using System.Collections;
using System.Drawing;
using Screen = System.Windows.Forms.Screen;
using Application = UnityEngine.Application;
using System.Drawing.Imaging;
// Drag windows desktop image using System.Drawing.dll
// guide on using System.Drawing.dll in unity : http://answers.unity3d.com/answers/253571/view.html *Note the .NET2.0 setting also
public class GrabDesktop : MonoBehaviour
{
void Start()
{
// screenshot source: http://stackoverflow.com/a/363008/5452781
//Create a new bitmap.
var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
// Create a graphics object from the bitmap.
var gfxScreenshot = System.Drawing.Graphics.FromImage(bmpScreenshot);
// Take the screenshot from the upper left corner to the right bottom corner.
gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
// Save the screenshot to the specified path that the user has chosen.
bmpScreenshot.Save(Application.dataPath + "/Screenshot.png", ImageFormat.Png);
}
}
|
using UnityEngine;
using System.Collections;
using System.Drawing;
using Screen = System.Windows.Forms.Screen;
using Application = UnityEngine.Application;
using System.Drawing.Imaging;
// Drag windows desktop image using System.Drawing.dll
// guide on using System.Drawing.dll in unity : http://answers.unity3d.com/answers/253571/view.html
public class GrabDesktop : MonoBehaviour
{
void Start()
{
// screenshot source: http://stackoverflow.com/a/363008/5452781
//Create a new bitmap.
var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
// Create a graphics object from the bitmap.
var gfxScreenshot = System.Drawing.Graphics.FromImage(bmpScreenshot);
// Take the screenshot from the upper left corner to the right bottom corner.
gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
// Save the screenshot to the specified path that the user has chosen.
bmpScreenshot.Save(Application.dataPath + "/Screenshot.png", ImageFormat.Png);
}
}
|
mit
|
C#
|
e16ad05054860a33ae3b45e69e57462e2d0ff04c
|
Test Refactor, consolidate Evaluate Add tests
|
ajlopez/ClojSharp
|
Src/ClojSharp.Core.Tests/EvaluateTests.cs
|
Src/ClojSharp.Core.Tests/EvaluateTests.cs
|
namespace ClojSharp.Core.Tests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClojSharp.Core.Compiler;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class EvaluateTests
{
private Machine machine;
[TestInitialize]
public void Setup()
{
this.machine = new Machine();
}
[TestMethod]
public void EvaluateInteger()
{
Assert.AreEqual(123, this.Evaluate("123", null));
}
[TestMethod]
public void EvaluateSymbolInContext()
{
Context context = new Context();
context.SetValue("one", 1);
Assert.AreEqual(1, this.Evaluate("one", context));
}
[TestMethod]
public void EvaluateAdd()
{
Assert.AreEqual(3, this.Evaluate("(+ 1 2)", this.machine.RootContext));
Assert.AreEqual(6, this.Evaluate("(+ 1 2 3)", this.machine.RootContext));
Assert.AreEqual(5, this.Evaluate("(+ 5)", this.machine.RootContext));
Assert.AreEqual(0, this.Evaluate("(+)", this.machine.RootContext));
}
private object Evaluate(string text, Context context)
{
Parser parser = new Parser(text);
var expr = parser.ParseExpression();
Assert.IsNull(parser.ParseExpression());
return this.machine.Evaluate(expr, context);
}
}
}
|
namespace ClojSharp.Core.Tests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClojSharp.Core.Compiler;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class EvaluateTests
{
private Machine machine;
[TestInitialize]
public void Setup()
{
this.machine = new Machine();
}
[TestMethod]
public void EvaluateInteger()
{
Assert.AreEqual(123, this.Evaluate("123", null));
}
[TestMethod]
public void EvaluateSymbolInContext()
{
Context context = new Context();
context.SetValue("one", 1);
Assert.AreEqual(1, this.Evaluate("one", context));
}
[TestMethod]
public void EvaluateAddTwoIntegers()
{
Assert.AreEqual(3, this.Evaluate("(+ 1 2)", this.machine.RootContext));
}
[TestMethod]
public void EvaluateAddThreeIntegers()
{
Assert.AreEqual(6, this.Evaluate("(+ 1 2 3)", this.machine.RootContext));
}
[TestMethod]
public void EvaluateOneInteger()
{
Assert.AreEqual(5, this.Evaluate("(+ 5)", this.machine.RootContext));
}
[TestMethod]
public void EvaluateNoInteger()
{
Assert.AreEqual(0, this.Evaluate("(+)", this.machine.RootContext));
}
private object Evaluate(string text, Context context)
{
Parser parser = new Parser(text);
var expr = parser.ParseExpression();
Assert.IsNull(parser.ParseExpression());
return this.machine.Evaluate(expr, context);
}
}
}
|
mit
|
C#
|
70f328725804391b79ed34bd25c38be9774c4106
|
Add test for cipher
|
aloisdg/algo
|
Algo/CaesarCipher/Program.cs
|
Algo/CaesarCipher/Program.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CaesarCipher
{
class Program
{
static void Main(string[] args)
{
string str = "je t'aime";
str = CaesarCipher.Encrypt(str, 6);
Console.WriteLine("Encrypted: {0}", str);
str = CaesarCipher.Decrypt(str, 6);
Console.WriteLine("Decrypted: {0}", str);
str = "js";
for (int i = 0; i < 20; i++)
{
var e = CaesarCipher.Encrypt(str, i);
var d = CaesarCipher.Decrypt(e, i);
Console.WriteLine("{0:D4} {1} {2} {3}", i, str == d ? "ok" : "ko", e, d);
}
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CaesarCipher
{
class Program
{
static void Main(string[] args)
{
string str = "je t'aime";
str = CaesarCipher.Encrypt(str, 6);
Console.WriteLine("Encrypted: {0}", str);
str = CaesarCipher.Decrypt(str, 6);
Console.WriteLine("Decrypted: {0}", str);
str = "je t'aime";
for (int i = 0; i < 20; i++)
{
Console.WriteLine(str == CaesarCipher.Decrypt(CaesarCipher.Encrypt(str, i), i)
? "{0} ok" : "{0} ko", i);
}
Console.ReadLine();
}
}
}
|
bsd-3-clause
|
C#
|
886aa87099ffe762ab692a54e18cf81f3b4c270e
|
Reset live tokens value when it can not be saved
|
Piotrekol/StreamCompanion,Piotrekol/StreamCompanion
|
plugins/OsuMemoryEventSource/LiveToken.cs
|
plugins/OsuMemoryEventSource/LiveToken.cs
|
using System;
using System.Diagnostics;
using StreamCompanionTypes.DataTypes;
using StreamCompanionTypes.Enums;
namespace OsuMemoryEventSource
{
public class LiveToken
{
public IToken Token { get; set; }
public Func<object> Updater;
public bool IsLazy { get; set; }
protected Lazy<object> Lazy = new Lazy<object>();
public LiveToken(IToken token, Func<object> updater)
{
Token = token;
Updater = updater;
_ = Lazy.Value;
}
public void Update(OsuStatus status = OsuStatus.All)
{
if (!Token.CanSave(status) || Updater == null)
{
Token.Reset();
return;
}
if (IsLazy)
{
if (Lazy.IsValueCreated)
{
Token.Value = Lazy = new Lazy<object>(Updater);
}
}
else
{
Token.Value = Updater();
}
}
}
}
|
using System;
using System.Diagnostics;
using StreamCompanionTypes.DataTypes;
using StreamCompanionTypes.Enums;
namespace OsuMemoryEventSource
{
public class LiveToken
{
public IToken Token { get; set; }
public Func<object> Updater;
public bool IsLazy { get; set; }
protected Lazy<object> Lazy = new Lazy<object>();
public LiveToken(IToken token, Func<object> updater)
{
Token = token;
Updater = updater;
_ = Lazy.Value;
}
public void Update(OsuStatus status = OsuStatus.All)
{
if (!Token.CanSave(status) || Updater == null)
{
return;
}
if (IsLazy)
{
if (Lazy.IsValueCreated)
{
Token.Value = Lazy = new Lazy<object>(Updater);
}
}
else
{
Token.Value = Updater();
}
}
}
}
|
mit
|
C#
|
6290d676b5d7f71dfaa7485d5310e6285e512256
|
Update CarroController.cs
|
cayodonatti/TopGearApi
|
TopGearApi/Controllers/CarroController.cs
|
TopGearApi/Controllers/CarroController.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TopGearApi.DataAccess;
using TopGearApi.Domain.Models;
using TopGearApi.Models;
namespace TopGearApi.Controllers
{
public class CarroController : TController<Carro>
{
private static CarroDA DA = new CarroDA();
[HttpGet]
public IEnumerable<Carro> GetByItem(int id)
{
return DA.GetByItem(id);
}
[HttpGet]
public IEnumerable<Carro> GetDisponiveis()
{
return DA.GetDisponiveis();
}
[HttpGet]
public IEnumerable<Carro> GetDisponiveisByAgencia(int id)
{
return DA.GetDisponiveisByAgencia(id);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TopGearApi.DataAccess;
using TopGearApi.Domain.Models;
using TopGearApi.Models;
namespace TopGearApi.Controllers
{
public class CarroController : TController<Carro>
{
private CarroDA DA = new CarroDA();
[HttpGet]
public IEnumerable<Carro> GetByItem(int id)
{
return DA.GetByItem(id);
}
[HttpGet]
public IEnumerable<Carro> GetDisponiveis()
{
return DA.GetDisponiveis();
}
[HttpGet]
public IEnumerable<Carro> GetDisponiveisByAgencia(int id)
{
return DA.GetDisponiveisByAgencia(id);
}
}
}
|
mit
|
C#
|
e2f32efeccb739a0281c6d8f12d67a3f6658d5e5
|
Update BackgroundWorker.cs
|
oskardudycz/EventSourcing.NetCore
|
Core/BackgroundWorkers/BackgroundWorker.cs
|
Core/BackgroundWorkers/BackgroundWorker.cs
|
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Core.BackgroundWorkers;
public class BackgroundWorker: BackgroundService
{
private readonly ILogger<BackgroundWorker> logger;
private readonly Func<CancellationToken, Task> perform;
public BackgroundWorker(
ILogger<BackgroundWorker> logger,
Func<CancellationToken, Task> perform
)
{
this.logger = logger;
this.perform = perform;
}
protected override Task ExecuteAsync(CancellationToken stoppingToken) =>
Task.Run(async () =>
{
await Task.Yield();
logger.LogInformation("Background worker started");
await perform(stoppingToken);
logger.LogInformation("Background worker stopped");
}, stoppingToken);
}
|
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Core.BackgroundWorkers;
public class BackgroundWorker: BackgroundService
{
private readonly ILogger<BackgroundWorker> logger;
private readonly Func<CancellationToken, Task> perform;
public BackgroundWorker(
ILogger<BackgroundWorker> logger,
Func<CancellationToken, Task> perform
)
{
this.logger = logger;
this.perform = perform;
}
protected override Task ExecuteAsync(CancellationToken stoppingToken) =>
Task.Run(async () =>
{
await Task.Yield();
logger.LogInformation("Background worker stopped");
await perform(stoppingToken);
logger.LogInformation("Background worker stopped");
}, stoppingToken);
}
|
mit
|
C#
|
e32316ca8586d9d0e3c734b523d877d7ec1ef5f9
|
Enable overriding of settings via command line arguments in the formats: /SettingName=value /SettingName:value
|
chucknorris/dropkick,chucknorris/dropkick,chucknorris/dropkick,chucknorris/dropkick
|
product/dropkick/Settings/SettingsParser.cs
|
product/dropkick/Settings/SettingsParser.cs
|
// Copyright 2007-2010 The Apache Software Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace dropkick.Settings
{
using System;
using System.IO;
using Magnum.Configuration;
public class SettingsParser
{
public T Parse<T>(FileInfo file, string commandLine, string environment) where T : new()
{
return (T)Parse(typeof (T), file, commandLine, environment);
}
public object Parse(Type t, FileInfo file, string commandLine, string environment)
{
var binder = ConfigurationBinderFactory.New(c =>
{
//c.AddJsonFile("global.conf");
//c.AddJsonFile("{0}.conf".FormatWith(environment));
//c.AddJsonFile(file.FullName);
var content = File.ReadAllText(file.FullName);
c.AddJson(content);
c.AddCommandLine(commandLine);
});
object result = binder.Bind(t);
return result;
}
}
}
|
// Copyright 2007-2010 The Apache Software Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace dropkick.Settings
{
using System;
using System.IO;
using Magnum.Configuration;
public class SettingsParser
{
public T Parse<T>(FileInfo file, string commandLine, string environment) where T : new()
{
return (T)Parse(typeof (T), file, commandLine, environment);
}
public object Parse(Type t, FileInfo file, string commandLine, string environment)
{
var binder = ConfigurationBinderFactory.New(c =>
{
//c.AddJsonFile("global.conf");
//c.AddJsonFile("{0}.conf".FormatWith(environment));
//c.AddJsonFile(file.FullName);
var content = File.ReadAllText(file.FullName);
c.AddJson(content);
//c.AddCommandLine(commandLine);
});
object result = binder.Bind(t);
return result;
}
}
}
|
apache-2.0
|
C#
|
cfa1dfa1a4daef0e8a0f992a275e184768859176
|
Split out into own method
|
NeoAdonis/osu,peppy/osu,UselessToucan/osu,smoogipooo/osu,EVAST9919/osu,johnneijzen/osu,NeoAdonis/osu,UselessToucan/osu,johnneijzen/osu,smoogipoo/osu,EVAST9919/osu,smoogipoo/osu,2yangk23/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,peppy/osu,2yangk23/osu,UselessToucan/osu,peppy/osu,ppy/osu,peppy/osu-new,ppy/osu
|
osu.Game.Rulesets.Mania/Skinning/ManiaLegacySkinTransformer.cs
|
osu.Game.Rulesets.Mania/Skinning/ManiaLegacySkinTransformer.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Textures;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Game.Rulesets.Scoring;
using osu.Game.Audio;
using osu.Game.Skinning;
namespace osu.Game.Rulesets.Mania.Skinning
{
public class ManiaLegacySkinTransformer : ISkin
{
private readonly ISkin source;
public ManiaLegacySkinTransformer(ISkin source)
{
this.source = source;
}
public Drawable GetDrawableComponent(ISkinComponent component)
{
switch (component)
{
case GameplaySkinComponent<HitResult> resultComponent:
return getResult(resultComponent);
}
return null;
}
private Drawable getResult(GameplaySkinComponent<HitResult> resultComponent)
{
switch (resultComponent.Component)
{
case HitResult.Miss:
return this.GetAnimation("mania-hit0", true, true);
case HitResult.Meh:
return this.GetAnimation("mania-hit50", true, true);
case HitResult.Ok:
return this.GetAnimation("mania-hit100", true, true);
case HitResult.Good:
return this.GetAnimation("mania-hit200", true, true);
case HitResult.Great:
return this.GetAnimation("mania-hit300", true, true);
case HitResult.Perfect:
return this.GetAnimation("mania-hit300g", true, true);
}
return null;
}
public Texture GetTexture(string componentName) => source.GetTexture(componentName);
public SampleChannel GetSample(ISampleInfo sample) => source.GetSample(sample);
public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) =>
source.GetConfig<TLookup, TValue>(lookup);
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Textures;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Game.Rulesets.Scoring;
using osu.Game.Audio;
using osu.Game.Skinning;
namespace osu.Game.Rulesets.Mania.Skinning
{
public class ManiaLegacySkinTransformer : ISkin
{
private readonly ISkin source;
public ManiaLegacySkinTransformer(ISkin source)
{
this.source = source;
}
public Drawable GetDrawableComponent(ISkinComponent component)
{
switch (component)
{
case GameplaySkinComponent<HitResult> resultComponent:
switch (resultComponent.Component)
{
case HitResult.Miss:
return this.GetAnimation("mania-hit0", true, true);
case HitResult.Meh:
return this.GetAnimation("mania-hit50", true, true);
case HitResult.Ok:
return this.GetAnimation("mania-hit100", true, true);
case HitResult.Good:
return this.GetAnimation("mania-hit200", true, true);
case HitResult.Great:
return this.GetAnimation("mania-hit300", true, true);
case HitResult.Perfect:
return this.GetAnimation("mania-hit300g", true, true);
}
break;
}
return null;
}
public Texture GetTexture(string componentName) => source.GetTexture(componentName);
public SampleChannel GetSample(ISampleInfo sample) => source.GetSample(sample);
public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) =>
source.GetConfig<TLookup, TValue>(lookup);
}
}
|
mit
|
C#
|
84621605351408293034e112b85140ff52651d4f
|
Fix Linux build to compile the new Palette class
|
BloomBooks/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork
|
src/BloomExe/Palette.cs
|
src/BloomExe/Palette.cs
|
using System.Drawing;
namespace Bloom
{
class Palette
{
public static Color LightTextAgainstDarkBackground = Color.WhiteSmoke;
public static Color SILInternationalBlue = Color.FromArgb(0,101,163);//NB: the "official" RGB is 0,91,163, but all samples are close to this one I'm using.
public static Color DarkTextAgainstBackgroundColor = Color.Black;
public static Color DisabledTextAgainstDarkBackColor = Color.Gray;
public static Color BloomRed = GetColor("#FFD65649");
public static Color BloomYellow = GetColor("#FEBF00");
public static Color GeneralBackground = GetColor("#2E2E2E");
public static Color SidePanelBackgroundColor = GeneralBackground;
public static Color SelectedTabBackground = SidePanelBackgroundColor;
public static Color UnselectedTabBackground = GetColor("#575757");
public static Color BookListSplitterColor = GetColor("#1a1a1a");
private static Color GetColor(string hexColor)
{
// Note that Mono doesn't have System.Windows.Media.
return ColorTranslator.FromHtml(hexColor);
}
}
}
|
using System.Drawing;
namespace Bloom
{
class Palette
{
public static Color LightTextAgainstDarkBackground = Color.WhiteSmoke;
public static Color SILInternationalBlue = Color.FromArgb(0,101,163);//NB: the "official" RGB is 0,91,163, but all samples are close to this one I'm using.
public static Color DarkTextAgainstBackgroundColor = Color.Black;
public static Color DisabledTextAgainstDarkBackColor = Color.Gray;
public static Color BloomRed = GetColor("#FFD65649");
public static Color BloomYellow = GetColor("#FEBF00");
public static Color GeneralBackground = GetColor("#2E2E2E");
public static Color SidePanelBackgroundColor = GeneralBackground;
public static Color SelectedTabBackground = SidePanelBackgroundColor;
public static Color UnselectedTabBackground = GetColor("#575757");
public static Color BookListSplitterColor = GetColor("#1a1a1a");
private static Color GetColor(string hexColor)
{
var c = (System.Windows.Media.Color )System.Windows.Media.ColorConverter.ConvertFromString(hexColor);
return Color.FromArgb(c.A, c.R, c.B, c.G);
}
}
}
|
mit
|
C#
|
7f344444bd3a88e992f3dbc287fadae5b1e28479
|
Add Thumbnail property
|
fmassaretto/formacao-talentos,fmassaretto/formacao-talentos,fmassaretto/formacao-talentos
|
Fatec.Treinamento.Model/Video.cs
|
Fatec.Treinamento.Model/Video.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Fatec.Treinamento.Model
{
public class Video
{
public int Id { get; set; }
public string Nome { get; set; }
public int Duracao { get; set; }
public string DuracaoFormatada {
get
{
TimeSpan time = TimeSpan.FromSeconds(Duracao);
return time.ToString(@"hh\:mm\:ss");
}
}
public string CodigoVideo { get; set; }
public string ThumbNail { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Fatec.Treinamento.Model
{
public class Video
{
public int Id { get; set; }
public string Nome { get; set; }
public int Duracao { get; set; }
public string DuracaoFormatada {
get
{
TimeSpan time = TimeSpan.FromSeconds(Duracao);
return time.ToString(@"hh\:mm\:ss");
}
}
public string CodigoVideo { get; set; }
}
}
|
apache-2.0
|
C#
|
24ba6673715564a5ced414e01c9bb1ea8c6fc4a3
|
fix DropoutLayer
|
cbovar/ConvNetSharp
|
src/ConvNetSharp.Core/Layers/DropoutLayer.cs
|
src/ConvNetSharp.Core/Layers/DropoutLayer.cs
|
using System;
using ConvNetSharp.Volume;
namespace ConvNetSharp.Core.Layers
{
public class DropoutLayer<T> : LayerBase<T> where T : struct, IEquatable<T>, IFormattable
{
public T DropProbability { get; set; }
public override void Backward(Volume<T> outputGradient)
{
this.OutputActivationGradients = outputGradient;
this.InputActivationGradients.Clear();
this.OutputActivation.DoDropoutGradient(this.InputActivation, this.OutputActivationGradients, this.InputActivationGradients, this.DropProbability);
}
protected override Volume<T> Forward(Volume<T> input, bool isTraining = false)
{
input.DoDropout(this.OutputActivation, isTraining, this.DropProbability);
return this.OutputActivation;
}
}
}
|
using System;
using ConvNetSharp.Volume;
namespace ConvNetSharp.Core.Layers
{
public class DropoutLayer<T> : LayerBase<T> where T : struct, IEquatable<T>, IFormattable
{
public T DropProbability { get; set; }
public override void Backward(Volume<T> outputGradient)
{
this.OutputActivationGradients = outputGradient;
this.InputActivationGradients.Clear();
this.OutputActivation.DoDropoutGradient(this.InputActivation, this.OutputActivationGradients, this.InputActivationGradients);
}
protected override Volume<T> Forward(Volume<T> input, bool isTraining = false)
{
input.DoDropout(this.OutputActivation, isTraining, this.DropProbability);
return this.OutputActivation;
}
}
}
|
mit
|
C#
|
b8bbbe2d558af7066040db365eac37a9fc97a853
|
Update ArkAccountTop.cs
|
kristjank/ark-net,sharkdev-j/ark-net
|
ark-net/Model/Account/ArkAccountTop.cs
|
ark-net/Model/Account/ArkAccountTop.cs
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ArkAccountTop.cs" company="Ark">
// MIT License
// //
// // Copyright (c) 2017 Kristjan Košič
// //
// // 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace ArkNet.Model.Account
{
/// <summary>
/// Represents an Ark Top Account model.
/// </summary>
///
// note: terminology might have been 'ArkTopAcccount'.
public class ArkAccountTop
{
/// <summary>
/// Address of the account.
/// </summary>
///
/// <value>Gets/sets the value as a <see cref="string"/>.</value>
///
public string Address { get; set; }
/// <summary>
/// Balance of the account.
/// </summary>
///
/// <value>Gets/sets the value as an <see cref="long"/>.</value>
///
public long Balance { get; set; }
/// <summary>
/// Public key of the account as a hexadecimal number.
/// </summary>
///
/// <value>Gets/sets the value as a <see cref="string"/>.</value>
///
public string PublicKey { get; set; }
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ArkAccountTop.cs" company="Ark Labs">
// MIT License
// //
// // Copyright (c) 2017 Kristjan Košič
// //
// // 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace ArkNet.Model.Account
{
/// <summary>
/// Represents an Ark Top Account model.
/// </summary>
///
// note: terminology might have been 'ArkTopAcccount'.
public class ArkAccountTop
{
/// <summary>
/// Address of the account.
/// </summary>
///
/// <value>Gets/sets the value as a <see cref="string"/>.</value>
///
public string Address { get; set; }
/// <summary>
/// Balance of the account.
/// </summary>
///
/// <value>Gets/sets the value as an <see cref="long"/>.</value>
///
public long Balance { get; set; }
/// <summary>
/// Public key of the account as a hexadecimal number.
/// </summary>
///
/// <value>Gets/sets the value as a <see cref="string"/>.</value>
///
public string PublicKey { get; set; }
}
}
|
mit
|
C#
|
4bf42066b48de46cb01b27053336604e3194a559
|
allow private props
|
prime31/Nez,prime31/Nez,ericmbernier/Nez,Blucky87/Nez,eumario/Nez,prime31/Nez
|
Nez-PCL/Utils/ReflectionUtils.cs
|
Nez-PCL/Utils/ReflectionUtils.cs
|
using System;
using System.Reflection;
namespace Nez
{
/// <summary>
/// helper class to fetch property delegates
/// </summary>
class ReflectionUtils
{
/// <summary>
/// either returns a super fast Delegate to set the given property or null if it couldn't be found
/// via reflection
/// </summary>
public static T setterForProperty<T>( System.Object targetObject, string propertyName )
{
// first get the property
#if NETFX_CORE
var propInfo = targetObject.GetType().GetRuntimeProperty( propertyName );
#else
var propInfo = targetObject.GetType().GetProperty( propertyName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public );
#endif
Assert.isNotNull( propInfo, "could not find property with name: " + propertyName );
#if NETFX_CORE
// Windows Phone/Store new API
return (T)(object)propInfo.SetMethod.CreateDelegate( typeof( T ), targetObject );
#else
return (T)(object)Delegate.CreateDelegate( typeof( T ), targetObject, propInfo.GetSetMethod( true ) );
#endif
}
/// <summary>
/// either returns a super fast Delegate to get the given property or null if it couldn't be found
/// via reflection
/// </summary>
public static T getterForProperty<T>( System.Object targetObject, string propertyName )
{
// first get the property
#if NETFX_CORE
var propInfo = targetObject.GetType().GetRuntimeProperty( propertyName );
#else
var propInfo = targetObject.GetType().GetProperty( propertyName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public );
#endif
Assert.isNotNull( propInfo, "could not find property with name: " + propertyName );
#if NETFX_CORE
// Windows Phone/Store new API
return (T)(object)propInfo.GetMethod.CreateDelegate( typeof( T ), targetObject );
#else
return (T)(object)Delegate.CreateDelegate( typeof( T ), targetObject, propInfo.GetGetMethod( true ) );
#endif
}
}
}
|
using System;
namespace Nez
{
/// <summary>
/// helper class to fetch property delegates
/// </summary>
class ReflectionUtils
{
/// <summary>
/// either returns a super fast Delegate to set the given property or null if it couldn't be found
/// via reflection
/// </summary>
public static T setterForProperty<T>( System.Object targetObject, string propertyName )
{
// first get the property
#if NETFX_CORE
var propInfo = targetObject.GetType().GetRuntimeProperty( propertyName );
#else
var propInfo = targetObject.GetType().GetProperty( propertyName );
#endif
Assert.isNotNull( propInfo, "could not find property with name: " + propertyName );
#if NETFX_CORE
// Windows Phone/Store new API
return (T)(object)propInfo.SetMethod.CreateDelegate( typeof( T ), targetObject );
#else
return (T)(object)Delegate.CreateDelegate( typeof( T ), targetObject, propInfo.GetSetMethod() );
#endif
}
/// <summary>
/// either returns a super fast Delegate to get the given property or null if it couldn't be found
/// via reflection
/// </summary>
public static T getterForProperty<T>( System.Object targetObject, string propertyName )
{
// first get the property
#if NETFX_CORE
var propInfo = targetObject.GetType().GetRuntimeProperty( propertyName );
#else
var propInfo = targetObject.GetType().GetProperty( propertyName );
#endif
Assert.isNotNull( propInfo, "could not find property with name: " + propertyName );
#if NETFX_CORE
// Windows Phone/Store new API
return (T)(object)propInfo.GetMethod.CreateDelegate( typeof( T ), targetObject );
#else
return (T)(object)Delegate.CreateDelegate( typeof( T ), targetObject, propInfo.GetGetMethod() );
#endif
}
}
}
|
mit
|
C#
|
49efb797f5322b4a32e67c36d7e14facf4910bd0
|
Bump 0.21.0
|
lstefano71/Nowin,Bobris/Nowin,Bobris/Nowin,Bobris/Nowin,lstefano71/Nowin,lstefano71/Nowin
|
Nowin/Properties/AssemblyInfo.cs
|
Nowin/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Nowin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Boris Letocha")]
[assembly: AssemblyProduct("Nowin")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fd085b68-3766-42af-ab6d-351b7741c685")]
// 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.21.0.0")]
[assembly: AssemblyFileVersion("0.21.0.0")]
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Nowin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Boris Letocha")]
[assembly: AssemblyProduct("Nowin")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fd085b68-3766-42af-ab6d-351b7741c685")]
// 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.20.0.0")]
[assembly: AssemblyFileVersion("0.20.0.0")]
|
mit
|
C#
|
b019f4e53d3850d6d5f82ac9c37ff2bfbae3092f
|
Remove unused constants.
|
ravimeda/cli,Faizan2304/cli,livarcocc/cli-1,EdwardBlair/cli,johnbeisner/cli,Faizan2304/cli,blackdwarf/cli,livarcocc/cli-1,Faizan2304/cli,dasMulli/cli,livarcocc/cli-1,svick/cli,EdwardBlair/cli,johnbeisner/cli,blackdwarf/cli,dasMulli/cli,blackdwarf/cli,harshjain2/cli,EdwardBlair/cli,ravimeda/cli,harshjain2/cli,ravimeda/cli,svick/cli,svick/cli,dasMulli/cli,harshjain2/cli,blackdwarf/cli,johnbeisner/cli
|
src/Microsoft.DotNet.Cli.Utils/Constants.cs
|
src/Microsoft.DotNet.Cli.Utils/Constants.cs
|
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.DotNet.PlatformAbstractions;
namespace Microsoft.DotNet.Cli.Utils
{
public static class Constants
{
private static Platform CurrentPlatform => RuntimeEnvironment.OperatingSystemPlatform;
public const string DefaultConfiguration = "Debug";
public static readonly string ProjectFileName = "project.json";
public static readonly string ExeSuffix = CurrentPlatform == Platform.Windows ? ".exe" : string.Empty;
public static readonly string BinDirectoryName = "bin";
public static readonly string ObjDirectoryName = "obj";
public static readonly string MSBUILD_EXE_PATH = "MSBUILD_EXE_PATH";
public static readonly string MSBuildExtensionsPath = "MSBuildExtensionsPath";
public static readonly string ProjectArgumentName = "<PROJECT>";
public static readonly string SolutionArgumentName = "<SLN_FILE>";
}
}
|
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.DotNet.PlatformAbstractions;
namespace Microsoft.DotNet.Cli.Utils
{
public static class Constants
{
private static Platform CurrentPlatform => RuntimeEnvironment.OperatingSystemPlatform;
public const string DefaultConfiguration = "Debug";
public static readonly string ProjectFileName = "project.json";
public static readonly string ExeSuffix = CurrentPlatform == Platform.Windows ? ".exe" : string.Empty;
public static readonly string ConfigSuffix = ".config";
// Priority order of runnable suffixes to look for and run
public static readonly string[] RunnableSuffixes = CurrentPlatform == Platform.Windows
? new string[] { ".exe", ".cmd", ".bat" }
: new string[] { string.Empty };
public static readonly string BinDirectoryName = "bin";
public static readonly string ObjDirectoryName = "obj";
public static readonly string DynamicLibSuffix = CurrentPlatform == Platform.Windows ? ".dll" :
CurrentPlatform == Platform.Darwin ? ".dylib" : ".so";
public static readonly string LibCoreClrFileName = (CurrentPlatform == Platform.Windows ? "coreclr" : "libcoreclr");
public static readonly string LibCoreClrName = LibCoreClrFileName + DynamicLibSuffix;
public static readonly string StaticLibSuffix = CurrentPlatform == Platform.Windows ? ".lib" : ".a";
public static readonly string ResponseFileSuffix = ".rsp";
public static readonly string PublishedHostExecutableName = "dotnet";
public static readonly string HostExecutableName = "corehost" + ExeSuffix;
public static readonly string[] HostBinaryNames = new string[] {
HostExecutableName,
(CurrentPlatform == Platform.Windows ? "hostpolicy" : "libhostpolicy") + DynamicLibSuffix,
(CurrentPlatform == Platform.Windows ? "hostfxr" : "libhostfxr") + DynamicLibSuffix
};
public static readonly string[] LibCoreClrBinaryNames = new string[]
{
"coreclr.dll",
"libcoreclr.so",
"libcoreclr.dylib"
};
public static readonly string MSBUILD_EXE_PATH = "MSBUILD_EXE_PATH";
public static readonly string MSBuildExtensionsPath = "MSBuildExtensionsPath";
public static readonly string ProjectArgumentName = "<PROJECT>";
public static readonly string SolutionArgumentName = "<SLN_FILE>";
}
}
|
mit
|
C#
|
06dfa68323cea0006cd2df9f80d4814ecab4798f
|
check if URI is valid in ArticleImage
|
ceee/ReadSharp,alexeib/ReadSharp
|
ReadSharp/Models/ArticleImage.cs
|
ReadSharp/Models/ArticleImage.cs
|
using System;
namespace ReadSharp
{
/// <summary>
/// Article image
/// </summary>
public class ArticleImage
{
/// <summary>
/// Gets or sets the identifier.
/// </summary>
/// <value>
/// The identifier.
/// </value>
public string ID { get; set; }
/// <summary>
/// Gets or sets the URI.
/// </summary>
/// <value>
/// The URI.
/// </value>
public Uri Uri { get; set; }
/// <summary>
/// Gets or sets the title.
/// </summary>
/// <value>
/// The title.
/// </value>
public string Title { get; set; }
/// <summary>
/// Gets or sets the alternative text.
/// </summary>
/// <value>
/// The alternative text.
/// </value>
public string AlternativeText { get; set; }
/// <summary>
/// Gets a value indicating whether [is valid URI].
/// </summary>
/// <value>
/// <c>true</c> if [is valid URI]; otherwise, <c>false</c>.
/// </value>
public bool IsValidUri
{
get { return Uri != null && Uri.IsWellFormedUriString(Uri.ToString(), UriKind.Absolute); }
}
}
}
|
using System;
namespace ReadSharp
{
/// <summary>
/// Article image
/// </summary>
public class ArticleImage
{
/// <summary>
/// Gets or sets the identifier.
/// </summary>
/// <value>
/// The identifier.
/// </value>
public string ID { get; set; }
/// <summary>
/// Gets or sets the URI.
/// </summary>
/// <value>
/// The URI.
/// </value>
public Uri Uri { get; set; }
/// <summary>
/// Gets or sets the title.
/// </summary>
/// <value>
/// The title.
/// </value>
public string Title { get; set; }
/// <summary>
/// Gets or sets the alternative text.
/// </summary>
/// <value>
/// The alternative text.
/// </value>
public string AlternativeText { get; set; }
}
}
|
mit
|
C#
|
a346fef3b7c1f4101742a8b251f6ee0422387604
|
use a queue instead
|
AzureAD/microsoft-authentication-library-for-dotnet,yamamoWorks/azure-activedirectory-library-for-dotnet,AzureAD/azure-activedirectory-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,bjartebore/azure-activedirectory-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet
|
src/ADAL.PCL/HttpMessageHandlerFactory.cs
|
src/ADAL.PCL/HttpMessageHandlerFactory.cs
|
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// 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.Concurrent;
using System.Collections.Generic;
using System.Net.Http;
namespace Microsoft.IdentityModel.Clients.ActiveDirectory
{
internal static class HttpMessageHandlerFactory
{
internal static HttpMessageHandler GetMessageHandler(bool useDefaultCredentials)
{
if (MockHandlerQueue.Count > 0)
{
MockHandlerQueue.Dequeue();
}
return new HttpClientHandler { UseDefaultCredentials = useDefaultCredentials };
}
private readonly static Queue<HttpMessageHandler> MockHandlerQueue = new Queue<HttpMessageHandler>();
public static void AddMockHandler(HttpMessageHandler mockHandler)
{
MockHandlerQueue.Enqueue(mockHandler);
}
public static void ClearMockHandlers()
{
MockHandlerQueue.Clear();
}
}
}
|
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// 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.Net.Http;
namespace Microsoft.IdentityModel.Clients.ActiveDirectory
{
internal static class HttpMessageHandlerFactory
{
internal static HttpMessageHandler GetMessageHandler(bool useDefaultCredentials)
{
if (MockHandlerList.Count > 0)
{
HttpMessageHandler retVal = MockHandlerList[0];
MockHandlerList.RemoveAt(0);
return retVal;
}
return new HttpClientHandler { UseDefaultCredentials = useDefaultCredentials };
}
private readonly static List<HttpMessageHandler> MockHandlerList = new List<HttpMessageHandler>();
public static void AddMockHandler(HttpMessageHandler mockHandler)
{
MockHandlerList.Add(mockHandler);
}
public static void ClearMockHandlers()
{
MockHandlerList.Clear();
}
}
}
|
mit
|
C#
|
27f4dc9a39ff6ec733ec215f4a3abbd8e210168b
|
Put performance test into separate method in console.
|
kangkot/ArangoDB-NET,yojimbo87/ArangoDB-NET
|
src/Arango/Arango.ConsoleTests/Program.cs
|
src/Arango/Arango.ConsoleTests/Program.cs
|
using System;
using System.Collections.Generic;
using Arango.Client;
using Arango.fastJSON;
namespace Arango.ConsoleTests
{
class Program
{
public static void Main(string[] args)
{
//PerformanceTests();
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
static void PerformanceTests()
{
var performance = new Performance();
//performance.TestSimpleSequentialHttpPostRequests();
//performance.TestRestSharpHttpPostRequests();
//performance.TestSimpleParallelHttpPostRequests();
performance.Dispose();
}
}
}
|
using System;
using System.Collections.Generic;
using Arango.Client;
using Arango.fastJSON;
namespace Arango.ConsoleTests
{
class Program
{
public static void Main(string[] args)
{
var performance = new Performance();
//performance.TestSimpleSequentialHttpPostRequests();
//performance.TestRestSharpHttpPostRequests();
//performance.TestSimpleParallelHttpPostRequests();
performance.Dispose();
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
|
mit
|
C#
|
5e08400bff4635e05dced57f86b66e0539cde964
|
Add XML comments to TraceLogAttribute
|
YevgeniyShunevych/Atata,YevgeniyShunevych/Atata,atata-framework/atata,atata-framework/atata
|
src/Atata/Attributes/TraceLogAttribute.cs
|
src/Atata/Attributes/TraceLogAttribute.cs
|
using System;
namespace Atata
{
/// <summary>
/// Indicates that component log messages should be written with <see cref="LogLevel.Trace"/> log level instead of <see cref="LogLevel.Info"/>.
/// Attribute is useful for sub-controls of complex controls to keep info log cleaner by skipping sub-control interactional log messages.
/// </summary>
/// <seealso cref="System.Attribute" />
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Property)]
public class TraceLogAttribute : Attribute
{
}
}
|
using System;
namespace Atata
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Property)]
public class TraceLogAttribute : Attribute
{
}
}
|
apache-2.0
|
C#
|
4506b7f3c71751b979af49f208476e42e74baabe
|
Add Equality checks to TopicAndPartitionValue
|
HCanber/kafkaclient-net
|
src/KafkaClient/TopicAndPartitionValue.cs
|
src/KafkaClient/TopicAndPartitionValue.cs
|
using System;
using System.Collections.Generic;
using Kafka.Client.Api;
namespace Kafka.Client
{
public class TopicAndPartitionValue<T> : IEquatable<TopicAndPartitionValue<T>>
{
private readonly TopicAndPartition _topicAndPartition;
private readonly T _value;
public TopicAndPartitionValue(TopicAndPartition topicAndPartition, T value)
{
if(topicAndPartition == null) throw new ArgumentNullException("topicAndPartition");
_topicAndPartition = topicAndPartition;
_value = value;
}
public TopicAndPartition TopicAndPartition
{
get { return _topicAndPartition; }
}
public T Value
{
get { return _value; }
}
public bool Equals(TopicAndPartitionValue<T> other)
{
if(ReferenceEquals(null, other)) return false;
if(ReferenceEquals(this, other)) return true;
return Equals(_topicAndPartition, other._topicAndPartition) && EqualityComparer<T>.Default.Equals(_value, other._value);
}
public override bool Equals(object obj)
{
if(ReferenceEquals(null, obj)) return false;
if(ReferenceEquals(this, obj)) return true;
if(obj.GetType() != this.GetType()) return false;
return Equals((TopicAndPartitionValue<T>) obj);
}
public override int GetHashCode()
{
unchecked
{
return _topicAndPartition.GetHashCode()*397 ^ EqualityComparer<T>.Default.GetHashCode(_value);
}
}
public static bool operator ==(TopicAndPartitionValue<T> left, TopicAndPartitionValue<T> right)
{
return Equals(left, right);
}
public static bool operator !=(TopicAndPartitionValue<T> left, TopicAndPartitionValue<T> right)
{
return !Equals(left, right);
}
}
}
|
using Kafka.Client.Api;
namespace Kafka.Client
{
public class TopicAndPartitionValue<T>
{
private readonly TopicAndPartition _topicAndPartition;
private readonly T _value;
public TopicAndPartitionValue(TopicAndPartition topicAndPartition, T value)
{
_topicAndPartition = topicAndPartition;
_value = value;
}
public TopicAndPartition TopicAndPartition
{
get { return _topicAndPartition; }
}
public T Value
{
get { return _value; }
}
}
}
|
mit
|
C#
|
49f24852c4b668a1dc076d79176e300d08e1389e
|
Fix for coverage
|
Kralizek/Nybus,Nybus-project/Nybus
|
src/Nybus/Utils/MessageDescriptorStore.cs
|
src/Nybus/Utils/MessageDescriptorStore.cs
|
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Nybus.Utils
{
public class MessageDescriptorStore : IMessageDescriptorStore
{
private readonly IDictionary<Type, MessageDescriptor> _descriptorsByType = new Dictionary<Type, MessageDescriptor>();
private readonly IDictionary<MessageDescriptor, Type> _typesByDescriptor = new Dictionary<MessageDescriptor, Type>(MessageDescriptor.EqualityComparer);
private readonly object _lock = new object();
public bool RegisterType(Type type)
{
lock (_lock)
{
if (!_descriptorsByType.ContainsKey(type) && TryGetDescriptorFromAttribute(type, out var descriptor) && !_typesByDescriptor.ContainsKey(descriptor))
{
_descriptorsByType.Add(type, descriptor);
_typesByDescriptor.Add(descriptor, type);
return true;
}
return false;
}
}
private bool TryGetDescriptorFromAttribute(Type type, out MessageDescriptor descriptor)
{
var attribute = type.GetCustomAttribute<MessageAttribute>();
if (attribute == null)
{
descriptor = MessageDescriptor.CreateFromType(type);
return true;
}
descriptor = MessageDescriptor.CreateFromAttribute(attribute);
return true;
}
public bool TryGetDescriptorForType(Type type, out MessageDescriptor descriptor) => _descriptorsByType.TryGetValue(type, out descriptor);
public bool TryGetTypeForDescriptor(MessageDescriptor descriptor, out Type type) => _typesByDescriptor.TryGetValue(descriptor, out type);
}
}
|
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Nybus.Utils
{
public class MessageDescriptorStore : IMessageDescriptorStore
{
private readonly IDictionary<Type, MessageDescriptor> _descriptorsByType = new Dictionary<Type, MessageDescriptor>();
private readonly IDictionary<MessageDescriptor, Type> _typesByDescriptor = new Dictionary<MessageDescriptor, Type>(MessageDescriptor.EqualityComparer);
private readonly object _lock = new object();
public bool RegisterType(Type type)
{
lock (_lock)
{
if (!_descriptorsByType.ContainsKey(type))
{
var descriptor = GetDescriptorForType(type);
if (!_typesByDescriptor.ContainsKey(descriptor))
{
_descriptorsByType.Add(type, descriptor);
_typesByDescriptor.Add(descriptor, type);
return true;
}
}
return false;
}
}
private MessageDescriptor GetDescriptorForType(Type type)
{
var attribute = type.GetCustomAttribute<MessageAttribute>();
if (attribute == null)
{
return type;
}
return MessageDescriptor.CreateFromAttribute(attribute);
}
public bool TryGetDescriptorForType(Type type, out MessageDescriptor descriptor) => _descriptorsByType.TryGetValue(type, out descriptor);
public bool TryGetTypeForDescriptor(MessageDescriptor descriptor, out Type type) => _typesByDescriptor.TryGetValue(descriptor, out type);
}
}
|
mit
|
C#
|
5b0e8831f6f68bc316d941fd5bb027b6f3914716
|
Handle invalid public keys in the SignatureEvidence class
|
openchain/openchain
|
src/Openchain.Ledger/SignatureEvidence.cs
|
src/Openchain.Ledger/SignatureEvidence.cs
|
// Copyright 2015 Coinprism, Inc.
//
// 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;
namespace Openchain.Ledger
{
/// <summary>
/// Represents a digital signature.
/// </summary>
public class SignatureEvidence
{
public SignatureEvidence(ByteString publicKey, ByteString signature)
{
this.PublicKey = publicKey;
this.Signature = signature;
}
/// <summary>
/// Gets the public key corresponding to the signature.
/// </summary>
public ByteString PublicKey { get; }
/// <summary>
/// Gets the digital signature.
/// </summary>
public ByteString Signature { get; }
/// <summary>
/// Verify that the signature is valid.
/// </summary>
/// <param name="mutationHash">The data being signed.</param>
/// <returns>A boolean indicating wheather the signature is valid.</returns>
public bool VerifySignature(byte[] mutationHash)
{
ECKey key;
try
{
key = new ECKey(PublicKey.ToByteArray());
}
catch (ArgumentException)
{
return false;
}
catch (IndexOutOfRangeException)
{
return false;
}
return key.VerifySignature(mutationHash, Signature.ToByteArray());
}
}
}
|
// Copyright 2015 Coinprism, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Openchain.Ledger
{
/// <summary>
/// Represents a digital signature.
/// </summary>
public class SignatureEvidence
{
public SignatureEvidence(ByteString publicKey, ByteString signature)
{
this.PublicKey = publicKey;
this.Signature = signature;
}
/// <summary>
/// Gets the public key corresponding to the signature.
/// </summary>
public ByteString PublicKey { get; }
/// <summary>
/// Gets the digital signature.
/// </summary>
public ByteString Signature { get; }
/// <summary>
/// Verify that the signature is valid.
/// </summary>
/// <param name="mutationHash">The data being signed.</param>
/// <returns>A boolean indicating wheather the signature is valid.</returns>
public bool VerifySignature(byte[] mutationHash)
{
ECKey key = new ECKey(PublicKey.ToByteArray());
return key.VerifySignature(mutationHash, Signature.ToByteArray());
}
}
}
|
apache-2.0
|
C#
|
600e8ed184ed4a62ede085c621349c188c6bc5f4
|
remove bio text
|
sitereactor/Umbraco-Lunch-App,sitereactor/Umbraco-Lunch-App
|
Chainbox.FoodApp.Web/Views/Partials/RegisterPartial.cshtml
|
Chainbox.FoodApp.Web/Views/Partials/RegisterPartial.cshtml
|
@using Chainbox.FoodApp.Controllers
@model Chainbox.FoodApp.ViewModels.RegisterModel
@using (Html.BeginUmbracoForm<RegisterController>("Register"))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>RegisterModel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
@Html.PasswordFor(model => model.Password)
@Html.ValidationMessageFor(model => model.Password)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
|
@using Chainbox.FoodApp.Controllers
@model Chainbox.FoodApp.ViewModels.RegisterModel
@using (Html.BeginUmbracoForm<RegisterController>("Register"))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>RegisterModel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
@Html.PasswordFor(model => model.Password)
@Html.ValidationMessageFor(model => model.Password)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Biography)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
|
mit
|
C#
|
eecae24d8ca2d6e959fa7a8f11038c8cda151419
|
Update RenameNamedRange.cs
|
aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET
|
Examples/CSharp/Data/AddOn/NamedRanges/RenameNamedRange.cs
|
Examples/CSharp/Data/AddOn/NamedRanges/RenameNamedRange.cs
|
using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Data.AddOn.NamedRanges
{
public class RenameNamedRange
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Open an existing Excel file that has a (global) named range "TestRange" in it
Workbook workbook = new Workbook(dataDir + "book1.xls");
//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
//Get the Cells of the sheet
Cells cells = sheet.Cells;
//Get the named range "MyRange"
Name name = workbook.Worksheets.Names["TestRange"];
//Rename it
name.Text = "NewRange";
//Save the Excel file
workbook.Save(dataDir + "RenamingRange.out.xlsx");
//ExEnd:1
}
}
}
|
using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Data.AddOn.NamedRanges
{
public class RenameNamedRange
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Open an existing Excel file that has a (global) named range "TestRange" in it
Workbook workbook = new Workbook(dataDir + "book1.xls");
//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
//Get the Cells of the sheet
Cells cells = sheet.Cells;
//Get the named range "MyRange"
Name name = workbook.Worksheets.Names["TestRange"];
//Rename it
name.Text = "NewRange";
//Save the Excel file
workbook.Save(dataDir + "RenamingRange.out.xlsx");
}
}
}
|
mit
|
C#
|
de8c7b4e54655e911a1de4dfbd9297c244876490
|
Refactor Pinger to give 1000ms timeout.
|
frozenskys/Helpers
|
Frozenskys.Helpers/Pinger.cs
|
Frozenskys.Helpers/Pinger.cs
|
namespace Frozenskys.Helpers
{
using System.Net;
using System.Net.Sockets;
public class Pinger
{
public string Send(IPAddress address)
{
var status = "";
using (var client = new TcpClient())
{
if (!client.ConnectAsync(address, 443).Wait(1000))
{
status = "No Connection";
}
else
{
status = "Ok";
}
}
return status;
}
}
}
|
namespace Frozenskys.Helpers
{
using System.Net;
using System.Net.Sockets;
public class Pinger
{
public string Send(IPAddress address)
{
using (var sckt = new TcpClient())
{
try
{
sckt.Connect(address, 443);
if (sckt.Connected)
{
sckt.Close();
return "Ok";
}
}
catch
{
return "No Connection";
}
}
return "Errm";
}
}
}
|
mit
|
C#
|
ec7c64a05f7cf542511b6534dd991200e208e089
|
Add client function
|
pgh7092/TessOCRMFC,pgh7092/TessOCRMFC
|
Form1.cs
|
Form1.cs
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net.Sockets;
namespace TessOCR
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnFileOpen_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "이미지파일|*.jpg;*.jpeg;*.png";
openFileDialog1.Title = "이미지열기";
openFileDialog1.FileName = "";
openFileDialog1.ShowDialog();
if (openFileDialog1.FileName != null)
textBox1.Text = openFileDialog1.FileName;
}
private void button1_Click(object sender, EventArgs e)
{
byte[] data = new Byte[1024];
String test = textBox1.Text;
//서버로 이미지 전송
using (var tcp = new TcpClient("192.168.188.128", 5007))
{
byte[] image = File.ReadAllBytes(test);
tcp.GetStream().Write(image, 0, image.Length);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TessOCR
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnFileOpen_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "이미지파일|*.jpg;*.jpeg;*.png";
openFileDialog1.Title = "이미지열기";
openFileDialog1.FileName = "";
openFileDialog1.ShowDialog();
if (openFileDialog1.FileName != null)
textBox1.Text = openFileDialog1.FileName;
}
}
}
|
mit
|
C#
|
4135fa340c7ae7623d84a66b5cd7466ced675c76
|
Fix console project.
|
haefele/YnabApi,haefele/Ynab
|
src/Console/Program.cs
|
src/Console/Program.cs
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ynab;
using Ynab.Desktop;
using Ynab.DeviceActions;
using Ynab.Dropbox;
using Ynab.Items;
namespace Console
{
class Program
{
public static void Main(string[] args)
{
Run().Wait();
}
private static async Task Run()
{
var watch = Stopwatch.StartNew();
var dropboxFileSystem = new DropboxFileSystem("");
var desktopFileSystem = new DesktopFileSystem();
YnabApi api = new YnabApi(desktopFileSystem);
var budgets = await api.GetBudgetsAsync();
var testBudget = budgets.First(f => f.BudgetName == "Test-Budget");
var registeredDevice = await testBudget.RegisterDevice(Environment.MachineName);
var allDevices = await testBudget.GetRegisteredDevicesAsync();
var fullKnowledgeDevice = allDevices.First(f => f.HasFullKnowledge);
var createPayee = new CreatePayeeDeviceAction
{
Name = "Bücherei"
};
var createTransaction = new CreateTransactionDeviceAction
{
Amount = -20.0m,
Account = (await fullKnowledgeDevice.GetAccountsAsync()).First(f => f.Name == "Geldbeutel"),
Category = null,
Memo = "#Mittagspause",
Payee = createPayee
};
await registeredDevice.ExecuteActions(createPayee, createTransaction);
watch.Stop();
System.Console.WriteLine(watch.Elapsed);
System.Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ynab;
using Ynab.Desktop;
using Ynab.DeviceActions;
using Ynab.Dropbox;
using Ynab.Items;
namespace Console
{
class Program
{
public static void Main(string[] args)
{
Run().Wait();
}
private static async Task Run()
{
var watch = Stopwatch.StartNew();
var dropboxFileSystem = new DropboxFileSystem("");
var desktopFileSystem = new DesktopFileSystem();
YnabApi api = new YnabApi(dropboxFileSystem);
var budgets = await api.GetBudgetsAsync();
var testBudget = budgets.First(f => f.BudgetName == "Test-Budget");
var registeredDevice = await testBudget.RegisterDevice(Environment.MachineName);
var allDevices = await testBudget.GetRegisteredDevicesAsync();
var fullKnowledgeDevice = allDevices.First(f => f.HasFullKnowledge);
var createPayee = new CreatePayeeDeviceAction
{
Name = "Bücherei"
};
var createTransaction = new CreateTransactionDeviceAction
{
Amount = -20.0m,
Account = (await fullKnowledgeDevice.GetAccountsAsync()).First(f => f.Name == "Geldbeutel"),
Category = new Category(),
Memo = "#Mittagspause",
Payee = createPayee
};
await registeredDevice.ExecuteActions(createPayee, createTransaction);
watch.Stop();
System.Console.WriteLine(watch.Elapsed);
System.Console.ReadLine();
}
}
}
|
mit
|
C#
|
6c50b7790204ce88653c2341839a8ff09147360c
|
fix array definiton
|
overtools/OWLib,kerzyte/OWLib
|
OWLib/Types/STUD/Subtitle.cs
|
OWLib/Types/STUD/Subtitle.cs
|
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace OWLib.Types.STUD {
[System.Diagnostics.DebuggerDisplay(OWLib.STUD.STUD_DEBUG_STR)]
public class Subtitle : ISTUDInstance {
// Subtitle is instance 1 (remember that we're programmers here) in 071 files.
public uint Id => 0x190D4773;
public string Name => "Subtitle";
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct SubtitleData {
public STUDInstanceInfo instance;
public uint arrayInfoOffset; // 96
public uint unk2; // 0
public uint unk3; // 0
public uint unk4; // 0
public uint unk5; // 0
public uint unk6; // 0
}
private SubtitleData data;
private string str;
public SubtitleData Data => data;
public string String => str;
public void Read(Stream input, OWLib.STUD stud) {
using (BinaryReader reader = new BinaryReader(input, Encoding.UTF8, true)) {
data = reader.Read<SubtitleData>();
input.Position = data.arrayInfoOffset;
// seems to use nonstandard array, defined by two uints, with one uint inbetween
uint count = reader.Read<uint>();
reader.Read<uint>(); // unk7, seems to be apart of the array definiton
uint offset = reader.Read<uint>();
if (count > 0) {
input.Position = offset;
str = new string(reader.ReadChars((int)count));
} else {
str = "";
}
}
}
}
}
|
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace OWLib.Types.STUD {
[System.Diagnostics.DebuggerDisplay(OWLib.STUD.STUD_DEBUG_STR)]
public class Subtitle : ISTUDInstance {
// Subtitle is instance 1 (remember that we're programmers here) in 071 files.
public uint Id => 0x190D4773;
public string Name => "Subtitle";
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct SubtitleData {
public STUDInstanceInfo instance;
public uint unk1; // 96
public uint unk2; // 0
public uint unk3; // 0
public uint unk4; // 0
public uint unk5; // 0
public uint unk6; // 0
public uint count;
public uint unk7;
public uint offset;
}
private SubtitleData data;
private string str;
public SubtitleData Data => data;
public string String => str;
public void Read(Stream input, OWLib.STUD stud) {
using (BinaryReader reader = new BinaryReader(input, Encoding.UTF8, true)) {
data = reader.Read<SubtitleData>();
char[] chars = new char[data.count];
if (data.count > 0) {
// seems to use nonstandard array, defined by two uints, with one uint inbetween
// see length, unk7, offset
input.Position = data.offset;
chars = reader.ReadChars((int)data.count);
}
str = new string(chars);
}
}
}
}
|
mit
|
C#
|
975e88077ce6134883311e6e595a358bbc0c74f2
|
test page object fix
|
Softlr/selenium-webdriver-extensions,RaYell/selenium-webdriver-extensions,Softlr/Selenium.WebDriver.Extensions,Softlr/selenium-webdriver-extensions
|
test/Selenium.WebDriver.Extensions.IntegrationTests/TestPage.cs
|
test/Selenium.WebDriver.Extensions.IntegrationTests/TestPage.cs
|
namespace Selenium.WebDriver.Extensions.IntegrationTests
{
using System;
using System.Diagnostics.CodeAnalysis;
using JetBrains.Annotations;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
using static Suppress.Category;
using static Suppress.CodeCracker;
[PublicAPI]
[ExcludeFromCodeCoverage]
internal class TestPage
{
private IWebDriver _driver;
[SuppressMessage(CODE_CRACKER, CC0057)]
public TestPage(IWebDriver driver)
{
_driver = driver ?? throw new ArgumentNullException(nameof(driver));
PageFactory.InitElements(driver, this);
}
[FindsBy(How = How.Custom, CustomFinderType = typeof(JQuerySelector), Using = "h1")]
public IWebElement HeadingJQuery { get; set; }
[FindsBy(How = How.Custom, CustomFinderType = typeof(SizzleSelector), Using = "h1")]
public IWebElement HeadingSizzle { get; set; }
}
}
|
namespace Selenium.WebDriver.Extensions.IntegrationTests
{
using System.Diagnostics.CodeAnalysis;
using JetBrains.Annotations;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
[PublicAPI]
[ExcludeFromCodeCoverage]
internal class TestPage
{
private IWebDriver _driver;
[SuppressMessage(Suppress.Category.CODE_CRACKER, Suppress.CodeCracker.CC0057)]
public TestPage(IWebDriver driver) => _driver = driver;
[FindsBy(How = How.Custom, CustomFinderType = typeof(JQuerySelector), Using = "h1")]
public IWebElement HeadingJQuery { get; set; }
[FindsBy(How = How.Custom, CustomFinderType = typeof(SizzleSelector), Using = "h1")]
public IWebElement HeadingSizzle { get; set; }
}
}
|
apache-2.0
|
C#
|
cbdd7cd0a0fe01b2b4f8bfeaad6a9d25bd2a9306
|
Fix "rate app" button in the about page.
|
ValentinMinder/pocketcampus,ValentinMinder/pocketcampus,ValentinMinder/pocketcampus,ValentinMinder/pocketcampus,ValentinMinder/pocketcampus,ValentinMinder/pocketcampus,ValentinMinder/pocketcampus,ValentinMinder/pocketcampus,ValentinMinder/pocketcampus
|
windows/Source/Main.WindowsRuntime/Services/AppRatingService.cs
|
windows/Source/Main.WindowsRuntime/Services/AppRatingService.cs
|
// Copyright (c) PocketCampus.Org 2014-15
// See LICENSE file for more details
// File author: Solal Pirelli
using System;
using Windows.System;
namespace PocketCampus.Main.Services
{
public sealed class AppRatingService : IAppRatingService
{
private const string AppId = "28f8300e-8a84-4e3e-8d68-9a07c5b2a83a";
public async void RequestRating()
{
// FRAMEWORK BUG: This seems to be the only correct way to do it.
// Despite MSDN documentation, other ways (e.g. reviewapp without appid, or REVIEW?PFN=) open Xbox Music...
await Launcher.LaunchUriAsync( new Uri( "ms-windows-store:reviewapp?appid=" + AppId, UriKind.Absolute ) );
}
}
}
|
// Copyright (c) PocketCampus.Org 2014-15
// See LICENSE file for more details
// File author: Solal Pirelli
using System;
using Windows.ApplicationModel;
using Windows.System;
namespace PocketCampus.Main.Services
{
public sealed class AppRatingService : IAppRatingService
{
public async void RequestRating()
{
await Launcher.LaunchUriAsync( new Uri( "ms-windows-store:REVIEW?PFN=" + Package.Current.Id.FamilyName ) );
}
}
}
|
bsd-3-clause
|
C#
|
fb69fdb506d5e8701f08fae42751a18ab5c8b56c
|
Test applies to MsSQLServer 2005/2008
|
ngbrown/nhibernate-core,RogerKratz/nhibernate-core,ManufacturingIntelligence/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,nkreipke/nhibernate-core,gliljas/nhibernate-core,fredericDelaporte/nhibernate-core,ngbrown/nhibernate-core,alobakov/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core,RogerKratz/nhibernate-core,livioc/nhibernate-core,livioc/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core,alobakov/nhibernate-core,nhibernate/nhibernate-core,alobakov/nhibernate-core,lnu/nhibernate-core,gliljas/nhibernate-core,gliljas/nhibernate-core,lnu/nhibernate-core,hazzik/nhibernate-core,gliljas/nhibernate-core,livioc/nhibernate-core,nkreipke/nhibernate-core,ManufacturingIntelligence/nhibernate-core,fredericDelaporte/nhibernate-core,hazzik/nhibernate-core,ngbrown/nhibernate-core,nhibernate/nhibernate-core,ManufacturingIntelligence/nhibernate-core,lnu/nhibernate-core,nkreipke/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core
|
src/NHibernate.Test/NHSpecificTest/NH645/HQLFunctionFixture.cs
|
src/NHibernate.Test/NHSpecificTest/NH645/HQLFunctionFixture.cs
|
using System;
using System.Collections;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Dialect.Function;
using NUnit.Framework;
using Environment=NHibernate.Cfg.Environment;
namespace NHibernate.Test.NHSpecificTest.NH645
{
[TestFixture]
public class HQLFunctionFixture : TestCase
{
private bool appliesToThisDialect = true;
protected override string MappingsAssembly
{
get { return "NHibernate.Test"; }
}
protected override bool AppliesTo(Dialect.Dialect dialect)
{
return appliesToThisDialect;
}
protected override IList Mappings
{
get { return new[] {"HQL.Animal.hbm.xml", "HQL.MaterialResource.hbm.xml"}; }
}
protected override void Configure(Configuration configuration)
{
if (Dialect is MsSql2005Dialect)
configuration.SetProperty(Environment.Dialect, typeof (CustomDialect).AssemblyQualifiedName);
else
appliesToThisDialect = false;
}
/// <summary>
/// Just test the parser can compile, and SqlException is expected.
/// </summary>
[Test]
public void SimpleWhere()
{
Run("from Animal a where freetext(a.Description, 'hey apple car')");
}
[Test]
public void SimpleWhereWithAnotherClause()
{
Run("from Animal a where freetext(a.Description, 'hey apple car') AND 1 = 1");
}
[Test]
public void SimpleWhereWithAnotherClause2()
{
Run("from Animal a where freetext(a.Description, 'hey apple car') AND a.Description <> 'foo'");
}
public void Run(string hql)
{
using(ISession s = OpenSession())
try
{
s.CreateQuery(hql).List();
}
catch (Exception ex)
{
if (ex is QueryException)
Assert.Fail("The parser think that 'freetext' is a boolean function");
}
}
}
public class CustomDialect : MsSql2005Dialect
{
public CustomDialect()
{
RegisterFunction("freetext", new SQLFunctionTemplate(null, "freetext($1,$2)"));
}
}
}
|
using System;
using System.Collections;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Dialect.Function;
using NUnit.Framework;
using Environment=NHibernate.Cfg.Environment;
namespace NHibernate.Test.NHSpecificTest.NH645
{
[TestFixture]
public class HQLFunctionFixture : TestCase
{
protected override string MappingsAssembly
{
get { return "NHibernate.Test"; }
}
protected override IList Mappings
{
get { return new[] {"HQL.Animal.hbm.xml", "HQL.MaterialResource.hbm.xml"}; }
}
protected override void Configure(Configuration configuration)
{
configuration.SetProperty(Environment.Dialect, typeof (CustomDialect).AssemblyQualifiedName);
}
/// <summary>
/// Just test the parser can compile, and SqlException is expected.
/// </summary>
[Test]
public void SimpleWhere()
{
Run("from Animal a where freetext(a.Description, 'hey apple car')");
}
[Test]
public void SimpleWhereWithAnotherClause()
{
Run("from Animal a where freetext(a.Description, 'hey apple car') AND 1 = 1");
}
[Test]
public void SimpleWhereWithAnotherClause2()
{
Run("from Animal a where freetext(a.Description, 'hey apple car') AND a.Description <> 'foo'");
}
public void Run(string hql)
{
using(ISession s = OpenSession())
try
{
s.CreateQuery(hql).List();
}
catch (Exception ex)
{
if (ex is QueryException)
Assert.Fail("The parser think that 'freetext' is a boolean function");
}
}
}
public class CustomDialect : MsSql2005Dialect
{
public CustomDialect()
{
RegisterFunction("freetext", new SQLFunctionTemplate(null, "freetext($1,$2)"));
}
}
}
|
lgpl-2.1
|
C#
|
c5edf3ba2913f8c127d7963361d0885e25cd9610
|
Modify ValuesController
|
gparlakov/chat-teamwork,gparlakov/chat-teamwork
|
WS-Team-Work/Chat.Services/Controllers/ValuesController.cs
|
WS-Team-Work/Chat.Services/Controllers/ValuesController.cs
|
using Chat.Models;
using Chat.Repository;
using Chat.Services.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Chat.Services.Controllers
{
public class ValuesController : ApiController
{
private MessageRepository messageRepository;
public ValuesController()
{
this.messageRepository = new MessageRepository(new Chat.Data.ChatContext());
}
// GET api/values
public IQueryable<MessageModel> Get()
{
var messages = this.messageRepository.All()
.Select(m => new MessageModel
{
Id = m.Id,
Content = m.Content
});
return messages;
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]Message newMessage)
{
this.messageRepository.Add(newMessage);
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
|
using Chat.Models;
using Chat.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Chat.Services.Controllers
{
public class ValuesController : ApiController
{
private MessageRepository messageRepository;
public ValuesController()
{
this.messageRepository = new MessageRepository(new Chat.Data.ChatContext());
}
// GET api/values
public IQueryable<MessageModel> Get()
{
var messages = this.messageRepository.All();
return messages;
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]Message newMessage)
{
this.messageRepository.Add(newMessage);
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
|
mit
|
C#
|
9be1db4f7df99f0b976ad8d991a2c417eec41be4
|
Update ContextTests.cs
|
Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D
|
tests/Core2D.UnitTests/Data/ContextTests.cs
|
tests/Core2D.UnitTests/Data/ContextTests.cs
|
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Core2D.Data;
using Xunit;
namespace Core2D.UnitTests
{
public class ContextTests
{
[Fact]
[Trait("Core2D.Data", "Database")]
public void Inherits_From_ObservableObject()
{
var target = new Context();
Assert.True(target is ObservableObject);
}
[Fact]
[Trait("Core2D.Data", "Database")]
public void Properties_Not_Null()
{
var target = new Context();
Assert.False(target.Properties.IsDefault);
}
[Fact]
[Trait("Core2D.Data", "Database")]
public void This_Operator_Returns_Null()
{
var target = new Context();
Assert.Null(target["Name1"]);
}
[Fact]
[Trait("Core2D.Data", "Database")]
public void This_Operator_Returns_Property_Value()
{
var target = new Context();
target.Properties = target.Properties.Add(Property.Create(target, "Name1", "Value1"));
Assert.Equal("Value1", target["Name1"]);
}
[Fact]
[Trait("Core2D.Data", "Database")]
public void This_Operator_Sets_Property_Value()
{
var target = new Context();
target.Properties = target.Properties.Add(Property.Create(target, "Name1", "Value1"));
target["Name1"] = "NewValue1";
Assert.Equal("NewValue1", target["Name1"]);
}
[Fact]
[Trait("Core2D.Data", "Database")]
public void This_Operator_Creates_Property()
{
var target = new Context();
Assert.Empty(target.Properties);
target["Name1"] = "Value1";
Assert.Equal("Value1", target.Properties[0].Value);
Assert.Equal(target, target.Properties[0].Owner);
}
}
}
|
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Core2D.Data;
using Xunit;
namespace Core2D.UnitTests
{
public class ContextTests
{
[Fact]
[Trait("Core2D.Data", "Database")]
public void Inherits_From_ObservableObject()
{
var target = new Context();
Assert.True(target is ObservableObject);
}
[Fact]
[Trait("Core2D.Data", "Database")]
public void Properties_Not_Null()
{
var target = new Context();
Assert.False(target.Properties.IsDefault);
}
[Fact]
[Trait("Core2D.Data", "Database")]
public void This_Operator_Returns_Null()
{
var target = new Context();
Assert.Null(target["Name1"]);
}
[Fact]
[Trait("Core2D.Data", "Database")]
public void This_Operator_Returns_Property_Value()
{
var target = new Context();
target.Properties = target.Properties.Add(Property.Create(target, "Name1", "Value1"));
Assert.Equal("Value1", target["Name1"]);
}
[Fact]
[Trait("Core2D.Data", "Database")]
public void This_Operator_Sets_Property_Value()
{
var target = new Context();
target.Properties = target.Properties.Add(Property.Create(target, "Name1", "Value1"));
target["Name1"] = "NewValue1";
Assert.Equal("NewValue1", target["Name1"]);
}
[Fact]
[Trait("Core2D.Data", "Database")]
public void This_Operator_Creates_Property()
{
var target = new Context();
Assert.Empty(target.Properties);
target["Name1"] = "Value1";
Assert.Contains("Value1", target.Properties);
Assert.Equal(target, target.Properties[0].Owner);
}
}
}
|
mit
|
C#
|
974ed711ecbc4b1300f9aab58b52253450691055
|
Fix timing problem with SettingProtectionHelper
|
hatton/libpalaso,marksvc/libpalaso,marksvc/libpalaso,hatton/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,gtryus/libpalaso,ddaspit/libpalaso,glasseyes/libpalaso,mccarthyrb/libpalaso,darcywong00/libpalaso,JohnThomson/libpalaso,andrew-polk/libpalaso,tombogle/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,chrisvire/libpalaso,darcywong00/libpalaso,mccarthyrb/libpalaso,ddaspit/libpalaso,ermshiperete/libpalaso,hatton/libpalaso,JohnThomson/libpalaso,glasseyes/libpalaso,tombogle/libpalaso,hatton/libpalaso,darcywong00/libpalaso,ddaspit/libpalaso,tombogle/libpalaso,gmartin7/libpalaso,chrisvire/libpalaso,gtryus/libpalaso,tombogle/libpalaso,JohnThomson/libpalaso,chrisvire/libpalaso,marksvc/libpalaso,ermshiperete/libpalaso,chrisvire/libpalaso,mccarthyrb/libpalaso,gmartin7/libpalaso,glasseyes/libpalaso,gtryus/libpalaso,sillsdev/libpalaso,JohnThomson/libpalaso,gtryus/libpalaso,andrew-polk/libpalaso,ermshiperete/libpalaso,andrew-polk/libpalaso,andrew-polk/libpalaso,ermshiperete/libpalaso,glasseyes/libpalaso,ddaspit/libpalaso,mccarthyrb/libpalaso,sillsdev/libpalaso
|
PalasoUIWindowsForms/SettingProtection/SettingsLauncherHelper.cs
|
PalasoUIWindowsForms/SettingProtection/SettingsLauncherHelper.cs
|
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace Palaso.UI.WindowsForms.SettingProtection
{
/// <summary>
/// This class takes an Settings-launching control & adds the behaviors needed to conform to the standard SIL "Rice Farmer" settings protection behavior.
/// If you use the standard SettingsLauncherButton, you don't have to worry about this class (it uses this). But if you have a need custom control for look/feel,
/// then add this compenent to the form and, *in code*, set the CustomSettingsControl. When you control is clicked, have it call LaunchSettingsIfAppropriate()
/// </summary>
public partial class SettingsLauncherHelper : Component
{
private Control _customSettingsControl;
public SettingsLauncherHelper(IContainer container)
{
InitializeComponent();
if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
{
if(container!=null)
container.Add(this);
_checkForCtrlKeyTimer.Enabled = true;
}
}
/// <summary>
/// The control we are suppose to help.
/// </summary>
public Control CustomSettingsControl
{
set
{
if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
{
_customSettingsControl = value;
UpdateDisplay();
}
}
}
/// <summary>
/// The control should call this when the user clicks on it. It will challenge if necessary, and carry out the supplied code if everything is rosy.
/// </summary>
/// <param name="settingsLaunchingFunction"></param>
/// <returns>DialogResult.Cancel if the challenge fails, otherwise whatever the settingsLaunchingFunction returns.</returns>
public DialogResult LaunchSettingsIfAppropriate(Func<DialogResult> settingsLaunchingFunction)
{
if (SettingsProtectionSingleton.Configuration.RequirePassword)
{
using (var dlg = new SettingsPasswordDialog(SettingsProtectionSingleton.FactoryPassword, SettingsPasswordDialog.Mode.Challenge))
{
if (DialogResult.OK != dlg.ShowDialog())
return DialogResult.Cancel;
}
}
var result = settingsLaunchingFunction();
UpdateDisplay();
return result;
}
private void UpdateDisplay()
{
if (_customSettingsControl == null)//sometimes get a tick before this has been set
return;
var keys = (Keys.Control | Keys.Shift);
_customSettingsControl.Visible = !SettingsProtectionSingleton.Configuration.NormallyHidden
|| ((Control.ModifierKeys & keys) == keys);
}
private void _checkForCtrlKeyTimer_Tick(object sender, EventArgs e)
{
UpdateDisplay();
}
}
}
|
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace Palaso.UI.WindowsForms.SettingProtection
{
/// <summary>
/// This class takes an Settings-launching control & adds the behaviors needed to conform to the standard SIL "Rice Farmer" settings protection behavior.
/// If you use the standard SettingsLauncherButton, you don't have to worry about this class (it uses this). But if you have a need custom control for look/feel,
/// then add this compenent to the form and, *in code*, set the CustomSettingsControl. When you control is clicked, have it call LaunchSettingsIfAppropriate()
/// </summary>
public partial class SettingsLauncherHelper : Component
{
private Control _customSettingsControl;
public SettingsLauncherHelper(IContainer container)
{
InitializeComponent();
if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
{
if(container!=null)
container.Add(this);
_checkForCtrlKeyTimer.Enabled = true;
}
}
/// <summary>
/// The control we are suppose to help.
/// </summary>
public Control CustomSettingsControl
{
set
{
if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
{
_customSettingsControl = value;
UpdateDisplay();
}
}
}
/// <summary>
/// The control should call this when the user clicks on it. It will challenge if necessary, and carry out the supplied code if everything is rosy.
/// </summary>
/// <param name="settingsLaunchingFunction"></param>
/// <returns>DialogResult.Cancel if the challenge fails, otherwise whatever the settingsLaunchingFunction returns.</returns>
public DialogResult LaunchSettingsIfAppropriate(Func<DialogResult> settingsLaunchingFunction)
{
if (SettingsProtectionSingleton.Configuration.RequirePassword)
{
using (var dlg = new SettingsPasswordDialog(SettingsProtectionSingleton.FactoryPassword, SettingsPasswordDialog.Mode.Challenge))
{
if (DialogResult.OK != dlg.ShowDialog())
return DialogResult.Cancel;
}
}
var result = settingsLaunchingFunction();
UpdateDisplay();
return result;
}
private void UpdateDisplay()
{
var keys = (Keys.Control | Keys.Shift);
_customSettingsControl.Visible = !SettingsProtectionSingleton.Configuration.NormallyHidden
|| ((Control.ModifierKeys & keys) == keys);
}
private void _checkForCtrlKeyTimer_Tick(object sender, EventArgs e)
{
UpdateDisplay();
}
}
}
|
mit
|
C#
|
41f0b3bac08392ca3b2a9360e435618791a898c5
|
fix comments in program class.
|
c0c0n3/winice
|
nice/Program.cs
|
nice/Program.cs
|
using System;
namespace nice
{
/// <summary>
/// Simple (or better, simplistic) program that mimics Unix's <c>nice</c>.
/// </summary>
class Program
{
ArgumentsParser Parser { get; set; }
Program(string[] args)
{
Parser = new ArgumentsParser(args);
}
ITask LookupTask()
{
IArguments a = Parser.Parse();
if (a is NoArguments)
{
return new PrintPriority();
}
if (a is SetPriorityArguments)
{
return new ExecWithPriority((SetPriorityArguments)a);
}
throw new MissingMethodException("no task for: " + a.GetType());
}
void Run()
{
int status = ExitCode.Ok;
try
{
status = LookupTask().Run();
} catch (ParseException e) {
Console.Error.WriteLine(e.Message);
status = ExitCode.InvalidArgs;
} catch (Exception e) {
Console.Error.WriteLine(e);
status = ExitCode.InternalError;
}
Environment.Exit(status);
}
static void Main(string[] args)
{
new Program(args).Run();
}
}
}
|
using System;
namespace nice
{
/// <summary>
/// Simple (or better, simplistic) program to mimic Unix's <c>nice</c>.
/// </summary>
/// <remarks>
/// TODO
/// NB only supports two ways:
/// 1. nice -n v cmd ...
/// 2. nice
///
/// </remarks>
class Program
{
ArgumentsParser Parser { get; set; }
Program(string[] args)
{
Parser = new ArgumentsParser(args);
}
ITask LookupTask()
{
IArguments a = Parser.Parse();
if (a is NoArguments)
{
return new PrintPriority();
}
if (a is SetPriorityArguments)
{
return new ExecWithPriority((SetPriorityArguments)a);
}
throw new MissingMethodException("no task for: " + a.GetType());
}
void Run()
{
int status = ExitCode.Ok;
try
{
status = LookupTask().Run();
} catch (ParseException e) {
Console.Error.WriteLine(e.Message);
status = ExitCode.InvalidArgs;
} catch (Exception e) {
Console.Error.WriteLine(e);
status = ExitCode.InternalError;
}
Environment.Exit(status);
}
static void Main(string[] args)
{
new Program(args).Run();
}
}
}
|
mit
|
C#
|
584bcd8b0040e18bcdcd1cb067cd31d944209c3e
|
Update TypeExtension.cs
|
NMSLanX/Natasha
|
src/Natasha/ExtensionApi/TypeExtension.cs
|
src/Natasha/ExtensionApi/TypeExtension.cs
|
using System;
using System.Collections.Generic;
namespace Natasha
{
public static class TypeExtension
{
public static bool IsSimpleType(this Type type)
{
return type.IsValueType || type == typeof(string) || type == typeof(Delegate) || type == typeof(MulticastDelegate);
}
public static bool IsImplementFrom(this Type type,Type iType)
{
HashSet<Type> types = new HashSet<Type>(type.GetInterfaces());
return types.Contains(iType);
}
public static bool IsImplementFrom<T>(this Type type)
{
HashSet<Type> types = new HashSet<Type>(type.GetInterfaces());
return types.Contains(typeof(T));
}
public static List<Type> GetAllGenericTypes(this Type type)
{
List<Type> result = new List<Type>
{
type
};
if (type.IsGenericType && type.FullName != null)
{
foreach (var item in type.GetGenericArguments())
{
result.AddRange(item.GetAllGenericTypes());
}
}
return result;
}
public static List<Type> GetAllGenericTypes<T>()
{
return typeof(T).GetAllGenericTypes();
}
public static string GetAvailableName(this Type type)
{
return AvailableNameReverser.GetName(type);
}
public static string GetDevelopName(this Type type)
{
return TypeNameReverser.GetName(type);
}
public static Type With(this Type type,params Type[] types)
{
return type.MakeGenericType(types);
}
}
}
|
using System;
using System.Collections.Generic;
namespace Natasha
{
public static class TypeExtension
{
public static bool IsImplementFrom(this Type type,Type iType)
{
HashSet<Type> types = new HashSet<Type>(type.GetInterfaces());
return types.Contains(iType);
}
public static bool IsImplementFrom<T>(this Type type)
{
HashSet<Type> types = new HashSet<Type>(type.GetInterfaces());
return types.Contains(typeof(T));
}
public static List<Type> GetAllGenericTypes(this Type type)
{
List<Type> result = new List<Type>
{
type
};
if (type.IsGenericType && type.FullName != null)
{
foreach (var item in type.GetGenericArguments())
{
result.AddRange(item.GetAllGenericTypes());
}
}
return result;
}
public static List<Type> GetAllGenericTypes<T>()
{
return typeof(T).GetAllGenericTypes();
}
public static string GetAvailableName(this Type type)
{
return AvailableNameReverser.GetName(type);
}
public static string GetDevelopName(this Type type)
{
return TypeNameReverser.GetName(type);
}
public static Type With(this Type type,params Type[] types)
{
return type.MakeGenericType(types);
}
public static bool IsOnceType(this Type type)
{
if (type==null){return false;}
return type.IsPrimitive
|| type == typeof(string)
|| type == typeof(Delegate)
|| type.IsEnum
|| type == typeof(object)
|| (!type.IsClass && !type.IsInterface);
}
}
}
|
mpl-2.0
|
C#
|
5040d136173960e7a1744885d44613f440b498a4
|
Update version
|
AdtecSoftware/Adtec.SagePayMvc,JeremySkinner/SagePayMvc,cergis-robert/SagePayMvc,IntegratedArts/SagePayMvc,AdtecSoftware/SagePayMvc
|
src/SagePayMvc/Properties/AssemblyInfo.cs
|
src/SagePayMvc/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("SagePayMvc")]
[assembly: AssemblyDescription("SagePay integration for ASP.NET MVC")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("The Sixth Form College Farnborough")]
[assembly: AssemblyProduct("SagePayMvc")]
[assembly: AssemblyCopyright("Copyright © The Sixth Form College Farnborough")]
[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("e4ae6ce2-795a-4018-a081-44cdf4aba537")]
// 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("3.1.0.0")]
[assembly: AssemblyFileVersion("3.1.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("SagePayMvc")]
[assembly: AssemblyDescription("SagePay integration for ASP.NET MVC")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("The Sixth Form College Farnborough")]
[assembly: AssemblyProduct("SagePayMvc")]
[assembly: AssemblyCopyright("Copyright © The Sixth Form College Farnborough")]
[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("e4ae6ce2-795a-4018-a081-44cdf4aba537")]
// 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("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
|
apache-2.0
|
C#
|
e423c93a16309129228bdc94d0c9680f2a8eec38
|
Fix HelpController for isolated intranet solutions (#7163)
|
hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,madsoulswe/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,NikRimington/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,leekelleher/Umbraco-CMS,NikRimington/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,madsoulswe/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,tcmorris/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,leekelleher/Umbraco-CMS,mattbrailsford/Umbraco-CMS,NikRimington/Umbraco-CMS,tcmorris/Umbraco-CMS,tcmorris/Umbraco-CMS,leekelleher/Umbraco-CMS,leekelleher/Umbraco-CMS,marcemarc/Umbraco-CMS,tcmorris/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abjerner/Umbraco-CMS,abjerner/Umbraco-CMS,bjarnef/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,bjarnef/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,mattbrailsford/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,bjarnef/Umbraco-CMS,bjarnef/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,hfloyd/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,madsoulswe/Umbraco-CMS,hfloyd/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,leekelleher/Umbraco-CMS,KevinJump/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS
|
src/Umbraco.Web/Editors/HelpController.cs
|
src/Umbraco.Web/Editors/HelpController.cs
|
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Threading.Tasks;
namespace Umbraco.Web.Editors
{
public class HelpController : UmbracoAuthorizedJsonController
{
private static HttpClient _httpClient;
public async Task<List<HelpPage>> GetContextHelpForPage(string section, string tree, string baseUrl = "https://our.umbraco.com")
{
var url = string.Format(baseUrl + "/Umbraco/Documentation/Lessons/GetContextHelpDocs?sectionAlias={0}&treeAlias={1}", section, tree);
try
{
if (_httpClient == null)
_httpClient = new HttpClient();
//fetch dashboard json and parse to JObject
var json = await _httpClient.GetStringAsync(url);
var result = JsonConvert.DeserializeObject<List<HelpPage>>(json);
if (result != null)
return result;
}
catch (HttpRequestException rex)
{
Logger.Info(GetType(), $"Check your network connection, exception: {rex.Message}");
}
return new List<HelpPage>();
}
}
[DataContract(Name = "HelpPage")]
public class HelpPage
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "description")]
public string Description { get; set; }
[DataMember(Name = "url")]
public string Url { get; set; }
[DataMember(Name = "type")]
public string Type { get; set; }
}
}
|
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Threading.Tasks;
namespace Umbraco.Web.Editors
{
public class HelpController : UmbracoAuthorizedJsonController
{
private static HttpClient _httpClient;
public async Task<List<HelpPage>> GetContextHelpForPage(string section, string tree, string baseUrl = "https://our.umbraco.com")
{
var url = string.Format(baseUrl + "/Umbraco/Documentation/Lessons/GetContextHelpDocs?sectionAlias={0}&treeAlias={1}", section, tree);
if (_httpClient == null)
_httpClient = new HttpClient();
//fetch dashboard json and parse to JObject
var json = await _httpClient.GetStringAsync(url);
var result = JsonConvert.DeserializeObject<List<HelpPage>>(json);
if (result != null)
return result;
return new List<HelpPage>();
}
}
[DataContract(Name = "HelpPage")]
public class HelpPage
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "description")]
public string Description { get; set; }
[DataMember(Name = "url")]
public string Url { get; set; }
[DataMember(Name = "type")]
public string Type { get; set; }
}
}
|
mit
|
C#
|
ccd2887a1ce0ac73b3f843c9244d7d23695d50ca
|
Update CalendarService.cs
|
marska/wundercal
|
src/Wundercal/Services/CalendarService.cs
|
src/Wundercal/Services/CalendarService.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using DDay.iCal;
using Wundercal.Services.Dto;
namespace Wundercal.Services
{
internal class CalendarService : ICalendarService
{
private readonly IICalendar _calendar;
internal CalendarService(Uri uri)
{
Console.WriteLine("Loading calendar ...");
_calendar = iCalendar.LoadFromUri(uri)[0];
}
public List<CalendarEvent> GetCalendarEvents(DateTime date)
{
Console.WriteLine("Geting calendar events ...");
var occurrences = _calendar.GetOccurrences(new iCalDateTime(date));
var calendarEvents = occurrences
.Select(o => new CalendarEvent(((IRecurringComponent)o.Source).Summary, DateUtil.GetSimpleDateTimeData(o.Period.StartTime)))
.Where(ce => !string.IsNullOrEmpty(ce.Summary))
.ToList();
return calendarEvents;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using DDay.iCal;
using Wundercal.Services.Dto;
namespace Wundercal.Services
{
internal class CalendarService : ICalendarService
{
private readonly IICalendar _calendar;
internal CalendarService(Uri uri)
{
Console.WriteLine("Loading calendar ...");
_calendar = iCalendar.LoadFromUri(uri)[0];
}
public List<CalendarEvent> GetCalendarEvents(DateTime date)
{
Console.WriteLine("Geting calendar events ...");
var calendarEvents = occurrences
.Select(o => new CalendarEvent(((IRecurringComponent)o.Source).Summary, DateUtil.GetSimpleDateTimeData(o.Period.StartTime)))
.Where(ce => !string.IsNullOrEmpty(ce.Summary))
.ToList();
return calendarEvents;
}
}
}
|
apache-2.0
|
C#
|
a6fc1280943dea4a38f1942b7234b65d31726238
|
Fix WaveOverlayContainer always being present
|
DrabWeb/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,2yangk23/osu,UselessToucan/osu,ZLima12/osu,smoogipooo/osu,johnneijzen/osu,DrabWeb/osu,2yangk23/osu,naoey/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,naoey/osu,johnneijzen/osu,EVAST9919/osu,peppy/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,EVAST9919/osu,naoey/osu,DrabWeb/osu,NeoAdonis/osu,peppy/osu-new,ppy/osu,peppy/osu,ZLima12/osu
|
osu.Game/Overlays/WaveOverlayContainer.cs
|
osu.Game/Overlays/WaveOverlayContainer.cs
|
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics;
using osu.Game.Graphics.Containers;
namespace osu.Game.Overlays
{
public abstract class WaveOverlayContainer : OsuFocusedOverlayContainer
{
protected readonly WaveContainer Waves;
protected override bool BlockNonPositionalInput => true;
protected override Container<Drawable> Content => Waves;
protected WaveOverlayContainer()
{
AddInternal(Waves = new WaveContainer
{
RelativeSizeAxes = Axes.Both,
});
}
protected override void PopIn()
{
base.PopIn();
Waves.Show();
this.FadeIn();
}
protected override void PopOut()
{
base.PopOut();
Waves.Hide();
// this is required or we will remain present even though our waves are hidden.
this.Delay(WaveContainer.DISAPPEAR_DURATION).FadeOut();
}
}
}
|
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics;
using osu.Game.Graphics.Containers;
namespace osu.Game.Overlays
{
public abstract class WaveOverlayContainer : OsuFocusedOverlayContainer
{
protected readonly WaveContainer Waves;
protected override bool BlockNonPositionalInput => true;
protected override Container<Drawable> Content => Waves;
protected WaveOverlayContainer()
{
AddInternal(Waves = new WaveContainer
{
RelativeSizeAxes = Axes.Both,
});
}
protected override void PopIn()
{
base.PopIn();
Waves.Show();
}
protected override void PopOut()
{
base.PopOut();
Waves.Hide();
}
}
}
|
mit
|
C#
|
2fdda154f3f6683828e3a332c32a390835fef8c9
|
Use momentjs rather than toLocaleString for better browser support
|
ritterim/AspNetBrowserLocale,kendaleiv/AspNetBrowserLocale
|
src/Core/HtmlHelpers.cs
|
src/Core/HtmlHelpers.cs
|
using System;
using System.Web.Mvc;
namespace AspNetBrowserLocale.Core
{
public static class HtmlHelpers
{
private const string NullValueDisplay = "—";
public static MvcHtmlString InitializeLocaleDateTime(this HtmlHelper htmlHelper)
{
return MvcHtmlString.Create(string.Format(
@"<script>
if (typeof moment === 'undefined') {{
document.write(unescape(""%3Cscript src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js'%3E%3C/script%3E""));
}}
</script>
<script>
(function() {{
'use strict';
var elements = document.querySelectorAll('[data-aspnet-browser-locale]');
for (var i = 0; i < elements.length; i++) {{
var element = elements[i];
var msString = element.dataset.aspnetBrowserLocale;
if (msString) {{
var m = moment(parseInt(msString, 10));
element.innerHTML = m.format('l LT');
}}
else {{
element.innerHTML = '{0}';
}}
}}
}})();
</script>",
NullValueDisplay));
}
public static MvcHtmlString LocaleDateTime(this HtmlHelper htmlHelper, DateTime? dateTime)
{
long? msSinceUnixEpoch = null;
if (dateTime.HasValue)
{
msSinceUnixEpoch = (long)((TimeSpan)(dateTime.Value.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))).TotalMilliseconds;
}
return MvcHtmlString.Create(string.Format(
@"<span data-aspnet-browser-locale=""{0}"">{1}</span>",
msSinceUnixEpoch,
dateTime.HasValue ? dateTime.Value.ToUniversalTime().ToString() + " UTC" : NullValueDisplay));
}
}
}
|
using System;
using System.Web.Mvc;
namespace AspNetBrowserLocale.Core
{
public static class HtmlHelpers
{
private const string NullValueDisplay = "—";
public static MvcHtmlString InitializeLocaleDateTime(this HtmlHelper htmlHelper)
{
return MvcHtmlString.Create(string.Format(
@"<script>
(function() {{
'use strict';
var elements = document.querySelectorAll('[data-aspnet-browser-locale]');
for (var i = 0; i < elements.length; i++) {{
var element = elements[i];
var msString = element.dataset.aspnetBrowserLocale;
if (msString) {{
var jsDate = new Date(parseInt(msString, 10));
element.innerHTML = jsDate.toLocaleString();
}}
else {{
element.innerHTML = '{0}';
}}
}}
}})();
</script>",
NullValueDisplay));
}
public static MvcHtmlString LocaleDateTime(this HtmlHelper htmlHelper, DateTime? dateTime)
{
long? msSinceUnixEpoch = null;
if (dateTime.HasValue)
{
msSinceUnixEpoch = (long)((TimeSpan)(dateTime.Value.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))).TotalMilliseconds;
}
return MvcHtmlString.Create(string.Format(
@"<span data-aspnet-browser-locale=""{0}"">{1}</span>",
msSinceUnixEpoch,
dateTime.HasValue ? dateTime.Value.ToUniversalTime().ToString() + " UTC" : NullValueDisplay));
}
}
}
|
mit
|
C#
|
febd4c5bfdfb808e5ce0d801f539aadf1fede9d4
|
Change text
|
richlander/test-repo
|
foo/Views/Home/Index.cshtml
|
foo/Views/Home/Index.cshtml
|
@using MvcSample.Web.Models
@model User
@{
Layout = "/Views/Shared/_Layout.cshtml";
ViewBag.Title = "Home Page";
string helloClass = null;
}
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
<p><a href="http://asp.net" class="btn btn-primary btn-large">Learn more »</a></p>
</div>
<div class="row">
<h3 title="@Model.Name" class="@helloClass">Hello OS X! Test.</h3>
</div>
|
@using MvcSample.Web.Models
@model User
@{
Layout = "/Views/Shared/_Layout.cshtml";
ViewBag.Title = "Home Page";
string helloClass = null;
}
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
<p><a href="http://asp.net" class="btn btn-primary btn-large">Learn more »</a></p>
</div>
<div class="row">
<h3 title="@Model.Name" class="@helloClass">Hello OS X!</h3>
</div>
|
mit
|
C#
|
4e79cf1e546f4db1613ef0725615e2970c26fc11
|
Update the explosion to appear exactly from the center of the asteroid
|
krasiymihajlov/CSharp_Game_Shooter
|
AsteroidsGame/AsteroidsGame/AsteroidsForm.cs
|
AsteroidsGame/AsteroidsGame/AsteroidsForm.cs
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AsteroidsGame
{
public partial class AsteroidsForm : Form
{
Random rdn = new Random();
SoundPlayer mouseSound = new SoundPlayer("../../Resources/Rocket.wav");
SoundPlayer explodeSound = new SoundPlayer("../../Resources/Bomb.wav");
public AsteroidsForm()
{
InitializeComponent();
ExplodingAsteroid.Hide();
}
private void AsteroidsForm_MouseMove(object sender, MouseEventArgs e)
{
// Show mouse position
mouseXposer.Text = $"X: {e.X} / Y: {e.Y}";
// Convert the cursor to Gunsight
PictureBox gunSight = new PictureBox() { Image = Image.FromFile(@"..\..\Resources\Gunsight.png") };
this.Cursor = new Cursor(((Bitmap)gunSight.Image).GetHicon());
}
private void AsteroidPositionTimer_Tick(object sender, EventArgs e)
{
var x = rdn.Next(Asteroid.Width, this.Width - Asteroid.Width);
var y = rdn.Next(Asteroid.Height, 340);
Asteroid.Location = new Point(x, y);
Asteroid.Show();
ExplodingAsteroid.Hide();
}
// Shot Outside the target
private void AsteroidsForm_MouseClick(object sender, MouseEventArgs e)
{
mouseSound.Play();
// Rocket.BlankShot();
}
// Shot Inside the target
private void Asteroid_MouseClick(object sender, MouseEventArgs e)
{
AsteroidPositionTimer.Stop();
mouseSound.Play();
// Rocket.DestroyTarget(e.X, e.Y);
Asteroid.Hide();
ExplodingAsteroid.Left = Asteroid.Left - 35;
ExplodingAsteroid.Top = Asteroid.Top - 40;
ExplodingAsteroid.Show();
explodeSound.Play();
AsteroidPositionTimer.Start();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AsteroidsGame
{
public partial class AsteroidsForm : Form
{
Random rdn = new Random();
SoundPlayer mouseSound = new SoundPlayer("../../Resources/Rocket.wav");
SoundPlayer explodeSound = new SoundPlayer("../../Resources/Bomb.wav");
public AsteroidsForm()
{
InitializeComponent();
ExplodingAsteroid.Hide();
}
private void AsteroidsForm_MouseMove(object sender, MouseEventArgs e)
{
// Show mouse position
mouseXposer.Text = $"X: {e.X} / Y: {e.Y}";
// Convert the cursor to Gunsight
PictureBox gunSight = new PictureBox() { Image = Image.FromFile(@"..\..\Resources\Gunsight.png") };
this.Cursor = new Cursor(((Bitmap)gunSight.Image).GetHicon());
}
private void AsteroidPositionTimer_Tick(object sender, EventArgs e)
{
var x = rdn.Next(Asteroid.Width, this.Width - Asteroid.Width);
var y = rdn.Next(Asteroid.Height, 340);
Asteroid.Location = new Point(x, y);
Asteroid.Show();
ExplodingAsteroid.Hide();
}
// Shot Outside the target
private void AsteroidsForm_MouseClick(object sender, MouseEventArgs e)
{
mouseSound.Play();
// Rocket.BlankShot();
}
// Shot Inside the target
private void Asteroid_MouseClick(object sender, MouseEventArgs e)
{
AsteroidPositionTimer.Stop();
mouseSound.Play();
// Rocket.DestroyTarget(e.X, e.Y);
Asteroid.Hide();
ExplodingAsteroid.Left = Asteroid.Left;
ExplodingAsteroid.Top = Asteroid.Top;
ExplodingAsteroid.Show();
explodeSound.Play();
AsteroidPositionTimer.Start();
}
}
}
|
mit
|
C#
|
a838942c23a7f289d8fbe9e38eb2f2e1b3818c04
|
Make the SUTA edit text form bigger
|
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
|
Battery-Commander.Web/Views/SUTA/Edit.cshtml
|
Battery-Commander.Web/Views/SUTA/Edit.cshtml
|
@model BatteryCommander.Web.Commands.UpdateSUTARequest
@using (Html.BeginForm("Edit", "SUTA", new { Model.Id }, FormMethod.Post, true, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.Supervisor)
@Html.DropDownListFor(model => model.Body.Supervisor, (IEnumerable<SelectListItem>)ViewBag.Supervisors)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.StartDate)
@Html.EditorFor(model => model.Body.StartDate)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.EndDate)
@Html.EditorFor(model => model.Body.EndDate)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.Reasoning)
@Html.TextAreaFor(model => model.Body.Reasoning, new { cols="40", rows="5" })
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.MitigationPlan)
@Html.TextAreaFor(model => model.Body.MitigationPlan, new { cols="40", rows="5" })
</div>
<button type="submit">Save</button>
}
|
@model BatteryCommander.Web.Commands.UpdateSUTARequest
@using (Html.BeginForm("Edit", "SUTA", new { Model.Id }, FormMethod.Post, true, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.Supervisor)
@Html.DropDownListFor(model => model.Body.Supervisor, (IEnumerable<SelectListItem>)ViewBag.Supervisors)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.StartDate)
@Html.EditorFor(model => model.Body.StartDate)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.EndDate)
@Html.EditorFor(model => model.Body.EndDate)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.Reasoning)
@Html.TextAreaFor(model => model.Body.Reasoning, new { cols="40", rows="5" })
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.MitigationPlan)
@Html.TextAreaFor(model => model.Body.MitigationPlan, new { cols="40", rows="5" })
</div>
<button type="submit">Save</button>
}
|
mit
|
C#
|
9f7a798adcf1217d4f14b268997c2e70b3c65b56
|
Add missing setters in the DTO
|
Gatecoin/api-gatecoin-dotnet,Gatecoin/API_client_csharp,Gatecoin/api-gatecoin-dotnet
|
Model/Currency.cs
|
Model/Currency.cs
|
using ServiceStack.ServiceInterface.ServiceModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GatecoinServiceInterface.Model;
namespace GatecoinServiceInterface.Model{
[Serializable]
public class Currency
{
public System.String Code {get; set; }
public System.Boolean Visible { get; private set; }
public System.String DisplayName {get; set; }
public System.String Symbol {get; set; }
public Boolean IsDigital {get; set; }
public System.Int32 DisplayDecimalPlace {get; set; }
public System.Boolean WithdrawalsEnabled {get; set; }
public System.Decimal WithdrawalFee {get; set; }
}
}
|
using ServiceStack.ServiceInterface.ServiceModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GatecoinServiceInterface.Model;
namespace GatecoinServiceInterface.Model{
[Serializable]
public class Currency
{
public System.String Code {get; set; }
public System.Boolean Visible { get; private set; }
public System.String DisplayName {get; set; }
public System.String Symbol {get; set; }
public Boolean IsDigital {get; set; }
public System.Int32 DisplayDecimalPlace {get; set; }
public System.Boolean WithdrawalsEnabled { get; }
public System.Decimal withdrawalFee {get; }
}
}
|
mit
|
C#
|
c7162532f488c557c3725cdd61b6a7ab719dd1ee
|
use API version as a document name (swagger)
|
dzimchuk/book-fast-service-fabric,dzimchuk/book-fast-service-fabric,dzimchuk/book-fast-service-fabric
|
Common/BookFast.Swagger/SwaggerExtensions.cs
|
Common/BookFast.Swagger/SwaggerExtensions.cs
|
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using System.IO;
namespace BookFast.Swagger
{
public static class SwaggerExtensions
{
public static void AddSwashbuckle(this IServiceCollection services, string title, string version, string xmlDocFileName)
{
services.AddSwaggerGen(options =>
{
options.SwaggerDoc(version, new Swashbuckle.AspNetCore.Swagger.Info
{
Title = title,
Version = version
});
options.OperationFilter<DefaultContentTypeOperationFilter>();
options.DescribeAllEnumsAsStrings();
});
if (!string.IsNullOrWhiteSpace(xmlDocFileName))
{
AddXmlComments(services, xmlDocFileName);
}
}
private static void AddXmlComments(IServiceCollection services, string xmlDocFileName)
{
var serviceProvider = services.BuildServiceProvider();
var hostEnv = serviceProvider.GetService<IHostingEnvironment>();
if (hostEnv.IsDevelopment())
{
var platformService = PlatformServices.Default;
var xmlDoc = Path.Combine(platformService.Application.ApplicationBasePath, xmlDocFileName);
if (!File.Exists(xmlDoc))
{
return; // ugly workaround as currently packaging does not pick the xml files (it used to in project.json era)
}
services.ConfigureSwaggerGen(options =>
{
options.IncludeXmlComments(xmlDoc);
});
}
}
}
}
|
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using System.IO;
namespace BookFast.Swagger
{
public static class SwaggerExtensions
{
public static void AddSwashbuckle(this IServiceCollection services, string title, string version, string xmlDocFileName)
{
services.AddSwaggerGen(options =>
{
options.SwaggerDoc($"{title} {version}", new Swashbuckle.AspNetCore.Swagger.Info
{
Title = title,
Version = version
});
options.OperationFilter<DefaultContentTypeOperationFilter>();
options.DescribeAllEnumsAsStrings();
});
if (!string.IsNullOrWhiteSpace(xmlDocFileName))
{
AddXmlComments(services, xmlDocFileName);
}
}
private static void AddXmlComments(IServiceCollection services, string xmlDocFileName)
{
var serviceProvider = services.BuildServiceProvider();
var hostEnv = serviceProvider.GetService<IHostingEnvironment>();
if (hostEnv.IsDevelopment())
{
var platformService = PlatformServices.Default;
var xmlDoc = Path.Combine(platformService.Application.ApplicationBasePath, xmlDocFileName);
if (!File.Exists(xmlDoc))
{
return; // ugly workaround as currently packaging does not pick the xml files (it used to in project.json era)
}
services.ConfigureSwaggerGen(options =>
{
options.IncludeXmlComments(xmlDoc);
});
}
}
}
}
|
mit
|
C#
|
061169e78864f978a4e22115db491341b9be3648
|
Fix assignment statement in update service example
|
teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets
|
ip-messaging/rest/services/update-service/update-service.4.x.cs
|
ip-messaging/rest/services/update-service/update-service.4.x.cs
|
// Download the twilio-csharp library from twilio.com/docs/csharp/install
using System;
using Twilio;
class Example {
static void Main (string[] args) {
// Find your Account Sid and Auth Token at twilio.com/user/account
const string accountSid = "accountSid";
const string authToken = "authToken";
const string serviceSid = "serviceSid";
const string friendlyName = "friendlyName";
const string defaultServiceRoleSid = "defaultServiceRoleSid";
const string defaultChannelRoleSid = "defaultChannelRoleSid";
const string defaultChannelCreatorRoleSid = "defaultChannelCreatorRoleSid";
const int typingIndicatorTimeout = 5;
Dictionary<string, string> webhooksParams;
// Update a service
var client = new TwilioIpMessagingClient(accountSid, authToken);
Service service = client.UpdateService(serviceSid,friendlyName,defaultServiceRoleSid,defaultChannelRoleSid,defaultChannelCreatorRoleSid,typingIndicatorTimeout,webhooksParams);
Console.WriteLine(service);
}
}
|
// Download the twilio-csharp library from twilio.com/docs/csharp/install
using System;
using Twilio;
class Example {
static void Main (string[] args) {
// Find your Account Sid and Auth Token at twilio.com/user/account
const string accountSid = "accountSid";
const string authToken = "authToken";
const string serviceSid = "serviceSid";
const string friendlyName = "friendlyName";
const string defaultServiceRoleSid = "defaultServiceRoleSid";
const string defaultChannelRoleSid = "defaultChannelRoleSid";
const string defaultChannelCreatorRoleSid = "defaultChannelCreatorRoleSid";
const int typingIndicatorTimeout = "typingIndicatorTimeout";
Dictionary<string, string> webhooksParams;
// Update a service
var client = new TwilioIpMessagingClient(accountSid, authToken);
Service service = client.UpdateService(serviceSid,friendlyName,defaultServiceRoleSid,defaultChannelRoleSid,defaultChannelCreatorRoleSid,typingIndicatorTimeout,webhooksParams);
Console.WriteLine(service);
}
}
|
mit
|
C#
|
b8251f66ea80f36f23e2c4c803c1b456b01a1191
|
Update with more efficient lookup and C# tuples
|
mre/the-coding-interview,mre/the-coding-interview,mre/the-coding-interview,mre/the-coding-interview,mre/the-coding-interview,mre/the-coding-interview,mre/the-coding-interview,mre/the-coding-interview,mre/the-coding-interview,mre/the-coding-interview,mre/the-coding-interview,mre/the-coding-interview,mre/the-coding-interview,mre/the-coding-interview,mre/the-coding-interview
|
problems/array-pair-sum/array_pair_sum.cs
|
problems/array-pair-sum/array_pair_sum.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World! 12091029");
ArrayPairSum(10, new int[] { 3, 4, 5, 6, 7 }); // [[4, 6], [3, 7]]
Console.WriteLine();
ArrayPairSum(8, new int[] { 3, 4, 5, 4, 4 }); // [[3, 5], [4, 4]]
Console.WriteLine();
ArrayPairSum(8, new int[] { 4 }); // []
Console.WriteLine();
ArrayPairSum(0, new int[] { 4, -4 }); // [[-4,4]]
Console.WriteLine();
}
public static int[][] ArrayPairSum(int sum, int[] input)
{
if (input == null || input.Length < 2)
return new int[][] { };
var seen = new HashSet<int>();
var result = new HashSet<(int x, int y)>();
for (int i = 0; i < input.Length; i++)
{
var num = input[i];
var target = sum - num;
if (!seen.Contains(target))
seen.Add(num);
else
result.Add((target, num));
}
foreach (var pair in result)
{
Console.Write("[" + pair.x + "," + pair.y + "]; ");
}
return result.Select(pair => new int[] { pair.x, pair.y }).ToArray();
}
}
}
|
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World! 12091029");
ArrayPairSum(10, new int[] { 3, 4, 5, 6, 7 }); // [[6, 4], [7, 3]]
Console.WriteLine();
ArrayPairSum(8, new int[] { 3, 4, 5, 4, 4 }); // [[3, 5], [4, 4], [4, 4], [4, 4]]
Console.WriteLine();
ArrayPairSum(8, new int[] { 4 }); // []
Console.WriteLine();
ArrayPairSum(0, new int[] { 4, -4 }); // [[-4,4]]
Console.WriteLine();
}
public static int[][] ArrayPairSum(int sum, int[] input)
{
if (input == null || input.Length < 2)
return new int[][] { };
Dictionary<int, int> complements = new Dictionary<int, int>();
for (int x = 0; x < input.Length; x++)
{
if (!complements.ContainsKey(sum - input[x]) && (input[x] != sum - input[x]))
{
complements.Add(sum - input[x], input[x]);
}
}
List<int[]> valids = new List<int[]>();
for (int x = 0; x < input.Length; x++)
{
if (complements.ContainsKey(input[x])
&& (input[x] != sum - input[x]))
{
valids.Add(new int[] { input[x], sum - input[x] });
complements.Remove(sum - input[x]);
}
}
for (int v = 0; v < valids.Count; v++)
{
Console.Write("[" + valids[v][0] + "," + valids[v][1] + "]; ");
}
int[][] output = new int[valids.Count][];
int index = 0;
foreach (var v in valids)
{
output[index++] = new int[2] { v[0], v[1] };
}
return output;
}
}
}
|
mit
|
C#
|
fb298a2e3c292f7262ad1ff9536dcc6dc8a0b457
|
Update GraphicsResource.cs
|
ericmbernier/Nez,prime31/Nez,eumario/Nez,prime31/Nez,prime31/Nez,Blucky87/Nez
|
Nez-PCL/Graphics/Batcher/GraphicsResource.cs
|
Nez-PCL/Graphics/Batcher/GraphicsResource.cs
|
using System;
using System.Diagnostics;
using Microsoft.Xna.Framework.Graphics;
using System.Reflection;
namespace Nez
{
/// <summary>
/// this class exists only so that we can sneak the Batcher through and have it work just like SpriteBatch with regard to resource handling.
/// </summary>
public abstract class GraphicsResource : IDisposable
{
public GraphicsDevice graphicsDevice
{
get
{
return _graphicsDevice;
}
internal set
{
Assert.isTrue( value != null );
if( _graphicsDevice == value )
return;
// VertexDeclaration objects can be bound to multiple GraphicsDevice objects
// during their lifetime. But only one GraphicsDevice should retain ownership.
if( _graphicsDevice != null )
{
updateResourceReference( false );
_selfReference = null;
}
_graphicsDevice = value;
_selfReference = new WeakReference( this );
updateResourceReference( true );
}
}
public bool isDisposed { get; private set; }
// The GraphicsDevice property should only be accessed in Dispose(bool) if the disposing
// parameter is true. If disposing is false, the GraphicsDevice may or may not be disposed yet.
GraphicsDevice _graphicsDevice;
WeakReference _selfReference;
internal GraphicsResource()
{}
~GraphicsResource()
{
// Pass false so the managed objects are not released
Dispose( false );
}
public void Dispose()
{
// Dispose of managed objects as well
Dispose( true );
// Since we have been manually disposed, do not call the finalizer on this object
GC.SuppressFinalize( this );
}
/// <summary>
/// The method that derived classes should override to implement disposing of managed and native resources.
/// </summary>
/// <param name="disposing">True if managed objects should be disposed.</param>
/// <remarks>Native resources should always be released regardless of the value of the disposing parameter.</remarks>
protected virtual void Dispose( bool disposing )
{
if( !isDisposed )
{
if( disposing )
{
// Release managed objects
}
// Remove from the global list of graphics resources
if( graphicsDevice != null )
updateResourceReference( false );
_selfReference = null;
_graphicsDevice = null;
isDisposed = true;
}
}
void updateResourceReference( bool shouldAdd )
{
var method = shouldAdd ? "AddResourceReference" : "RemoveResourceReference";
var methodInfo = ReflectionUtils.getMethodInfo( graphicsDevice, method );
methodInfo.Invoke( graphicsDevice, new object[] { _selfReference } );
}
}
}
|
using System;
using System.Diagnostics;
using Microsoft.Xna.Framework.Graphics;
using System.Reflection;
namespace Nez
{
/// <summary>
/// this class exists only so that we can sneak the Bather through and have it work just like SpriteBatch with regard to resource handling.
/// </summary>
public abstract class GraphicsResource : IDisposable
{
public GraphicsDevice graphicsDevice
{
get
{
return _graphicsDevice;
}
internal set
{
Assert.isTrue( value != null );
if( _graphicsDevice == value )
return;
// VertexDeclaration objects can be bound to multiple GraphicsDevice objects
// during their lifetime. But only one GraphicsDevice should retain ownership.
if( _graphicsDevice != null )
{
updateResourceReference( false );
_selfReference = null;
}
_graphicsDevice = value;
_selfReference = new WeakReference( this );
updateResourceReference( true );
}
}
public bool isDisposed { get; private set; }
// The GraphicsDevice property should only be accessed in Dispose(bool) if the disposing
// parameter is true. If disposing is false, the GraphicsDevice may or may not be disposed yet.
GraphicsDevice _graphicsDevice;
WeakReference _selfReference;
internal GraphicsResource()
{}
~GraphicsResource()
{
// Pass false so the managed objects are not released
Dispose( false );
}
public void Dispose()
{
// Dispose of managed objects as well
Dispose( true );
// Since we have been manually disposed, do not call the finalizer on this object
GC.SuppressFinalize( this );
}
/// <summary>
/// The method that derived classes should override to implement disposing of managed and native resources.
/// </summary>
/// <param name="disposing">True if managed objects should be disposed.</param>
/// <remarks>Native resources should always be released regardless of the value of the disposing parameter.</remarks>
protected virtual void Dispose( bool disposing )
{
if( !isDisposed )
{
if( disposing )
{
// Release managed objects
}
// Remove from the global list of graphics resources
if( graphicsDevice != null )
updateResourceReference( false );
_selfReference = null;
_graphicsDevice = null;
isDisposed = true;
}
}
void updateResourceReference( bool shouldAdd )
{
var method = shouldAdd ? "AddResourceReference" : "RemoveResourceReference";
var methodInfo = ReflectionUtils.getMethodInfo( graphicsDevice, method );
methodInfo.Invoke( graphicsDevice, new object[] { _selfReference } );
}
}
}
|
mit
|
C#
|
0aefe648c083c48c2c95c58fa015720d7df10771
|
Add tag for Scene logs; Code alignment;
|
KonH/UDBase
|
Components/Log/LogTags.cs
|
Components/Log/LogTags.cs
|
using UnityEngine;
using System.Collections;
namespace UDBase.Components.Log {
public class LogTags {
public const int Common = 1;
public const int UI = 2;
public const int Scene = 3;
string[] _names = new string[]{"Common", "UI", "Scene"};
public virtual string GetName(int index) {
switch( index ) {
case Common : return "Common";
case UI : return "UI";
case Scene : return "Scene";
}
return "Unknown";
}
public virtual string[] GetNames() {
return _names;
}
}
}
|
using UnityEngine;
using System.Collections;
namespace UDBase.Components.Log {
public class LogTags {
public const int Common = 1;
public const int UI = 2;
string[] _names = new string[]{"Common", "UI"};
public virtual string GetName(int index) {
switch( index ) {
case Common: {
return "Common";
}
case UI: {
return "UI";
}
}
return "Unknown";
}
public virtual string[] GetNames() {
return _names;
}
}
}
|
mit
|
C#
|
ea26192f7a1257dc36465c621fc7aff38e286ed8
|
Update GetUpdateVersion.cs
|
afroraydude/First_Unity_Game,afroraydude/First_Unity_Game,afroraydude/First_Unity_Game
|
Real_Game/Assets/Scripts/GetUpdateVersion.cs
|
Real_Game/Assets/Scripts/GetUpdateVersion.cs
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class GetUpdateVersion : MonoBehaviour {
public WWW update;
public Button updateButton;
public Text updateButtonText;
public string updateURL;
public float version;
public string gotVersionText;
public float gotVersion;
// Use this for initialization
void Start () {
updateButtonText.resizeTextMaxSize = 14;
updateButtonText.resizeTextForBestFit = true;
/**
StartCoroutine( Do() );
//or the less efficient version that takes a string, but is limited to a single parameter.:
StartCoroutine("Do" , parameter);
//The advantage to the string version is that you can call stop coroutine:
StopCoroutine("Do");
*/
}
// Update is called once per frame
void Update () {
StartCoroutine (GetVersion ());
StopCoroutine (GetVersion ());
}
IEnumerator GetUpdateData () {
update = new WWW (updateURL);
yield return update;
gotVersionText = updateWWW.text.ToString();
print (gotVersionText);
gotVersion = float.Parse (gotVersionText);
print (gotVersion);
CheckIfVersionIsLatest ();
}
void CheckIfVersionIsLatest () {
if (gotVersion == version || Application.isWebPlayer) {
updateButton.enabled = false;
updateButtonText.text = "Up to Date";
} else {
// end
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class GetUpdateVersion : MonoBehaviour {
public WWW update;
public Button updateButton;
public Text updateButtonText;
public string updateURL;
public float version;
public string gotVersionText;
public float gotVersion;
// Use this for initialization
void Start () {
updateButtonText.resizeTextMaxSize = 14;
updateButtonText.resizeTextForBestFit = true;
/**
StartCoroutine( Do() );
//or the less efficient version that takes a string, but is limited to a single parameter.:
StartCoroutine("Do" , parameter);
//The advantage to the string version is that you can call stop coroutine:
StopCoroutine("Do");
*/
}
// Update is called once per frame
void Update () {
StartCoroutine (GetVersion ());
StopCoroutine (GetVersion ());
}
IEnumerator GetUpdateData (string url) {
update = new WWW (url);
yield return update;
gotVersionText = updateWWW.text.ToString();
print (gotVersionText);
gotVersion = float.Parse (gotVersionText);
print (gotVersion);
CheckIfVersionIsLatest ();
}
void CheckIfVersionIsLatest () {
if (gotVersion == version || Application.isWebPlayer) {
updateButton.enabled = false;
updateButtonText.text = "Up to Date";
} else {
// end
}
}
}
|
mit
|
C#
|
4fc0ec40cf89d079f52a56e4158cf8a580c3d154
|
Update KnownNetwork.cs
|
EricZimmerman/RegistryPlugins
|
RegistryPlugin.KnownNetworks/KnownNetwork.cs
|
RegistryPlugin.KnownNetworks/KnownNetwork.cs
|
using System;
using RegistryPluginBase.Interfaces;
namespace RegistryPlugin.KnownNetworks
{
public class KnownNetwork:IValueOut
{
public enum NameTypes
{
Wireless = 71,
Wired = 6,
WWAN = 23,
Unknown = 0
}
public KnownNetwork(string networkName, NameTypes type, DateTimeOffset firstConnect, DateTimeOffset lastConnect,
bool managed, string dnsSuffix, string gatewayMacAddress, string profileGuid)
{
NetworkName = networkName;
NameType = type;
FirstConnectLOCAL = firstConnect.DateTime;
LastConnectedLOCAL = lastConnect.DateTime;
Managed = managed;
DNSSuffix = dnsSuffix;
GatewayMacAddress = gatewayMacAddress;
ProfileGUID = profileGuid;
}
public string NetworkName { get; private set; }
public NameTypes NameType { get; }
public DateTime FirstConnectLOCAL { get; }
public DateTime LastConnectedLOCAL { get; }
public bool Managed { get; private set; }
public string DNSSuffix { get; private set; }
public string GatewayMacAddress { get; private set; }
public string ProfileGUID { get; }
public void UpdateInfo(string macAddress, string dnsSuffix, string networkName, bool managed)
{
GatewayMacAddress = macAddress;
DNSSuffix = dnsSuffix;
NetworkName = networkName;
Managed = managed;
}
public string BatchKeyPath { get; set; }
public string BatchValueName { get; set; }
public string BatchValueData1 => $"Name: {NetworkName} Type: {NameType}";
public string BatchValueData2 => $"First Connect LOCAL: {FirstConnectLOCAL:yyyy-MM-dd HH:mm:ss.fffffff} Last Connect LOCAL: {LastConnectedLOCAL:yyyy-MM-dd HH:mm:ss.fffffff}";
public string BatchValueData3 => $"Gateway MAC: {GatewayMacAddress}";
}
}
|
using System;
using RegistryPluginBase.Interfaces;
namespace RegistryPlugin.KnownNetworks
{
public class KnownNetwork:IValueOut
{
public enum NameTypes
{
Wireless = 71,
Wired = 6,
WWAN = 23,
Unknown = 0
}
public KnownNetwork(string networkName, NameTypes type, DateTimeOffset firstConnect, DateTimeOffset lastConnect,
bool managed, string dnsSuffix, string gatewayMacAddress, string profileGuid)
{
NetworkName = networkName;
NameType = type;
FirstConnectLOCAL = firstConnect.DateTime;
LastConnectedLOCAL = lastConnect.DateTime;
Managed = managed;
DNSSuffix = dnsSuffix;
GatewayMacAddress = gatewayMacAddress;
ProfileGUID = profileGuid;
}
public string NetworkName { get; private set; }
public NameTypes NameType { get; }
public DateTime FirstConnectLOCAL { get; }
public DateTime LastConnectedLOCAL { get; }
public bool Managed { get; private set; }
public string DNSSuffix { get; private set; }
public string GatewayMacAddress { get; private set; }
public string ProfileGUID { get; }
public void UpdateInfo(string macAddress, string dnsSuffix, string networkName, bool managed)
{
GatewayMacAddress = macAddress;
DNSSuffix = dnsSuffix;
NetworkName = networkName;
Managed = managed;
}
public string BatchKeyPath { get; set; }
public string BatchValueName { get; set; }
public string BatchValueData1 => $"Name: {NetworkName} Type: {NameType}";
public string BatchValueData2 => $"First Connect LOCAL: {FirstConnectLOCAL:yyyy-MM-dd HH:mm:ss.fffffff} Last Connect LOCAL: {LastConnectedLOCAL:yyyy-MM-dd HH:mm:ss.fffffff})";
public string BatchValueData3 => $"Gateway MAC: {GatewayMacAddress}";
}
}
|
mit
|
C#
|
1ab7879785a20b51db43c671d6250f614dbcdeef
|
Fix of LocalChecker sometimes loopback could be already part of dictionary throwing exception on duplicate add.
|
pysco68/Nowin,et1975/Nowin,modulexcite/Nowin,lstefano71/Nowin,lstefano71/Nowin,pysco68/Nowin,Bobris/Nowin,et1975/Nowin,pysco68/Nowin,modulexcite/Nowin,modulexcite/Nowin,et1975/Nowin,Bobris/Nowin,Bobris/Nowin,lstefano71/Nowin
|
Nowin/IpIsLocalChecker.cs
|
Nowin/IpIsLocalChecker.cs
|
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
namespace Nowin
{
public class IpIsLocalChecker : IIpIsLocalChecker
{
readonly Dictionary<IPAddress, bool> _dict;
public IpIsLocalChecker()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
_dict = host.AddressList.Where(
a => a.AddressFamily == AddressFamily.InterNetwork || a.AddressFamily == AddressFamily.InterNetworkV6).
ToDictionary(p => p, p => true);
_dict[IPAddress.Loopback] = true;
_dict[IPAddress.IPv6Loopback] = true;
}
public bool IsLocal(IPAddress address)
{
return _dict.ContainsKey(address);
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
namespace Nowin
{
public class IpIsLocalChecker : IIpIsLocalChecker
{
readonly Dictionary<IPAddress, bool> _dict;
public IpIsLocalChecker()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
_dict=host.AddressList.Where(
a => a.AddressFamily == AddressFamily.InterNetwork || a.AddressFamily == AddressFamily.InterNetworkV6).
ToDictionary(p => p, p => true);
_dict.Add(IPAddress.Loopback,true);
_dict.Add(IPAddress.IPv6Loopback,true);
}
public bool IsLocal(IPAddress address)
{
return _dict.ContainsKey(address);
}
}
}
|
mit
|
C#
|
781fc4a2bc7696e69ee611d09063ca58b7c6bec5
|
Create Asset Menu
|
UTC-SkillsUSA-2015/SkillsUSA-2015
|
Assets/Scripts/AttackData.cs
|
Assets/Scripts/AttackData.cs
|
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
[CreateAssetMenu(fileName = "Attack Data", menuName = "Attack Data")]
public class AttackData : ScriptableObject {
// Note: Values of the AttackData are separated into fields and their property
// encapsulations. Fields are accessed by the designers through Inspector;
// Properties are accessed by other scripts, making the values in the
// object unmodifiable.
#region Fields
/// <summary>
/// The priority of the attack. Higher priorities will cancel out lower
/// priorities. Equal priorities will cancel out each other.
/// </summary>
[SerializeField]
int m_priority = 0;
/// <summary>
/// The damage dealt by the attack.
/// </summary>
[SerializeField]
int m_dmg = 0;
/// <summary>
/// The amount of chip damage the attack deals.
/// </summary>
[SerializeField]
[Range(0,1)]
float m_chip = 0;
/// <summary>
/// The velocity the hit fighter takes on when struck by this attack.
/// </summary>
[SerializeField]
Vector2 m_launch = Vector2.zero;
/// <summary>
/// Whether the attack puts the opponent into launch state (no cancel),
/// or merely damaged state (cancellable).
/// </summary>
[SerializeField]
bool m_launchState = false;
#endregion
#region Properties
public int Priority {
get {
return m_priority;
}
}
public int Dmg {
get {
return m_dmg;
}
}
public float Chip {
get {
return m_chip;
}
}
public Vector2 Launch {
get {
return m_launch;
}
}
public bool LaunchState {
get {
return m_launchState;
}
}
#endregion
public override int GetHashCode () {
int istof;
istof = (m_dmg + (347 << Mathf.Abs (m_priority))) * 54;
istof += this.name.GetHashCode () >> 2;
istof *= (m_priority * 67 + (int) (m_chip * 97570));
istof += (int) (m_launch.magnitude * (100 * m_chip) * (m_launchState ? 1 : -1));
istof *= 789 << (int) (m_chip * 10);
return istof;
}
}
|
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class AttackData : ScriptableObject {
// Note: Values of the AttackData are separated into fields and their property
// encapsulations. Fields are accessed by the designers through Inspector;
// Properties are accessed by other scripts, making the values in the
// object unmodifiable.
#region Fields
/// <summary>
/// The priority of the attack. Higher priorities will cancel out lower
/// priorities. Equal priorities will cancel out each other.
/// </summary>
[SerializeField]
int m_priority = 0;
/// <summary>
/// The damage dealt by the attack.
/// </summary>
[SerializeField]
int m_dmg = 0;
/// <summary>
/// The amount of chip damage the attack deals.
/// </summary>
[SerializeField]
[Range(0,1)]
float m_chip = 0;
/// <summary>
/// The velocity the hit fighter takes on when struck by this attack.
/// </summary>
[SerializeField]
Vector2 m_launch = Vector2.zero;
/// <summary>
/// Whether the attack puts the opponent into launch state (no cancel),
/// or merely damaged state (cancellable).
/// </summary>
[SerializeField]
bool m_launchState = false;
#endregion
#region Properties
public int Priority {
get {
return m_priority;
}
}
public int Dmg {
get {
return m_dmg;
}
}
public float Chip {
get {
return m_chip;
}
}
public Vector2 Launch {
get {
return m_launch;
}
}
public bool LaunchState {
get {
return m_launchState;
}
}
#endregion
public override int GetHashCode () {
int istof;
istof = (m_dmg + (347 << Mathf.Abs (m_priority))) * 54;
istof += this.name.GetHashCode () >> 2;
istof *= (m_priority * 67 + (int) (m_chip * 97570));
istof += (int) (m_launch.magnitude * (100 * m_chip) * (m_launchState ? 1 : -1));
istof *= 789 << (int) (m_chip * 10);
return istof;
}
}
|
apache-2.0
|
C#
|
a6e72cfcb4ed0f84191ef460b80052adf490b1ee
|
Fix issue #9
|
gentlecat/unipong
|
Assets/BallMovement.cs
|
Assets/BallMovement.cs
|
using UnityEngine;
public class BallMovement :MonoBehaviour
{
public Vector2 Direction;
public GameObject Camera;
// Players
public GameObject PlayerLeft;
public GameObject PlayerRight;
// Score
public GameObject ScoreLeft;
public GameObject ScoreRight;
// Borders
public float BorderLeft = -10;
public float BorderRight = 10;
// Sounds
public AudioClip HitSound;
// Safe direction
private bool goingDown;
private bool goingRight;
void Start ()
{
// Ball starts by going to the top right side
Direction.x = 6;
Direction.y = 8;
goingDown = false;
goingRight = true;
}
void FixedUpdate ()
{
// Win detection
if (transform.position.x < BorderLeft && !goingRight) { // Right wins
Reset ();
ScoreRight.guiText.text = (int.Parse (ScoreRight.guiText.text) + 1).ToString ();
} else if (transform.position.x > BorderRight && goingRight) { // Left wins
Reset ();
ScoreLeft.guiText.text = (int.Parse (ScoreLeft.guiText.text) + 1).ToString ();
}
rigidbody2D.velocity = Direction;
}
void OnCollisionEnter2D (Collision2D other)
{
Vector3 dir = (other.gameObject.transform.position - gameObject.transform.position).normalized;
if (other.gameObject == PlayerRight || other.gameObject == PlayerLeft) { // Detecting collision with a player
AudioSource.PlayClipAtPoint(HitSound, transform.position);
if (dir.y > -0.96f && dir.y < 0.96f) // { Detects if ball hits side of a player
ChangeDirectionX();
} else {
ChangeDirectionY();
}
} else { // Or border
ChangeDirectionY ();
}
}
void Reset ()
{
Vector3 newPos = new Vector3 (0, 0, 0);
transform.position = newPos;
ChangeDirectionX ();
}
void ChangeDirectionX ()
{
Direction.x *= -1;
goingRight = !goingRight;
}
void ChangeDirectionY ()
{
Direction.y *= -1;
goingDown = !goingDown;
}
}
|
using UnityEngine;
public class BallMovement :MonoBehaviour
{
public Vector2 Direction;
public GameObject Camera;
// Players
public GameObject PlayerLeft;
public GameObject PlayerRight;
// Score
public GameObject ScoreLeft;
public GameObject ScoreRight;
// Borders
public float BorderLeft = -10;
public float BorderRight = 10;
// Sounds
public AudioClip HitSound;
// Safe direction
private bool goingDown;
private bool goingRight;
void Start ()
{
// Ball starts by going to the top right side
Direction.x = 6;
Direction.y = 8;
goingDown = false;
goingRight = true;
}
void FixedUpdate ()
{
// Win detection
if (transform.position.x < BorderLeft && !goingRight) { // Right wins
Reset ();
ScoreRight.guiText.text = (int.Parse (ScoreRight.guiText.text) + 1).ToString ();
} else if (transform.position.x > BorderRight && goingRight) { // Left wins
Reset ();
ScoreLeft.guiText.text = (int.Parse (ScoreLeft.guiText.text) + 1).ToString ();
}
rigidbody2D.velocity = Direction;
}
void OnCollisionEnter2D (Collision2D other)
{
if (other.gameObject == PlayerRight || other.gameObject == PlayerLeft) { // Detecting collision with a player
ChangeDirectionX ();
AudioSource.PlayClipAtPoint (HitSound, transform.position);
} else { // Or border
ChangeDirectionY ();
}
}
void Reset ()
{
Vector3 newPos = new Vector3 (0, 0, 0);
transform.position = newPos;
ChangeDirectionX ();
}
void ChangeDirectionX ()
{
Direction.x *= -1;
goingRight = !goingRight;
}
void ChangeDirectionY ()
{
Direction.y *= -1;
goingDown = !goingDown;
}
}
|
mit
|
C#
|
3340e57ff6f602b11d8cded3bb8bc26276302962
|
Correct press/release behavior when dragging pointer in and out of the object
|
zeh/unity-tidbits
|
objects/SimpleButton.cs
|
objects/SimpleButton.cs
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SimpleButton:MonoBehaviour {
/*
A button with simple actions; syntax sugar
*/
// Properties
private bool _isPointerOver;
private bool _isPressed;
// ================================================================================================================
// MAIN EVENT INTERFACE -------------------------------------------------------------------------------------------
// Gives warnings on Android:
// "Game scripts or other custom code contains OnMouse_ event handlers. Presence of such handlers might impact performance on handheld devices."
// Use separate events?
// http://wiki.unity3d.com/index.php/OnMouseDown
void OnMouseDown() {
// Called when the user has pressed the mouse button while over the GUIElement or Collider.
_isPressed = true;
animatePress();
}
void OnMouseDrag() {
// Called every frame when the user has clicked on a GUIElement or Collider and is still holding down the mouse (inside or not)
}
void OnMouseEnter() {
// Called when the mouse entered the GUIElement or Collider.
_isPointerOver = true;
if (_isPressed) animatePress();
animateOver();
}
void OnMouseExit() {
// Called when the mouse is not any longer over the GUIElement or Collider.
_isPointerOver = false;
if (_isPressed) animateRelease();
animateOut();
}
void OnMouseOver() {
// Called every frame while the mouse is over the GUIElement or Collider.
}
void OnMouseUpAsButton() {
// Only called when the mouse is released over the same GUIElement or Collider as it was pressed. This is called BEFORE OnMouseUp
if (_isPressed) {
performAction();
}
}
void OnMouseUp() {
// Called when the user has released the mouse button
if (_isPressed) {
_isPressed = false;
animateRelease();
}
}
// ================================================================================================================
// PUBLIC INTERFACE -----------------------------------------------------------------------------------------------
// ================================================================================================================
// ACCESSOR INTERFACE ---------------------------------------------------------------------------------------------
protected bool isPointerOver {
get {
return _isPointerOver;
}
}
protected bool isPressed {
get {
return _isPressed;
}
}
// ================================================================================================================
// EXTENDABLE INTERFACE -------------------------------------------------------------------------------------------
protected virtual void animatePress() {
// Press
}
protected virtual void animateRelease() {
// Release
}
protected virtual void animateOver() {
// Pointer over
}
protected virtual void animateOut() {
// Pointer out
}
protected virtual void performAction() {
// Pressed and released without moving: execute action
}
// ================================================================================================================
// INTERNAL INTERFACE ---------------------------------------------------------------------------------------------
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SimpleButton:MonoBehaviour {
/*
A button with simple actions; syntax sugar
*/
// Properties
private bool _isPointerOver;
private bool _isPressed;
// ================================================================================================================
// MAIN EVENT INTERFACE -------------------------------------------------------------------------------------------
// http://docs.unity3d.com/ScriptReference/MonoBehaviour.html
void OnMouseDown() {
// Called when the user has pressed the mouse button while over the GUIElement or Collider.
_isPressed = true;
animatePress();
}
void OnMouseDrag() {
// Called every frame when the user has clicked on a GUIElement or Collider and is still holding down the mouse (inside or not)
}
void OnMouseEnter() {
// Called when the mouse entered the GUIElement or Collider.
_isPointerOver = true;
animateOver();
}
void OnMouseExit() {
// Called when the mouse is not any longer over the GUIElement or Collider.
_isPointerOver = false;
animateOut();
}
void OnMouseOver() {
// Called every frame while the mouse is over the GUIElement or Collider.
}
void OnMouseUpAsButton() {
// Only called when the mouse is released over the same GUIElement or Collider as it was pressed. This is called BEFORE OnMouseUp
if (_isPressed) {
performAction();
}
}
void OnMouseUp() {
// Called when the user has released the mouse button
if (_isPressed) {
_isPressed = false;
animateRelease();
}
}
// ================================================================================================================
// PUBLIC INTERFACE -----------------------------------------------------------------------------------------------
// ================================================================================================================
// ACCESSOR INTERFACE ---------------------------------------------------------------------------------------------
protected bool isPointerOver {
get {
return _isPointerOver;
}
}
protected bool isPressed {
get {
return _isPressed;
}
}
// ================================================================================================================
// EXTENDABLE INTERFACE -------------------------------------------------------------------------------------------
protected virtual void animatePress() {
// Press
}
protected virtual void animateRelease() {
// Release
}
protected virtual void animateOver() {
// Pointer over
}
protected virtual void animateOut() {
// Pointer out
}
protected virtual void performAction() {
// Pressed and released without moving: execute action
}
// ================================================================================================================
// INTERNAL INTERFACE ---------------------------------------------------------------------------------------------
}
|
mit
|
C#
|
3b983d1e685d6842933cb8b2f3d1f27c9acb71fa
|
select method should alwas set the flag to select
|
sqlkata/querybuilder
|
QueryBuilder/Query.Select.cs
|
QueryBuilder/Query.Select.cs
|
using System;
namespace SqlKata
{
public partial class Query
{
public Query Select(params string[] columns)
{
Method = "select";
foreach (var column in columns)
{
Add("select", new Column
{
Name = column
});
}
return this;
}
/// <summary>
/// Add a new "raw" select expression to the query.
/// </summary>
/// <returns></returns>
public Query SelectRaw(string expression, params object[] bindings)
{
Method = "select";
Add("select", new RawColumn
{
Expression = expression,
Bindings = Helper.Flatten(bindings).ToArray()
});
return this;
}
public Query Select(params object[] columns)
{
foreach (var item in columns)
{
if (item is Raw)
{
SelectRaw((item as Raw).Value, (item as Raw).Bindings);
}
else if (item is string)
{
Select((string)item);
}
else
{
throw new ArgumentException("only string and Raw are allowed");
}
}
return this;
}
public Query Select(Query query, string alias)
{
Method = "select";
Add("select", new QueryColumn
{
Query = query.As(alias).SetEngineScope(EngineScope),
});
return this;
}
public Query Select(Func<Query, Query> callback, string alias)
{
return Select(callback.Invoke(NewChild()), alias);
}
}
}
|
using System;
namespace SqlKata
{
public partial class Query
{
public Query Select(params string[] columns)
{
foreach (var column in columns)
{
Add("select", new Column
{
Name = column
});
}
return this;
}
/// <summary>
/// Add a new "raw" select expression to the query.
/// </summary>
/// <returns></returns>
public Query SelectRaw(string expression, params object[] bindings)
{
Add("select", new RawColumn
{
Expression = expression,
Bindings = Helper.Flatten(bindings).ToArray()
});
return this;
}
public Query Select(params object[] columns)
{
foreach (var item in columns)
{
if (item is Raw)
{
SelectRaw((item as Raw).Value, (item as Raw).Bindings);
}
else if (item is string)
{
Select((string)item);
}
else
{
throw new ArgumentException("only string and Raw are allowed");
}
}
return this;
}
public Query Select(Query query, string alias)
{
Add("select", new QueryColumn
{
Query = query.As(alias).SetEngineScope(EngineScope),
});
return this;
}
public Query Select(Func<Query, Query> callback, string alias)
{
return Select(callback.Invoke(NewChild()), alias);
}
}
}
|
mit
|
C#
|
11c48cc697687ae6f529534938448d140625d8c1
|
Fix offset bug
|
mstrother/BmpListener
|
src/BmpListener/Bmp/PeerUpNotification.cs
|
src/BmpListener/Bmp/PeerUpNotification.cs
|
using System;
using System.Net;
using BmpListener.Bgp;
using System.Linq;
using BmpListener.MiscUtil.Conversion;
namespace BmpListener.Bmp
{
public class PeerUpNotification : BmpMessage
{
public IPAddress LocalAddress { get; private set; }
public int LocalPort { get; private set; }
public int RemotePort { get; private set; }
public BgpOpenMessage SentOpenMessage { get; private set; }
public BgpOpenMessage ReceivedOpenMessage { get; private set; }
public override void Decode(byte[] data, int offset)
{
if (((PeerHeader.Flags & (1 << 7)) != 0))
{
var ipBytes = new byte[16];
Array.Copy(data, offset, ipBytes, 0, 4);
LocalAddress = new IPAddress(ipBytes);
}
else
{
var ipBytes = new byte[4];
Array.Copy(data, offset + 12, ipBytes, 0, 4);
LocalAddress = new IPAddress(ipBytes);
}
offset += 16;
LocalPort = EndianBitConverter.Big.ToUInt16(data, offset);
offset += 2;
RemotePort = EndianBitConverter.Big.ToUInt16(data, offset);
offset += 2;
SentOpenMessage = BgpMessage.DecodeMessage(data, offset) as BgpOpenMessage;
offset += SentOpenMessage.Header.Length;
ReceivedOpenMessage = BgpMessage.DecodeMessage(data, offset) as BgpOpenMessage;
}
}
}
|
using System;
using System.Net;
using BmpListener.Bgp;
using System.Linq;
using BmpListener.MiscUtil.Conversion;
namespace BmpListener.Bmp
{
public class PeerUpNotification : BmpMessage
{
public IPAddress LocalAddress { get; private set; }
public int LocalPort { get; private set; }
public int RemotePort { get; private set; }
public BgpOpenMessage SentOpenMessage { get; private set; }
public BgpOpenMessage ReceivedOpenMessage { get; private set; }
public override void Decode(byte[] data, int offset)
{
if (((PeerHeader.Flags & (1 << 7)) != 0))
{
var ipBytes = new byte[16];
Array.Copy(data, offset, ipBytes, 0, 4);
LocalAddress = new IPAddress(ipBytes);
offset += 4;
}
else
{
var ipBytes = new byte[4];
Array.Copy(data, offset + 12, ipBytes, 0, 4);
LocalAddress = new IPAddress(ipBytes);
offset += 16;
}
LocalPort = EndianBitConverter.Big.ToUInt16(data, offset);
offset += 2;
RemotePort = EndianBitConverter.Big.ToUInt16(data, offset);
offset += 2;
SentOpenMessage = BgpMessage.DecodeMessage(data, offset) as BgpOpenMessage;
offset += SentOpenMessage.Header.Length;
ReceivedOpenMessage = BgpMessage.DecodeMessage(data, offset) as BgpOpenMessage;
}
}
}
|
mit
|
C#
|
7b62fb48bcbb2b739ca8459e5b71f813470e3f1e
|
Fix feed for @LeomarisReyes
|
planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
|
src/Firehose.Web/Authors/LeomarisReyes.cs
|
src/Firehose.Web/Authors/LeomarisReyes.cs
|
using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class LeomarisReyes : IAmACommunityMember
{
public string FirstName => "Leomaris";
public string LastName => "Reyes";
public string ShortBioOrTagLine => "is a software engineer";
public string StateOrRegion => "Dominican Republic";
public string EmailAddress => "reyes.leomaris@gmail.com";
public string TwitterHandle => "leomarisreyes11";
public string GravatarHash => "ae78e84a683611c7b72c9ba829c125e0";
public string GitHubHandle => "LeomarisReyes";
public GeoPosition Position => new GeoPosition(18.470880, -69.911525);
public Uri WebSite => new Uri("https://askxammy.com/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://askxammy.com/feed"); } }
public string FeedLanguageCode => "en";
}
}
|
using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class LeomarisReyes : IAmACommunityMember
{
public string FirstName => "Leomaris";
public string LastName => "Reyes";
public string ShortBioOrTagLine => "is a software engineer";
public string StateOrRegion => "Dominican Republic";
public string EmailAddress => "reyes.leomaris@gmail.com";
public string TwitterHandle => "leomarisreyes11";
public string GravatarHash => "ae78e84a683611c7b72c9ba829c125e0";
public string GitHubHandle => "LeomarisReyes";
public GeoPosition Position => new GeoPosition(18.470880, -69.911525);
public Uri WebSite => new Uri("https://askxammy.com/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://askxammy.com/rss"); } }
public string FeedLanguageCode => "en";
}
}
|
mit
|
C#
|
0991a9255f81cb15d23d7001a3b8f10846151c53
|
Remove empty lines...
|
mbrenn/datenmeister-new,mbrenn/datenmeister-new,mbrenn/datenmeister-new,mbrenn/datenmeister-new,mbrenn/datenmeister-new
|
src/Web/DatenMeister.WebServer/Startup.cs
|
src/Web/DatenMeister.WebServer/Startup.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace DatenMeister.WebServer
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace DatenMeister.WebServer
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
}
|
mit
|
C#
|
dd86edc964a9859debd654b1bdb90f693fdd5dee
|
Change logger type for NLog error messages to be based on exception if possible
|
DarthFubuMVC/FubuMVC.Loggers,DarthFubuMVC/FubuMVC.Loggers
|
src/FubuMVC.NLog/NLogListener.cs
|
src/FubuMVC.NLog/NLogListener.cs
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using FubuCore;
using FubuCore.Descriptions;
using FubuCore.Logging;
using FubuCore.Util;
using NLog;
using Logger = NLog.Logger;
namespace FubuMVC.NLog
{
public class NLogListener : ILogListener
{
private readonly Cache<Type, Logger> _logger;
public NLogListener()
{
_logger = new Cache<Type, Logger>(x => LogManager.GetLogger(x.FullName));
}
public bool IsDebugEnabled
{
get { return true; }
}
public bool IsInfoEnabled
{
get { return true; }
}
public void Debug(string message)
{
DebugMessage(message);
}
public void DebugMessage(object message)
{
_logger[message.GetType()].Debug(Description.For(message));
}
public void Error(string message, Exception ex)
{
var loggerType = ex != null ? ex.GetType() : message.GetType();
_logger[loggerType].ErrorException(message, ex);
}
public void Error(object correlationId, string message, Exception ex)
{
Error(message, ex);
}
public void Info(string message)
{
InfoMessage(message);
}
public void InfoMessage(object message)
{
_logger[message.GetType()].Info(Description.For(message));
}
public bool ListensFor(Type type)
{
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using FubuCore;
using FubuCore.Descriptions;
using FubuCore.Logging;
using FubuCore.Util;
using NLog;
using Logger = NLog.Logger;
namespace FubuMVC.NLog
{
public class NLogListener : ILogListener
{
private readonly Cache<Type, Logger> _logger;
public NLogListener()
{
_logger = new Cache<Type, Logger>(x => LogManager.GetLogger(x.FullName));
}
public bool IsDebugEnabled
{
get { return true; }
}
public bool IsInfoEnabled
{
get { return true; }
}
public void Debug(string message)
{
DebugMessage(message);
}
public void DebugMessage(object message)
{
_logger[message.GetType()].Debug(Description.For(message));
}
public void Error(string message, Exception ex)
{
_logger[message.GetType()].ErrorException(message, ex);
}
public void Error(object correlationId, string message, Exception ex)
{
Error(message, ex);
}
public void Info(string message)
{
InfoMessage(message);
}
public void InfoMessage(object message)
{
_logger[message.GetType()].Info(Description.For(message));
}
public bool ListensFor(Type type)
{
return true;
}
}
}
|
apache-2.0
|
C#
|
68965c9b27966b99f888df3dbd4ed3dd9958bca4
|
Update index.cshtml
|
aidka011/apmathcloudaida
|
site/index.cshtml
|
site/index.cshtml
|
@{
var txt = Request.QueryString["txtstring"];
}
<html>
<body>
<p>The dateTime is @txt</p>
</body>
</html>
|
@{
var txt = Request.Params["txtstring"];
}
<html>
<body>
<p>The dateTime is @txt</p>
</body>
</html>
|
mit
|
C#
|
da5dba62021f2c6ff34680c1c0af612cdcfc0865
|
Replace size request with preferred height / width
|
PintaProject/Pinta,PintaProject/Pinta,PintaProject/Pinta
|
Pinta.Gui.Widgets/Widgets/FilledAreaBin.cs
|
Pinta.Gui.Widgets/Widgets/FilledAreaBin.cs
|
//
// FilledAreaBin.cs
//
// Author:
// Jonathan Pobst <monkey@jpobst.com>
//
// Copyright (c) 2015 Jonathan Pobst
//
// 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 Gdk;
using Gtk;
namespace Pinta.Gui.Widgets
{
public class FilledAreaBin : Bin
{
private Widget child;
protected override void OnAdded (Widget widget)
{
base.OnAdded (widget);
child = widget;
}
protected override void OnRemoved (Widget widget)
{
base.OnRemoved (widget);
child = null;
}
protected override void OnGetPreferredHeight(out int minimum_height, out int natural_height)
{
if (child != null)
child.GetPreferredHeight(out minimum_height, out natural_height);
else
base.OnGetPreferredHeight(out minimum_height, out natural_height);
}
protected override void OnGetPreferredWidth(out int minimum_width, out int natural_width)
{
if (child != null)
child.GetPreferredWidth(out minimum_width, out natural_width);
else
base.OnGetPreferredWidth(out minimum_width, out natural_width);
}
protected override void OnSizeAllocated (Rectangle allocation)
{
base.OnSizeAllocated (allocation);
if (child != null)
child.Allocation = allocation;
}
}
}
|
//
// FilledAreaBin.cs
//
// Author:
// Jonathan Pobst <monkey@jpobst.com>
//
// Copyright (c) 2015 Jonathan Pobst
//
// 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 Gdk;
using Gtk;
namespace Pinta.Gui.Widgets
{
public class FilledAreaBin : Bin
{
private Widget child;
protected override void OnAdded (Widget widget)
{
base.OnAdded (widget);
child = widget;
}
protected override void OnRemoved (Widget widget)
{
base.OnRemoved (widget);
child = null;
}
protected override void OnSizeRequested (ref Requisition requisition)
{
if (child != null)
requisition = child.SizeRequest ();
else
base.OnSizeRequested (ref requisition);
}
protected override void OnSizeAllocated (Rectangle allocation)
{
base.OnSizeAllocated (allocation);
if (child != null)
child.Allocation = allocation;
}
}
}
|
mit
|
C#
|
b933827336b5232a86075553f1110468c2f25014
|
fix extra bytes on public key address
|
ArsenShnurkov/BitSharp
|
BitSharp.Wallet/Address/Top10000Address.cs
|
BitSharp.Wallet/Address/Top10000Address.cs
|
using BitSharp.Common;
using BitSharp.Core.Domain;
using BitSharp.Core.Script;
using BitSharp.Wallet.Base58;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace BitSharp.Wallet.Address
{
public class Top10000Address : IWalletAddress
{
public IEnumerable<UInt256> GetOutputScriptHashes()
{
using (var stream = this.GetType().Assembly.GetManifestResourceStream("BitSharp.Wallet.Address.Top10000.txt"))
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line == "")
continue;
yield return AddressToOutputScriptHash(line);
}
}
}
public bool IsMatcher
{
get { return false; }
}
public bool MatchesTxOutput(TxOutput txOutput, Common.UInt256 txOutputScriptHash)
{
throw new NotSupportedException();
}
public IEnumerable<IWalletAddress> ToWalletAddresses()
{
foreach (var outputScriptHash in this.GetOutputScriptHashes())
yield return new OutputScriptHashAddress(outputScriptHash);
}
private UInt256 AddressToOutputScriptHash(string address)
{
var sha256 = new SHA256Managed();
var publicKeyHash = Base58Encoding.DecodeWithCheckSum(address);
//TODO
while (publicKeyHash.Length > 0 && publicKeyHash[0] == 0)
publicKeyHash = publicKeyHash.Skip(1).ToArray();
var outputScript = new PayToPublicKeyHashBuilder().CreateOutputFromPublicKeyHash(publicKeyHash);
var outputScriptHash = new UInt256(sha256.ComputeHash(outputScript));
return outputScriptHash;
}
}
}
|
using BitSharp.Common;
using BitSharp.Core.Domain;
using BitSharp.Core.Script;
using BitSharp.Wallet.Base58;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace BitSharp.Wallet.Address
{
public class Top10000Address : IWalletAddress
{
public IEnumerable<UInt256> GetOutputScriptHashes()
{
using (var stream = this.GetType().Assembly.GetManifestResourceStream("BitSharp.Wallet.Address.Top10000.txt"))
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line == "")
continue;
yield return AddressToOutputScriptHash(line);
}
}
}
public bool IsMatcher
{
get { return false; }
}
public bool MatchesTxOutput(TxOutput txOutput, Common.UInt256 txOutputScriptHash)
{
throw new NotSupportedException();
}
public IEnumerable<IWalletAddress> ToWalletAddresses()
{
foreach (var outputScriptHash in this.GetOutputScriptHashes())
yield return new OutputScriptHashAddress(outputScriptHash);
}
private UInt256 AddressToOutputScriptHash(string address)
{
var sha256 = new SHA256Managed();
var publicKeyHash = Base58Encoding.DecodeWithCheckSum(address);
var outputScript = new PayToPublicKeyHashBuilder().CreateOutputFromPublicKeyHash(publicKeyHash);
var outputScriptHash = new UInt256(sha256.ComputeHash(outputScript));
return outputScriptHash;
}
}
}
|
unlicense
|
C#
|
79169cc59c559e3b66c99560409a283d2c8814bd
|
Fix `PropertySetter` query object types
|
alastairs/BobTheBuilder
|
BobTheBuilder/Activation/PropertySetter.cs
|
BobTheBuilder/Activation/PropertySetter.cs
|
using BobTheBuilder.ArgumentStore.Queries;
using System;
namespace BobTheBuilder.Activation
{
internal class PropertySetter
{
private IArgumentStoreQuery propertyValuesQuery;
public PropertySetter(IArgumentStoreQuery propertyValuesQuery)
{
if (propertyValuesQuery == null)
{
throw new ArgumentNullException("propertyValuesQuery");
}
this.propertyValuesQuery = propertyValuesQuery;
}
public void PopulatePropertiesOn<T>(T instance) where T: class
{
var destinationType = typeof(T);
var propertyValues = propertyValuesQuery.Execute(destinationType);
foreach (var member in propertyValues)
{
var property = destinationType.GetProperty(member.Name);
property.SetValue(instance, member.Value);
}
}
}
}
|
using BobTheBuilder.ArgumentStore.Queries;
using System;
namespace BobTheBuilder.Activation
{
internal class PropertySetter
{
private PropertyValuesQuery propertyValuesQuery;
public PropertySetter(PropertyValuesQuery propertyValuesQuery)
{
if (propertyValuesQuery == null)
{
throw new ArgumentNullException("propertyValuesQuery");
}
this.propertyValuesQuery = propertyValuesQuery;
}
public void PopulatePropertiesOn<T>(T instance) where T: class
{
var destinationType = typeof(T);
var propertyValues = propertyValuesQuery.Execute(destinationType);
foreach (var member in propertyValues)
{
var property = destinationType.GetProperty(member.Name);
property.SetValue(instance, member.Value);
}
}
}
}
|
apache-2.0
|
C#
|
437f3bb0207105d25609eac5e22ced579606dc4e
|
Fix version number
|
mono/tao,mono/tao,OpenRA/tao,OpenRA/tao
|
Framework/Projects/Tao.Sdl/AssemblyInfo.cs
|
Framework/Projects/Tao.Sdl/AssemblyInfo.cs
|
#region License
/*
MIT License
Copyright 2003-2005 Tao Framework Team
http://www.taoframework.com
All rights reserved.
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 License
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
[assembly: AllowPartiallyTrustedCallers]
[assembly: AssemblyCompany("Tao Framework -- http://www.taoframework.com")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Retail")]
#endif
[assembly: AssemblyCopyright("Copyright 2003-2005 Tao Framework Team. All rights reserved.")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyDefaultAlias("Tao.Sdl")]
[assembly: AssemblyDelaySign(false)]
#if WIN32
[assembly: AssemblyDescription("Tao Framework SDL Binding For .NET (Windows)")]
#elif LINUX
[assembly: AssemblyDescription("Tao Framework SDL Binding For .NET (Linux)")]
#endif
[assembly: AssemblyFileVersion("1.2.7.2")]
[assembly: AssemblyInformationalVersion("1.2.7.2")]
#if STRONG
[assembly: AssemblyKeyFile(@"..\..\Solutions\Tao.Sdl\Solution Items\Tao.Sdl.snk")]
#else
[assembly: AssemblyKeyFile("")]
#endif
[assembly: AssemblyKeyName("")]
#if DEBUG
[assembly: AssemblyProduct("Tao.Sdl.dll *** Debug Build ***")]
#else
[assembly: AssemblyProduct("Tao.Sdl.dll")]
#endif
#if WIN32
[assembly: AssemblyTitle("Tao Framework SDL Binding For .NET (Windows)")]
#elif LINUX
[assembly: AssemblyTitle("Tao Framework SDL Binding For .NET (Linux)")]
#endif
[assembly: AssemblyTrademark("Tao Framework -- http://www.taoframework.com")]
[assembly: AssemblyVersion("1.2.7.2")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.Execution)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.SkipVerification)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.UnmanagedCode)]
|
#region License
/*
MIT License
Copyright 2003-2005 Tao Framework Team
http://www.taoframework.com
All rights reserved.
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 License
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
[assembly: AllowPartiallyTrustedCallers]
[assembly: AssemblyCompany("Tao Framework -- http://www.taoframework.com")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Retail")]
#endif
[assembly: AssemblyCopyright("Copyright 2003-2005 Tao Framework Team. All rights reserved.")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyDefaultAlias("Tao.Sdl")]
[assembly: AssemblyDelaySign(false)]
#if WIN32
[assembly: AssemblyDescription("Tao Framework SDL Binding For .NET (Windows)")]
#elif LINUX
[assembly: AssemblyDescription("Tao Framework SDL Binding For .NET (Linux)")]
#endif
[assembly: AssemblyFileVersion("1.2.7.1")]
[assembly: AssemblyInformationalVersion("1.2.7.1")]
#if STRONG
[assembly: AssemblyKeyFile(@"..\..\Solutions\Tao.Sdl\Solution Items\Tao.Sdl.snk")]
#else
[assembly: AssemblyKeyFile("")]
#endif
[assembly: AssemblyKeyName("")]
#if DEBUG
[assembly: AssemblyProduct("Tao.Sdl.dll *** Debug Build ***")]
#else
[assembly: AssemblyProduct("Tao.Sdl.dll")]
#endif
#if WIN32
[assembly: AssemblyTitle("Tao Framework SDL Binding For .NET (Windows)")]
#elif LINUX
[assembly: AssemblyTitle("Tao Framework SDL Binding For .NET (Linux)")]
#endif
[assembly: AssemblyTrademark("Tao Framework -- http://www.taoframework.com")]
[assembly: AssemblyVersion("1.2.7.1")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.Execution)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.SkipVerification)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.UnmanagedCode)]
|
mit
|
C#
|
0d15bb776645c8b5182da08a9a1d68258bae0c5c
|
Add warmup attribute to test runner factory
|
Hammerstad/Moya
|
Moya.Runner/Factories/TestRunnerFactory.cs
|
Moya.Runner/Factories/TestRunnerFactory.cs
|
namespace Moya.Runner.Factories
{
using System;
using System.Collections.Generic;
using Attributes;
using Exceptions;
using Extensions;
using Moya.Utility;
using Runners;
public class TestRunnerFactory : ITestRunnerFactory
{
private readonly IDictionary<Type, Type> attributeTestRunnerMapping = new Dictionary<Type, Type>
{
{ typeof(StressAttribute), typeof(StressTestRunner) },
{ typeof(WarmupAttribute), typeof(WarmupTestRunner) },
};
public ITestRunner GetTestRunnerForAttribute(Type type)
{
if (!Reflection.TypeIsMoyaAttribute(type))
{
throw new MoyaException("Unable to provide moya test runner for type {0}".FormatWith(type));
}
Type typeOfTestRunner = attributeTestRunnerMapping[type];
ITestRunner instance = (ITestRunner)Activator.CreateInstance(typeOfTestRunner);
ITestRunner timerDecoratedInstance = new TimerDecorator(instance);
return timerDecoratedInstance;
}
}
}
|
namespace Moya.Runner.Factories
{
using System;
using System.Collections.Generic;
using Attributes;
using Exceptions;
using Extensions;
using Moya.Utility;
using Runners;
public class TestRunnerFactory : ITestRunnerFactory
{
private readonly IDictionary<Type, Type> attributeTestRunnerMapping = new Dictionary<Type, Type>
{
{ typeof(StressAttribute), typeof(StressTestRunner) }
};
public ITestRunner GetTestRunnerForAttribute(Type type)
{
if (!Reflection.TypeIsMoyaAttribute(type))
{
throw new MoyaException("Unable to provide moya test runner for type {0}".FormatWith(type));
}
Type typeOfTestRunner = attributeTestRunnerMapping[type];
ITestRunner instance = (ITestRunner)Activator.CreateInstance(typeOfTestRunner);
ITestRunner timerDecoratedInstance = new TimerDecorator(instance);
return timerDecoratedInstance;
}
}
}
|
mit
|
C#
|
2f32c4d4d1d4edb62a167746e7203d481773edff
|
Fix title of match song select
|
johnneijzen/osu,NeoAdonis/osu,DrabWeb/osu,peppy/osu,smoogipoo/osu,peppy/osu,ppy/osu,UselessToucan/osu,EVAST9919/osu,ZLima12/osu,peppy/osu,smoogipoo/osu,smoogipooo/osu,2yangk23/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,DrabWeb/osu,2yangk23/osu,EVAST9919/osu,UselessToucan/osu,DrabWeb/osu,UselessToucan/osu,ZLima12/osu,ppy/osu,naoey/osu,peppy/osu-new,johnneijzen/osu,naoey/osu,naoey/osu,ppy/osu
|
osu.Game/Screens/Select/MatchSongSelect.cs
|
osu.Game/Screens/Select/MatchSongSelect.cs
|
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using Humanizer;
using osu.Game.Online.Multiplayer;
using osu.Game.Screens.Multi;
namespace osu.Game.Screens.Select
{
public class MatchSongSelect : SongSelect, IMultiplayerScreen
{
public Action<PlaylistItem> Selected;
public string ShortTitle => "song selection";
public override string Title => ShortTitle.Humanize();
protected override bool OnStart()
{
var item = new PlaylistItem
{
Beatmap = Beatmap.Value.BeatmapInfo,
Ruleset = Ruleset.Value,
RulesetID = Ruleset.Value.ID ?? 0
};
item.RequiredMods.AddRange(SelectedMods.Value);
Selected?.Invoke(item);
if (IsCurrentScreen)
Exit();
return true;
}
}
}
|
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Game.Online.Multiplayer;
using osu.Game.Screens.Multi;
namespace osu.Game.Screens.Select
{
public class MatchSongSelect : SongSelect, IMultiplayerScreen
{
public Action<PlaylistItem> Selected;
public string ShortTitle => "song selection";
protected override bool OnStart()
{
var item = new PlaylistItem
{
Beatmap = Beatmap.Value.BeatmapInfo,
Ruleset = Ruleset.Value,
RulesetID = Ruleset.Value.ID ?? 0
};
item.RequiredMods.AddRange(SelectedMods.Value);
Selected?.Invoke(item);
if (IsCurrentScreen)
Exit();
return true;
}
}
}
|
mit
|
C#
|
72c4ff8e591e84a3f249be9c4d06408609eeb3a4
|
use bottom in sample
|
MarcBruins/TTGSnackbar-Xamarin-iOS
|
Sample/TTGSnackbarSample/ViewController.cs
|
Sample/TTGSnackbarSample/ViewController.cs
|
using System;
using System.Threading.Tasks;
using TTGSnackBar;
using UIKit;
namespace TTGSnackbarSample
{
public partial class ViewController : UIViewController
{
protected ViewController(IntPtr handle) : base(handle)
{
// Note: this .ctor should not contain any initialization logic.
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
}
partial void buttonClicked(UIButton sender)
{
var snackbar = new TTGSnackbar("Hello Xamarin snackbar", TTGSnackbarDuration.Long);
snackbar.AnimationType = TTGSnackbarAnimationType.FadeInFadeOut;
// Action 1
snackbar.ActionText = "Yes";
snackbar.ActionTextColor = UIColor.Green;
snackbar.ActionBlock = (t) => { Console.WriteLine("clicked yes"); };
// Action 2
snackbar.SecondActionText = "No";
snackbar.SecondActionTextColor = UIColor.Magenta;
snackbar.SecondActionBlock = (t) => { Console.WriteLine("clicked no"); };
// Dissmiss Callback
snackbar.DismissBlock = (t) => { Console.WriteLine("dismissed snackbar"); };
snackbar.Icon = UIImage.FromBundle("EmojiCool");
//snackbar.LocationType = TTGSnackbarLocation.Top;
snackbar.Show();
}
public void cancel()
{
//do something
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
// Perform any additional setup after loading the view, typically from a nib.
}
public override void DidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
// Release any cached data, images, etc that aren't in use.
}
}
}
|
using System;
using System.Threading.Tasks;
using TTGSnackBar;
using UIKit;
namespace TTGSnackbarSample
{
public partial class ViewController : UIViewController
{
protected ViewController(IntPtr handle) : base(handle)
{
// Note: this .ctor should not contain any initialization logic.
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
}
partial void buttonClicked(UIButton sender)
{
var snackbar = new TTGSnackbar("Hello Xamarin snackbar", TTGSnackbarDuration.Long);
snackbar.AnimationType = TTGSnackbarAnimationType.FadeInFadeOut;
// Action 1
snackbar.ActionText = "Yes";
snackbar.ActionTextColor = UIColor.Green;
snackbar.ActionBlock = (t) => { Console.WriteLine("clicked yes"); };
// Action 2
snackbar.SecondActionText = "No";
snackbar.SecondActionTextColor = UIColor.Magenta;
snackbar.SecondActionBlock = (t) => { Console.WriteLine("clicked no"); };
// Dissmiss Callback
snackbar.DismissBlock = (t) => { Console.WriteLine("dismissed snackbar"); };
snackbar.Icon = UIImage.FromBundle("EmojiCool");
snackbar.LocationType = TTGSnackbarLocation.Top;
snackbar.Show();
}
public void cancel()
{
//do something
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
// Perform any additional setup after loading the view, typically from a nib.
}
public override void DidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
// Release any cached data, images, etc that aren't in use.
}
}
}
|
mit
|
C#
|
f721bd243a53a2309bb555e99e5daa8a2ed253e3
|
Add Console.WriteLine for currentNewEnergy
|
kw90/SantasSledge
|
Santa/MetaHeuristics/SimulatedAnnealing.cs
|
Santa/MetaHeuristics/SimulatedAnnealing.cs
|
using System;
using System.Collections.Generic;
using Common;
using FirstSolution.Algos;
namespace MetaHeuristics
{
public class SimulatedAnnealing : ISolver
{
double _temperature;
Random random = new Random();
double _coolingRate;
public SimulatedAnnealing(double temperature, double coolingRate)
{
this._temperature = temperature;
this._coolingRate = coolingRate;
}
public SimulatedAnnealing()
{
_temperature = 1000000;
_coolingRate = 0.003;
}
private double acceptanceProbability(double energy, double newEnergy, double temperature)
{
if (newEnergy < energy) return 1.0;
return Math.Exp((energy - newEnergy) / temperature);
}
public List<Gift> Solve(List<Tour> tours)
{
int numberOfTours = tours.Count;
List<Tour> bestTours = new List<Tour>();
while (_temperature > 1)
{
int randomNumber1 = random.Next(0, numberOfTours);
int randomNumber2 = random.Next(0, numberOfTours);
Tour first = tours[randomNumber1];
Tour second = tours[randomNumber2];
double firstWRW = Common.Algos.WeightedReindeerWeariness.Calculate(first);
double secondWRW = Common.Algos.WeightedReindeerWeariness.Calculate(second);
double currentEnergy = firstWRW + secondWRW;
List<Tour> changedTours = RouteImprovement.Swap(tours[randomNumber1], tours[randomNumber2]) as List<Tour>;
first = changedTours[0];
second = changedTours[1];
firstWRW = Common.Algos.WeightedReindeerWeariness.Calculate(first);
secondWRW = Common.Algos.WeightedReindeerWeariness.Calculate(second);
double neighbourEnergy = firstWRW + secondWRW;
if (acceptanceProbability(currentEnergy, neighbourEnergy, _temperature) >= random.Next(0, 1))
{
tours[randomNumber1] = changedTours[0];
tours[randomNumber2] = changedTours[1];
}
var currentNewEnergy = Common.Algos.WeightedReindeerWeariness.Calculate(bestTours);
Console.WriteLine("{0}, {1}", currentEnergy, currentNewEnergy);
if (currentEnergy < currentNewEnergy)
{
bestTours = tours;
}
_temperature *= 1 - _coolingRate;
}
List<Gift> bestGiftOrder = new List<Gift>();
foreach (Tour tour in bestTours)
{
bestGiftOrder.AddRange(tour.Gifts);
}
return bestGiftOrder;
}
}
}
|
using System;
using System.Collections.Generic;
using Common;
using FirstSolution.Algos;
namespace MetaHeuristics
{
public class SimulatedAnnealing : ISolver
{
double _temperature;
Random random = new Random();
double _coolingRate;
public SimulatedAnnealing(double temperature, double coolingRate)
{
this._temperature = temperature;
this._coolingRate = coolingRate;
}
public SimulatedAnnealing()
{
_temperature = 1000000;
_coolingRate = 0.003;
}
private double acceptanceProbability(double energy, double newEnergy, double temperature)
{
if (newEnergy < energy) return 1.0;
return Math.Exp((energy - newEnergy) / temperature);
}
public List<Gift> Solve(List<Tour> tours)
{
int numberOfTours = tours.Count;
List<Tour> bestTours = new List<Tour>();
while (_temperature > 1)
{
int randomNumber1 = random.Next(0, numberOfTours);
int randomNumber2 = random.Next(0, numberOfTours);
Tour first = tours[randomNumber1];
Tour second = tours[randomNumber2];
double firstWRW = Common.Algos.WeightedReindeerWeariness.Calculate(first);
double secondWRW = Common.Algos.WeightedReindeerWeariness.Calculate(second);
double currentEnergy = firstWRW + secondWRW;
List<Tour> changedTours = RouteImprovement.Swap(tours[randomNumber1], tours[randomNumber2]) as List<Tour>;
first = changedTours[0];
second = changedTours[1];
firstWRW = Common.Algos.WeightedReindeerWeariness.Calculate(first);
secondWRW = Common.Algos.WeightedReindeerWeariness.Calculate(second);
double neighbourEnergy = firstWRW + secondWRW;
if (acceptanceProbability(currentEnergy, neighbourEnergy, _temperature) >= random.Next(0, 1))
{
tours[randomNumber1] = changedTours[0];
tours[randomNumber2] = changedTours[1];
}
if (currentEnergy < Common.Algos.WeightedReindeerWeariness.Calculate(bestTours))
{
bestTours = tours;
}
_temperature *= 1 - _coolingRate;
}
List<Gift> bestGiftOrder = new List<Gift>();
foreach (Tour tour in bestTours)
{
bestGiftOrder.AddRange(tour.Gifts);
}
return bestGiftOrder;
}
}
}
|
mit
|
C#
|
f34ecf8d35f18c137cca92dc970f2b80041aeb1b
|
add string.Reverse() and string.FromBase()
|
martinlindhe/Punku
|
punku/Extensions/StringExtensions.cs
|
punku/Extensions/StringExtensions.cs
|
using System;
using System.Text;
using Punku;
public static class StringExtensions
{
/**
* repeat the string count times
*/
public static string Repeat (this string input, int count)
{
var builder = new StringBuilder ((input == null ? 0 : input.Length) * count);
for (int i = 0; i < count; i++)
builder.Append (input);
return builder.ToString ();
}
/**
* @return reversed string
*/
public static string Reverse (this string input)
{
if (input == null)
return null;
char[] array = input.ToCharArray ();
Array.Reverse (array);
return new String (array);
}
/**
* return the number of times letter occurs
*/
public static int Count (this string input, char letter)
{
int count = 0;
foreach (char c in input)
if (c == letter)
count++;
return count;
}
/**
* true if string only contains 0-9
*/
public static bool IsNumbersOnly (this string input)
{
if (input == "")
return false;
foreach (char c in input)
if (c < '0' || c > '9')
return false;
return true;
}
/**
* true if string only contains 0-9, a-z or A-Z
*/
public static bool IsAlphanumeric (this string input)
{
if (input == "")
return false;
foreach (char c in input)
if ((c < '0' || c > '9') && (c < 'a' || c > 'z') && (c < 'A' || c > 'Z'))
return false;
return true;
}
/**
* true if string is a palindrome, like "racecar"
*/
public static bool IsPalindrome (this string input)
{
if (input.Trim ().Length < 1)
return false;
char[] a1 = input.ToCharArray ();
char[] a2 = input.ToCharArray ();
Array.Reverse (a2);
for (int i = 0; i < a1.Length; i++)
if (a1 [i] != a2 [i])
return false;
return true;
}
/**
* Decodes a base-x encoded value
*/
public static ulong FromBase (this string input, uint numberBase)
{
// TODO verify all digits are valid numbers in numberBase
var reversed = input.Reverse ();
ulong result = 0;
int pos = 0;
foreach (char c in reversed) {
result += c * (ulong)Math.Pow (numberBase, pos);
pos++;
}
return result;
}
/**
* Returns a Base64 encoded representation of the string, converted to UTF-8
*/
public static string ToBase64 (this string input)
{
return System.Text.ASCIIEncoding.UTF8.GetBytes (input).ToBase64 ();
}
/**
* Decodes a Base64 string to UTF-8
*/
public static string FromBase64 (this string input)
{
return System.Text.ASCIIEncoding.UTF8.GetString (input.FromBase64ToByteArray ());
}
/**
* Decodes a Base64 string to byte[] array
*/
public static byte[] FromBase64ToByteArray (this string input)
{
return System.Convert.FromBase64String (input);
}
}
|
using System;
using System.Text;
using Punku;
public static class StringExtensions
{
/**
* repeat the string count times
*/
public static string Repeat (this string input, int count)
{
var builder = new StringBuilder ((input == null ? 0 : input.Length) * count);
for (int i = 0; i < count; i++)
builder.Append (input);
return builder.ToString ();
}
/**
* return the number of times letter occurs
*/
public static int Count (this string input, char letter)
{
int count = 0;
foreach (char c in input)
if (c == letter)
count++;
return count;
}
/**
* true if string only contains 0-9
*/
public static bool IsNumbersOnly (this string input)
{
if (input == "")
return false;
foreach (char c in input)
if (c < '0' || c > '9')
return false;
return true;
}
/**
* true if string only contains 0-9, a-z or A-Z
*/
public static bool IsAlphanumeric (this string input)
{
if (input == "")
return false;
foreach (char c in input)
if ((c < '0' || c > '9') && (c < 'a' || c > 'z') && (c < 'A' || c > 'Z'))
return false;
return true;
}
/**
* true if string is a palindrome, like "racecar"
*/
public static bool IsPalindrome (this string input)
{
if (input.Trim ().Length < 1)
return false;
char[] a1 = input.ToCharArray ();
char[] a2 = input.ToCharArray ();
Array.Reverse (a2);
for (int i = 0; i < a1.Length; i++)
if (a1 [i] != a2 [i])
return false;
return true;
}
/**
* Returns a Base64 encoded representation of the string, converted to UTF-8
*/
public static string ToBase64 (this string input)
{
return System.Text.ASCIIEncoding.UTF8.GetBytes (input).ToBase64 ();
}
/**
* Decodes a Base64 string to UTF-8
*/
public static string FromBase64 (this string input)
{
return System.Text.ASCIIEncoding.UTF8.GetString (input.FromBase64ToByteArray ());
}
/**
* Decodes a Base64 string to byte[] array
*/
public static byte[] FromBase64ToByteArray (this string input)
{
return System.Convert.FromBase64String (input);
}
}
|
mit
|
C#
|
55421b0065a8e22b66e260ae594463a04d1bdbf5
|
Add missing full stop
|
NeoAdonis/osu,ppy/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,smoogipooo/osu,peppy/osu,ppy/osu,UselessToucan/osu,peppy/osu,peppy/osu-new,UselessToucan/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu
|
osu.Game.Rulesets.Mania/Mods/ManiaModMirror.cs
|
osu.Game.Rulesets.Mania/Mods/ManiaModMirror.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Mods;
using System.Linq;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Mania.Beatmaps;
namespace osu.Game.Rulesets.Mania.Mods
{
public class ManiaModMirror : Mod, IApplicableToBeatmap
{
public override string Name => "Mirror";
public override string Acronym => "MR";
public override ModType Type => ModType.Conversion;
public override string Description => "Notes are flipped horizontally.";
public override double ScoreMultiplier => 1;
public override bool Ranked => true;
public void ApplyToBeatmap(IBeatmap beatmap)
{
var availableColumns = ((ManiaBeatmap)beatmap).TotalColumns;
beatmap.HitObjects.OfType<ManiaHitObject>().ForEach(h => h.Column = availableColumns - 1 - h.Column);
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Mods;
using System.Linq;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Mania.Beatmaps;
namespace osu.Game.Rulesets.Mania.Mods
{
public class ManiaModMirror : Mod, IApplicableToBeatmap
{
public override string Name => "Mirror";
public override string Acronym => "MR";
public override ModType Type => ModType.Conversion;
public override string Description => "Notes are flipped horizontally";
public override double ScoreMultiplier => 1;
public override bool Ranked => true;
public void ApplyToBeatmap(IBeatmap beatmap)
{
var availableColumns = ((ManiaBeatmap)beatmap).TotalColumns;
beatmap.HitObjects.OfType<ManiaHitObject>().ForEach(h => h.Column = availableColumns - 1 - h.Column);
}
}
}
|
mit
|
C#
|
1c4a3c584a76fb9ecbf7b56d6d62850fcc89b88d
|
Use correct lookup type to ensure username based lookups always prefer username
|
ppy/osu,peppy/osu,peppy/osu-new,NeoAdonis/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu
|
osu.Game/Online/API/Requests/GetUserRequest.cs
|
osu.Game/Online/API/Requests/GetUserRequest.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Users;
using osu.Game.Rulesets;
namespace osu.Game.Online.API.Requests
{
public class GetUserRequest : APIRequest<User>
{
private readonly string lookup;
public readonly RulesetInfo Ruleset;
private readonly LookupType lookupType;
/// <summary>
/// Gets the currently logged-in user.
/// </summary>
public GetUserRequest()
{
}
/// <summary>
/// Gets a user from their ID.
/// </summary>
/// <param name="userId">The user to get.</param>
/// <param name="ruleset">The ruleset to get the user's info for.</param>
public GetUserRequest(long? userId = null, RulesetInfo ruleset = null)
{
lookup = userId.ToString();
lookupType = LookupType.Id;
Ruleset = ruleset;
}
/// <summary>
/// Gets a user from their username.
/// </summary>
/// <param name="username">The user to get.</param>
/// <param name="ruleset">The ruleset to get the user's info for.</param>
public GetUserRequest(string username = null, RulesetInfo ruleset = null)
{
lookup = username;
lookupType = LookupType.Username;
Ruleset = ruleset;
}
protected override string Target => lookup != null ? $@"users/{lookup}/{Ruleset?.ShortName}?k={lookupType.ToString().ToLower()}" : $@"me/{Ruleset?.ShortName}";
private enum LookupType
{
Id,
Username
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Users;
using osu.Game.Rulesets;
namespace osu.Game.Online.API.Requests
{
public class GetUserRequest : APIRequest<User>
{
private readonly string userIdentifier;
public readonly RulesetInfo Ruleset;
/// <summary>
/// Gets the currently logged-in user.
/// </summary>
public GetUserRequest()
{
}
/// <summary>
/// Gets a user from their ID.
/// </summary>
/// <param name="userId">The user to get.</param>
/// <param name="ruleset">The ruleset to get the user's info for.</param>
public GetUserRequest(long? userId = null, RulesetInfo ruleset = null)
{
this.userIdentifier = userId.ToString();
Ruleset = ruleset;
}
/// <summary>
/// Gets a user from their username.
/// </summary>
/// <param name="username">The user to get.</param>
/// <param name="ruleset">The ruleset to get the user's info for.</param>
public GetUserRequest(string username = null, RulesetInfo ruleset = null)
{
this.userIdentifier = username;
Ruleset = ruleset;
}
protected override string Target => userIdentifier != null ? $@"users/{userIdentifier}/{Ruleset?.ShortName}" : $@"me/{Ruleset?.ShortName}";
}
}
|
mit
|
C#
|
69bc3ef98c4d3e664560f14257caf5f4856cc743
|
Replace two xml comment instances of 'OmitOnRecursionGuard' with 'RecursionGuard'
|
yuva2achieve/AutoFixture,sean-gilliam/AutoFixture,yuva2achieve/AutoFixture,adamchester/AutoFixture,sbrockway/AutoFixture,mrinaldi/AutoFixture,sergeyshushlyapin/AutoFixture,olegsych/AutoFixture,sbrockway/AutoFixture,olegsych/AutoFixture,amarant/AutoFixture,hackle/AutoFixture,zvirja/AutoFixture,StevenJiang2015/AutoFixture,adamchester/AutoFixture,dcastro/AutoFixture,sergeyshushlyapin/AutoFixture,dcastro/AutoFixture,mrinaldi/AutoFixture,amarant/AutoFixture,dlongest/AutoFixture,Pvlerick/AutoFixture,AutoFixture/AutoFixture,dlongest/AutoFixture,hackle/AutoFixture,StevenJiang2015/AutoFixture
|
Src/AutoFixture/OmitOnRecursionBehavior.cs
|
Src/AutoFixture/OmitOnRecursionBehavior.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ploeh.AutoFixture.Kernel;
namespace Ploeh.AutoFixture
{
/// <summary>
/// Decorates an <see cref="ISpecimenBuilder" /> with a
/// <see cref="RecursionGuard" />.
/// </summary>
public class OmitOnRecursionBehavior : ISpecimenBuilderTransformation
{
/// <summary>
/// Decorates the supplied <see cref="ISpecimenBuilder" /> with an
/// <see cref="RecursionGuard"/>.
/// </summary>
/// <param name="builder">The builder to decorate.</param>
/// <returns>
/// <paramref name="builder" /> decorated with an
/// <see cref="RecursionGuard" />.
/// </returns>
public ISpecimenBuilder Transform(ISpecimenBuilder builder)
{
if (builder == null)
throw new ArgumentNullException("builder");
return new RecursionGuard(builder, new OmitOnRecursionHandler());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ploeh.AutoFixture.Kernel;
namespace Ploeh.AutoFixture
{
/// <summary>
/// Decorates an <see cref="ISpecimenBuilder" /> with a
/// <see cref="OmitOnRecursionGuard" />.
/// </summary>
public class OmitOnRecursionBehavior : ISpecimenBuilderTransformation
{
/// <summary>
/// Decorates the supplied <see cref="ISpecimenBuilder" /> with an
/// <see cref="OmitOnRecursionGuard"/>.
/// </summary>
/// <param name="builder">The builder to decorate.</param>
/// <returns>
/// <paramref name="builder" /> decorated with an
/// <see cref="RecursionGuard" />.
/// </returns>
public ISpecimenBuilder Transform(ISpecimenBuilder builder)
{
if (builder == null)
throw new ArgumentNullException("builder");
return new RecursionGuard(builder, new OmitOnRecursionHandler());
}
}
}
|
mit
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.