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 |
|---|---|---|---|---|---|---|---|---|
506754719260c505ef2a5c2b5535988856eda9a1 | refactor the Program class | LukeWinikates/dotnet-toolbox,dotnet-toolbox/dotnet-toolbox,dotnet-toolbox/dotnet-toolbox,LukeWinikates/dotnet-toolbox,LukeWinikates/dotnet-toolbox,dotnet-toolbox/dotnet-toolbox,LukeWinikates/dotnet-toolbox,dotnet-toolbox/dotnet-toolbox | src/dotnet-toolbox.worker/Program.cs | src/dotnet-toolbox.worker/Program.cs | using System;
using System.Threading;
using StackExchange.Redis;
using dotnet_toolbox.worker.PackageCrawler;
using dotnet_toolbox.worker.PackageCrawling;
using dotnet_toolbox.common.Env;
using dotnet_toolbox.common;
namespace dotnet_toolbox.worker
{
public class Program
{
private ConnectionMultiplexer muxer;
private RealTimerProvider timerProvider;
public Program(ConnectionMultiplexer muxer, RealTimerProvider timerProvider)
{
this.muxer = muxer;
this.timerProvider = timerProvider;
}
public static void Main(string[] args)
{
Console.WriteLine("Starting Background Worker Process");
var muxer = ConnectionMultiplexer.Connect(EnvironmentReader.FromEnvironment().RedisConnectionString);
Console.WriteLine("DB Connection Successful");
var timerProvider = new RealTimerProvider();
new Program(muxer, timerProvider).Run();
}
public void Run()
{
Console.WriteLine("Starting crawler");
new PackageCrawlerJobListener(timerProvider, CreatePackagesDbConnection(), new Crawler(CreatePackagesDbConnection(), new NuspecDownload())).Listen();
Console.Read(); // block forever
}
private IDatabase CreatePackagesDbConnection()
{
return muxer.GetDatabase(Constants.Redis.PACKAGES_DB);
}
}
public class RealTimerProvider : ITimerProvider
{
public void StartWithCallback(Action action)
{
var timer = new Timer(_ => {
Console.WriteLine("Timer triggered");
action();
Console.WriteLine("Timer callback completed");
}, null, 1000, 2000);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
using StackExchange.Redis;
using dotnet_toolbox.worker.PackageCrawler;
using dotnet_toolbox.worker.PackageCrawling;
using dotnet_toolbox.common.Env;
using dotnet_toolbox.common;
namespace dotnet_toolbox.worker
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Starting Background Worker Process");
var muxer = ConnectionMultiplexer.Connect(EnvironmentReader.FromEnvironment().RedisConnectionString);
var db = muxer.GetDatabase(Constants.Redis.PACKAGES_DB);
Console.WriteLine("DB Connection Successful");
var timerProvider = new RealTimerProvider();
Console.WriteLine("Starting crawler");
new PackageCrawlerJobListener(timerProvider, db, new Crawler(db, new NuspecDownload())).Listen();
Console.Read(); // block forever
}
}
public class RealTimerProvider : ITimerProvider
{
public void StartWithCallback(Action action)
{
var timer = new Timer(_ => action(), null, 1000, 1000);
}
}
}
| mit | C# |
c0c8b36f8d06ff78bd5625f943cc2da1d66576ec | Format trivial problem at bottom-right. | ethankennerly/add-it-up,ethankennerly/add-it-up | Assets/Scripts/Model.cs | Assets/Scripts/Model.cs | using System; // Array
using System.Collections.Generic; // List
public class Model
{
public ViewModel view = new ViewModel();
public bool isVerbose = true;
private string[] text = new string[]{"Canvas", "Text"};
private string[] digits = new string[]{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
};
private string entry = "";
private string page = "";
private string footer = "";
private string problem = "";
private int lineMax = 9;
private string state = "";
private int score = 0;
private List<int> remains = new List<int>();
public void Start()
{
state = "start";
}
private void SetText(string[] address, string text)
{
ControllerUtil.SetNews(view.news, address, text, "text");
}
private void SetState(string[] address, string state)
{
ControllerUtil.SetNews(view.news, address, state);
}
public void OnMouseDown(string name)
{
if (isVerbose) {
Toolkit.Log("OnMouseDown: " + name);
}
}
public void InputString(string input)
{
if (isVerbose) {
Toolkit.Log("InputString: " + input);
}
if (" " == input || "\n" == input) {
Submit();
}
if ("\b" == input) {
RemoveLastDigit();
}
else {
int digit = Array.IndexOf(digits, input);
if (0 <= digit) {
InputDigit(input);
}
}
}
public void InputDigit(string input)
{
if (entry.Length < lineMax) {
entry += input;
}
}
public void RemoveLastDigit()
{
if (1 <= entry.Length) {
entry = entry.Substring(0, entry.Length - 1);
}
}
private string FormatProblem()
{
int lineCount = 6;
string problem = "";
for (int index = lineCount - 1; 0 <= index; index--) {
if (index < remains.Count) {
problem += remains[index];
}
problem += "\n";
}
return problem;
}
private string Format()
{
string formatted;
problem = FormatProblem();
if ("" == entry) {
footer = "SCORE\n" + score;
}
else {
footer = "ENTER\n" + entry;
}
formatted = problem + footer;
return formatted;
}
public void Update()
{
if ("start" == state) {
page = "ADD1TUP\n\n\n\n\nPRESS\nENTEROR\nSPACEKEY";
}
else {
page = Format();
}
SetText(text, page);
}
private void Submit()
{
entry = "";
if ("start" == state) {
state = "play";
remains.Add(3);
remains.Add(2);
}
}
}
| using System; // Array
public class Model
{
public ViewModel view = new ViewModel();
public bool isVerbose = true;
private string[] text = new string[]{"Canvas", "Text"};
private string[] digits = new string[]{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
};
private string entry = "";
private string page = "";
private string footer = "";
private string problem = "";
private int lineMax = 9;
private string state = "";
private int score = 0;
public void Start()
{
state = "start";
}
private void SetText(string[] address, string text)
{
ControllerUtil.SetNews(view.news, address, text, "text");
}
private void SetState(string[] address, string state)
{
ControllerUtil.SetNews(view.news, address, state);
}
public void OnMouseDown(string name)
{
if (isVerbose) {
Toolkit.Log("OnMouseDown: " + name);
}
}
public void InputString(string input)
{
if (isVerbose) {
Toolkit.Log("InputString: " + input);
}
if (" " == input || "\n" == input) {
Submit();
}
if ("\b" == input) {
RemoveLastDigit();
}
else {
int digit = Array.IndexOf(digits, input);
if (0 <= digit) {
InputDigit(input);
}
}
}
public void InputDigit(string input)
{
if (entry.Length < lineMax) {
entry += input;
}
}
public void RemoveLastDigit()
{
if (1 <= entry.Length) {
entry = entry.Substring(0, entry.Length - 1);
}
}
private string Format()
{
string formatted;
problem = "\n\n\n\n\n\n";
if ("" == entry) {
footer = "SCORE\n" + score;
}
else {
footer = "ENTER\n" + entry;
}
formatted = problem + footer;
return formatted;
}
public void Update()
{
if ("start" == state) {
page = "ADD1TUP\n\n\n\n\nPRESS\nENTEROR\nSPACEKEY";
}
else {
page = Format();
}
SetText(text, page);
}
private void Submit()
{
entry = "";
if ("start" == state) {
state = "play";
}
}
}
| mit | C# |
60f597dd79fc2dcbf8807361b8dde5fe91d16e2d | Add ControlFlow.Fail shim | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.SourceGenerators/Shims/ControlFlow.cs | source/Nuke.SourceGenerators/Shims/ControlFlow.cs | // Copyright 2021 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using JetBrains.Annotations;
namespace Nuke.Common.IO
{
public static class TextTasks
{
public static string[] ReadAllLines(string path)
{
return File.ReadAllLines(path);
}
}
}
namespace Nuke.Common
{
public static class ControlFlow
{
[AssertionMethod]
[ContractAnnotation("obj:null=>halt")]
public static T NotNull<T>(
[AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull]
this T obj,
string message = null)
{
return obj ?? throw new Exception(message ?? $"{typeof(T).Name} != null");
}
public static void Assert(bool condition, string message)
{
if (!condition)
throw new Exception(message);
}
public static void Fail(string message)
{
throw new Exception(message);
}
}
}
| // Copyright 2021 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using JetBrains.Annotations;
namespace Nuke.Common.IO
{
public static class TextTasks
{
public static string[] ReadAllLines(string path)
{
return File.ReadAllLines(path);
}
}
}
namespace Nuke.Common
{
public static class ControlFlow
{
[AssertionMethod]
[ContractAnnotation("obj:null=>halt")]
public static T NotNull<T>(
[AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull]
this T obj,
string message = null)
{
return obj ?? throw new Exception(message ?? $"{typeof(T).Name} != null");
}
public static void Assert(bool condition, string message)
{
if (!condition)
throw new Exception(message);
}
}
}
| mit | C# |
27382f37dbd086881d8a09e682d31dc7b79a18f2 | Fix typo in IGeolocator | jamesmontemagno/GeolocatorPlugin,jamesmontemagno/GeolocatorPlugin | src/Geolocator.Plugin.Abstractions/IGeolocator.cs | src/Geolocator.Plugin.Abstractions/IGeolocator.cs | using System;
using System.Threading;
using System.Threading.Tasks;
namespace Plugin.Geolocator.Abstractions
{
/// <summary>
/// Interface for Geolocator
/// </summary>
public interface IGeolocator
{
/// <summary>
/// Position error event handler
/// </summary>
event EventHandler<PositionErrorEventArgs> PositionError;
/// <summary>
/// Position changed event handler
/// </summary>
event EventHandler<PositionEventArgs> PositionChanged;
/// <summary>
/// Desired accuracy in meteres
/// </summary>
double DesiredAccuracy { get; set; }
/// <summary>
/// Gets if you are listening for location changes
/// </summary>
bool IsListening { get; }
/// <summary>
/// Gets if device supports heading
/// </summary>
bool SupportsHeading { get; }
/// <summary>
/// Gets if geolocation is available on device
/// </summary>
bool IsGeolocationAvailable { get; }
/// <summary>
/// Gets if geolocation is enabled on device
/// </summary>
bool IsGeolocationEnabled { get; }
/// <summary>
/// Gets position async with specified parameters
/// </summary>
/// <param name="timeoutMilliseconds">Timeout in milliseconds to wait, Default Infinite</param>
/// <param name="token">Cancelation token</param>
/// <param name="includeHeading">If you would like to include heading</param>
/// <returns>Position</returns>
Task<Position> GetPositionAsync(int timeoutMilliseconds = Timeout.Infinite, CancellationToken? token = null, bool includeHeading = false);
/// <summary>
/// Start listening for changes
/// </summary>
/// <param name="minTime">Time</param>
/// <param name="minDistance">Distance</param>
/// <param name="includeHeading">Include heading or not</param>
/// <param name="settings">Optional settings (iOS only)</param>
Task<bool> StartListeningAsync(int minTime, double minDistance, bool includeHeading = false, ListenerSettings settings = null);
/// <summary>
/// Stop listening
/// </summary>
Task<bool> StopListeningAsync();
}
}
| using System;
using System.Threading;
using System.Threading.Tasks;
namespace Plugin.Geolocator.Abstractions
{
/// <summary>
/// Interface for Geolocator
/// </summary>
public interface IGeolocator
{
/// <summary>
/// Position error event handler
/// </summary>
event EventHandler<PositionErrorEventArgs> PositionError;
/// <summary>
/// Position changed event handler
/// </summary>
event EventHandler<PositionEventArgs> PositionChanged;
/// <summary>
/// Desired accuracy in meteres
/// </summary>
double DesiredAccuracy { get; set; }
/// <summary>
/// Gets if you are listening for location changes
/// </summary>
bool IsListening { get; }
/// <summary>
/// Gets if device supports heading
/// </summary>
bool SupportsHeading { get; }
/// <summary>
/// Gets if geolocation is available on device
/// </summary>
bool IsGeolocationAvailable { get; }
/// <summary>
/// Gets if geolocation is enabled on device
/// </summary>
bool IsGeolocationEnabled { get; }
/// <summary>
/// Gets position async with specified parameters
/// </summary>
/// <param name="timeoutMilliseconds">Timeout in milliseconds to wait, Default Infinite</param>
/// <param name="token">Cancelation token</param>
/// <param name="includeHeading">If you would like to include heading</param>
/// <returns>Position</returns>
Task<Position> GetPositionAsync(int timeoutMilliseconds = Timeout.Infinite, CancellationToken? token = null, bool includeHeading = false);
/// <summary>
/// Start listening for changes
/// </summary>
/// <param name="minTime">Time</param>
/// <param name="minDistance">Distance</param>
/// <param name="includeHeading">Include heading or not</param>
/// <param name="settings">Optional settings (iOS only)</param>
Task<bool> StartListeningAsync(int minTime, double minDistance, bool includeHeading = false, ListenerSettings settings = null);
/// <summary>
/// Stop linstening
/// </summary>
Task<bool> StopListeningAsync();
}
}
| mit | C# |
87b335250f81dbb26cef0789b3a477116906437c | Add controller to minimal API, #3711 | quails4Eva/NSwag,RSuter/NSwag,quails4Eva/NSwag,quails4Eva/NSwag,RSuter/NSwag,RSuter/NSwag,RSuter/NSwag,quails4Eva/NSwag,RSuter/NSwag | src/NSwag.Sample.NET60Minimal/Program.cs | src/NSwag.Sample.NET60Minimal/Program.cs | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System;
var builder = WebApplication.CreateBuilder(args);
// Optional: Use controllers
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddOpenApiDocument(settings =>
{
settings.Title = "Minimal API";
settings.Version = "v1";
});
var app = builder.Build();
app.UseDeveloperExceptionPage();
app.UseOpenApi();
app.UseSwaggerUi3();
app.MapGet("/", (Func<string>)(() => "Hello World!"))
.WithTags("General");
app.MapGet("/sum/{a}/{b}", (int a, int b) => a + b)
.WithName("CalculateSum")
.WithTags("Calculator");
// Optional: Use controllers
app.UseRouting();
app.UseEndpoints(x =>
{
x.MapControllers();
});
app.Run();
[ApiController]
[Route("examples")]
public class ExampleController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok("Get Method");
}
} | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddOpenApiDocument(settings =>
{
settings.Title = "Minimal API";
settings.Version = "v1";
});
var app = builder.Build();
app.UseDeveloperExceptionPage();
app.UseOpenApi();
app.UseSwaggerUi3();
app.MapGet("/", (Func<string>)(() => "Hello World!"))
.WithTags("General");
app.MapGet("/sum/{a}/{b}", (Func<int, int, int>)((a, b) => a + b))
.WithName("CalculateSum")
.WithTags("Calculator");
app.Run(); | mit | C# |
4413cd916aa413ca6694b6bb8806579aa017fe00 | remove unuse code | xizhe-zhang/aspnet5-angular2-typescript,xizhe-zhang/aspnet5-angular2-typescript,xizhe-zhang/aspnet5-angular2-typescript,xizhe-zhang/aspnet5-angular2-typescript | src/PhotoGallery/Views/Home/Index.cshtml | src/PhotoGallery/Views/Home/Index.cshtml | @{
ViewBag.Title = "PhotoGallery";
}
@section styles
{
<link href="~/lib/css/jquery.fancybox.css" rel="stylesheet" />
<link href="~/lib/css/alertify.core.css" rel="stylesheet" />
<link href="~/lib/css/alertify.bootstrap.css" rel="stylesheet" />
<link href="~/lib/css/flipclock.css" rel="stylesheet" />
<link href="~/lib/css/style.css" rel="stylesheet" />
@*<link href="~/lib/css/alertify.default.css" rel="stylesheet" />*@
}
<pos-app style="height: 100vh;" id="pos">
<div style="display:flex; justify-content: center; align-items: center; font-size: 20px; height: 100vh; background-color: white;">
<i class="fa fa-refresh fa-spin fa-3x fa-fw"></i>
<span>Loading...</span>
</div>
</pos-app>
@section scripts
{
<script src="~/lib/js/jquery.fancybox.pack.js"></script>
<script src="~/lib/js/alertify.min.js"></script>
<script src="~/lib/js/qrcode.min.js"></script>
<script src="~/lib/js/flipclock.min.js"></script>
}
@section customScript
{
System.import('app').catch(console.log.bind(console));
$(document).ready(function() {
$('.fancybox').fancybox();
});
} | @{
ViewBag.Title = "PhotoGallery";
}
@section styles
{
<link href="~/lib/css/jquery.fancybox.css" rel="stylesheet" />
<link href="~/lib/css/alertify.core.css" rel="stylesheet" />
<link href="~/lib/css/alertify.bootstrap.css" rel="stylesheet" />
<link href="~/lib/css/flipclock.css" rel="stylesheet" />
<link href="~/lib/css/style.css" rel="stylesheet" />
@*<link href="~/lib/css/alertify.default.css" rel="stylesheet" />*@
}
<pos-app style="height: 100vh;" id="pos">
<div style="display:flex; justify-content: center; align-items: center; font-size: 20px; height: 100vh; background-color: white;">
<i class="fa fa-refresh fa-spin fa-3x fa-fw"></i>
<span>Loading...</span>
</div>
</pos-app>
@section scripts
{
<script src="~/lib/js/jquery.fancybox.pack.js"></script>
<script src="~/lib/js/alertify.min.js"></script>
<script src="~/lib/js/qrcode.min.js"></script>
<script src="~/lib/js/flipclock.min.js"></script>
}
@section customScript
{
System.import('app').catch(console.log.bind(console));
$(document).ready(function() {
$('.fancybox').fancybox();
});
var serverFeed = {};
} | mit | C# |
ea725ccdbe06aefd005bec450eebc1bdee4b90bb | Remove unused using | feliwir/openSage,feliwir/openSage | src/OpenSage.Game/Graphics/Util/ConversionExtensions.cs | src/OpenSage.Game/Graphics/Util/ConversionExtensions.cs | using System.Numerics;
using OpenSage.Data.Ini;
namespace OpenSage.Graphics.Util
{
public static class ConversionExtensions
{
public static Vector3 ToVector3(this IniColorRgb value)
{
return new Vector3(value.R / 255.0f, value.G / 255.0f, value.B / 255.0f);
}
public static Vector3 ToVector3(this Coord3D value)
{
return new Vector3(value.X, value.Y, value.Z);
}
}
}
| using System.Numerics;
using OpenSage.Data.Ini;
using OpenSage.Mathematics;
namespace OpenSage.Graphics.Util
{
public static class ConversionExtensions
{
public static Vector3 ToVector3(this IniColorRgb value)
{
return new Vector3(value.R / 255.0f, value.G / 255.0f, value.B / 255.0f);
}
public static Vector3 ToVector3(this Coord3D value)
{
return new Vector3(value.X, value.Y, value.Z);
}
}
}
| mit | C# |
a37bf0f675f150d6e29b1b91668145931c1641e8 | Update CardView.cs | xamarinhq/app-evolve,xamarinhq/app-evolve | src/XamarinEvolve.Clients.UI/Controls/CardView.cs | src/XamarinEvolve.Clients.UI/Controls/CardView.cs | using Xamarin.Forms;
namespace XamarinEvolve.Clients.UI
{
public class CardView : Frame
{
public CardView()
{
Padding = 0;
if (Device.OS == TargetPlatform.iOS)
{
HasShadow = false;
OutlineColor = Color.Transparent;
BackgroundColor = Color.Transparent;
}
}
}
}
| using Xamarin.Forms;
namespace XamarinEvolve.Clients.UI
{
public class CardView : Frame
{
public CardView()
{
Padding = 0;
if (Device.OS == TargetPlatform.iOS || Device.OS == TargetPlatform.iOS)
{
HasShadow = false;
OutlineColor = Color.Transparent;
BackgroundColor = Color.Transparent;
}
}
}
}
| mit | C# |
f303816c20cd7c8da21464bb30c5cd0dbdc12481 | Clean up AssemblyWeaver unused using and fields. | FloodProject/flood,FloodProject/flood,FloodProject/flood | src/Tools/EngineWeaver/AssemblyWeaver.cs | src/Tools/EngineWeaver/AssemblyWeaver.cs | using EngineWeaver.Util;
using Mono.Cecil;
namespace EngineWeaver
{
public class AssemblyWeaver
{
private AssemblyDefinition destAssembly;
public AssemblyWeaver(string destAssemblyPath)
{
destAssembly = CecilUtils.GetAssemblyDef(destAssemblyPath);
}
public void AddAssembly(string origAssemblyPath)
{
var origAssembly = CecilUtils.GetAssemblyDef(origAssemblyPath);
var copier = new CecilCopier(origAssembly.MainModule, destAssembly.MainModule);
foreach (var origType in origAssembly.MainModule.Types)
if(origType.BaseType != null)
copier.Copy(origType);
copier.Process();
}
public void Write(string outputAssemblyPath)
{
var writerParameters = new WriterParameters();
writerParameters.WriteSymbols = destAssembly.MainModule.HasSymbols;
writerParameters.SymbolWriterProvider = new Mono.Cecil.Pdb.PdbWriterProvider();
destAssembly.Write(outputAssemblyPath, writerParameters);
}
}
}
| using EngineWeaver.Util;
using Mono.Cecil;
using Mono.Cecil.Cil;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace EngineWeaver
{
public class AssemblyWeaver
{
private string destAssemblyPath;
private AssemblyDefinition destAssembly;
public AssemblyWeaver(string destAssemblyPath)
{
this.destAssemblyPath = destAssemblyPath;
destAssembly = CecilUtils.GetAssemblyDef(destAssemblyPath);
}
public void AddAssembly(string origAssemblyPath)
{
var origAssembly = CecilUtils.GetAssemblyDef(origAssemblyPath);
var copier = new CecilCopier(origAssembly.MainModule, destAssembly.MainModule);
foreach (var origType in origAssembly.MainModule.Types)
if(origType.BaseType != null)
copier.Copy(origType);
copier.Process();
}
public void Write(string outputAssemblyPath)
{
var writerParameters = new WriterParameters();
writerParameters.WriteSymbols = destAssembly.MainModule.HasSymbols;
writerParameters.SymbolWriterProvider = new Mono.Cecil.Pdb.PdbWriterProvider();
destAssembly.Write(outputAssemblyPath, writerParameters);
}
}
}
| bsd-2-clause | C# |
3e116026cc62479d275324c9836afb15a8c486e5 | Make edu levels cacheable | roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University | R7.University/entities/EduLevelInfo.cs | R7.University/entities/EduLevelInfo.cs | //
// EduLevelInfo.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2015
//
// 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 DotNetNuke.ComponentModel.DataAnnotations;
namespace R7.University
{
public enum EduType
{
School = 'S',
Intermediate = 'I',
High = 'H',
Additional = 'A'
}
[TableName ("University_EduLevels")]
[PrimaryKey ("EduLevelID", AutoIncrement = true)]
[Cacheable]
public class EduLevelInfo: IReferenceEntity
{
#region Properties
public int EduLevelID { get; set; }
[ColumnName ("Type")]
public string EduTypeString { get; set; }
[IgnoreColumn]
public EduType EduType
{
get { return (EduType)EduTypeString [0]; }
set { EduTypeString = ((char)value).ToString (); }
}
#endregion
#region IReferenceEntity implementation
public string Title { get; set; }
public string ShortTitle { get; set; }
[IgnoreColumn]
public string DisplayShortTitle
{
get { return FormatShortTitle (Title, ShortTitle); }
}
public static string FormatShortTitle (string title, string shortTitle)
{
return !string.IsNullOrWhiteSpace (shortTitle)? shortTitle : title;
}
#endregion
}
}
| //
// EduLevelInfo.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2015
//
// 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 DotNetNuke.ComponentModel.DataAnnotations;
namespace R7.University
{
public enum EduType
{
School = 'S',
Intermediate = 'I',
High = 'H',
Additional = 'A'
}
[TableName ("University_EduLevels")]
[PrimaryKey ("EduLevelID", AutoIncrement = true)]
public class EduLevelInfo: IReferenceEntity
{
#region Properties
public int EduLevelID { get; set; }
[ColumnName ("Type")]
public string EduTypeString { get; set; }
[IgnoreColumn]
public EduType EduType
{
get { return (EduType)EduTypeString [0]; }
set { EduTypeString = ((char)value).ToString (); }
}
#endregion
#region IReferenceEntity implementation
public string Title { get; set; }
public string ShortTitle { get; set; }
[IgnoreColumn]
public string DisplayShortTitle
{
get { return FormatShortTitle (Title, ShortTitle); }
}
public static string FormatShortTitle (string title, string shortTitle)
{
return !string.IsNullOrWhiteSpace (shortTitle)? shortTitle : title;
}
#endregion
}
}
| agpl-3.0 | C# |
02dffaf794bda9f3b1a5c9a4516392f0716ce900 | Add JsonRpc version to JsonRequest | KAAndrey/JSON-RPC.NET,Astn/JSON-RPC.NET,Astn/JSON-RPC.NET,Astn/JSON-RPC.NET,KAAndrey/JSON-RPC.NET,KAAndrey/JSON-RPC.NET | Json-Rpc/JsonRequest.cs | Json-Rpc/JsonRequest.cs | using Newtonsoft.Json;
namespace AustinHarris.JsonRpc
{
/// <summary>
/// Represents a JsonRpc request
/// </summary>
[JsonObject(MemberSerialization.OptIn)]
public class JsonRequest
{
public JsonRequest()
{
}
public JsonRequest(string method, object pars, object id)
{
Method = method;
Params = pars;
Id = id;
}
[JsonProperty("jsonrpc")]
public string JsonRpc => "2.0";
[JsonProperty("method")]
public string Method { get; set; }
[JsonProperty("params")]
public object Params { get; set; }
[JsonProperty("id")]
public object Id { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace AustinHarris.JsonRpc
{
/// <summary>
/// Represents a JsonRpc request
/// </summary>
[JsonObject(MemberSerialization.OptIn)]
public class JsonRequest
{
public JsonRequest()
{
}
[JsonProperty("method")]
public string Method { get; set; }
[JsonProperty("params")]
public object Params { get; set; }
[JsonProperty("id")]
public object Id { get; set; }
}
}
| mit | C# |
fc85a5d1d510304f93edfb1a84625ef446c0c8e6 | Add forceStartSpeed slider to MicrogameStage | Barleytree/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare | Assets/Scripts/Stage/MicrogameStage.cs | Assets/Scripts/Stage/MicrogameStage.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MicrogameStage : Stage
{
public static string microgameId;
[Header("Override settings for debugging")]
[Header("Force Microgame must be changed when played from this scene")]
[Header("DO NOT COMMIT CHANGES TO THESE!")]
[SerializeField]
private string forceMicrogame;
[SerializeField]
private int forceDifficulty;
[SerializeField]
[Range(1, StageController.MAX_SPEED)]
private int forceStartSpeed = 1;
[SerializeField]
private bool speedUpEveryCycle = false;
public override void onStageStart()
{
//Update collection if microgame is forced, in case it's in the project but hasn't been added to the collection, for debugging
if (!string.IsNullOrEmpty(forceMicrogame))
{
GameController.instance.microgameCollection.updateMicrogames();
microgameId = forceMicrogame;
}
base.onStageStart();
}
public override Microgame getMicrogame(int num)
{
Microgame microgame = new Microgame(microgameId);
microgame.microgameId = microgameId;
return microgame;
}
public override int getMicrogameDifficulty(Microgame microgame, int num)
{
return forceDifficulty < 1 ? ((num % 3) + 1) : forceDifficulty;
}
public override int getStartSpeed()
{
return forceStartSpeed;
}
public override string getDiscordState(int microgameIndex)
{
return TextHelper.getLocalizedText("microgame." + microgameId + ".igname", microgameId);
}
public override Interruption[] getInterruptions(int num)
{
if ((!speedUpEveryCycle) && (num == 0 || num % 3 > 0))
return new Interruption[0];
return new Interruption[0].add(new Interruption(Interruption.SpeedChange.SpeedUp));
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MicrogameStage : Stage
{
public static string microgameId;
[Header("Override settings for debugging")]
[Header("Force Microgame must be changed when played from this scene")]
[Header("DO NOT COMMIT CHANGES TO THESE!")]
[SerializeField]
private string forceMicrogame;
[SerializeField]
private int forceDifficulty;
[SerializeField]
private bool speedUpEveryCycle = false;
public override void onStageStart()
{
//Update collection if microgame is forced, in case it's in the project but hasn't been added to the collection, for debugging
if (!string.IsNullOrEmpty(forceMicrogame))
{
GameController.instance.microgameCollection.updateMicrogames();
microgameId = forceMicrogame;
}
base.onStageStart();
}
public override Microgame getMicrogame(int num)
{
Microgame microgame = new Microgame(microgameId);
microgame.microgameId = microgameId;
return microgame;
}
public override int getMicrogameDifficulty(Microgame microgame, int num)
{
return forceDifficulty < 1 ? ((num % 3) + 1) : forceDifficulty;
}
public override string getDiscordState(int microgameIndex)
{
return TextHelper.getLocalizedText("microgame." + microgameId + ".igname", microgameId);
}
public override Interruption[] getInterruptions(int num)
{
if ((!speedUpEveryCycle) && (num == 0 || num % 3 > 0))
return new Interruption[0];
return new Interruption[0].add(new Interruption(Interruption.SpeedChange.SpeedUp));
}
}
| mit | C# |
71c86c1a9752cca2fde2582bb8f1f7d70b8351b0 | Clear the context in DrawThread.Cleanup regardless of backend | peppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework | osu.Framework/Threading/DrawThread.cs | osu.Framework/Threading/DrawThread.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.Statistics;
using System;
using System.Collections.Generic;
using osu.Framework.Development;
using osu.Framework.Graphics.OpenGL;
using osu.Framework.Platform;
using osuTK;
namespace osu.Framework.Threading
{
public class DrawThread : GameThread
{
private readonly GameHost host;
public DrawThread(Action onNewFrame, GameHost host)
: base(onNewFrame, "Draw")
{
this.host = host;
}
public override bool IsCurrent => ThreadSafety.IsDrawThread;
protected sealed override void OnInitialize()
{
var window = host.Window;
if (window != null)
{
window.MakeCurrent();
GLWrapper.Initialize(host);
GLWrapper.Reset(new Vector2(window.ClientSize.Width, window.ClientSize.Height));
}
}
internal sealed override void MakeCurrent()
{
base.MakeCurrent();
ThreadSafety.IsDrawThread = true;
// Seems to be required on some drivers as the context is lost from the draw thread.
host.Window?.MakeCurrent();
}
protected sealed override void Cleanup()
{
base.Cleanup();
host.Window.ClearCurrent();
}
internal override IEnumerable<StatisticsCounterType> StatisticsCounters => new[]
{
StatisticsCounterType.VBufBinds,
StatisticsCounterType.VBufOverflow,
StatisticsCounterType.TextureBinds,
StatisticsCounterType.FBORedraw,
StatisticsCounterType.DrawCalls,
StatisticsCounterType.ShaderBinds,
StatisticsCounterType.VerticesDraw,
StatisticsCounterType.VerticesUpl,
StatisticsCounterType.Pixels,
};
}
}
| // 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.Statistics;
using System;
using System.Collections.Generic;
using osu.Framework.Development;
using osu.Framework.Graphics.OpenGL;
using osu.Framework.Platform;
using osuTK;
using osuTK.Graphics;
namespace osu.Framework.Threading
{
public class DrawThread : GameThread
{
private readonly GameHost host;
public DrawThread(Action onNewFrame, GameHost host)
: base(onNewFrame, "Draw")
{
this.host = host;
}
public override bool IsCurrent => ThreadSafety.IsDrawThread;
protected sealed override void OnInitialize()
{
var window = host.Window;
if (window != null)
{
window.MakeCurrent();
GLWrapper.Initialize(host);
GLWrapper.Reset(new Vector2(window.ClientSize.Width, window.ClientSize.Height));
}
}
internal sealed override void MakeCurrent()
{
base.MakeCurrent();
ThreadSafety.IsDrawThread = true;
// Seems to be required on some drivers as the context is lost from the draw thread.
host.Window?.MakeCurrent();
}
protected sealed override void Cleanup()
{
base.Cleanup();
// specifically for mobile platforms so SDL does not need to be considered yet
if (GraphicsContext.CurrentContext != null)
GraphicsContext.CurrentContext.MakeCurrent(null);
}
internal override IEnumerable<StatisticsCounterType> StatisticsCounters => new[]
{
StatisticsCounterType.VBufBinds,
StatisticsCounterType.VBufOverflow,
StatisticsCounterType.TextureBinds,
StatisticsCounterType.FBORedraw,
StatisticsCounterType.DrawCalls,
StatisticsCounterType.ShaderBinds,
StatisticsCounterType.VerticesDraw,
StatisticsCounterType.VerticesUpl,
StatisticsCounterType.Pixels,
};
}
}
| mit | C# |
a1a7ddbb4bf22789aa06aa29ea0514e1ff4b227b | Mark articles_case with NullableStringBooleanFormatter | elastic/elasticsearch-net,elastic/elasticsearch-net | src/Nest/Analysis/TokenFilters/ElisionTokenFilter.cs | src/Nest/Analysis/TokenFilters/ElisionTokenFilter.cs | using System.Collections.Generic;
using System.Runtime.Serialization;
using Elasticsearch.Net;
namespace Nest
{
/// <summary>
/// A token filter which removes elisions. For example, “l’avion” (the plane) will tokenized as “avion” (plane).
/// </summary>
public interface IElisionTokenFilter : ITokenFilter
{
/// <summary>
/// Accepts articles setting which is a set of stop words articles
/// </summary>
[DataMember(Name = "articles")]
IEnumerable<string> Articles { get; set; }
/// <summary>
/// Whether articles should be handled case-insensitively. Defaults to <c>false</c>.
/// </summary>
[DataMember(Name = "articles_case")]
[JsonFormatter(typeof(NullableStringBooleanFormatter))]
bool? ArticlesCase { get; set; }
}
/// <inheritdoc cref="IElisionTokenFilter" />
public class ElisionTokenFilter : TokenFilterBase, IElisionTokenFilter
{
public ElisionTokenFilter() : base("elision") { }
/// <inheritdoc />
public IEnumerable<string> Articles { get; set; }
/// <inheritdoc />
public bool? ArticlesCase { get; set; }
}
/// <inheritdoc cref="IElisionTokenFilter" />
public class ElisionTokenFilterDescriptor
: TokenFilterDescriptorBase<ElisionTokenFilterDescriptor, IElisionTokenFilter>, IElisionTokenFilter
{
protected override string Type => "elision";
IEnumerable<string> IElisionTokenFilter.Articles { get; set; }
bool? IElisionTokenFilter.ArticlesCase { get; set; }
/// <inheritdoc cref="IElisionTokenFilter.Articles"/>
public ElisionTokenFilterDescriptor Articles(IEnumerable<string> articles) => Assign(articles, (a, v) => a.Articles = v);
/// <inheritdoc cref="IElisionTokenFilter.Articles"/>
public ElisionTokenFilterDescriptor Articles(params string[] articles) => Assign(articles, (a, v) => a.Articles = v);
/// <inheritdoc cref="IElisionTokenFilter.ArticlesCase"/>
public ElisionTokenFilterDescriptor ArticlesCase(bool? articlesCase = true) => Assign(articlesCase, (a, v) => a.ArticlesCase = v);
}
}
| using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Nest
{
/// <summary>
/// A token filter which removes elisions. For example, “l’avion” (the plane) will tokenized as “avion” (plane).
/// </summary>
public interface IElisionTokenFilter : ITokenFilter
{
/// <summary>
/// Accepts articles setting which is a set of stop words articles
/// </summary>
[DataMember(Name = "articles")]
IEnumerable<string> Articles { get; set; }
/// <summary>
/// Whether articles should be handled case-insensitively. Defaults to <c>false</c>.
/// </summary>
[DataMember(Name = "articles_case")]
bool? ArticlesCase { get; set; }
}
/// <inheritdoc cref="IElisionTokenFilter" />
public class ElisionTokenFilter : TokenFilterBase, IElisionTokenFilter
{
public ElisionTokenFilter() : base("elision") { }
/// <inheritdoc />
public IEnumerable<string> Articles { get; set; }
/// <inheritdoc />
public bool? ArticlesCase { get; set; }
}
/// <inheritdoc cref="IElisionTokenFilter" />
public class ElisionTokenFilterDescriptor
: TokenFilterDescriptorBase<ElisionTokenFilterDescriptor, IElisionTokenFilter>, IElisionTokenFilter
{
protected override string Type => "elision";
IEnumerable<string> IElisionTokenFilter.Articles { get; set; }
bool? IElisionTokenFilter.ArticlesCase { get; set; }
/// <inheritdoc cref="IElisionTokenFilter.Articles"/>
public ElisionTokenFilterDescriptor Articles(IEnumerable<string> articles) => Assign(articles, (a, v) => a.Articles = v);
/// <inheritdoc cref="IElisionTokenFilter.Articles"/>
public ElisionTokenFilterDescriptor Articles(params string[] articles) => Assign(articles, (a, v) => a.Articles = v);
/// <inheritdoc cref="IElisionTokenFilter.ArticlesCase"/>
public ElisionTokenFilterDescriptor ArticlesCase(bool? articlesCase = true) => Assign(articlesCase, (a, v) => a.ArticlesCase = v);
}
}
| apache-2.0 | C# |
4e6ae71b73337e85a17b8c88b130b98a087e7328 | Use standard lifecycle creation | Esri/arcgis-toolkit-dotnet | src/Toolkit.Forms/LayerLegend/LayerLegendRenderer.cs | src/Toolkit.Forms/LayerLegend/LayerLegendRenderer.cs | // /*******************************************************************************
// * Copyright 2012-2018 Esri
// *
// * 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.
// ******************************************************************************/
#if !NETSTANDARD2_0
using System.ComponentModel;
using Xamarin.Forms;
#if __ANDROID__
using Xamarin.Forms.Platform.Android;
#elif __IOS__
using Xamarin.Forms.Platform.iOS;
#elif NETFX_CORE
using Xamarin.Forms.Platform.UWP;
#endif
[assembly: ExportRenderer(typeof(Esri.ArcGISRuntime.Toolkit.Xamarin.Forms.LayerLegend), typeof(Esri.ArcGISRuntime.Toolkit.Xamarin.Forms.LayerLegendRenderer))]
namespace Esri.ArcGISRuntime.Toolkit.Xamarin.Forms
{
internal class LayerLegendRenderer : ViewRenderer<LayerLegend, UI.Controls.LayerLegend>
{
#if __ANDROID__
public LayerLegendRenderer(Android.Content.Context context)
: base(context)
{
}
#endif
protected override void OnElementChanged(ElementChangedEventArgs<LayerLegend> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
if (Control == null)
{
#if __ANDROID__
UI.Controls.LayerLegend ctrl = new UI.Controls.LayerLegend(Context);
#else
UI.Controls.LayerLegend ctrl = new UI.Controls.LayerLegend();
#endif
ctrl.IncludeSublayers = Element.IncludeSublayers;
ctrl.LayerContent = Element.LayerContent;
SetNativeControl(ctrl);
}
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (Control != null)
{
if (e.PropertyName == LayerLegend.IncludeSublayersProperty.PropertyName)
{
Control.IncludeSublayers = Element.IncludeSublayers;
}
else if (e.PropertyName == LayerLegend.LayerContentProperty.PropertyName)
{
Control.LayerContent = Element.LayerContent;
}
}
base.OnElementPropertyChanged(sender, e);
}
}
}
#endif | // /*******************************************************************************
// * Copyright 2012-2018 Esri
// *
// * 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.
// ******************************************************************************/
#if !NETSTANDARD2_0
using Xamarin.Forms;
#if __ANDROID__
using Xamarin.Forms.Platform.Android;
#elif __IOS__
using Xamarin.Forms.Platform.iOS;
#elif NETFX_CORE
using Xamarin.Forms.Platform.UWP;
#endif
[assembly: ExportRenderer(typeof(Esri.ArcGISRuntime.Toolkit.Xamarin.Forms.LayerLegend), typeof(Esri.ArcGISRuntime.Toolkit.Xamarin.Forms.LayerLegendRenderer))]
namespace Esri.ArcGISRuntime.Toolkit.Xamarin.Forms
{
internal class LayerLegendRenderer : ViewRenderer<LayerLegend, UI.Controls.LayerLegend>
{
#if __ANDROID__
public LayerLegendRenderer(Android.Content.Context context)
: base(context)
{
}
#endif
protected override void OnElementChanged(ElementChangedEventArgs<LayerLegend> e)
{
base.OnElementChanged(e);
if (Control == null)
{
SetNativeControl(e.NewElement?.NativeLayerLegend);
}
}
#if !NETFX_CORE
/// <inheritdoc />
protected override bool ManageNativeControlLifetime => false;
#endif
}
}
#endif | apache-2.0 | C# |
77460aae03572e0420e55085b13c6aff5292effa | Add GroupManager.TryGetGroup (string) | ermau/Tempest.Social | Desktop/Tempest.Social/GroupManager.cs | Desktop/Tempest.Social/GroupManager.cs | //
// GroupManager.cs
//
// Author:
// Eric Maupin <me@ermau.com>
//
// Copyright (c) 2013 Eric Maupin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace Tempest.Social
{
public sealed class GroupManager
{
public event Action<Group> GroupUpdated;
public Group CreateGroup (Person person)
{
if (person == null)
throw new ArgumentNullException ("person");
while (this.groups.ContainsKey (this.nextId))
Interlocked.Increment (ref this.nextId);
var group = new Group (this.nextId, person.Identity);
this.groups.Add (group.Id, group);
return group;
}
public void JoinGroup (Group group, Person person)
{
if (group == null)
throw new ArgumentNullException ("group");
if (person == null)
throw new ArgumentNullException ("person");
if (!this.groups.TryGetValue (group.Id, out group))
return;
group.Participants.Add (person.Identity);
OnGroupUpdated (group);
}
public void LeaveGroup (Group group, Person person)
{
if (person == null)
throw new ArgumentNullException ("person");
if (group == null)
throw new ArgumentNullException ("group");
if (!this.groups.TryGetValue (group.Id, out group))
return;
if (!group.Participants.Remove (person.Identity))
return;
OnGroupUpdated (group);
if (group.Participants.Count == 0)
this.groups.Remove (group.Id);
}
public bool TryGetGroup (int groupId, out Group group)
{
return this.groups.TryGetValue (groupId, out group);
}
public bool TryGetGroup (string identity, out Group group)
{
if (identity == null)
throw new ArgumentNullException ("identity");
group = null;
foreach (Group g in this.groups.Values) {
if (g.Participants.Contains (identity)) {
group = g;
return true;
}
}
return false;
}
private int nextId;
private readonly Dictionary<int, Group> groups = new Dictionary<int, Group>();
private void OnGroupUpdated (Group group)
{
var updated = GroupUpdated;
if (updated != null)
updated (group);
}
}
} | //
// GroupManager.cs
//
// Author:
// Eric Maupin <me@ermau.com>
//
// Copyright (c) 2013 Eric Maupin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Tempest.Social
{
public sealed class GroupManager
{
public event Action<Group> GroupUpdated;
public Group CreateGroup (Person person)
{
if (person == null)
throw new ArgumentNullException ("person");
while (this.groups.ContainsKey (this.nextId))
Interlocked.Increment (ref this.nextId);
var group = new Group (this.nextId, person.Identity);
this.groups.Add (group.Id, group);
return group;
}
public void JoinGroup (Group group, Person person)
{
if (group == null)
throw new ArgumentNullException ("group");
if (person == null)
throw new ArgumentNullException ("person");
if (!this.groups.TryGetValue (group.Id, out group))
return;
group.Participants.Add (person.Identity);
OnGroupUpdated (group);
}
public void LeaveGroup (Group group, Person person)
{
if (person == null)
throw new ArgumentNullException ("person");
if (group == null)
throw new ArgumentNullException ("group");
if (!this.groups.TryGetValue (group.Id, out group))
return;
if (!group.Participants.Remove (person.Identity))
return;
OnGroupUpdated (group);
if (group.Participants.Count == 0)
this.groups.Remove (group.Id);
}
public bool TryGetGroup (int groupId, out Group group)
{
return this.groups.TryGetValue (groupId, out group);
}
private int nextId;
private readonly Dictionary<int, Group> groups = new Dictionary<int, Group>();
private void OnGroupUpdated (Group group)
{
var updated = GroupUpdated;
if (updated != null)
updated (group);
}
}
} | mit | C# |
aca975a41dac8e2dd967ef30e3c252cb990192f2 | Improve and comment AwaitableDisposable API | madelson/DistributedLock | DistributedLock/AwaitableDisposable.cs | DistributedLock/AwaitableDisposable.cs | using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace Medallion.Threading
{
/// <summary>
/// Non-disposable awaitable wrapper type for <see cref="Task{TResult}"/> where <typeparamref name="TDisposable"/> is
/// <see cref="IDisposable"/>. This uses type-safety to help consumers avoid the easy mistake of disposing the
/// <see cref="Task{TResult}"/> rather than the underlying <see cref="IDisposable"/>:
///
/// <code>
/// // wrong (won't compile if AcquireAsync() returns AwaitableDisposable)
/// using (var handle = myLock.AcquireAsync()) { ... }
///
/// // right
/// using (var handle = await myLock.AcquireAsync()) { ... }
/// </code>
/// </summary>
public struct AwaitableDisposable<TDisposable> where TDisposable : IDisposable
{
/// <summary>
/// Constructs a new instance of <see cref="AwaitableDisposable{TDisposable}"/> from the given <paramref name="task"/>
/// </summary>
public AwaitableDisposable(Task<TDisposable> task)
{
this.Task = task ?? throw new ArgumentNullException(nameof(task));
}
/// <summary>
/// Retrieves the underlying <see cref="Task{TResult}"/> instance
/// </summary>
public Task<TDisposable> Task { get; }
/// <summary>
/// Implements the awaitable pattern
/// </summary>
public TaskAwaiter<TDisposable> GetAwaiter() => this.Task.GetAwaiter();
/// <summary>
/// Equivalent to <see cref="Task.ConfigureAwait(bool)"/>
/// </summary>
public ConfiguredTaskAwaitable<TDisposable> ConfigureAwait(bool continueOnCapturedContext) => this.Task.ConfigureAwait(continueOnCapturedContext);
}
}
| using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace Medallion.Threading
{
public struct AwaitableDisposable<TDisposable> where TDisposable : IDisposable
{
internal AwaitableDisposable(Task<TDisposable> task)
{
this.Task = task ?? throw new ArgumentNullException(nameof(task));
}
public Task<TDisposable> Task { get; }
public TaskAwaiter<TDisposable> GetAwaiter() => this.Task.GetAwaiter();
public ConfiguredTaskAwaitable<TDisposable> ConfigureAwait(bool continueOnCapturedContext) => this.Task.ConfigureAwait(continueOnCapturedContext);
// todo do we want this?
public static implicit operator Task<TDisposable>(AwaitableDisposable<TDisposable> source) => source.Task;
}
}
| mit | C# |
6131704fafe74c16d64ad13560fdef89c6b6b9fa | Call truss and nonlinear cantilever examples from Program.cs. | VasilisMerevis/MSolve,VasilisMerevis/MSolve | ISAAR.MSolve.SamplesConsole/Program.cs | ISAAR.MSolve.SamplesConsole/Program.cs | using ISAAR.MSolve.Analyzers;
using ISAAR.MSolve.Logging;
using ISAAR.MSolve.Matrices;
using ISAAR.MSolve.PreProcessor;
using ISAAR.MSolve.Problems;
using ISAAR.MSolve.Solvers.Skyline;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ISAAR.MSolve.SamplesConsole
{
class Program
{
private static void SolveBuildingInNoSoilSmall()
{
VectorExtensions.AssignTotalAffinityCount();
Model model = new Model();
model.SubdomainsDictionary.Add(1, new Subdomain() { ID = 1 });
BeamBuildingBuilder.MakeBeamBuilding(model, 20, 20, 20, 5, 4, model.NodesDictionary.Count + 1,
model.ElementsDictionary.Count + 1, 1, 4, false, false);
model.Loads.Add(new Load() { Amount = -100, Node = model.Nodes[21], DOF = DOFType.X });
model.ConnectDataStructures();
SolverSkyline solver = new SolverSkyline(model);
ProblemStructural provider = new ProblemStructural(model, solver.SubdomainsDictionary);
LinearAnalyzer analyzer = new LinearAnalyzer(solver, solver.SubdomainsDictionary);
StaticAnalyzer parentAnalyzer = new StaticAnalyzer(provider, analyzer, solver.SubdomainsDictionary);
analyzer.LogFactories[1] = new LinearAnalyzerLogFactory(new int[] { 420 });
parentAnalyzer.BuildMatrices();
parentAnalyzer.Initialize();
parentAnalyzer.Solve();
}
static void Main(string[] args)
{
//SolveBuildingInNoSoilSmall();
//CantileverExample.Cantilever2DExample();
CantileverExampleNL.Cantilever2DExample();
//CantileverExampleOneElement.Cantilever2DExample();
TrussExample.Truss2DExample();
}
}
}
| using ISAAR.MSolve.Analyzers;
using ISAAR.MSolve.Logging;
using ISAAR.MSolve.Matrices;
using ISAAR.MSolve.PreProcessor;
using ISAAR.MSolve.Problems;
using ISAAR.MSolve.Solvers.Skyline;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ISAAR.MSolve.SamplesConsole
{
class Program
{
private static void SolveBuildingInNoSoilSmall()
{
VectorExtensions.AssignTotalAffinityCount();
Model model = new Model();
model.SubdomainsDictionary.Add(1, new Subdomain() { ID = 1 });
BeamBuildingBuilder.MakeBeamBuilding(model, 20, 20, 20, 5, 4, model.NodesDictionary.Count + 1,
model.ElementsDictionary.Count + 1, 1, 4, false, false);
model.Loads.Add(new Load() { Amount = -100, Node = model.Nodes[21], DOF = DOFType.X });
model.ConnectDataStructures();
SolverSkyline solver = new SolverSkyline(model);
ProblemStructural provider = new ProblemStructural(model, solver.SubdomainsDictionary);
LinearAnalyzer analyzer = new LinearAnalyzer(solver, solver.SubdomainsDictionary);
StaticAnalyzer parentAnalyzer = new StaticAnalyzer(provider, analyzer, solver.SubdomainsDictionary);
analyzer.LogFactories[1] = new LinearAnalyzerLogFactory(new int[] { 420 });
parentAnalyzer.BuildMatrices();
parentAnalyzer.Initialize();
parentAnalyzer.Solve();
}
static void Main(string[] args)
{
//SolveBuildingInNoSoilSmall();
//CantileverExample.Cantilever2DExample();
CantileverExampleNL.Cantilever2DExample();
//CantileverExampleOneElement.Cantilever2DExample();
}
}
}
| apache-2.0 | C# |
0f234af366f2a8da3703bb519d3e68224b9f0252 | Add some settings to bugsnag | File-New-Project/EarTrumpet | EarTrumpet/Services/ErrorReportingService.cs | EarTrumpet/Services/ErrorReportingService.cs | using Bugsnag;
using Bugsnag.Clients;
using EarTrumpet.Extensions;
using EarTrumpet.Misc;
using System;
using System.Diagnostics;
using System.IO;
using Windows.ApplicationModel;
namespace EarTrumpet.Services
{
class ErrorReportingService
{
internal static void Initialize()
{
try
{
#if DEBUG
WPFClient.Config.ApiKey = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\eartrumpet.bugsnag.apikey");
#endif
WPFClient.Config.AppVersion = App.Current.HasIdentity() ? Package.Current.Id.Version.ToVersionString() : "DevInternal";
WPFClient.Start();
WPFClient.Config.BeforeNotify(OnBeforeNotify);
}
catch (Exception ex)
{
Trace.WriteLine(ex);
}
}
private static bool OnBeforeNotify(Event error)
{
// Remove default metadata we don't need nor want.
error.Metadata.AddToTab("Device", "machineName", "<redacted>");
error.Metadata.AddToTab("Device", "hostname", "<redacted>");
error.Metadata.AddToTab("AppSettings", "IsLightTheme", GetNoError(() => SystemSettings.IsLightTheme));
error.Metadata.AddToTab("AppSettings", "IsRTL", GetNoError(() => SystemSettings.IsRTL));
error.Metadata.AddToTab("AppSettings", "IsTransparencyEnabled", GetNoError(() => SystemSettings.IsTransparencyEnabled));
error.Metadata.AddToTab("AppSettings", "UseAccentColor", GetNoError(() => SystemSettings.UseAccentColor));
return true;
}
private static string GetNoError(Func<object> get)
{
try
{
var ret = get();
return ret == null ? "null" : ret.ToString();
}
catch (Exception ex)
{
return $"{ex}";
}
}
}
}
| using Bugsnag;
using Bugsnag.Clients;
using EarTrumpet.Extensions;
using System;
using System.Diagnostics;
using System.IO;
using Windows.ApplicationModel;
namespace EarTrumpet.Services
{
class ErrorReportingService
{
internal static void Initialize()
{
try
{
#if DEBUG
WPFClient.Config.ApiKey = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\eartrumpet.bugsnag.apikey");
#endif
WPFClient.Config.AppVersion = App.Current.HasIdentity() ? Package.Current.Id.Version.ToVersionString() : "DevInternal";
WPFClient.Start();
WPFClient.Config.BeforeNotify(OnBeforeNotify);
}
catch (Exception ex)
{
Trace.WriteLine(ex);
}
}
private static bool OnBeforeNotify(Event error)
{
error.Metadata.AddToTab("Device", "machineName", "<redacted>");
error.Metadata.AddToTab("Device", "hostname", "<redacted>");
return true;
}
}
}
| mit | C# |
76d2397aa0ff57c20bdb1913f33208df5885ac24 | Make obsolete | shyamnamboodiripad/roslyn,bartdesmet/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,sharwell/roslyn,KevinRansom/roslyn,eriawan/roslyn,sharwell/roslyn,diryboy/roslyn,eriawan/roslyn,wvdd007/roslyn,dotnet/roslyn,KevinRansom/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,AmadeusW/roslyn,eriawan/roslyn,KevinRansom/roslyn,weltkante/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,wvdd007/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,weltkante/roslyn,physhi/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,dotnet/roslyn,physhi/roslyn,diryboy/roslyn,dotnet/roslyn,mavasani/roslyn,weltkante/roslyn,AmadeusW/roslyn,wvdd007/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn | src/EditorFeatures/Core/Extensibility/NavigationBar/NavigationBarItem.cs | src/EditorFeatures/Core/Extensibility/NavigationBar/NavigationBarItem.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor
{
internal abstract class NavigationBarItem
{
public string Text { get; }
public Glyph Glyph { get; }
public bool Bolded { get; }
public bool Grayed { get; }
public int Indent { get; }
public ImmutableArray<NavigationBarItem> ChildItems { get; }
public ImmutableArray<TextSpan> Spans { get; internal set; }
internal ImmutableArray<ITrackingSpan> TrackingSpans { get; set; } = ImmutableArray<ITrackingSpan>.Empty;
// Legacy constructor for TypeScript.
[Obsolete("Use the constructor that uses ImmutableArray")]
public NavigationBarItem(string text, Glyph glyph, IList<TextSpan> spans, IList<NavigationBarItem>? childItems = null, int indent = 0, bool bolded = false, bool grayed = false)
: this(text, glyph, spans.ToImmutableArrayOrEmpty(), childItems.ToImmutableArrayOrEmpty(), indent, bolded, grayed)
{
}
public NavigationBarItem(
string text,
Glyph glyph,
ImmutableArray<TextSpan> spans,
ImmutableArray<NavigationBarItem> childItems = default,
int indent = 0,
bool bolded = false,
bool grayed = false)
{
this.Text = text;
this.Glyph = glyph;
this.Spans = spans;
this.ChildItems = childItems.NullToEmpty();
this.Indent = indent;
this.Bolded = bolded;
this.Grayed = grayed;
}
internal void InitializeTrackingSpans(ITextSnapshot textSnapshot)
{
this.TrackingSpans = this.Spans.SelectAsArray(s => textSnapshot.CreateTrackingSpan(s.ToSpan(), SpanTrackingMode.EdgeExclusive));
this.ChildItems.Do(i => i.InitializeTrackingSpans(textSnapshot));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor
{
internal abstract class NavigationBarItem
{
public string Text { get; }
public Glyph Glyph { get; }
public bool Bolded { get; }
public bool Grayed { get; }
public int Indent { get; }
public ImmutableArray<NavigationBarItem> ChildItems { get; }
public ImmutableArray<TextSpan> Spans { get; internal set; }
internal ImmutableArray<ITrackingSpan> TrackingSpans { get; set; } = ImmutableArray<ITrackingSpan>.Empty;
// Legacy constructor for TypeScript.
public NavigationBarItem(string text, Glyph glyph, IList<TextSpan> spans, IList<NavigationBarItem>? childItems = null, int indent = 0, bool bolded = false, bool grayed = false)
: this(text, glyph, spans.ToImmutableArrayOrEmpty(), childItems.ToImmutableArrayOrEmpty(), indent, bolded, grayed)
{
}
public NavigationBarItem(
string text,
Glyph glyph,
ImmutableArray<TextSpan> spans,
ImmutableArray<NavigationBarItem> childItems = default,
int indent = 0,
bool bolded = false,
bool grayed = false)
{
this.Text = text;
this.Glyph = glyph;
this.Spans = spans;
this.ChildItems = childItems.NullToEmpty();
this.Indent = indent;
this.Bolded = bolded;
this.Grayed = grayed;
}
internal void InitializeTrackingSpans(ITextSnapshot textSnapshot)
{
this.TrackingSpans = this.Spans.SelectAsArray(s => textSnapshot.CreateTrackingSpan(s.ToSpan(), SpanTrackingMode.EdgeExclusive));
this.ChildItems.Do(i => i.InitializeTrackingSpans(textSnapshot));
}
}
}
| mit | C# |
d78f08064c80a60858e69e0cf89ba1c7b238d744 | Update src/Features/LanguageServer/Protocol/ILspWorkspaceRegistrationService.cs | weltkante/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,KevinRansom/roslyn,sharwell/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,weltkante/roslyn,mavasani/roslyn,dotnet/roslyn,diryboy/roslyn,dotnet/roslyn,diryboy/roslyn,sharwell/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,KevinRansom/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn | src/Features/LanguageServer/Protocol/ILspWorkspaceRegistrationService.cs | src/Features/LanguageServer/Protocol/ILspWorkspaceRegistrationService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.LanguageServer
{
/// <summary>
/// Allows workspaces to register themselves to be considered when LSP requests come in. Any workspace
/// registered will be probed for a matching document/solution which can be given to the request handler
/// to operate on.
/// </summary>
internal interface ILspWorkspaceRegistrationService
{
/// <summary>
/// Get all current registered <see cref="Workspace"/>s. Used to find the appropriate workspace
/// corresponding to a particular <see cref="Document"/> request.
/// </summary>
ImmutableArray<Workspace> GetAllRegistrations();
/// <summary>
/// Returns the host/primary <see cref="Workspace"/> used for global operations associated
/// with the entirety of the user's code (for example 'diagnostics' or 'search').
/// </summary>
Workspace? TryGetHostWorkspace();
/// <summary>
/// Register the specified workspace for consideration for LSP requests.
/// </summary>
void Register(Workspace workspace);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.LanguageServer
{
/// <summary>
/// Allows workspaces to register themselves to be considered when LSP requests come in. Any workspace
/// registered will be probed for a matching document/solution which can be given to the request handler
/// to operate on.
/// </summary>
internal interface ILspWorkspaceRegistrationService
{
/// <summary>
/// Get all current registered <see cref="Workspace"/>s. Used to find the appropriate workspace
/// corresponding to a particular <see cref="Document"/> request.
/// </summary>
ImmutableArray<Workspace> GetAllRegistrations();
/// <summary>
/// Returns the host/priamry <see cref="Workspace"/> used for global operations associated
/// with the entirety of the user's code (for example 'diagnostics' or 'search').
/// </summary>
Workspace? TryGetHostWorkspace();
/// <summary>
/// Register the specified workspace for consideration for LSP requests.
/// </summary>
void Register(Workspace workspace);
}
}
| mit | C# |
745d410e9261f38ea94aae2474d62d192a1d750b | Make 'SeaPortZoneClusterConsumption' a power consumer; not supplier. | Miragecoder/Urbanization,Miragecoder/Urbanization,Miragecoder/Urbanization | src/Mirage.Urbanization/ZoneConsumption/SeaPortZoneClusterConsumption.cs | src/Mirage.Urbanization/ZoneConsumption/SeaPortZoneClusterConsumption.cs | using System;
using System.Drawing;
using Mirage.Urbanization.ZoneConsumption.Base;
using Mirage.Urbanization.ZoneConsumption.Base.Behaviours;
namespace Mirage.Urbanization.ZoneConsumption
{
public class SeaPortZoneClusterConsumption : StaticZoneClusterConsumption
{
public SeaPortZoneClusterConsumption(Func<ZoneInfoFinder> createZoneInfoFinderFunc)
: base(
createZoneInfoFinderFunc: createZoneInfoFinderFunc,
electricityBehaviour: new ElectricityConsumerBehaviour(60),
pollutionInUnits: 90,
color: Color.Navy,
widthInZones: 4,
heightInZones: 4
)
{
}
public override char KeyChar { get { return 'y'; } }
private readonly ICrimeBehaviour _crimeBehaviour = new DynamicCrimeBehaviour(() => 20);
public override ICrimeBehaviour CrimeBehaviour { get { return _crimeBehaviour; } }
public override int Value { get { return 5000; } }
public override string Name { get { return "Sea port"; } }
}
} | using System;
using System.Drawing;
using Mirage.Urbanization.ZoneConsumption.Base;
using Mirage.Urbanization.ZoneConsumption.Base.Behaviours;
namespace Mirage.Urbanization.ZoneConsumption
{
public class SeaPortZoneClusterConsumption : StaticZoneClusterConsumption
{
public SeaPortZoneClusterConsumption(Func<ZoneInfoFinder> createZoneInfoFinderFunc)
: base(
createZoneInfoFinderFunc: createZoneInfoFinderFunc,
electricityBehaviour: new ElectricitySupplierBehaviour(960),
pollutionInUnits: 90,
color: Color.Navy,
widthInZones: 4,
heightInZones: 4
)
{
}
public override char KeyChar { get { return 'y'; } }
private readonly ICrimeBehaviour _crimeBehaviour = new DynamicCrimeBehaviour(() => 20);
public override ICrimeBehaviour CrimeBehaviour { get { return _crimeBehaviour; } }
public override int Value { get { return 5000; } }
public override string Name { get { return "Sea port"; } }
}
} | mit | C# |
d684d09b7775971c6b45562a17c166dcf0fb6a2d | Remove remaining virtual specifiers from the GitCommand | Thulur/GitDataExplorer,Thulur/GitStatisticsAnalyzer | GitStatisticsAnalyzer/Commands/GitCommand.cs | GitStatisticsAnalyzer/Commands/GitCommand.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using GitStatisticsAnalyzer.Results;
namespace GitStatisticsAnalyzer.Commands
{
/// <summary>
/// Git command class, which encapsulates most of the command creation.
/// </summary>
class GitCommand<T> : IGitCommand<T>, IGitCommand where T : class, IResult, new()
{
public GitCommand(string commandName, string workingDir)
{
this.workingDir = workingDir;
this.commandName = commandName;
InitCommand();
}
public int LineCount
{
get; private set;
}
public IList<string> Lines { get; protected set; }
public T Result { get; protected set; }
public string Parameters { get; set; } = "";
private void InitCommand()
{
info.CreateNoWindow = true;
info.RedirectStandardError = true;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
info.FileName = "git.exe";
info.Arguments = commandName;
info.WorkingDirectory = workingDir;
}
public void RunCommand()
{
info.Arguments += " " + Parameters;
Process process = new Process();
process.StartInfo = info;
process.Start();
string gitOuput = process.StandardOutput.ReadToEnd();
process.WaitForExit();
process.Close();
Lines = gitOuput.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
CreateResult();
}
protected void CreateResult()
{
Result = new T();
Result.ParseResult(Lines);
}
private readonly string workingDir;
private readonly string commandName;
private readonly ProcessStartInfo info = new ProcessStartInfo();
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using GitStatisticsAnalyzer.Results;
namespace GitStatisticsAnalyzer.Commands
{
/// <summary>
/// Git command class, which encapsulates most of the command creation.
/// </summary>
class GitCommand<T> : IGitCommand<T>, IGitCommand where T : class, IResult, new()
{
public GitCommand(string commandName, string workingDir)
{
this.workingDir = workingDir;
this.commandName = commandName;
InitCommand();
}
public int LineCount
{
get; protected set;
}
public IList<string> Lines { get; protected set; }
public T Result { get; protected set; }
public string Parameters { get; set; } = "";
private void InitCommand()
{
info.CreateNoWindow = true;
info.RedirectStandardError = true;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
info.FileName = "git.exe";
info.Arguments = commandName;
info.WorkingDirectory = workingDir;
}
public virtual void RunCommand()
{
info.Arguments += " " + Parameters;
Process process = new Process();
process.StartInfo = info;
process.Start();
string gitOuput = process.StandardOutput.ReadToEnd();
process.WaitForExit();
process.Close();
Lines = gitOuput.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
CreateResult();
}
protected virtual void CreateResult()
{
Result = new T();
Result.ParseResult(Lines);
}
private readonly string workingDir;
private readonly string commandName;
private readonly ProcessStartInfo info = new ProcessStartInfo();
}
}
| apache-2.0 | C# |
8cc7549bf5f9ce2763b2dddd35c4bb6f4da2bd06 | fix image for event | PatrykSzwer/FetaProject | FetaProject/FetaProject.iOS/PinImage.cs | FetaProject/FetaProject.iOS/PinImage.cs | using System;
using UIKit;
namespace FetaProject.iOS
{
public class PinImage
{
public string selectImage(string typeOfPin)
{
string type= "";
int imageCounter=0;
string[] arrayOfImage = {
"Icons/event.png",
"Icons/food.png",
"Icons/help.png",
"Icons/WC.png"
};
if(typeOfPin == "food")
{
imageCounter = 1;
}else if(typeOfPin=="help")
{
imageCounter = 2;
}else if(typeOfPin=="WC")
{
imageCounter = 3;
}else
{
imageCounter = 0;
}
type = arrayOfImage[imageCounter];
return type;
}
}
} | using System;
using UIKit;
namespace FetaProject.iOS
{
public class PinImage
{
public string selectImage(string typeOfPin)
{
string type= "";
int imageCounter=0;
string[] arrayOfImage = {
"Icons/event.png",
"Icons/food.png",
"Icons/help.png",
"Icons/WC.png"
};
if(typeOfPin == "event")
{
imageCounter = 0;
}else if(typeOfPin == "food")
{
imageCounter = 1;
}else if(typeOfPin=="help")
{
imageCounter = 2;
}else if(typeOfPin=="WC")
{
imageCounter = 3;
}
type = arrayOfImage[imageCounter];
return type;
}
}
} | apache-2.0 | C# |
b3f8936f0b8c6ac6b39d4f7bd7b963dfc06a0e6e | Reduce size of test_data for ARM requests to 8MB/2 | projectkudu/kudu,projectkudu/kudu,projectkudu/kudu,shibayan/kudu,EricSten-MSFT/kudu,shibayan/kudu,shibayan/kudu,EricSten-MSFT/kudu,shibayan/kudu,shibayan/kudu,EricSten-MSFT/kudu,EricSten-MSFT/kudu,projectkudu/kudu,EricSten-MSFT/kudu,projectkudu/kudu | Kudu.Contracts/Functions/FunctionTestData.cs | Kudu.Contracts/Functions/FunctionTestData.cs | namespace Kudu.Contracts.Functions
{
public class FunctionTestData
{
// ARM has a limit of 8 MB -> 8388608 bytes
// divid by 2 to limit the over all size of test data to half of arm requirement to be safe.
public const long PackageMaxSizeInBytes = 8388608 / 2;
public long BytesLeftInPackage { get; set; } = PackageMaxSizeInBytes;
public bool DeductFromBytesLeftInPackage(long fileSize)
{
long spaceLeft = BytesLeftInPackage - fileSize;
if (spaceLeft >= 0)
{
BytesLeftInPackage = spaceLeft;
return true;
}
return false;
}
}
} | namespace Kudu.Contracts.Functions
{
public class FunctionTestData
{
// test shows test_data of size 8310000 bytes still delivers as an ARM package
// whereas test_data of size 8388608 bytes fails
public const long PackageMaxSizeInBytes = 8300000;
public long BytesLeftInPackage { get; set; } = PackageMaxSizeInBytes;
public bool DeductFromBytesLeftInPackage(long fileSize)
{
long spaceLeft = BytesLeftInPackage - fileSize;
if (spaceLeft >= 0)
{
BytesLeftInPackage = spaceLeft;
return true;
}
return false;
}
}
}
| apache-2.0 | C# |
a066f9e3c3d56b922e1a8cd0bfc28db320143e09 | remove reuse flag from benchmark, always reuse | sebastienros/jint,sebastienros/jint | Jint.Benchmark/SingleScriptBenchmark.cs | Jint.Benchmark/SingleScriptBenchmark.cs | using BenchmarkDotNet.Attributes;
namespace Jint.Benchmark
{
[MemoryDiagnoser]
public abstract class SingleScriptBenchmark
{
private Engine sharedJint;
#if ENGINE_COMPARISON
private Jurassic.ScriptEngine sharedJurassic;
private NiL.JS.Core.Context sharedNilJs;
#endif
protected abstract string Script { get; }
[Params(10)]
public virtual int N { get; set; }
[GlobalSetup]
public void Setup()
{
sharedJint = new Engine();
#if ENGINE_COMPARISON
sharedJurassic = new Jurassic.ScriptEngine();
sharedNilJs = new NiL.JS.Core.Context();
#endif
}
[Benchmark]
public bool Jint()
{
bool done = false;
for (var i = 0; i < N; i++)
{
sharedJint.Execute(Script);
done |= sharedJint.GetValue("done").AsBoolean();
}
return done;
}
#if ENGINE_COMPARISON
[Benchmark]
public bool Jurassic()
{
bool done = false;
for (var i = 0; i < N; i++)
{
sharedJurassic.Execute(Script);
done |= sharedJurassic.GetGlobalValue<bool>("done");
}
return done;
}
[Benchmark]
public bool NilJS()
{
bool done = false;
for (var i = 0; i < N; i++)
{
sharedNilJs.Eval(Script);
done |= (bool) sharedNilJs.GetVariable("done");
}
return done;
}
#endif
}
} | using BenchmarkDotNet.Attributes;
namespace Jint.Benchmark
{
[MemoryDiagnoser]
public abstract class SingleScriptBenchmark
{
private Engine sharedJint;
#if ENGINE_COMPARISON
private Jurassic.ScriptEngine sharedJurassic;
private NiL.JS.Core.Context sharedNilJs;
#endif
protected abstract string Script { get; }
[Params(10)]
public virtual int N { get; set; }
[Params(true, false)]
public bool ReuseEngine { get; set; }
[GlobalSetup]
public void Setup()
{
sharedJint = new Engine();
#if ENGINE_COMPARISON
sharedJurassic = new Jurassic.ScriptEngine();
sharedNilJs = new NiL.JS.Core.Context();
#endif
}
[Benchmark]
public bool Jint()
{
bool done = false;
for (var i = 0; i < N; i++)
{
var jintEngine = ReuseEngine ? sharedJint : new Engine();
jintEngine.Execute(Script);
done |= jintEngine.GetValue("done").AsBoolean();
}
return done;
}
#if ENGINE_COMPARISON
[Benchmark]
public bool Jurassic()
{
bool done = false;
for (var i = 0; i < N; i++)
{
var jurassicEngine = ReuseEngine ? sharedJurassic : new Jurassic.ScriptEngine();
jurassicEngine.Execute(Script);
done |= jurassicEngine.GetGlobalValue<bool>("done");
}
return done;
}
[Benchmark]
public bool NilJS()
{
bool done = false;
for (var i = 0; i < N; i++)
{
var nilcontext = ReuseEngine ? sharedNilJs : new NiL.JS.Core.Context();
nilcontext.Eval(Script);
done |= (bool) nilcontext.GetVariable("done");
}
return done;
}
#endif
}
} | bsd-2-clause | C# |
9afa6581984b4462264cbb7ccb8f045a7e93c04d | Edit namespace | Vtek/Pulsar | Pulsar/Content/ContentLoadException.cs | Pulsar/Content/ContentLoadException.cs | /* License
*
* The MIT License (MIT)
*
* Copyright (c) 2014, Sylvain PONTOREAU (pontoreau.sylvain@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
namespace Pulsar.Content
{
/// <summary>
/// Exception used to report errors from the ContentManager method.
/// </summary>
public sealed class ContentLoadException : Exception
{
/// <summary>
/// Create a new instance of ContentLoadException.
/// </summary>
/// <param name="message">Message of the exception.</param>
public ContentLoadException(string message)
: base(message)
{
}
/// <summary>
/// Create a new instance of ContentLoadException.
/// </summary>
/// <param name="message">Message of the exception.</param>
/// <param name="innerException">Inner exception that throw the Pulsar Exception.</param>
public ContentLoadException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
| /* License
*
* The MIT License (MIT)
*
* Copyright (c) 2014, Sylvain PONTOREAU (pontoreau.sylvain@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
namespace Pulsar
{
/// <summary>
/// Exception used to report errors from the ContentManager method.
/// </summary>
public sealed class ContentLoadException : Exception
{
/// <summary>
/// Create a new instance of ContentLoadException.
/// </summary>
/// <param name="message">Message of the exception.</param>
public ContentLoadException(string message)
: base(message)
{
}
/// <summary>
/// Create a new instance of ContentLoadException.
/// </summary>
/// <param name="message">Message of the exception.</param>
/// <param name="innerException">Inner exception that throw the Pulsar Exception.</param>
public ContentLoadException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
| mit | C# |
8ad8fe7e8eee2d19421fe22ee6d1088783b902e2 | complete dotnet-build invocation test cases | EdwardBlair/cli,Faizan2304/cli,livarcocc/cli-1,ravimeda/cli,harshjain2/cli,johnbeisner/cli,harshjain2/cli,blackdwarf/cli,svick/cli,livarcocc/cli-1,Faizan2304/cli,blackdwarf/cli,harshjain2/cli,ravimeda/cli,johnbeisner/cli,dasMulli/cli,svick/cli,EdwardBlair/cli,dasMulli/cli,dasMulli/cli,Faizan2304/cli,ravimeda/cli,EdwardBlair/cli,svick/cli,johnbeisner/cli,blackdwarf/cli,blackdwarf/cli,livarcocc/cli-1 | test/dotnet-msbuild.Tests/GivenDotnetBuildInvocation.cs | test/dotnet-msbuild.Tests/GivenDotnetBuildInvocation.cs | using Microsoft.DotNet.Tools.Build;
using FluentAssertions;
using Xunit;
namespace Microsoft.DotNet.Cli.MSBuild.Tests
{
public class GivenDotnetBuildInvocation
{
[Theory]
[InlineData(new string[] { }, @"exec <msbuildpath> /m /v:m /t:Build /clp:Summary")]
[InlineData(new string[] { "-o", "foo" }, @"exec <msbuildpath> /m /v:m /t:Build /p:OutputPath=foo /clp:Summary")]
[InlineData(new string[] { "--output", "foo" }, @"exec <msbuildpath> /m /v:m /t:Build /p:OutputPath=foo /clp:Summary")]
[InlineData(new string[] { "-o", "foo1 foo2" }, @"exec <msbuildpath> /m /v:m /t:Build ""/p:OutputPath=foo1 foo2"" /clp:Summary")]
[InlineData(new string[] { "--no-incremental" }, @"exec <msbuildpath> /m /v:m /t:Rebuild /clp:Summary")]
[InlineData(new string[] { "-f", "framework" }, @"exec <msbuildpath> /m /v:m /t:Build /p:TargetFramework=framework /clp:Summary")]
[InlineData(new string[] { "--framework", "framework" }, @"exec <msbuildpath> /m /v:m /t:Build /p:TargetFramework=framework /clp:Summary")]
[InlineData(new string[] { "-r", "runtime" }, @"exec <msbuildpath> /m /v:m /t:Build /p:RuntimeIdentifier=runtime /clp:Summary")]
[InlineData(new string[] { "--runtime", "runtime" }, @"exec <msbuildpath> /m /v:m /t:Build /p:RuntimeIdentifier=runtime /clp:Summary")]
[InlineData(new string[] { "-c", "configuration" }, @"exec <msbuildpath> /m /v:m /t:Build /p:Configuration=configuration /clp:Summary")]
[InlineData(new string[] { "--configuration", "configuration" }, @"exec <msbuildpath> /m /v:m /t:Build /p:Configuration=configuration /clp:Summary")]
[InlineData(new string[] { "--version-suffix", "mysuffix" }, @"exec <msbuildpath> /m /v:m /t:Build /p:VersionSuffix=mysuffix /clp:Summary")]
[InlineData(new string[] { "--no-dependencies" }, @"exec <msbuildpath> /m /v:m /t:Build /p:BuildProjectReferences=false /clp:Summary")]
[InlineData(new string[] { "-v", "verbosity" }, @"exec <msbuildpath> /m /v:m /t:Build /verbosity:verbosity /clp:Summary")]
[InlineData(new string[] { "--verbosity", "verbosity" }, @"exec <msbuildpath> /m /v:m /t:Build /verbosity:verbosity /clp:Summary")]
[InlineData(new string[] { "--no-incremental", "-o", "myoutput", "-r", "myruntime", "-v", "diag" }, @"exec <msbuildpath> /m /v:m /t:Rebuild /p:OutputPath=myoutput /p:RuntimeIdentifier=myruntime /verbosity:diag /clp:Summary")]
public void WhenArgsArePassedThenMsbuildInvocationIsCorrect(string[] args, string expectedCommand)
{
var msbuildPath = "<msbuildpath>";
BuildCommand.FromArgs(args, msbuildPath)
.GetProcessStartInfo().Arguments.Should().Be(expectedCommand);
}
}
}
| using Microsoft.DotNet.Tools.Build;
using FluentAssertions;
using Xunit;
namespace Microsoft.DotNet.Cli.MSBuild.Tests
{
public class GivenDotnetBuildInvocation
{
[Theory]
[InlineData(new string[] { }, @"exec <msbuildpath> /m /v:m /t:Build /clp:Summary")]
[InlineData(new string[] { "-o", "foo" }, @"exec <msbuildpath> /m /v:m /t:Build /p:OutputPath=foo /clp:Summary")]
[InlineData(new string[] { "--output", "foo" }, @"exec <msbuildpath> /m /v:m /t:Build /p:OutputPath=foo /clp:Summary")]
[InlineData(new string[] { "-o", "foo1 foo2" }, @"exec <msbuildpath> /m /v:m /t:Build ""/p:OutputPath=foo1 foo2"" /clp:Summary")]
public void WhenNoArgsArePassedThenMsbuildInvocationIsCorrect(string[] args, string expectedCommand)
{
var msbuildPath = "<msbuildpath>";
BuildCommand.FromArgs(args, msbuildPath)
.GetProcessStartInfo().Arguments.Should().Be(expectedCommand);
}
}
}
| mit | C# |
7d209a099e3018735ea0c198f2a5b443acd9d8d4 | Update GameManager.cs | afroraydude/First_Unity_Game,afroraydude/First_Unity_Game,afroraydude/First_Unity_Game | Real_Game/Assets/Scripts/GameManager.cs | Real_Game/Assets/Scripts/GameManager.cs | using UnityEngine;
using System.Collections;
public class GameManager : MonoBehaviour {
// Score based stuff
public float highScore = 0f;
//Level based stuff
public int currentLevel = 0;
public int unlockedLevel;
// Things that deal with GUI or whatever
public Rect stopwatchRect;
public Rect stopwatchBoxRect;
public Rect highScoreRect;
public Rect highScoreBox;
public GUISkin skin;
// Stuff that deals with the ingame stopwatch, which is my answer to the score system.
public float startTime;
private string currentTime;
public string highTime;
// Once the level loads this happens
void Start()
{
//DontDestroyOnLoad(gameObject);
if (PlayerPrefs.GetInt("LevelsCompleted") > 0)
{
currentLevel = PlayerPrefs.GetInt("LevelsCompleted");
}
else
{
currentLevel = 0;
}
}
// This is ran every tick
void Update()
{
//This records the time it took to complete the level
startTime += Time.deltaTime;
//This puts it into a string so that it can be viewed on the GUI
currentTime = string.Format ("{0:0.0}", startTime);
}
// GUI goes here
void OnGUI()
{
GUI.skin = skin;
GUI.Box (stopwatchBoxRect, "");
GUI.Label(stopwatchRect, currentTime, skin.GetStyle ("Stopwatch"));
GUI.Label (highScoreRect, PlayerPrefs.GetString("Level" + currentLevel.ToString() + "Score"));
GUI.Box (highScoreBox, "");
}
/**
* Alternative to the Maine Menu having to save information
*/
public void MainMenuToLevelOne()
{
currentLevel +=1;
PlayerPrefs.SetInt("LevelsCompleted", currentLevel);
PlayerPrefs.Save();
Application.LoadLevel(currentLevel);
}
public void BackToMainMenu()
{
currentLevel -=1;
PlayerPrefs.SetInt("LevelsCompleted", currentLevel);
PlayerPrefs.Save();
Application.LoadLevel(currentLevel);
}
// For when the player completes a level
// TODO: Fix issue in flash were it does not care if the high score is > or < the startTime, it always overrides it.
public void CompleteLevel()
{
if(highScore > startTime || highScore == 0)
{
highScore = startTime;
highTime = string.Format ("{0:0.0}", highScore);
PlayerPrefs.SetString("Level" + currentLevel.ToString() + "Score", highTime);
}
if (currentLevel < 5)
{
currentLevel +=1;
PlayerPrefs.SetInt("LevelsCompleted", currentLevel);
PlayerPrefs.GetInt("LevelsCompleted");
PlayerPrefs.Save();
Application.LoadLevel(currentLevel);
}
else
{
print ("Please increase level amount.");
}
}
}
| using UnityEngine;
using System.Collections;
public class GameManager : MonoBehaviour {
// Score based stuff
public float highScore = 0f;
//Level based stuff
public int currentLevel = 0;
public int unlockedLevel;
// Things that deal with GUI or whatever
public Rect stopwatchRect;
public Rect stopwatchBoxRect;
public Rect highScoreRect;
public Rect highScoreBox;
public GUISkin skin;
// Stuff that deals with the ingame stopwatch, which is my answer to the score system.
public float startTime;
private string currentTime;
public string highTime;
// Once the level loads this happens
void Start()
{
//DontDestroyOnLoad(gameObject);
if (PlayerPrefs.GetInt("LevelsCompleted") > 0)
{
currentLevel = PlayerPrefs.GetInt("LevelsCompleted");
}
else
{
currentLevel = 0;
}
}
// This is ran every tick
void Update()
{
//This records the time it took to complete the level
startTime += Time.deltaTime;
//This puts it into a string so that it can be viewed on the GUI
currentTime = string.Format ("{0:0.0}", startTime);
}
// GUI goes here
void OnGUI()
{
GUI.skin = skin;
GUI.Box (stopwatchBoxRect, "");
GUI.Label(stopwatchRect, currentTime, skin.GetStyle ("Stopwatch"));
GUI.Label (highScoreRect, PlayerPrefs.GetString("Level" + currentLevel.ToString() + "Score"));
GUI.Box (highScoreBox, "");
}
/**
* So the main menu doesn't need to use another object in the scene to run,
* Also so that there wont be a stopwatch calculationg time in the main menu.
* The end screen doesn't need this because it is just a GUI.
*/
public void MainMenuToLevelOne()
{
currentLevel +=1;
PlayerPrefs.SetInt("LevelsCompleted", currentLevel);
PlayerPrefs.Save();
Application.LoadLevel(currentLevel);
}
public void BackToMainMenu()
{
currentLevel -=1;
PlayerPrefs.SetInt("LevelsCompleted", currentLevel);
PlayerPrefs.Save();
Application.LoadLevel(currentLevel);
}
// For when the player completes a level
// TODO: Fix issue in flash were it does not care if the high score is > or < the startTime, it always overrides it.
public void CompleteLevel()
{
if(highScore > startTime || highScore == 0)
{
highScore = startTime;
highTime = string.Format ("{0:0.0}", highScore);
PlayerPrefs.SetString("Level" + currentLevel.ToString() + "Score", highTime);
}
if (currentLevel < 5)
{
currentLevel +=1;
PlayerPrefs.SetInt("LevelsCompleted", currentLevel);
PlayerPrefs.GetInt("LevelsCompleted");
PlayerPrefs.Save();
Application.LoadLevel(currentLevel);
}
else
{
print ("Please increase level amount.");
}
}
}
| mit | C# |
1896e89911abf7a8d9bc19254b61a9829f15ebaa | Add hardcoded board bool | Zyrio/ictus,Zyrio/ictus | src/Ictus/Data/Models/Tag.cs | src/Ictus/Data/Models/Tag.cs | using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace Ictus.Data.Models
{
public class Tag
{
public Guid Id { get; set; }
public string Name { get; set; }
public int FileCount { get; set; }
[NotMapped]
public bool Board { get; set; } = true;
}
} | using System;
namespace Ictus.Data.Models
{
public class Tag
{
public Guid Id { get; set; }
public string Name { get; set; }
public int FileCount { get; set; }
}
} | mit | C# |
899c5c816ad1bdb2802ece46fdeec4bc81c85c13 | update demo | chinaboard/PureCat | PureCat.Demo/Program.cs | PureCat.Demo/Program.cs | using PureCat.Context;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace PureCat.Demo
{
class Program
{
static Random _rand = new Random();
static void Main(string[] args)
{
PureCatClient.Initialize();
while (true)
{
var a = DateTime.Now.Second;
Console.WriteLine(DateTime.Now);
var context = PureCatClient.DoTransaction("Do", nameof(DoTest), DoTest);
var b = DateTime.Now.Second;
PureCatClient.DoTransaction("Do", nameof(Add), () => Add(a, b, context));
}
}
static CatContext DoTest()
{
var times = _rand.Next(1000);
Thread.Sleep(times);
PureCatClient.LogEvent("Do", nameof(DoTest), "0", $"sleep {times}");
return PureCatClient.LogRemoteCallClient("callAdd");
}
static void Add(int a, int b, CatContext context = null)
{
PureCatClient.LogRemoteCallServer(context);
PureCatClient.LogEvent("Do", nameof(Add), "0", $"{a} + {b} = {a + b}");
}
}
}
| using PureCat.Context;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace PureCat.Demo
{
class Program
{
static Random _rand = new Random();
static void Main(string[] args)
{
PureCat.Initialize();
while (true)
{
var a = DateTime.Now.Second;
Console.WriteLine(DateTime.Now);
var context = PureCat.DoTransaction("Do", nameof(DoTest), DoTest);
var b = DateTime.Now.Second;
PureCat.DoTransaction("Do", nameof(Add), () => Add(a, b, context));
}
}
static CatContext DoTest()
{
var times = _rand.Next(1000);
Thread.Sleep(times);
PureCat.LogEvent("Do", nameof(DoTest), "0", $"sleep {times}");
return PureCat.LogRemoteCallClient("callAdd");
}
static void Add(int a, int b, CatContext context = null)
{
PureCat.LogRemoteCallServer(context);
PureCat.LogEvent("Do", nameof(Add), "0", $"{a} + {b} = {a + b}");
}
}
}
| mit | C# |
d8e77e052f3ce794ec44fb335ad87ca8fa78c26c | Fix appveyor update checker | gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer | LmpUpdater/Appveyor/AppveyorUpdateChecker.cs | LmpUpdater/Appveyor/AppveyorUpdateChecker.cs | using JsonFx.Json;
using JsonFx.Serialization;
using JsonFx.Serialization.Resolvers;
using LmpGlobal;
using LmpUpdater.Appveyor.Contracts;
using System;
using System.Net;
namespace LmpUpdater.Appveyor
{
public class AppveyorUpdateChecker
{
private static readonly JsonReader Reader = new JsonReader(new DataReaderSettings(new DataContractResolverStrategy()));
public static RootObject LatestBuild
{
get
{
try
{
using (var wc = new WebClient())
{
wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
var json = wc.DownloadString(RepoConstants.AppveyorUrl);
return Reader.Read<RootObject>(json);
}
}
catch (Exception)
{
//Ignore as either we don't have internet connection or something like that...
}
return null;
}
}
public static Version GetLatestVersion()
{
var versionComponents = LatestBuild?.build.version.Split('.');
return versionComponents != null && versionComponents.Length >= 3 ?
new Version(int.Parse(versionComponents[0]), int.Parse(versionComponents[1]), int.Parse(versionComponents[2])) :
new Version("0.0.0");
}
}
}
| using JsonFx.Json;
using JsonFx.Serialization;
using JsonFx.Serialization.Resolvers;
using LmpGlobal;
using LmpUpdater.Appveyor.Contracts;
using System;
using System.Net;
namespace LmpUpdater.Appveyor
{
public class AppveyorUpdateChecker
{
private static readonly JsonReader Reader = new JsonReader(new DataReaderSettings(new DataContractResolverStrategy()));
public static RootObject LatestBuild
{
get
{
try
{
using (var wc = new WebClient())
{
wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
var json = wc.DownloadString(RepoConstants.AppveyorUrl);
return Reader.Read<RootObject>(json);
}
}
catch (Exception)
{
//Ignore as either we don't have internet connection or something like that...
}
return null;
}
}
public static Version GetLatestVersion()
{
var versionComponents = LatestBuild?.build.version.Split('.');
return versionComponents != null && versionComponents.Length == 3 ?
new Version(int.Parse(versionComponents[0]), int.Parse(versionComponents[1]), int.Parse(versionComponents[2])) :
new Version("0.0.0");
}
}
}
| mit | C# |
c3a04f03d3266a8b11c8400db75579cca0e64fe4 | Remove XmlArray Attribute | Trojaner25/Rocket-Regions,Trojaner25/Rocket-Safezone | RegionsConfiguration.cs | RegionsConfiguration.cs | using System.Collections.Generic;
using System.Xml.Serialization;
using Rocket.API;
using RocketRegions.Model;
namespace RocketRegions
{
public class RegionsConfiguration : IRocketPluginConfiguration
{
public int UpdateFrameCount { get; set; }
public List<Region> Regions { get; set; }
public List<ushort> NoEquipWeaponIgnoredItems { get; set; }
public string UrlOpenMessage { get; set; }
public List<ushort> NoEquipIgnoredItems { get; set; }
public void LoadDefaults()
{
Regions = new List<Region>();
UpdateFrameCount = 10;
UrlOpenMessage = "Visit webpage";
NoEquipWeaponIgnoredItems = new List<ushort> {1337};
NoEquipIgnoredItems = new List<ushort> { 1337 };
}
}
}
| using System.Collections.Generic;
using System.Xml.Serialization;
using Rocket.API;
using RocketRegions.Model;
namespace RocketRegions
{
public class RegionsConfiguration : IRocketPluginConfiguration
{
public int UpdateFrameCount { get; set; }
public List<Region> Regions { get; set; }
[XmlArray("Item")]
public List<ushort> NoEquipWeaponIgnoredItems { get; set; }
public string UrlOpenMessage { get; set; }
[XmlArray("Item")]
public List<ushort> NoEquipIgnoredItems { get; set; }
public void LoadDefaults()
{
Regions = new List<Region>();
UpdateFrameCount = 10;
UrlOpenMessage = "Visit webpage";
NoEquipWeaponIgnoredItems = new List<ushort> {1337};
NoEquipIgnoredItems = new List<ushort> { 1337 };
}
}
}
| agpl-3.0 | C# |
4843126d529e1dbfab034960b2fdb386585e6f0f | Emphasize the current thread. | GunioRobot/sdb-cli,GunioRobot/sdb-cli | Mono.Debugger.Cli/Commands/ThreadsCommand.cs | Mono.Debugger.Cli/Commands/ThreadsCommand.cs | using System.Collections.Generic;
using Mono.Debugger.Cli.Debugging;
using Mono.Debugger.Cli.Logging;
namespace Mono.Debugger.Cli.Commands
{
public sealed class ThreadsCommand : ICommand
{
public string Name
{
get { return "Threads"; }
}
public string Description
{
get { return "Lists all active threads."; }
}
public IEnumerable<string> Arguments
{
get { return Argument.None(); }
}
public void Execute(CommandArguments args)
{
var session = SoftDebugger.Session;
if (SoftDebugger.State == DebuggerState.Null)
{
Logger.WriteErrorLine("No session active.");
return;
}
if (SoftDebugger.State == DebuggerState.Initialized)
{
Logger.WriteErrorLine("No process active.");
return;
}
var threads = session.VirtualMachine.GetThreads();
foreach (var thread in threads)
{
var id = thread.Id.ToString();
if (thread.IsThreadPoolThread)
id += " (TP)";
var str = string.Format("[{0}: {1}] {2}: {3}", thread.Domain.FriendlyName, id, thread.Name, thread.ThreadState);
if (thread.Id == session.ActiveThread.Id)
Logger.WriteEmphasisLine("{0}", str);
else
Logger.WriteInfoLine("{0}", str);
}
}
}
}
| using System.Collections.Generic;
using Mono.Debugger.Cli.Debugging;
using Mono.Debugger.Cli.Logging;
namespace Mono.Debugger.Cli.Commands
{
public sealed class ThreadsCommand : ICommand
{
public string Name
{
get { return "Threads"; }
}
public string Description
{
get { return "Lists all active threads."; }
}
public IEnumerable<string> Arguments
{
get { return Argument.None(); }
}
public void Execute(CommandArguments args)
{
var session = SoftDebugger.Session;
if (SoftDebugger.State == DebuggerState.Null)
{
Logger.WriteErrorLine("No session active.");
return;
}
if (SoftDebugger.State == DebuggerState.Initialized)
{
Logger.WriteErrorLine("No process active.");
return;
}
var threads = session.VirtualMachine.GetThreads();
foreach (var thread in threads)
{
var id = thread.Id.ToString();
if (thread.IsThreadPoolThread)
id += " (TP)";
Logger.WriteInfoLine("[{0}: {1}] {2}: {3}", thread.Domain.FriendlyName, id, thread.Name, thread.ThreadState);
}
}
}
}
| mit | C# |
ec4571abc577d6c372f32fce156a0d606340facc | Add concurrency handling | peasy/Samples,peasy/Samples,peasy/Samples | Orders.com.DAL.EF/InventoryItemRepository.cs | Orders.com.DAL.EF/InventoryItemRepository.cs | using System;
using System.Linq;
using System.Threading.Tasks;
using Orders.com.DataProxy;
using Orders.com.Domain;
using System.Data.Entity;
using Peasy;
using Peasy.Exception;
using Orders.com.Extensions;
namespace Orders.com.DAL.EF
{
public class InventoryItemRepository : OrdersDotComRepositoryBase<InventoryItem>, IInventoryItemDataProxy
{
public InventoryItem GetByProduct(long productID)
{
using (var context = GetDbContext())
{
return context.Set<InventoryItem>().First(i => i.ProductID == productID);
}
}
public async Task<InventoryItem> GetByProductAsync(long productID)
{
using (var context = GetDbContext())
{
var items = await context.Set<InventoryItem>().Where(i => i.ProductID == productID).ToListAsync();
return items.First();
}
}
protected override void OnBeforeUpdateExecuted(DbContext context, InventoryItem entity)
{
var existing = context.Set<InventoryItem>()
.FirstOrDefault(e => e.ID.Equals(entity.ID) && e.Version == entity.Version);
if (existing == null)
throw new ConcurrencyException($"{entity.GetType().Name} with id {entity.ID.ToString()} was already changed");
entity.IncrementVersionByOne();
}
protected override async Task OnBeforeUpdateExecutedAsync(DbContext context, InventoryItem entity)
{
var existing = await context.Set<InventoryItem>()
.FirstOrDefaultAsync(e => e.ID.Equals(entity.ID) && e.Version == entity.Version);
if (existing == null)
throw new ConcurrencyException($"{entity.GetType().Name} with id {entity.ID.ToString()} was already changed");
entity.IncrementVersionByOne();
}
}
} | using System;
using System.Linq;
using System.Threading.Tasks;
using Orders.com.DataProxy;
using Orders.com.Domain;
using System.Data.Entity;
namespace Orders.com.DAL.EF
{
public class InventoryItemRepository : OrdersDotComRepositoryBase<InventoryItem>, IInventoryItemDataProxy
{
public InventoryItem GetByProduct(long productID)
{
using (var context = GetDbContext())
{
return context.Set<InventoryItem>().First(i => i.ProductID == productID);
}
}
public async Task<InventoryItem> GetByProductAsync(long productID)
{
using (var context = GetDbContext())
{
var items = await context.Set<InventoryItem>().Where(i => i.ProductID == productID).ToListAsync();
return items.First();
}
}
}
}
| mit | C# |
4440dc1824e2476f1ea20c21bd4df079ac7b2c89 | remove commented lines from extensions | dbaeck/ai-playground,dbaeck/ai-playground,dbaeck/ai-playground,dbaeck/ai-playground | AIPlayground/AIPlayground/Extensions.cs | AIPlayground/AIPlayground/Extensions.cs | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AIPlayground.Search.Algorithm;
using AIPlayground.Search.Problem.State;
namespace AIPlayground
{
public static class Extensions
{
}
}
| using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AIPlayground.Search.Algorithm;
using AIPlayground.Search.Problem.State;
namespace AIPlayground
{
public static class Extensions
{
// public static void Enqueue(this ObservableCollection<SearchNode> fringe, IEnumerable<SearchNode> nodes)
// {
// foreach (var searchNode in nodes)
// {
// //fringe.Add(searchNode);
// fringe.Insert((fringe.Count==0)?0:fringe.Count-1,searchNode);
// }
// }
//
// public static SearchNode Dequeue(this ObservableCollection<SearchNode> fringe)
// {
// return fringe.GetAndRemoveFirst();
// }
//
// public static T GetAndRemoveFirst<T>(this ObservableCollection<T> list)
// {
// if (list.Count() != 0)
// {
// var temp = list.First();
// list.RemoveAt(0);
// return temp;
// }
// return default(T);
// }
//
// public static SearchNode Pop(this ObservableCollection<SearchNode> fringe)
// {
// return fringe.GetAndRemoveFirst();
// }
//
// public static void Push(this ObservableCollection<SearchNode> fringe, IEnumerable<SearchNode> nodes)
// {
// var a = nodes.Reverse();
// foreach (var node in a)
// {
// fringe.Insert(0,node);
// }
// }
}
}
| mit | C# |
94cbf4ca3a081ece1458fdc0731b2d202778fb5d | Fix outdated message | danielchalmers/SteamAccountSwitcher | SteamAccountSwitcher/TrayIconHelper.cs | SteamAccountSwitcher/TrayIconHelper.cs | using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Hardcodet.Wpf.TaskbarNotification;
using SteamAccountSwitcher.Properties;
namespace SteamAccountSwitcher
{
public static class TrayIconHelper
{
public static readonly ObservableCollection<object> AccountMenuItems = new();
public static void ShowRunningInTrayBalloon()
{
ShowTrayBalloon("Running in tray\n" + "Right click to switch accounts", BalloonIcon.Info);
}
private static void ShowTrayBalloon(string text, BalloonIcon icon)
{
App.TrayIcon?.ShowBalloonTip(AssemblyInfo.Title, text, icon);
}
public static void CreateTrayIcon()
{
App.TrayIcon ??= (TaskbarIcon)Application.Current.FindResource("TrayIcon");
RefreshTrayIconMenu();
}
public static void RefreshTrayIconMenu()
{
AccountMenuItems.Clear();
var items = GetAccountMenuItems();
foreach (var item in items)
{
AccountMenuItems.Add(item);
}
}
private static IEnumerable<Control> GetAccountMenuItems()
{
if (App.Accounts == null || App.Accounts.Count <= 0)
yield break;
foreach (var account in App.Accounts)
{
var item = new MenuItem { Header = account.GetDisplayName() };
if (Settings.Default.ColorCodeAccountMenuItems)
{
item.Foreground = new SolidColorBrush(account.TextColor);
item.Background = new SolidColorBrush(account.Color);
}
item.Click += (sender, args) => account.SwitchTo(false);
yield return item;
}
yield return new Separator();
}
}
} | using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Hardcodet.Wpf.TaskbarNotification;
using SteamAccountSwitcher.Properties;
namespace SteamAccountSwitcher
{
public static class TrayIconHelper
{
public static readonly ObservableCollection<object> AccountMenuItems = new();
public static void ShowRunningInTrayBalloon()
{
ShowTrayBalloon("Running in tray\n" + "Double click icon to open", BalloonIcon.Info);
}
private static void ShowTrayBalloon(string text, BalloonIcon icon)
{
App.TrayIcon?.ShowBalloonTip(AssemblyInfo.Title, text, icon);
}
public static void CreateTrayIcon()
{
App.TrayIcon ??= (TaskbarIcon)Application.Current.FindResource("TrayIcon");
RefreshTrayIconMenu();
}
public static void RefreshTrayIconMenu()
{
AccountMenuItems.Clear();
var items = GetAccountMenuItems();
foreach (var item in items)
{
AccountMenuItems.Add(item);
}
}
private static IEnumerable<Control> GetAccountMenuItems()
{
if (App.Accounts == null || App.Accounts.Count <= 0)
yield break;
foreach (var account in App.Accounts)
{
var item = new MenuItem { Header = account.GetDisplayName() };
if (Settings.Default.ColorCodeAccountMenuItems)
{
item.Foreground = new SolidColorBrush(account.TextColor);
item.Background = new SolidColorBrush(account.Color);
}
item.Click += (sender, args) => account.SwitchTo(false);
yield return item;
}
yield return new Separator();
}
}
} | mit | C# |
854ab03caddfa692084f1169b8958582f4be1b73 | enable sensitive data logging during data test to help determine data errors | collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists | server/tests/FilterLists.Data.Tests/SeedFilterListsDbContextTests.cs | server/tests/FilterLists.Data.Tests/SeedFilterListsDbContextTests.cs | using System.Threading;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace FilterLists.Data.Tests
{
public class SeedFilterListsDbContextTests
{
[Fact]
public void Migrate_DoesNotThrowException()
{
// TODO: replace with Polly or similar to optimize time waste
// allow time for db to init
Thread.Sleep(20000);
const string connString = "Server=mariadb;Database=filterlists;Uid=filterlists;Pwd=filterlists;";
var options = new DbContextOptionsBuilder<FilterListsDbContext>().UseMySql(connString,
m => m.MigrationsAssembly("FilterLists.Data.Migrations").ServerVersion(Constants.ServerVersion))
.EnableSensitiveDataLogging().Options;
using var context = new FilterListsDbContext(options);
context.Database.Migrate();
}
}
} | using System.Threading;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace FilterLists.Data.Tests
{
public class SeedFilterListsDbContextTests
{
[Fact]
public void Migrate_DoesNotThrowException()
{
// TODO: replace with Polly or similar to optimize time waste
// allow time for db to init
Thread.Sleep(20000);
const string connString = "Server=mariadb;Database=filterlists;Uid=filterlists;Pwd=filterlists;";
var options = new DbContextOptionsBuilder<FilterListsDbContext>().UseMySql(connString,
m => m.MigrationsAssembly("FilterLists.Data.Migrations").ServerVersion(Constants.ServerVersion))
.Options;
using var context = new FilterListsDbContext(options);
context.Database.Migrate();
}
}
} | mit | C# |
b1d09d0f1c1ae3f4e2abf59937062034688d8ccc | Add new generators in proper location | kugelrund/LiveSplit,stoye/LiveSplit,ROMaster2/LiveSplit,zoton2/LiveSplit,Jiiks/LiveSplit,Fluzzarn/LiveSplit,zoton2/LiveSplit,Glurmo/LiveSplit,stoye/LiveSplit,Glurmo/LiveSplit,Dalet/LiveSplit,kugelrund/LiveSplit,PackSciences/LiveSplit,chloe747/LiveSplit,Dalet/LiveSplit,zoton2/LiveSplit,stoye/LiveSplit,PackSciences/LiveSplit,ROMaster2/LiveSplit,PackSciences/LiveSplit,Fluzzarn/LiveSplit,Dalet/LiveSplit,chloe747/LiveSplit,Jiiks/LiveSplit,Fluzzarn/LiveSplit,Glurmo/LiveSplit,kugelrund/LiveSplit,chloe747/LiveSplit,LiveSplit/LiveSplit,Jiiks/LiveSplit,ROMaster2/LiveSplit | LiveSplit/LiveSplit.View/View/ChooseComparisonsDialog.cs | LiveSplit/LiveSplit.View/View/ChooseComparisonsDialog.cs | using LiveSplit.Model.Comparisons;
using LiveSplit.UI;
using LiveSplit.UI.Components;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Xml;
namespace LiveSplit.View
{
public partial class ChooseComparisonsDialog : Form
{
public IDictionary<string, bool> ComparisonGeneratorStates { get; set; }
protected bool DialogInitialized;
public ChooseComparisonsDialog()
{
InitializeComponent();
DialogInitialized = false;
comparisonsListBox.Items.AddRange(new []
{
BestSegmentsComparisonGenerator.ComparisonName,
BestSplitTimesComparisonGenerator.ComparisonName,
AverageSegmentsComparisonGenerator.ComparisonName,
PercentileComparisonGenerator.ComparisonName,
NoneComparisonGenerator.ComparisonName
});
}
private void btnOK_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void comparisonsListBox_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (DialogInitialized)
{
var generatorName = (string)comparisonsListBox.Items[e.Index];
if (ComparisonGeneratorStates.ContainsKey(generatorName))
ComparisonGeneratorStates[generatorName] = e.NewValue == CheckState.Checked;
else
{
ComparisonGeneratorStates.Clear();
foreach (var item in comparisonsListBox.Items)
{
if ((string)item == generatorName)
ComparisonGeneratorStates[generatorName] = e.NewValue == CheckState.Checked;
else
ComparisonGeneratorStates[(string)item] = comparisonsListBox.GetItemChecked(comparisonsListBox.Items.IndexOf(item));
}
}
}
}
private void ChooseComparisonsDialog_Load(object sender, EventArgs e)
{
foreach (var generator in ComparisonGeneratorStates)
{
comparisonsListBox.SetItemChecked(comparisonsListBox.Items.IndexOf(generator.Key), generator.Value);
}
DialogInitialized = true;
}
}
}
| using LiveSplit.Model.Comparisons;
using LiveSplit.UI;
using LiveSplit.UI.Components;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Xml;
namespace LiveSplit.View
{
public partial class ChooseComparisonsDialog : Form
{
public IDictionary<string, bool> ComparisonGeneratorStates { get; set; }
protected bool DialogInitialized;
public ChooseComparisonsDialog()
{
InitializeComponent();
DialogInitialized = false;
comparisonsListBox.Items.AddRange(new []
{
BestSegmentsComparisonGenerator.ComparisonName,
BestSplitTimesComparisonGenerator.ComparisonName,
AverageSegmentsComparisonGenerator.ComparisonName,
PercentileComparisonGenerator.ComparisonName,
NoneComparisonGenerator.ComparisonName
});
}
private void btnOK_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void comparisonsListBox_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (DialogInitialized)
ComparisonGeneratorStates[(string)comparisonsListBox.Items[e.Index]] = e.NewValue == CheckState.Checked;
}
private void ChooseComparisonsDialog_Load(object sender, EventArgs e)
{
foreach (var generator in ComparisonGeneratorStates)
{
comparisonsListBox.SetItemChecked(comparisonsListBox.Items.IndexOf(generator.Key), generator.Value);
}
DialogInitialized = true;
}
}
}
| mit | C# |
8c6280152c87c3fbd6a2353af12302b6810935f8 | Remove SpecsFor from WebSocketTests | noobot/SlackConnector | src/SlackConnector.Tests.Unit/SlackConnectionTests/WebSocketTests.cs | src/SlackConnector.Tests.Unit/SlackConnectionTests/WebSocketTests.cs | using System;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using Should;
using SlackConnector.Connections.Sockets;
using SlackConnector.Models;
namespace SlackConnector.Tests.Unit.SlackConnectionTests
{
internal class WebSocketTests
{
[Test, AutoMoqData]
public async Task should_detect_disconnect(Mock<IWebSocketClient> webSocket, SlackConnection slackConnection)
{
// given
bool connectionChangedValue = false;
slackConnection.OnDisconnect += () => connectionChangedValue = true;
var info = new ConnectionInformation { WebSocket = webSocket.Object };
await slackConnection.Initialise(info);
// when
webSocket.Raise(x => x.OnClose += null, new EventArgs());
// then
connectionChangedValue.ShouldBeTrue();
slackConnection.IsConnected.ShouldBeFalse();
slackConnection.ConnectedSince.ShouldBeNull();
}
}
} | using System;
using System.Collections.Generic;
using NUnit.Framework;
using Should;
using SlackConnector.Connections.Sockets;
using SlackConnector.Models;
using SpecsFor;
namespace SlackConnector.Tests.Unit.SlackConnectionTests
{
public static class WebSocketTests
{
internal class when_socket_disconnects_given_valid_setup : SpecsFor<SlackConnection>
{
private bool ConnectionChangedValue { get; set; }
protected override void Given()
{
base.Given();
SUT.OnDisconnect += () => ConnectionChangedValue = true;
var info = new ConnectionInformation { WebSocket = GetMockFor<IWebSocketClient>().Object };
SUT.Initialise(info).Wait();
}
protected override void When()
{
GetMockFor<IWebSocketClient>()
.Raise(x => x.OnClose += null, new EventArgs());
}
[Test]
public void then_should_detect_diconnect()
{
ConnectionChangedValue.ShouldBeTrue();
}
[Test]
public void then_should_not_detect_as_connected()
{
SUT.IsConnected.ShouldBeFalse();
SUT.ConnectedSince.ShouldBeNull();
}
}
}
} | mit | C# |
ecd4d9b20c0d4feaf450fdb367f09edbd376659e | Fix rounding error in SphericalMercator for #1212 | charlenni/Mapsui,pauldendulk/Mapsui,charlenni/Mapsui | Mapsui/Projection/SphericalMercator.cs | Mapsui/Projection/SphericalMercator.cs | using Mapsui.Geometries;
using System;
namespace Mapsui.Projection
{
public class SphericalMercator
{
private const double Radius = 6378137;
private const double D2R = Math.PI/180;
private const double HalfPi = Math.PI/2;
public static Point FromLonLat(double lon, double lat)
{
var lonRadians = D2R * lon;
var latRadians = D2R * lat;
var x = Radius * lonRadians;
var y = Radius * Math.Log(Math.Tan(Math.PI * 0.25 + latRadians * 0.5));
return new Point(x, y);
}
public static Point ToLonLat(double x, double y)
{
var ts = Math.Exp(-y / Radius);
var latRadians = HalfPi - 2 * Math.Atan(ts);
var lonRadians = x / Radius;
var lon = lonRadians / D2R;
var lat = latRadians / D2R;
return new Point(lon, lat);
}
}
} | using Mapsui.Geometries;
using System;
namespace Mapsui.Projection
{
public class SphericalMercator
{
private const double Radius = 6378137;
private const double D2R = Math.PI/180;
private const double HalfPi = Math.PI/2;
public static Point FromLonLat(double lon, double lat)
{
var lonRadians = D2R * lon;
var latRadians = D2R * lat;
var x = Radius * lonRadians;
var y = Radius * Math.Log(Math.Tan(Math.PI * 0.25 + latRadians * 0.5));
return new Point((float)x, (float)y);
}
public static Point ToLonLat(double x, double y)
{
var ts = Math.Exp(-y / (Radius));
var latRadians = HalfPi - 2 * Math.Atan(ts);
var lonRadians = x / Radius;
var lon = lonRadians / D2R;
var lat = latRadians / D2R;
return new Point((float)lon, (float)lat);
}
}
} | mit | C# |
f847bcb37fec183d538daeea9ee112f3eb7ccebe | Test confirm msg | darkoverlordofdata/minimart,darkoverlordofdata/minimart,darkoverlordofdata/minimart | Minimart/Controllers/HomeController.cs | Minimart/Controllers/HomeController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using Minimart.Models;
namespace Minimart.Controllers
{
public class HomeController : Controller
{
private MinimartEntities storeDB = new MinimartEntities();
public HomeController()
{
ViewBag.Title = "Mini-Mart";
ViewBag.MenuHome = "";
ViewBag.MenuCatalog = "";
ViewBag.MenuCart = "";
ViewBag.MenuCheckout = "";
}
public ActionResult Index(string confirm = "")
{
ViewBag.MenuHome = "active";
ViewBag.Confirmation = confirm;
MM_GetBrand_Result brand = storeDB.MM_GetBrand(1).ElementAt(0);
ViewBag.Confirmation = brand.name;
return View();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using Minimart.Models;
namespace Minimart.Controllers
{
public class HomeController : Controller
{
private MinimartEntities storeDB = new MinimartEntities();
public HomeController()
{
ViewBag.Title = "Mini-Mart";
ViewBag.MenuHome = "";
ViewBag.MenuCatalog = "";
ViewBag.MenuCart = "";
ViewBag.MenuCheckout = "";
}
public ActionResult Index(string confirm = "")
{
ViewBag.MenuHome = "active";
ViewBag.Confirmation = confirm;
MM_GetBrand_Result brand = storeDB.MM_GetBrand(1).ElementAt(0);
ViewBag.BrandName = brand.name;
return View();
}
}
}
| mit | C# |
a8832d0f75c9efaee4c4a756c23212e6a8e3512f | Add comment regarding public key of Behaviors.snk | Microsoft/XamlBehaviors,Microsoft/XamlBehaviors,Microsoft/XamlBehaviors | src/BehaviorsSDKManaged/Microsoft.Xaml.Interactions/Properties/AssemblyInfo.cs | src/BehaviorsSDKManaged/Microsoft.Xaml.Interactions/Properties/AssemblyInfo.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Microsoft.Xaml.Interactions")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Microsoft.Xaml.Interactions")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015-2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// Behaviors.snk public key is 0024000004800000940000000602000000240000525341310004000001000100e5435599803109fe684072f487ec0670f2766325a25d47089633ffb5d9a56bf115a705bc0632660aeecfe00248951540865f481613845080859feafc5d9b55750395e7ca4c2124136d17bc9e73f0371d802fc2c9e8308f6f8b0ab3096661d2d1b0cbbbcb6de3fe711ef415f29271088537081b09ad1ee08ce8020b22031cdebd
[assembly: InternalsVisibleTo("ManagedUnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100e5435599803109fe684072f487ec0670f2766325a25d47089633ffb5d9a56bf115a705bc0632660aeecfe00248951540865f481613845080859feafc5d9b55750395e7ca4c2124136d17bc9e73f0371d802fc2c9e8308f6f8b0ab3096661d2d1b0cbbbcb6de3fe711ef415f29271088537081b09ad1ee08ce8020b22031cdebd")] | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Microsoft.Xaml.Interactions")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Microsoft.Xaml.Interactions")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015-2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: InternalsVisibleTo("ManagedUnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100e5435599803109fe684072f487ec0670f2766325a25d47089633ffb5d9a56bf115a705bc0632660aeecfe00248951540865f481613845080859feafc5d9b55750395e7ca4c2124136d17bc9e73f0371d802fc2c9e8308f6f8b0ab3096661d2d1b0cbbbcb6de3fe711ef415f29271088537081b09ad1ee08ce8020b22031cdebd")] | mit | C# |
42686d6d34f7e8427dc4e0f8f2823df1b10a8f52 | Remove unused usings | tgstation/tgstation-server-tools,tgstation/tgstation-server,tgstation/tgstation-server | tests/Tgstation.Server.Host.Tests/Components/Chat/Providers/TestIrcProvider.cs | tests/Tgstation.Server.Host.Tests/Components/Chat/Providers/TestIrcProvider.cs | using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
using System.Threading.Tasks;
using Tgstation.Server.Api.Models;
using Tgstation.Server.Host.Core;
using Tgstation.Server.Host.Jobs;
using Tgstation.Server.Host.Models;
using Tgstation.Server.Host.System;
namespace Tgstation.Server.Host.Components.Chat.Providers.Tests
{
[TestClass]
public sealed class TestIrcProvider
{
[TestMethod]
public async Task TestConstructionAndDisposal()
{
Assert.ThrowsException<ArgumentNullException>(() => new IrcProvider(null, null, null, null, null));
var mockJobManager = new Mock<IJobManager>();
Assert.ThrowsException<ArgumentNullException>(() => new IrcProvider(mockJobManager.Object, null, null, null, null));
var mockAss = new Mock<IAssemblyInformationProvider>();
Assert.ThrowsException<ArgumentNullException>(() => new IrcProvider(mockJobManager.Object, mockAss.Object, null, null, null));
var mockAsyncDelayer = new Mock<IAsyncDelayer>();
Assert.ThrowsException<ArgumentNullException>(() => new IrcProvider(mockJobManager.Object, mockAss.Object, mockAsyncDelayer.Object, null, null));
var mockLogger = new Mock<ILogger<IrcProvider>>();
Assert.ThrowsException<ArgumentNullException>(() => new IrcProvider(mockJobManager.Object, mockAss.Object, mockAsyncDelayer.Object, mockLogger.Object, null));
var mockBot = new ChatBot
{
Name = "test",
Provider = ChatProvider.Irc
};
Assert.ThrowsException<InvalidOperationException>(() => new IrcProvider(mockJobManager.Object, mockAss.Object, mockAsyncDelayer.Object, mockLogger.Object, mockBot));
mockBot.ConnectionString = new IrcConnectionStringBuilder
{
Address = "localhost",
Nickname = "test",
UseSsl = true,
Port = 6667
}.ToString();
await new IrcProvider(mockJobManager.Object, mockAss.Object, mockAsyncDelayer.Object, mockLogger.Object, mockBot).DisposeAsync();
}
}
}
| using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Tgstation.Server.Api.Models;
using Tgstation.Server.Host.Core;
using Tgstation.Server.Host.Jobs;
using Tgstation.Server.Host.Models;
using Tgstation.Server.Host.System;
namespace Tgstation.Server.Host.Components.Chat.Providers.Tests
{
[TestClass]
public sealed class TestIrcProvider
{
[TestMethod]
public async Task TestConstructionAndDisposal()
{
Assert.ThrowsException<ArgumentNullException>(() => new IrcProvider(null, null, null, null, null));
var mockJobManager = new Mock<IJobManager>();
Assert.ThrowsException<ArgumentNullException>(() => new IrcProvider(mockJobManager.Object, null, null, null, null));
var mockAss = new Mock<IAssemblyInformationProvider>();
Assert.ThrowsException<ArgumentNullException>(() => new IrcProvider(mockJobManager.Object, mockAss.Object, null, null, null));
var mockAsyncDelayer = new Mock<IAsyncDelayer>();
Assert.ThrowsException<ArgumentNullException>(() => new IrcProvider(mockJobManager.Object, mockAss.Object, mockAsyncDelayer.Object, null, null));
var mockLogger = new Mock<ILogger<IrcProvider>>();
Assert.ThrowsException<ArgumentNullException>(() => new IrcProvider(mockJobManager.Object, mockAss.Object, mockAsyncDelayer.Object, mockLogger.Object, null));
var mockBot = new ChatBot
{
Name = "test",
Provider = ChatProvider.Irc
};
Assert.ThrowsException<InvalidOperationException>(() => new IrcProvider(mockJobManager.Object, mockAss.Object, mockAsyncDelayer.Object, mockLogger.Object, mockBot));
mockBot.ConnectionString = new IrcConnectionStringBuilder
{
Address = "localhost",
Nickname = "test",
UseSsl = true,
Port = 6667
}.ToString();
await new IrcProvider(mockJobManager.Object, mockAss.Object, mockAsyncDelayer.Object, mockLogger.Object, mockBot).DisposeAsync();
}
}
}
| agpl-3.0 | C# |
a654e6f9353b7bbf0c7b9fc6c3cc9c1135aa37af | Fix comment for MockMessageHandler (did not | DimensionDataCBUSydney/Watt | Watt.Tests/Mocks/MockMessageHandler.cs | Watt.Tests/Mocks/MockMessageHandler.cs | using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace DD.Cloud.WebApi.TemplateToolkit.Tests.Mocks
{
/// <summary>
/// Mock <see cref="DelegatingHandler"/> that calls an arbitrary delegate to receive and respond to a message.
/// </summary>
public sealed class MockMessageHandler
: DelegatingHandler
{
/// <summary>
/// The handler implementation.
/// </summary>
readonly Func<HttpRequestMessage, Task<HttpResponseMessage>> _handlerImplementation;
/// <summary>
/// Create a new mock message handler.
/// </summary>
/// <param name="handlerImplementation">
/// The handler implementation.
/// </param>
public MockMessageHandler(Func<HttpRequestMessage, HttpResponseMessage> handlerImplementation)
{
if (handlerImplementation == null)
throw new ArgumentNullException("handlerImplementation");
_handlerImplementation = request => Task<HttpResponseMessage>.Factory.StartNew(
() => handlerImplementation(request)
);
}
/// <summary>
/// Create a new mock message handler.
/// </summary>
/// <param name="handlerImplementation">
/// The handler implementation.
/// </param>
public MockMessageHandler(Func<HttpRequestMessage, Task<HttpResponseMessage>> handlerImplementation)
{
if (handlerImplementation == null)
throw new ArgumentNullException("handlerImplementation");
_handlerImplementation = handlerImplementation;
}
/// <summary>
/// Asynchronously handle a request
/// </summary>
/// <param name="request">
/// The request message.
/// </param>
/// <param name="cancellationToken">
/// A cancellation token that can be used to cancel the operation.
/// </param>
/// <returns>
/// A <see cref="Task{TResult}"/> representing the asynchronous operation, whose result is the response message.
/// </returns>
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request == null)
throw new ArgumentNullException("request");
return await _handlerImplementation(request);
}
}
}
| using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace DD.Cloud.WebApi.TemplateToolkit.Tests.Mocks
{
/// <summary>
/// Mock <see cref="DelegatingHandler"/> that raises an event to receive and respond to a message.
/// </summary>
public sealed class MockMessageHandler
: DelegatingHandler
{
/// <summary>
/// The handler implementation.
/// </summary>
readonly Func<HttpRequestMessage, Task<HttpResponseMessage>> _handlerImplementation;
/// <summary>
/// Create a new mock message handler.
/// </summary>
/// <param name="handlerImplementation">
/// The handler implementation.
/// </param>
public MockMessageHandler(Func<HttpRequestMessage, HttpResponseMessage> handlerImplementation)
{
if (handlerImplementation == null)
throw new ArgumentNullException("handlerImplementation");
_handlerImplementation = request => Task<HttpResponseMessage>.Factory.StartNew(
() => handlerImplementation(request)
);
}
/// <summary>
/// Create a new mock message handler.
/// </summary>
/// <param name="handlerImplementation">
/// The handler implementation.
/// </param>
public MockMessageHandler(Func<HttpRequestMessage, Task<HttpResponseMessage>> handlerImplementation)
{
if (handlerImplementation == null)
throw new ArgumentNullException("handlerImplementation");
_handlerImplementation = handlerImplementation;
}
/// <summary>
/// Asynchronously handle a request
/// </summary>
/// <param name="request">
/// The request message.
/// </param>
/// <param name="cancellationToken">
/// A cancellation token that can be used to cancel the operation.
/// </param>
/// <returns>
/// A <see cref="Task{TResult}"/> representing the asynchronous operation, whose result is the response message.
/// </returns>
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request == null)
throw new ArgumentNullException("request");
return await _handlerImplementation(request);
}
}
}
| mit | C# |
5aeb127a9e7420b11e4ff52866f4c7395812639c | Fix instructions | marcelopetersen/CustomConfigurationSections | Petersen.CustomConfiguration/NestedClassesConfiguration/PlannerSection.cs | Petersen.CustomConfiguration/NestedClassesConfiguration/PlannerSection.cs | using System;
using System.Configuration;
namespace Petersen.CustomConfiguration.NestedClassesConfiguration
{
public class PlannerSection : ConfigurationSection
{
/*///////////////////////////////////////////////////////////////////
// With root element, set ROOT_ELEMENT_NAME="sections"
<plannerSection>
<sections>
<section id="teams">
<pagination itemsperpage="10" visiblePages="15" />
</section>
</sections>
<plannerSection>
// With no root element, set ROOT_ELEMENT_NAME=""
<plannerSection>
<section id="teams">
<pagination itemsperpage="10" visiblePages="15" />
</section>
<plannerSection>
///////////////////////////////////////////////////////////////////*/
private const string ROOT_ELEMENT_NAME = "sections";
[ConfigurationProperty(ROOT_ELEMENT_NAME, IsDefaultCollection = true, IsKey = false, IsRequired = true)]
public SectionCollection Sections
{
get
{
return base[ROOT_ELEMENT_NAME] as SectionCollection;
}
set
{
base[ROOT_ELEMENT_NAME] = value;
}
}
}
}
| using System;
using System.Configuration;
namespace Petersen.CustomConfiguration.NestedClassesConfiguration
{
public class PlannerSection : ConfigurationSection
{
/*///////////////////////////////////////////////////////////////////
// With no root elements, set ROOT_ELEMENT_NAME="sections"
<plannerSection>
<sections>
<section id="teams">
<pagination itemsperpage="10" visiblePages="15" />
</section>
</sections>
<plannerSection>
// With no root element, set ROOT_ELEMENT_NAME=""
<plannerSection>
<section id="teams">
<pagination itemsperpage="10" visiblePages="15" />
</section>
<plannerSection>
///////////////////////////////////////////////////////////////////*/
private const string ROOT_ELEMENT_NAME = "sections";
[ConfigurationProperty(ROOT_ELEMENT_NAME, IsDefaultCollection = true, IsKey = false, IsRequired = true)]
public SectionCollection Sections
{
get
{
return base[ROOT_ELEMENT_NAME] as SectionCollection;
}
set
{
base[ROOT_ELEMENT_NAME] = value;
}
}
}
}
| mit | C# |
ac564ff5e0575ce3b191ef9be0983fe6c340fccd | Update DeserializerBase.cs | tiksn/TIKSN-Framework | TIKSN.Core/Serialization/DeserializerBase.cs | TIKSN.Core/Serialization/DeserializerBase.cs | using System;
namespace TIKSN.Serialization
{
public abstract class DeserializerBase<TSerial> : IDeserializer<TSerial> where TSerial : class
{
public T Deserialize<T>(TSerial serial)
{
try
{
return this.DeserializeInternal<T>(serial);
}
catch (Exception ex)
{
throw new DeserializerException("Deserialization failed.", ex);
}
}
protected abstract T DeserializeInternal<T>(TSerial serial);
}
}
| using System;
namespace TIKSN.Serialization
{
public abstract class DeserializerBase<TSerial> : IDeserializer<TSerial> where TSerial : class
{
public T Deserialize<T>(TSerial serial)
{
try
{
return DeserializeInternal<T>(serial);
}
catch (Exception ex)
{
throw new DeserializerException("Deserialization failed.", ex);
}
}
protected abstract T DeserializeInternal<T>(TSerial serial);
}
} | mit | C# |
5b869594966d9a326eea3bf4cddffe55287b126a | Fix unused variable | MrHant/tiver-fowl.Drivers,MrHant/tiver-fowl.Drivers | Tiver.Fowl.Drivers/Configuration/DriversConfiguration.cs | Tiver.Fowl.Drivers/Configuration/DriversConfiguration.cs | using System.IO;
using System.Reflection;
namespace Tiver.Fowl.Drivers.Configuration
{
public class DriversConfiguration
{
/// <summary>
/// Location for binaries to be saved
/// Defaults to assembly location
/// </summary>
public string DownloadLocation { get; set; } = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
/// <summary>
/// Configured driver instances
/// </summary>
public DriverElement[] Instances { get; set; } = {};
/// <summary>
/// Timeout to be used for HTTP requests
/// Value in seconds
/// </summary>
public int HttpTimeout { get; set; } = 100;
}
}
| using System.IO;
using System.Reflection;
namespace Tiver.Fowl.Drivers.Configuration
{
public class DriversConfiguration
{
private string _downloadLocation;
/// <summary>
/// Location for binaries to be saved
/// Defaults to assembly location
/// </summary>
public string DownloadLocation { get; set; } = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
/// <summary>
/// Configured driver instances
/// </summary>
public DriverElement[] Instances { get; set; } = {};
/// <summary>
/// Timeout to be used for HTTP requests
/// Value in seconds
/// </summary>
public int HttpTimeout { get; set; } = 100;
}
}
| mit | C# |
c43f2cdb2886e2bb0603335500cccc0dc3867e30 | Change type of MaximumBytesPerSec to long | witoong623/TirkxDownloader,witoong623/TirkxDownloader | Models/Settings/DownloadingSetting.cs | Models/Settings/DownloadingSetting.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using MetroTrilithon.Serialization;
namespace TirkxDownloader.Models.Settings
{
public class DownloadingSetting
{
public static SerializableProperty<long> MaximumBytesPerSec { get; }
= new SerializableProperty<long>(GetKey(), SettingsProviders.Local, 0);
public static SerializableProperty<byte> MaxConcurrentDownload { get; }
= new SerializableProperty<byte>(GetKey(), SettingsProviders.Local, 1);
private static string GetKey([CallerMemberName] string caller = "")
{
return nameof(DownloadingSetting) + "." + caller;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using MetroTrilithon.Serialization;
namespace TirkxDownloader.Models.Settings
{
public class DownloadingSetting
{
public static SerializableProperty<int> MaximumBytesPerSec { get; }
= new SerializableProperty<int>(GetKey(), SettingsProviders.Local, 0);
public static SerializableProperty<byte> MaxConcurrentDownload { get; }
= new SerializableProperty<byte>(GetKey(), SettingsProviders.Local, 1);
private static string GetKey([CallerMemberName] string caller = "")
{
return nameof(DownloadingSetting) + "." + caller;
}
}
}
| mit | C# |
a8702c132d866524c7e631380de3fc27a4ee66ad | Add timeout to decoration etl-run | Seddryck/NBi,Seddryck/NBi | NBi.Xml/Decoration/Command/EtlRunXml.cs | NBi.Xml/Decoration/Command/EtlRunXml.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using NBi.Core.Etl;
using NBi.Xml.Items;
namespace NBi.Xml.Decoration.Command
{
public class EtlRunXml : DecorationCommandXml, IEtlRunCommand
{
[XmlAttribute("server")]
public string Server { get; set; }
[XmlAttribute("path")]
public string Path { get; set; }
[XmlAttribute("name")]
public string Name { get; set; }
[XmlAttribute("username")]
public string UserName { get; set; }
[XmlAttribute("password")]
public string Password { get; set; }
[XmlAttribute("catalog")]
public string Catalog { get; set; }
[XmlAttribute("folder")]
public string Folder { get; set; }
[XmlAttribute("project")]
public string Project { get; set; }
[XmlAttribute("bits-32")]
public bool Is32Bits { get; set; }
[XmlAttribute("timeout")]
public int Timeout { get; set; }
[XmlIgnore]
public List<EtlParameter> Parameters
{
get
{
return InternalParameters.ToList<EtlParameter>();
}
set
{
throw new NotImplementedException();
}
}
[XmlElement("parameter")]
public List<EtlParameterXml> InternalParameters { get; set; }
public EtlRunXml()
{
InternalParameters = new List<EtlParameterXml>();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using NBi.Core.Etl;
using NBi.Xml.Items;
namespace NBi.Xml.Decoration.Command
{
public class EtlRunXml : DecorationCommandXml, IEtlRunCommand
{
[XmlAttribute("server")]
public string Server { get; set; }
[XmlAttribute("path")]
public string Path { get; set; }
[XmlAttribute("name")]
public string Name { get; set; }
[XmlAttribute("username")]
public string UserName { get; set; }
[XmlAttribute("password")]
public string Password { get; set; }
[XmlAttribute("catalog")]
public string Catalog { get; set; }
[XmlAttribute("folder")]
public string Folder { get; set; }
[XmlAttribute("project")]
public string Project { get; set; }
[XmlAttribute("bits-32")]
public bool Is32Bits { get; set; }
[XmlIgnore]
public List<EtlParameter> Parameters
{
get
{
return InternalParameters.ToList<EtlParameter>();
}
set
{
throw new NotImplementedException();
}
}
[XmlElement("parameter")]
public List<EtlParameterXml> InternalParameters { get; set; }
public EtlRunXml()
{
InternalParameters = new List<EtlParameterXml>();
}
}
}
| apache-2.0 | C# |
cbfc0f9dcd7cdf8d7c1ab61144661bb3a84d0478 | Make InvokeOnce thread-safe | ivanz/Machine.Specifications.TeamCityParallelRunner,marketinvoice/Machine.Specifications.TeamCityParallelRunner | ParallelMSpecRunner/Utils/InvokeOnce.cs | ParallelMSpecRunner/Utils/InvokeOnce.cs | using System;
using System.Threading;
namespace ParallelMSpecRunner.Utils
{
internal class InvokeOnce<T>
{
private readonly Action<T> _invocation;
private int _wasInvoked;
private const int TRUE = 1;
private const int FALSE = 0;
public InvokeOnce(Action<T> invocation)
{
_invocation = invocation;
_wasInvoked = FALSE;
}
public void Invoke(T value)
{
if (Interlocked.CompareExchange(ref _wasInvoked, TRUE, FALSE) == FALSE)
_invocation(value);
}
public bool WasInvoked {
get { return _wasInvoked == TRUE; }
}
}
} | using System;
namespace ParallelMSpecRunner.Utils
{
internal class InvokeOnce<T>
{
private readonly Action<T> _invocation;
public InvokeOnce(Action<T> invocation)
{
_invocation = invocation;
}
public void Invoke(T value)
{
if (WasInvoked)
return;
WasInvoked = true;
_invocation(value);
}
public bool WasInvoked { get; private set; }
}
} | mit | C# |
bdb52a2b25af651a831249d087907f8ffb5640f1 | Add cropping options into Generate-Tilemap directly. | Prof9/PixelPet | PixelPet/Commands/GenerateTilemapCmd.cs | PixelPet/Commands/GenerateTilemapCmd.cs | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace PixelPet.Commands {
internal class GenerateTilemapCmd : CliCommand {
public GenerateTilemapCmd()
: base("Generate-Tilemap",
new Parameter("palette-size", "ps", false, new ParameterValue("count", "16")),
new Parameter("no-reduce", "nr", false),
new Parameter("x", "x", false, new ParameterValue("pixels", "0")),
new Parameter("y", "y", false, new ParameterValue("pixels", "0")),
new Parameter("width", "w", false, new ParameterValue("pixels", "-1")),
new Parameter("height", "h", false, new ParameterValue("pixels", "-1"))
) { }
public override void Run(Workbench workbench, Cli cli) {
cli.Log("Generating tilemap...");
int palSize = FindNamedParameter("--palette-size").Values[0].ToInt32();
bool noReduce = FindNamedParameter("--no-reduce" ).IsPresent;
int x = FindNamedParameter("--x" ).Values[0].ToInt32();
int y = FindNamedParameter("--y" ).Values[0].ToInt32();
int w = FindNamedParameter("--width" ).Values[0].ToInt32();
int h = FindNamedParameter("--height" ).Values[0].ToInt32();
using (Bitmap bmp = workbench.GetCroppedBitmap(x, y, w, h, cli)) {
workbench.Tilemap = new Tilemap(bmp, workbench.Tileset, workbench.Palette, palSize, !noReduce);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace PixelPet.Commands {
internal class GenerateTilemapCmd : CliCommand {
public GenerateTilemapCmd()
: base("Generate-Tilemap", new Parameter[] {
new Parameter("palette-size", "ps", false, new ParameterValue("count", "16")),
new Parameter("no-reduce", "nr", false),
}) { }
public override void Run(Workbench workbench, Cli cli) {
cli.Log("Generating tilemap...");
int palSize = FindNamedParameter("--palette-size").Values[0].ToInt32();
bool noReduce = FindNamedParameter("--no-reduce").IsPresent;
workbench.Tilemap = new Tilemap(workbench.Bitmap, workbench.Tileset, workbench.Palette, palSize, !noReduce);
}
}
}
| mit | C# |
f526bd2b253ad831231445e45739f27d87ed106e | Fix build error | mattgwagner/alert-roster | alert-roster.web/Models/EmailSender.cs | alert-roster.web/Models/EmailSender.cs | using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
namespace alert_roster.web.Models
{
public class EmailSender
{
private static readonly Logger log = LogManager.GetCurrentClassLogger();
public static String EmailSubject = ConfigurationManager.AppSettings["Email.Subject"];
public static String FromAddress = ConfigurationManager.AppSettings["Email.FromAddress"];
public static String SmtpServer = ConfigurationManager.AppSettings["MAILGUN_SMTP_SERVER"];
public static int SmtpPort = int.Parse(ConfigurationManager.AppSettings["MAILGUN_SMTP_PORT"]);
public static String SmtpUser = ConfigurationManager.AppSettings["MAILGUN_SMTP_LOGIN"];
public static String SmtpPassword = ConfigurationManager.AppSettings["MAILGUN_SMTP_PASSWORD"];
public static Boolean EnableSsl = true;
public static Boolean IsBodyHtml = false;
public static void Send(IEnumerable<String> Recipients, String content)
{
using (var smtp = new SmtpClient { Host = SmtpServer, Port = SmtpPort, EnableSsl = EnableSsl, Credentials = new NetworkCredential { UserName = SmtpUser, Password = SmtpPassword } })
using (var message = new MailMessage { IsBodyHtml = IsBodyHtml })
{
if (Recipients.Any())
{
message.From = new MailAddress(FromAddress);
message.Subject = EmailSubject;
foreach (var recipient in Recipients)
{
message.Bcc.Add(new MailAddress(recipient));
}
message.Body = content;
smtp.Send(message);
}
}
}
}
} | using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
namespace alert_roster.web.Models
{
public class EmailSender
{
private static readonly Logger log = LogManager.GetCurrentClassLogger();
public static String EmailSubject = ConfigurationManager.AppSettings["Email.Subject"];
public static String FromAddress = ConfigurationManager.AppSettings["Email.FromAddress"];
public static String SmtpServer = ConfigurationManager.AppSettings["MAILGUN_SMTP_SERVER"];
public static int SmtpPort = int.Parse(ConfigurationManager.AppSettings["MAILGUN_SMTP_PORT"]);
public static String SmtpUser = ConfigurationManager.AppSettings["MAILGUN_SMTP_LOGIN"];
public static String SmtpPassword = ConfigurationManager.AppSettings["MAILGUN_SMTP_PASSWORD"];
public static Boolean EnableSsl = true;
public static Boolean IsBodyHtml = false;
public static void Send(IEnumerable<String> Recipients, String content)
{
using (var smtp = new SmtpClient { Host = SmtpServer, Port = SmtpPort, EnableSsl = EnableSsl, Credentials = new NetworkCredential { UserName = SmtpUser, Password = SmtpPassword } })
using (var message = new MailMessage { IsBodyHtml = IsBodyHtml })
{
if (Recipients.Any())
{
message.From = new MailAddress(FromAddress);
message.Subject = EmailSubject;
foreach (var recipient in recipients)
{
message.Bcc.Add(new MailAddress(recipient));
}
message.Body = content;
smtp.Send(message);
}
}
}
}
} | mit | C# |
1a27b333aa6e97443fe8149b1321d2cc347aa47c | fix unit tests | dc0d32/RangePermute | RangePermute.Tests/RangePermuteTests.cs | RangePermute.Tests/RangePermuteTests.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
namespace RangePermute.Tests
{
[TestClass]
public class RangePermuteTests
{
[TestMethod]
public void TestSmallRanges()
{
for (int rangeMax = 0; rangeMax < 1000; rangeMax++)
{
var idealRange = Enumerable.Range(0, rangeMax).Aggregate(new HashSet<ulong>(), (hs, i) => { hs.Add((ulong)i); return hs; });
var algoRange = RangeEnumerable.Range((ulong)rangeMax).Aggregate(new HashSet<ulong>(), (hs, i) => { hs.Add((ulong)i); return hs; });
idealRange.SymmetricExceptWith(algoRange);
Assert.AreEqual(idealRange.Count, 0);
}
}
[TestMethod]
public void TestLargeRange()
{
var testRange = 100000;
var seen = new BitArray(testRange);
var count = 0;
foreach (var idx in RangeEnumerable.Range((ulong)testRange))
{
Assert.IsFalse(seen[(int)idx]);
seen[(int)idx] = true;
count++;
}
Assert.AreEqual(count, testRange);
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
namespace RangePermute.Tests
{
[TestClass]
public class RangePermuteTests
{
[TestMethod]
public void TestSmallRanges()
{
for (int rangeMax = 0; rangeMax < 1000; rangeMax++)
{
var idealRange = Enumerable.Range(0, rangeMax).Aggregate(new HashSet<ulong>(), (hs, i) => { hs.Add((ulong)i); return hs; });
var algoRange = RangeEnumerable.Range((ulong)rangeMax).Aggregate(new HashSet<ulong>(), (hs, i) => { hs.Add((ulong)i); return hs; });
idealRange.SymmetricExceptWith(algoRange);
Assert.AreEqual(idealRange.Count, 0);
}
}
[TestMethod]
public void TestLargeRange()
{
var testRange = 100000;
var seen = new BitArray(testRange);
foreach (var idx in RangeEnumerable.Range((ulong)testRange))
{
Assert.IsFalse(seen[(int)idx]);
seen[(int)idx] = true;
}
}
}
}
| mit | C# |
efbc09f27fa3bdc370be261e5062cf96879cba86 | Build and publish nuget package | RockFramework/Rock.Logging | Rock.Logging/Properties/AssemblyInfo.cs | Rock.Logging/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("Rock.Logging")]
[assembly: AssemblyDescription("Rock logger.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Quicken Loans")]
[assembly: AssemblyProduct("Rock.Logging")]
[assembly: AssemblyCopyright("Copyright © Quicken Loans 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("71736a4b-21bc-46f3-9bb7-f9c9a260f723")]
// 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.9.0.0")]
[assembly: AssemblyFileVersion("0.9.8")]
[assembly: AssemblyInformationalVersion("0.9.8")]
| 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("Rock.Logging")]
[assembly: AssemblyDescription("Rock logger.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Quicken Loans")]
[assembly: AssemblyProduct("Rock.Logging")]
[assembly: AssemblyCopyright("Copyright © Quicken Loans 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("71736a4b-21bc-46f3-9bb7-f9c9a260f723")]
// 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.9.0.0")]
[assembly: AssemblyFileVersion("0.9.7")]
[assembly: AssemblyInformationalVersion("0.9.7")]
| mit | C# |
c2f0cd1792f2946c2b13d10ad445453b11975595 | Add ability to set text halo color. | Smartrak/TileSharp,Smartrak/TileSharp | TileSharp/Symbolizers/TextSymbolizer.cs | TileSharp/Symbolizers/TextSymbolizer.cs | using System.Drawing;
namespace TileSharp.Symbolizers
{
/// <summary>
/// https://github.com/mapnik/mapnik/wiki/TextSymbolizer
/// </summary>
public class TextSymbolizer : Symbolizer
{
public readonly string LabelAttribute;
public readonly PlacementType Placement;
public readonly ContentAlignment Alignment;
public readonly int FontSize;
public readonly Color TextColor;
public readonly Color TextHaloColor;
/// <summary>
/// The distance between repeated labels.
/// 0: A single label is placed in the center.
/// Based on Mapnik Spacing
/// </summary>
public readonly int Spacing;
public TextSymbolizer(string labelAttribute, PlacementType placement, int fontSize, ContentAlignment alignment = ContentAlignment.MiddleCenter, int spacing = 0, Color? textColor = null, Color? textHaloColor = null)
{
LabelAttribute = labelAttribute;
Placement = placement;
Alignment = alignment;
Spacing = spacing;
FontSize = fontSize;
TextColor = textColor ?? Color.Black;
TextHaloColor = textHaloColor ?? Color.White;
}
public enum PlacementType
{
Line,
Point
}
}
}
| using System.Drawing;
namespace TileSharp.Symbolizers
{
/// <summary>
/// https://github.com/mapnik/mapnik/wiki/TextSymbolizer
/// </summary>
public class TextSymbolizer : Symbolizer
{
public readonly string LabelAttribute;
public readonly PlacementType Placement;
public readonly ContentAlignment Alignment;
public readonly int FontSize;
public readonly Color TextColor;
public readonly Color TextHaloColor;
/// <summary>
/// The distance between repeated labels.
/// 0: A single label is placed in the center.
/// Based on Mapnik Spacing
/// </summary>
public readonly int Spacing;
public TextSymbolizer(string labelAttribute, PlacementType placement, int fontSize, ContentAlignment alignment = ContentAlignment.MiddleCenter, int spacing = 0, Color? textColor = null)
{
LabelAttribute = labelAttribute;
Placement = placement;
Alignment = alignment;
Spacing = spacing;
FontSize = fontSize;
TextColor = textColor ?? Color.Black;
TextHaloColor = Color.White;
}
public enum PlacementType
{
Line,
Point
}
}
}
| bsd-2-clause | C# |
f3ff7ba55a85f76d7ae8c041bbd2d56958433dd3 | Fix an animation bug with Mice to Snuffboxes | StefanoFiumara/Harry-Potter-Unity | Assets/Scripts/HarryPotterUnity/Cards/Spells/Transfigurations/MiceToSnuffboxes.cs | Assets/Scripts/HarryPotterUnity/Cards/Spells/Transfigurations/MiceToSnuffboxes.cs | using System.Collections.Generic;
using HarryPotterUnity.Cards.Generic;
using JetBrains.Annotations;
namespace HarryPotterUnity.Cards.Spells.Transfigurations
{
[UsedImplicitly]
public class MiceToSnuffboxes : GenericSpell {
public override List<GenericCard> GetValidTargets()
{
var validCards = Player.InPlay.GetCreaturesInPlay();
validCards.AddRange(Player.OppositePlayer.InPlay.GetCreaturesInPlay());
return validCards;
}
protected override void SpellAction(List<GenericCard> selectedCards)
{
int i = 0;
foreach(var card in selectedCards) {
card.Player.Hand.Add(card, preview: false, adjustSpacing: card.Player.IsLocalPlayer && i == 1);
card.Player.InPlay.Remove(card);
i++;
}
}
}
}
| using System.Collections.Generic;
using HarryPotterUnity.Cards.Generic;
using JetBrains.Annotations;
namespace HarryPotterUnity.Cards.Spells.Transfigurations
{
[UsedImplicitly]
public class MiceToSnuffboxes : GenericSpell {
public override List<GenericCard> GetValidTargets()
{
var validCards = Player.InPlay.GetCreaturesInPlay();
validCards.AddRange(Player.OppositePlayer.InPlay.GetCreaturesInPlay());
return validCards;
}
protected override void SpellAction(List<GenericCard> selectedCards)
{
foreach(var card in selectedCards) {
card.Player.Hand.Add(card, false);
card.Player.InPlay.Remove(card);
}
}
}
}
| mit | C# |
d4c751bd0b09e8d5771eaabf7a8f0c788b9b57c4 | Save feature added for testing. | aykanatm/ProjectMarkdown | ProjectMarkdown/ViewModels/MainWindowViewModel.cs | ProjectMarkdown/ViewModels/MainWindowViewModel.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using ProjectMarkdown.Annotations;
namespace ProjectMarkdown.ViewModels
{
public class MainWindowViewModel : INotifyPropertyChanged
{
private string _currentDocumentPath;
private string _currentText;
private string _currentHtml;
public string CurrentDocumentPath
{
get { return _currentDocumentPath; }
set
{
if (value == _currentDocumentPath) return;
_currentDocumentPath = value;
OnPropertyChanged(nameof(CurrentDocumentPath));
}
}
public string CurrentText
{
get { return _currentText; }
set
{
if (value == _currentText) return;
_currentText = value;
OnPropertyChanged(nameof(CurrentText));
}
}
public string CurrentHtml
{
get { return _currentHtml; }
set
{
if (value == _currentHtml) return;
_currentHtml = value;
OnPropertyChanged(nameof(CurrentHtml));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public ICommand SaveDocumentCommand { get; set; }
public MainWindowViewModel()
{
if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
{
return;
}
using (var sr = new StreamReader("Example.html"))
{
CurrentHtml = sr.ReadToEnd();
}
LoadCommands();
CurrentDocumentPath = "Untitled.md";
}
private void LoadCommands()
{
SaveDocumentCommand = new RelayCommand(SaveDocument, CanSaveDocument);
}
public void SaveDocument(object obj)
{
using (var sr = new StreamReader("Example.html"))
{
CurrentHtml = sr.ReadToEnd();
}
}
public bool CanSaveDocument(object obj)
{
return true;
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using ProjectMarkdown.Annotations;
namespace ProjectMarkdown.ViewModels
{
public class MainWindowViewModel : INotifyPropertyChanged
{
private string _currentDocumentPath;
public string CurrentDocumentPath
{
get { return _currentDocumentPath; }
set
{
if (value == _currentDocumentPath) return;
_currentDocumentPath = value;
OnPropertyChanged(nameof(CurrentDocumentPath));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public MainWindowViewModel()
{
if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
{
return;
}
CurrentDocumentPath = "Untitled.md";
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
| mit | C# |
a0d0255b0fd90d7eba06af5d5e26a03a3390deae | Revert "[LinkWith] Renamed NeedsCpp to IsCxx" | jorik041/maccore,mono/maccore,cwensley/maccore | src/ObjCRuntime/LinkWithAttribute.cs | src/ObjCRuntime/LinkWithAttribute.cs | //
// Authors: Jeffrey Stedfast
//
// Copyright 2011 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
namespace MonoMac.ObjCRuntime {
[Flags]
public enum LinkTarget {
Simulator = 1,
ArmV6 = 2,
ArmV7 = 4,
Thumb = 8,
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true)]
public class LinkWithAttribute : Attribute {
public LinkWithAttribute (string libraryName, LinkTarget target, string linkerFlags)
{
LibraryName = libraryName;
LinkerFlags = linkerFlags;
LinkTarget = target;
}
public LinkWithAttribute (string libraryName, LinkTarget target)
{
LibraryName = libraryName;
LinkTarget = target;
}
public LinkWithAttribute (string libraryName)
{
LibraryName = libraryName;
}
public bool ForceLoad {
get; set;
}
public string LibraryName {
get; private set;
}
public string LinkerFlags {
get; set;
}
public LinkTarget LinkTarget {
get; set;
}
public bool NeedsGccExceptionHandling {
get; set;
}
public bool NeedsCpp {
get; set;
}
}
}
| //
// Authors: Jeffrey Stedfast
//
// Copyright 2011 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
namespace MonoMac.ObjCRuntime {
[Flags]
public enum LinkTarget {
Simulator = 1,
ArmV6 = 2,
ArmV7 = 4,
Thumb = 8,
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true)]
public class LinkWithAttribute : Attribute {
public LinkWithAttribute (string libraryName, LinkTarget target, string linkerFlags)
{
LibraryName = libraryName;
LinkerFlags = linkerFlags;
LinkTarget = target;
}
public LinkWithAttribute (string libraryName, LinkTarget target)
{
LibraryName = libraryName;
LinkTarget = target;
}
public LinkWithAttribute (string libraryName)
{
LibraryName = libraryName;
}
public bool ForceLoad {
get; set;
}
public string LibraryName {
get; private set;
}
public string LinkerFlags {
get; set;
}
public LinkTarget LinkTarget {
get; set;
}
public bool NeedsGccExceptionHandling {
get; set;
}
public bool IsCxx {
get; set;
}
}
}
| apache-2.0 | C# |
0ea57acb58a3ef5e25433b087e345382f2805a1c | Update SwaggerToCSharpClientGeneratorSettings.cs | quails4Eva/NSwag,NSwag/NSwag,NSwag/NSwag,quails4Eva/NSwag,NSwag/NSwag,RSuter/NSwag,quails4Eva/NSwag,NSwag/NSwag,RSuter/NSwag,RSuter/NSwag,quails4Eva/NSwag,RSuter/NSwag,RSuter/NSwag | src/NSwag.CodeGeneration.CSharp/SwaggerToCSharpClientGeneratorSettings.cs | src/NSwag.CodeGeneration.CSharp/SwaggerToCSharpClientGeneratorSettings.cs | //-----------------------------------------------------------------------
// <copyright file="SwaggerToCSharpClientGeneratorSettings.cs" company="NSwag">
// Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/NSwag/NSwag/blob/master/LICENSE.md</license>
// <author>Rico Suter, mail@rsuter.com</author>
//-----------------------------------------------------------------------
namespace NSwag.CodeGeneration.CSharp
{
/// <summary>Settings for the <see cref="SwaggerToCSharpClientGenerator"/>.</summary>
public class SwaggerToCSharpClientGeneratorSettings : SwaggerToCSharpGeneratorSettings
{
/// <summary>Initializes a new instance of the <see cref="SwaggerToCSharpClientGeneratorSettings"/> class.</summary>
public SwaggerToCSharpClientGeneratorSettings()
{
ClassName = "{controller}Client";
GenerateExceptionClasses = true;
ExceptionClass = "SwaggerException";
GenerateResponseClasses = true;
ResponseClass = "SwaggerResponse";
}
/// <summary>Gets or sets the full name of the base class.</summary>
public string ClientBaseClass { get; set; }
/// <summary>Gets or sets the full name of the configuration class (<see cref="ClientBaseClass"/> must be set).</summary>
public string ConfigurationClass { get; set; }
/// <summary>Gets or sets a value indicating whether to generate exception classes (default: true).</summary>
public bool GenerateExceptionClasses { get; set; }
/// <summary>Gets or sets the name of the exception class (supports the '{controller}' placeholder, default 'SwaggerException').</summary>
public string ExceptionClass { get; set; }
/// <summary>Gets or sets a value indicating whether to wrap success responses to allow full response access (experimental).</summary>
public bool WrapSuccessResponses { get; set; }
/// <summary>Gets or sets a value indicating whether to generate the response classes (only needed when WrapSuccessResponses == true, default: true).</summary>
public bool GenerateResponseClasses { get; set; }
/// <summary>Gets or sets the name of the response class (supports the '{controller}' placeholder, default 'SwaggerResponse').</summary>
public string ResponseClass { get; set; }
/// <summary>Gets or sets a value indicating whether an HttpClient instance is injected into the client.</summary>
public bool InjectHttpClient { get; set; }
/// <summary>Gets or sets a value indicating whether to call CreateHttpClientAsync on the base class to create a new HttpClient instance (cannot be used when the HttpClient is injected).</summary>
public bool UseHttpClientCreationMethod { get; set; }
/// <summary>Gets or sets a value indicating whether to call CreateHttpRequestMessageAsync on the base class to create a new HttpRequestMethod.</summary>
public bool UseHttpRequestMessageCreationMethod { get; set; }
}
}
| //-----------------------------------------------------------------------
// <copyright file="SwaggerToCSharpClientGeneratorSettings.cs" company="NSwag">
// Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/NSwag/NSwag/blob/master/LICENSE.md</license>
// <author>Rico Suter, mail@rsuter.com</author>
//-----------------------------------------------------------------------
namespace NSwag.CodeGeneration.CSharp
{
/// <summary>Settings for the <see cref="SwaggerToCSharpClientGenerator"/>.</summary>
public class SwaggerToCSharpClientGeneratorSettings : SwaggerToCSharpGeneratorSettings
{
/// <summary>Initializes a new instance of the <see cref="SwaggerToCSharpClientGeneratorSettings"/> class.</summary>
public SwaggerToCSharpClientGeneratorSettings()
{
ClassName = "{controller}Client";
GenerateExceptionClasses = true;
ExceptionClass = "SwaggerException";
GenerateResponseClasses = true;
ResponseClass = "SwaggerResponse";
}
/// <summary>Gets or sets the full name of the base class.</summary>
public string ClientBaseClass { get; set; }
/// <summary>Gets or sets the full name of the configuration class (<see cref="ClientBaseClass"/> must be set).</summary>
public string ConfigurationClass { get; set; }
/// <summary>Gets or sets a value indicating whether to generate exception classes (default: true).</summary>
public bool GenerateExceptionClasses { get; set; }
/// <summary>Gets or sets the name of the exception class (supports the '{controller}' placeholder).</summary>
public string ExceptionClass { get; set; }
/// <summary>Gets or sets a value indicating whether to wrap success responses to allow full response access (experimental).</summary>
public bool WrapSuccessResponses { get; set; }
/// <summary>Gets or sets a value indicating whether to generate the response classes (only needed when WrapSuccessResponses == true, default: true).</summary>
public bool GenerateResponseClasses { get; set; }
/// <summary>Gets or sets the name of the response class (supports the '{controller}' placeholder).</summary>
public string ResponseClass { get; set; }
/// <summary>Gets or sets a value indicating whether an HttpClient instance is injected into the client.</summary>
public bool InjectHttpClient { get; set; }
/// <summary>Gets or sets a value indicating whether to call CreateHttpClientAsync on the base class to create a new HttpClient instance (cannot be used when the HttpClient is injected).</summary>
public bool UseHttpClientCreationMethod { get; set; }
/// <summary>Gets or sets a value indicating whether to call CreateHttpRequestMessageAsync on the base class to create a new HttpRequestMethod.</summary>
public bool UseHttpRequestMessageCreationMethod { get; set; }
}
}
| mit | C# |
09cc3f89ed5cd4ba67cf7a527c76c27bf6a3825a | Make sure the decimal field value converter can handle double values when converting | bjarnef/Umbraco-CMS,tcmorris/Umbraco-CMS,leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,NikRimington/Umbraco-CMS,abryukhov/Umbraco-CMS,marcemarc/Umbraco-CMS,hfloyd/Umbraco-CMS,robertjf/Umbraco-CMS,bjarnef/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,bjarnef/Umbraco-CMS,hfloyd/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,rasmuseeg/Umbraco-CMS,marcemarc/Umbraco-CMS,NikRimington/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,KevinJump/Umbraco-CMS,madsoulswe/Umbraco-CMS,leekelleher/Umbraco-CMS,abryukhov/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,mattbrailsford/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,umbraco/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abjerner/Umbraco-CMS,abjerner/Umbraco-CMS,rasmuseeg/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,leekelleher/Umbraco-CMS,robertjf/Umbraco-CMS,madsoulswe/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,rasmuseeg/Umbraco-CMS,tcmorris/Umbraco-CMS,mattbrailsford/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,madsoulswe/Umbraco-CMS,NikRimington/Umbraco-CMS,abjerner/Umbraco-CMS,hfloyd/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,bjarnef/Umbraco-CMS,tcmorris/Umbraco-CMS,leekelleher/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS | src/Umbraco.Core/PropertyEditors/ValueConverters/DecimalValueConverter.cs | src/Umbraco.Core/PropertyEditors/ValueConverters/DecimalValueConverter.cs | using System;
using System.Globalization;
using Umbraco.Core.Models.PublishedContent;
namespace Umbraco.Core.PropertyEditors.ValueConverters
{
[DefaultPropertyValueConverter]
public class DecimalValueConverter : PropertyValueConverterBase
{
public override bool IsConverter(PublishedPropertyType propertyType)
=> Constants.PropertyEditors.Aliases.Decimal.Equals(propertyType.EditorAlias);
public override Type GetPropertyValueType(PublishedPropertyType propertyType)
=> typeof (decimal);
public override PropertyCacheLevel GetPropertyCacheLevel(PublishedPropertyType propertyType)
=> PropertyCacheLevel.Element;
public override object ConvertSourceToIntermediate(IPublishedElement owner, PublishedPropertyType propertyType, object source, bool preview)
{
if (source == null)
{
return 0M;
}
// is it already a decimal?
if(source is decimal)
{
return source;
}
// is it a double?
if(source is double sourceDouble)
{
return Convert.ToDecimal(sourceDouble);
}
// is it a string?
if (source is string sourceString)
{
return decimal.TryParse(sourceString, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out decimal d) ? d : 0M;
}
// couldn't convert the source value - default to zero
return 0M;
}
}
}
| using System;
using System.Globalization;
using Umbraco.Core.Models.PublishedContent;
namespace Umbraco.Core.PropertyEditors.ValueConverters
{
[DefaultPropertyValueConverter]
public class DecimalValueConverter : PropertyValueConverterBase
{
public override bool IsConverter(PublishedPropertyType propertyType)
=> Constants.PropertyEditors.Aliases.Decimal.Equals(propertyType.EditorAlias);
public override Type GetPropertyValueType(PublishedPropertyType propertyType)
=> typeof (decimal);
public override PropertyCacheLevel GetPropertyCacheLevel(PublishedPropertyType propertyType)
=> PropertyCacheLevel.Element;
public override object ConvertSourceToIntermediate(IPublishedElement owner, PublishedPropertyType propertyType, object source, bool preview)
{
if (source == null) return 0M;
// in XML a decimal is a string
if (source is string sourceString)
{
return decimal.TryParse(sourceString, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out decimal d) ? d : 0M;
}
// in the database an a decimal is an a decimal
// default value is zero
return source is decimal ? source : 0M;
}
}
}
| mit | C# |
74dc2b4a1acde8ebf66faac5b7f4657a8c3a4b5e | Use nameof and remove unneeded namespace imports | fgreinacher/corefx,parjong/corefx,jlin177/corefx,rubo/corefx,MaggieTsang/corefx,Petermarcu/corefx,weltkante/corefx,yizhang82/corefx,dotnet-bot/corefx,mmitche/corefx,YoupHulsebos/corefx,weltkante/corefx,tijoytom/corefx,wtgodbe/corefx,nbarbettini/corefx,marksmeltzer/corefx,krk/corefx,ericstj/corefx,gkhanna79/corefx,shimingsg/corefx,elijah6/corefx,lggomez/corefx,stone-li/corefx,jlin177/corefx,fgreinacher/corefx,dhoehna/corefx,shimingsg/corefx,dhoehna/corefx,Petermarcu/corefx,Jiayili1/corefx,ravimeda/corefx,jlin177/corefx,JosephTremoulet/corefx,axelheer/corefx,ravimeda/corefx,Ermiar/corefx,ericstj/corefx,zhenlan/corefx,tijoytom/corefx,shimingsg/corefx,rjxby/corefx,nbarbettini/corefx,YoupHulsebos/corefx,rahku/corefx,fgreinacher/corefx,alexperovich/corefx,nbarbettini/corefx,krytarowski/corefx,billwert/corefx,marksmeltzer/corefx,wtgodbe/corefx,wtgodbe/corefx,tijoytom/corefx,mazong1123/corefx,nchikanov/corefx,zhenlan/corefx,Ermiar/corefx,DnlHarvey/corefx,cydhaselton/corefx,krk/corefx,MaggieTsang/corefx,JosephTremoulet/corefx,richlander/corefx,krytarowski/corefx,parjong/corefx,stephenmichaelf/corefx,twsouthwick/corefx,ericstj/corefx,mmitche/corefx,Ermiar/corefx,stone-li/corefx,stephenmichaelf/corefx,Jiayili1/corefx,marksmeltzer/corefx,ericstj/corefx,krk/corefx,stone-li/corefx,cydhaselton/corefx,billwert/corefx,seanshpark/corefx,rjxby/corefx,twsouthwick/corefx,rahku/corefx,weltkante/corefx,marksmeltzer/corefx,ravimeda/corefx,yizhang82/corefx,DnlHarvey/corefx,ptoonen/corefx,rubo/corefx,wtgodbe/corefx,elijah6/corefx,weltkante/corefx,ptoonen/corefx,stone-li/corefx,nchikanov/corefx,krytarowski/corefx,krytarowski/corefx,lggomez/corefx,dhoehna/corefx,gkhanna79/corefx,JosephTremoulet/corefx,jlin177/corefx,mazong1123/corefx,DnlHarvey/corefx,Jiayili1/corefx,dotnet-bot/corefx,ViktorHofer/corefx,elijah6/corefx,zhenlan/corefx,zhenlan/corefx,richlander/corefx,YoupHulsebos/corefx,twsouthwick/corefx,billwert/corefx,gkhanna79/corefx,alexperovich/corefx,yizhang82/corefx,richlander/corefx,mazong1123/corefx,seanshpark/corefx,JosephTremoulet/corefx,DnlHarvey/corefx,twsouthwick/corefx,the-dwyer/corefx,billwert/corefx,krk/corefx,BrennanConroy/corefx,JosephTremoulet/corefx,seanshpark/corefx,alexperovich/corefx,the-dwyer/corefx,YoupHulsebos/corefx,mazong1123/corefx,axelheer/corefx,mmitche/corefx,dotnet-bot/corefx,Jiayili1/corefx,ViktorHofer/corefx,the-dwyer/corefx,zhenlan/corefx,dhoehna/corefx,alexperovich/corefx,BrennanConroy/corefx,rahku/corefx,mmitche/corefx,rubo/corefx,lggomez/corefx,nbarbettini/corefx,alexperovich/corefx,mmitche/corefx,fgreinacher/corefx,mazong1123/corefx,seanshpark/corefx,mazong1123/corefx,elijah6/corefx,shimingsg/corefx,krytarowski/corefx,tijoytom/corefx,the-dwyer/corefx,elijah6/corefx,tijoytom/corefx,nchikanov/corefx,ravimeda/corefx,nbarbettini/corefx,lggomez/corefx,JosephTremoulet/corefx,tijoytom/corefx,richlander/corefx,MaggieTsang/corefx,gkhanna79/corefx,parjong/corefx,dhoehna/corefx,axelheer/corefx,DnlHarvey/corefx,rjxby/corefx,krk/corefx,jlin177/corefx,shimingsg/corefx,dotnet-bot/corefx,ViktorHofer/corefx,stone-li/corefx,parjong/corefx,weltkante/corefx,marksmeltzer/corefx,ravimeda/corefx,Petermarcu/corefx,richlander/corefx,marksmeltzer/corefx,shimingsg/corefx,weltkante/corefx,lggomez/corefx,nbarbettini/corefx,the-dwyer/corefx,Ermiar/corefx,lggomez/corefx,YoupHulsebos/corefx,rubo/corefx,DnlHarvey/corefx,stephenmichaelf/corefx,billwert/corefx,parjong/corefx,zhenlan/corefx,parjong/corefx,tijoytom/corefx,gkhanna79/corefx,ericstj/corefx,twsouthwick/corefx,ravimeda/corefx,seanshpark/corefx,cydhaselton/corefx,rahku/corefx,zhenlan/corefx,rahku/corefx,cydhaselton/corefx,Petermarcu/corefx,alexperovich/corefx,rubo/corefx,cydhaselton/corefx,nchikanov/corefx,Petermarcu/corefx,billwert/corefx,ViktorHofer/corefx,krytarowski/corefx,dotnet-bot/corefx,Ermiar/corefx,dotnet-bot/corefx,ravimeda/corefx,dhoehna/corefx,rjxby/corefx,seanshpark/corefx,stone-li/corefx,jlin177/corefx,dotnet-bot/corefx,wtgodbe/corefx,stone-li/corefx,mazong1123/corefx,cydhaselton/corefx,shimingsg/corefx,dhoehna/corefx,twsouthwick/corefx,jlin177/corefx,yizhang82/corefx,richlander/corefx,krk/corefx,MaggieTsang/corefx,rjxby/corefx,gkhanna79/corefx,ptoonen/corefx,stephenmichaelf/corefx,DnlHarvey/corefx,axelheer/corefx,krytarowski/corefx,MaggieTsang/corefx,Ermiar/corefx,ViktorHofer/corefx,parjong/corefx,krk/corefx,YoupHulsebos/corefx,lggomez/corefx,stephenmichaelf/corefx,JosephTremoulet/corefx,Jiayili1/corefx,richlander/corefx,ViktorHofer/corefx,elijah6/corefx,marksmeltzer/corefx,axelheer/corefx,BrennanConroy/corefx,mmitche/corefx,elijah6/corefx,rjxby/corefx,axelheer/corefx,wtgodbe/corefx,ptoonen/corefx,Jiayili1/corefx,ericstj/corefx,YoupHulsebos/corefx,Jiayili1/corefx,the-dwyer/corefx,mmitche/corefx,weltkante/corefx,ptoonen/corefx,rahku/corefx,yizhang82/corefx,ptoonen/corefx,Petermarcu/corefx,cydhaselton/corefx,stephenmichaelf/corefx,ptoonen/corefx,yizhang82/corefx,seanshpark/corefx,MaggieTsang/corefx,MaggieTsang/corefx,the-dwyer/corefx,rjxby/corefx,Ermiar/corefx,twsouthwick/corefx,nchikanov/corefx,stephenmichaelf/corefx,billwert/corefx,ericstj/corefx,yizhang82/corefx,wtgodbe/corefx,rahku/corefx,ViktorHofer/corefx,nbarbettini/corefx,nchikanov/corefx,gkhanna79/corefx,Petermarcu/corefx,nchikanov/corefx,alexperovich/corefx | src/System.Diagnostics.TraceSource/src/System/Diagnostics/SwitchLevelAttribute.cs | src/System.Diagnostics.TraceSource/src/System/Diagnostics/SwitchLevelAttribute.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Diagnostics
{
[AttributeUsage(AttributeTargets.Class)]
public sealed class SwitchLevelAttribute : Attribute
{
private Type _type;
public SwitchLevelAttribute(Type switchLevelType)
{
SwitchLevelType = switchLevelType;
}
public Type SwitchLevelType
{
get { return _type; }
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
_type = value;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Collections;
namespace System.Diagnostics
{
[AttributeUsage(AttributeTargets.Class)]
public sealed class SwitchLevelAttribute : Attribute
{
private Type _type;
public SwitchLevelAttribute(Type switchLevelType)
{
SwitchLevelType = switchLevelType;
}
public Type SwitchLevelType
{
get { return _type; }
set
{
if (value == null)
throw new ArgumentNullException("value");
_type = value;
}
}
}
}
| mit | C# |
a4b69a30492b4ced7dc22b41609e900f5a246868 | add auto number for payment. | robertzml/Phoebe | Phoebe.Core/BL/PaymentBusiness.cs | Phoebe.Core/BL/PaymentBusiness.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace Phoebe.Core.BL
{
using SqlSugar;
using Phoebe.Base.Framework;
using Phoebe.Core.Entity;
using Phoebe.Core.Utility;
/// <summary>
/// 缴费业务类
/// </summary>
public class PaymentBusiness : AbstractBusiness<Payment, string>, IBaseBL<Payment, string>
{
#region Method
public override (bool success, string errorMessage, Payment t) Create(Payment entity, SqlSugarClient db = null)
{
if (db == null)
db = GetInstance();
SequenceRecordBusiness recordBusiness = new SequenceRecordBusiness();
entity.Id = Guid.NewGuid().ToString();
entity.TicketNumber = recordBusiness.GetNextSequence(db, "Payment", entity.PaidTime);
entity.CreateTime = DateTime.Now;
entity.Status = 0;
var t = db.Insertable(entity).ExecuteReturnEntity();
return (true, "", t);
}
#endregion //Method
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace Phoebe.Core.BL
{
using SqlSugar;
using Phoebe.Base.Framework;
using Phoebe.Core.Entity;
using Phoebe.Core.Utility;
/// <summary>
/// 缴费业务类
/// </summary>
public class PaymentBusiness : AbstractBusiness<Payment, string>, IBaseBL<Payment, string>
{
#region Method
public override (bool success, string errorMessage, Payment t) Create(Payment entity, SqlSugarClient db = null)
{
if (db == null)
db = GetInstance();
entity.Id = Guid.NewGuid().ToString();
entity.CreateTime = DateTime.Now;
entity.Status = 0;
var t = db.Insertable(entity).ExecuteReturnEntity();
return (true, "", t);
}
#endregion //Method
}
}
| mit | C# |
5cd4e025fa2d42ea5c65950301e5a6215228488b | bump the version number for latest changes | Notulp/Pluton,Notulp/Pluton | Pluton/Properties/AssemblyInfo.cs | Pluton/Properties/AssemblyInfo.cs | using System.Reflection;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Pluton")]
[assembly: AssemblyDescription("A server mod for the active branch of the survival sandbox game Rust")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Pluton")]
[assembly: AssemblyCopyright("Pluton Team")]
[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.2.9.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Pluton")]
[assembly: AssemblyDescription("A server mod for the active branch of the survival sandbox game Rust")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Pluton")]
[assembly: AssemblyCopyright("Pluton Team")]
[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.2.6.*")]
// 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# |
ac33cbd31741fbebe972852dea397d318aec17a6 | Clean up code. | enarod/enarod-web-api,enarod/enarod-web-api,enarod/enarod-web-api | Infopulse.EDemocracy.Data/Repositories/UserDetailRepository.cs | Infopulse.EDemocracy.Data/Repositories/UserDetailRepository.cs | using Infopulse.EDemocracy.Data.Interfaces;
using Infopulse.EDemocracy.Model;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
namespace Infopulse.EDemocracy.Data.Repositories
{
public class UserDetailRepository : IUserDetailRepository
{
public int GetUserId(string userEmail)
{
using (var db = new EDEntities())
{
var userID = db.Database.SqlQuery<int>(
"sp_User_GetIdByEmail @UserEmail",
new SqlParameter()
{
ParameterName = "UserEmail",
DbType = DbType.String,
Value = userEmail,
Direction = ParameterDirection.Input
});
return userID.SingleOrDefault();
}
}
public UserDetail Update(UserDetail user)
{
using (var db = new EDEntities())
{
var userDetailFromDb = db.UserDetails.SingleOrDefault(ud => ud.UserID == user.UserID);
user.ID = userDetailFromDb.ID;
db.Entry(userDetailFromDb).CurrentValues.SetValues(user);
db.SaveChanges();
return db.UserDetails.SingleOrDefault(ud => ud.ID == user.ID);
}
}
}
} | using Infopulse.EDemocracy.Data.Interfaces;
using Infopulse.EDemocracy.Model;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
namespace Infopulse.EDemocracy.Data.Repositories
{
public class UserDetailRepository : IUserDetailRepository
{
public int GetUserId(string userEmail)
{
using (var db = new EDEntities())
{
var userID = db.Database.SqlQuery<int>(
"sp_User_GetIdByEmail @UserEmail",
new SqlParameter()
{
ParameterName = "UserEmail",
DbType = DbType.String,
Value = userEmail,
Direction = ParameterDirection.Input
});
return userID.SingleOrDefault();
}
}
public UserDetail Update(UserDetail user)
{
using (var db = new EDEntities())
{
var userDetailFromDb = db.UserDetails.SingleOrDefault(ud => ud.UserID == user.UserID);
user.ID = userDetailFromDb.ID;
db.Entry(userDetailFromDb).CurrentValues.SetValues(user);
////db.UserDetails.Attach(user);
//var entry = db.Entry(user);
//entry.State = EntityState.Modified;
db.SaveChanges();
return db.UserDetails.SingleOrDefault(ud => ud.ID == user.ID);
}
}
}
} | cc0-1.0 | C# |
17dc787956bf1d2943b25667a37f04acfee3b43c | remove some c.wls | Gankov/gtk-sharp,antoniusriha/gtk-sharp,akrisiun/gtk-sharp,orion75/gtk-sharp,sillsdev/gtk-sharp,Gankov/gtk-sharp,orion75/gtk-sharp,Gankov/gtk-sharp,openmedicus/gtk-sharp,Gankov/gtk-sharp,openmedicus/gtk-sharp,openmedicus/gtk-sharp,antoniusriha/gtk-sharp,orion75/gtk-sharp,Gankov/gtk-sharp,openmedicus/gtk-sharp,orion75/gtk-sharp,openmedicus/gtk-sharp,akrisiun/gtk-sharp,antoniusriha/gtk-sharp,sillsdev/gtk-sharp,sillsdev/gtk-sharp,Gankov/gtk-sharp,openmedicus/gtk-sharp,antoniusriha/gtk-sharp,akrisiun/gtk-sharp,sillsdev/gtk-sharp,orion75/gtk-sharp,sillsdev/gtk-sharp,akrisiun/gtk-sharp,akrisiun/gtk-sharp,antoniusriha/gtk-sharp,openmedicus/gtk-sharp | glib/ManagedValue.cs | glib/ManagedValue.cs | // GLib.ManagedValue.cs : Managed types boxer
//
// Author: Rachel Hestilow <hestilow@ximian.com>
//
// Copyright (c) 2002 Rachel Hestilow
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Collections;
using System.Runtime.InteropServices;
using GLib;
internal class ManagedValue {
[CDeclCallback]
delegate IntPtr CopyFunc (IntPtr gch);
[CDeclCallback]
delegate void FreeFunc (IntPtr gch);
static CopyFunc copy;
static FreeFunc free;
static GType boxed_type = GType.Invalid;
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_boxed_type_register_static (IntPtr typename, CopyFunc copy_func, FreeFunc free_func);
public static GType GType {
get {
if (boxed_type == GType.Invalid) {
copy = new CopyFunc (Copy);
free = new FreeFunc (Free);
IntPtr name = Marshaller.StringToPtrGStrdup ("GtkSharpValue");
boxed_type = new GLib.GType (g_boxed_type_register_static (name, copy, free));
Marshaller.Free (name);
}
return boxed_type;
}
}
static IntPtr Copy (IntPtr ptr)
{
GCHandle gch = (GCHandle) ptr;
return (IntPtr) GCHandle.Alloc (gch.Target);
}
static void Free (IntPtr ptr)
{
GCHandle gch = (GCHandle) ptr;
gch.Free ();
}
public static IntPtr WrapObject (object obj)
{
return (IntPtr) GCHandle.Alloc (obj);
}
public static object ObjectForWrapper (IntPtr ptr)
{
return ((GCHandle)ptr).Target;
}
}
}
| // GLib.ManagedValue.cs : Managed types boxer
//
// Author: Rachel Hestilow <hestilow@ximian.com>
//
// Copyright (c) 2002 Rachel Hestilow
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Collections;
using System.Runtime.InteropServices;
using GLib;
internal class ManagedValue {
[CDeclCallback]
delegate IntPtr CopyFunc (IntPtr gch);
[CDeclCallback]
delegate void FreeFunc (IntPtr gch);
static CopyFunc copy;
static FreeFunc free;
static GType boxed_type = GType.Invalid;
[DllImport("libgobject-2.0-0.dll")]
static extern IntPtr g_boxed_type_register_static (IntPtr typename, CopyFunc copy_func, FreeFunc free_func);
public static GType GType {
get {
if (boxed_type == GType.Invalid) {
copy = new CopyFunc (Copy);
free = new FreeFunc (Free);
IntPtr name = Marshaller.StringToPtrGStrdup ("GtkSharpValue");
boxed_type = new GLib.GType (g_boxed_type_register_static (name, copy, free));
Marshaller.Free (name);
}
return boxed_type;
}
}
static IntPtr Copy (IntPtr ptr)
{
Console.WriteLine ("Copying ManagedGValue: " + ptr);
GCHandle gch = (GCHandle) ptr;
return (IntPtr) GCHandle.Alloc (gch.Target);
}
static void Free (IntPtr ptr)
{
Console.WriteLine ("Freeing ManagedGValue: " + ptr);
GCHandle gch = (GCHandle) ptr;
gch.Free ();
}
public static IntPtr WrapObject (object obj)
{
Console.WriteLine ("Wrapping Object in ManagedGValue: " + obj);
return (IntPtr) GCHandle.Alloc (obj);
}
public static object ObjectForWrapper (IntPtr ptr)
{
Console.WriteLine ("Getting object of ManagedGValue: " + ptr);
return ((GCHandle)ptr).Target;
}
}
}
| lgpl-2.1 | C# |
34ae0dfb5afa9356fe85f1a831624a5fa56169f3 | Implement humanize test localization for current culture. | oceanho/aspnetboilerplate,fengyeju/aspnetboilerplate,virtualcca/aspnetboilerplate,berdankoca/aspnetboilerplate,AlexGeller/aspnetboilerplate,ilyhacker/aspnetboilerplate,fengyeju/aspnetboilerplate,yuzukwok/aspnetboilerplate,verdentk/aspnetboilerplate,beratcarsi/aspnetboilerplate,andmattia/aspnetboilerplate,jaq316/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,verdentk/aspnetboilerplate,carldai0106/aspnetboilerplate,virtualcca/aspnetboilerplate,jaq316/aspnetboilerplate,ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,oceanho/aspnetboilerplate,yuzukwok/aspnetboilerplate,ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,yuzukwok/aspnetboilerplate,zquans/aspnetboilerplate,luchaoshuai/aspnetboilerplate,ryancyq/aspnetboilerplate,ilyhacker/aspnetboilerplate,ShiningRush/aspnetboilerplate,Nongzhsh/aspnetboilerplate,andmattia/aspnetboilerplate,AlexGeller/aspnetboilerplate,virtualcca/aspnetboilerplate,verdentk/aspnetboilerplate,berdankoca/aspnetboilerplate,carldai0106/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,luchaoshuai/aspnetboilerplate,zquans/aspnetboilerplate,carldai0106/aspnetboilerplate,beratcarsi/aspnetboilerplate,ryancyq/aspnetboilerplate,ShiningRush/aspnetboilerplate,andmattia/aspnetboilerplate,zclmoon/aspnetboilerplate,carldai0106/aspnetboilerplate,zclmoon/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,zquans/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,ilyhacker/aspnetboilerplate,AlexGeller/aspnetboilerplate,beratcarsi/aspnetboilerplate,ShiningRush/aspnetboilerplate,jaq316/aspnetboilerplate,zclmoon/aspnetboilerplate,Nongzhsh/aspnetboilerplate,berdankoca/aspnetboilerplate,oceanho/aspnetboilerplate,Nongzhsh/aspnetboilerplate,fengyeju/aspnetboilerplate | src/Abp/Localization/LocalizationSourceHelper.cs | src/Abp/Localization/LocalizationSourceHelper.cs | using System.Globalization;
using Abp.Configuration.Startup;
using Abp.Extensions;
using Abp.Logging;
namespace Abp.Localization
{
public static class LocalizationSourceHelper
{
public static string ReturnGivenNameOrThrowException(ILocalizationConfiguration configuration, string sourceName, string name, CultureInfo culture)
{
var exceptionMessage = $"Can not find '{name}' in localization source '{sourceName}'!";
if (!configuration.ReturnGivenTextIfNotFound)
{
throw new AbpException(exceptionMessage);
}
LogHelper.Logger.Warn(exceptionMessage);
string notFoundText;
#if NET46
notFoundText = configuration.HumanizeTextIfNotFound
? name.ToSentenceCase(culture)
: name;
#else
using (CultureInfoHelper.Use(culture))
{
notFoundText = configuration.HumanizeTextIfNotFound
? name.ToSentenceCase()
: name;
}
#endif
return configuration.WrapGivenTextIfNotFound
? $"[{notFoundText}]"
: notFoundText;
}
}
}
| using System.Globalization;
using Abp.Configuration.Startup;
using Abp.Extensions;
using Abp.Logging;
namespace Abp.Localization
{
public static class LocalizationSourceHelper
{
public static string ReturnGivenNameOrThrowException(ILocalizationConfiguration configuration, string sourceName, string name, CultureInfo culture)
{
var exceptionMessage = $"Can not find '{name}' in localization source '{sourceName}'!";
if (!configuration.ReturnGivenTextIfNotFound)
{
throw new AbpException(exceptionMessage);
}
LogHelper.Logger.Warn(exceptionMessage);
#if NET46
var notFoundText = configuration.HumanizeTextIfNotFound
? name.ToSentenceCase(culture)
: name;
#else
var notFoundText = configuration.HumanizeTextIfNotFound
? name.ToSentenceCase() //TODO: Removed culture since it's not supported by netstandard
: name;
#endif
return configuration.WrapGivenTextIfNotFound
? $"[{notFoundText}]"
: notFoundText;
}
}
}
| mit | C# |
bee994cb165b41a50f3b023312679a89f564dc13 | Correct test project name. | sharpjs/PSql,sharpjs/PSql | PSql.Core/Properties/AssemblyInfo.cs | PSql.Core/Properties/AssemblyInfo.cs | /*
Copyright (C) 2019 Jeffrey Sharp
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
// Security
//
// All types and members are security-critical, except where
// being security-critical violates an inheritance rule.
// http://msdn.microsoft.com/en-us/library/dd233102.aspx
//
[assembly: SecurityRules(SecurityRuleSet.Level2)]
[assembly: InternalsVisibleTo("PSql.Core.Tests")]
// COM Compliance
[assembly: ComVisible(false)]
| /*
Copyright (C) 2019 Jeffrey Sharp
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
// Security
//
// All types and members are security-critical, except where
// being security-critical violates an inheritance rule.
// http://msdn.microsoft.com/en-us/library/dd233102.aspx
//
[assembly: SecurityRules(SecurityRuleSet.Level2)]
[assembly: InternalsVisibleTo("PSql.Tests")]
// COM Compliance
[assembly: ComVisible(false)]
| isc | C# |
34fa7f578cb203920e8f3a743390d0a516a8d8d3 | update jwt example | plivo/plivo-dotnet,plivo/plivo-dotnet | examples/Jwt.cs | examples/Jwt.cs | using System;
using System.Collections.Generic;
using Plivo;
namespace Plivo
{
class MainClass
{
public static void Main(string[] args)
{
var token0 = new Plivo.AccessToken("MADADADADADADADADADA", "qwerty", "username")
.WithOutgoing(true)
.WithIncoming(false)
.WithValidFrom(DateTime.Parse("2020-03-22"))
.WithLifetime(TimeSpan.FromHours(2))
.WithUid("uuid");
Console.WriteLine(token0.ToJwt());
var token1 = new Plivo.AccessToken("MADADADADADADADADADA", "qwerty", "username")
.WithOutgoing(true)
.WithIncoming(false)
.WithValidFrom(DateTime.Parse("2020-03-22"))
.WithValidTill(DateTime.Parse("2020-03-23"))
.WithUid("uuid");
Console.WriteLine(token1.ToJwt());
var token2 = new Plivo.AccessToken("MADADADADADADADADADA", "qwerty", "username")
.WithOutgoing(true)
.WithIncoming(false)
.WithLifetime(TimeSpan.FromHours(2))
.WithValidTill(DateTime.Parse("2020-03-22"))
.WithUid("uuid");
Console.WriteLine(token2.ToJwt());
}
}
}
| using System;
using System.Collections.Generic;
using Plivo;
namespace Plivo
{
class MainClass
{
public static void Main(string[] args)
{
var token = new Plivo.AccessToken("MADADADADADADADADADA", "qwerty", "username")
.WithOutgoing(true)
.WithIncoming(false)
.WithLifetime(TimeSpan.FromHours(2))
.WithValidTill(DateTime.Parse("2020-04-24"))
.WithUid("uuid");
Console.WriteLine(token.ToJwt());
}
}
} | mit | C# |
b8d175459d01ff80fde8b482fb379344167b76d5 | Test commit | transsight/testproject,transsight/testproject | src/stress.samples/Program.cs | src/stress.samples/Program.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using stress.execution;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace stress.samples
{
internal class Program
{
private static void Main(string[] args)
{
CancellationTokenSource tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(20));
new ConcurrentDictionaryLoadTesting().SimpleLoad(tokenSource.Token);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using stress.execution;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace stress.samples
{
internal class Program
{
private static void Main(string[] args)
{
CancellationTokenSource tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(20));
new ConcurrentDictionaryLoadTesting().SimpleLoad(tokenSource.Token);
}
}
}
| mit | C# |
44cf47aeeda4d5fc6839c4b7165db54111e34d10 | Add some documentation to the async interfaces | matrostik/SQLitePCL.pretty,bordoley/SQLitePCL.pretty | SQLitePCL.pretty.Async/Interfaces.cs | SQLitePCL.pretty.Async/Interfaces.cs | /*
Copyright 2014 David Bordoley
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.Diagnostics.Contracts;
using System.Threading.Tasks;
namespace SQLitePCL.pretty
{
[ContractClass(typeof(IAsyncDatabaseConnectionContract))]
public interface IAsyncDatabaseConnection : IDisposable
{
/// <summary>
/// A hot <a cref="IObservable"/> of this connection's SQLite trace events.
/// <see href="https://sqlite.org/c3ref/profile.html"/>
/// </summary>
IObservable<DatabaseTraceEventArgs> Trace { get; }
/// <summary>
/// A hot <a cref="IObservable"/> of this connection's SQLite profile events.
/// <see href="https://sqlite.org/c3ref/profile.html"/>
/// </summary>
IObservable<DatabaseProfileEventArgs> Profile { get; }
/// <summary>
/// A hot <a cref="IObservable"/> of this connection's SQLite update events.
/// <see href="https://sqlite.org/c3ref/update_hook.html"/>
/// </summary>
IObservable<DatabaseUpdateEventArgs> Update { get; }
/// <summary>
/// Shutdown the underlying operations queue used by the <see cref="IAsyncDatabaseConnection"/>
/// and prevents the queuing of additional database access requests. Requests to access the database
/// prior to the call to <see cref="DisposeAsync"/> are allowed to complete, after which underlying
/// <see cref="IDatabaseConnection"/> is disposed.
/// </summary>
/// <returns>
/// A task which completes once all previously queue operations are completed and the
/// underlying<see cref="IDatabaseConnection"/> is disposed.</returns>
Task DisposeAsync();
/// <summary>
/// Returns a cold IObservable which schedules the function f on the database operation queue each
/// time it is is subscribed to. The published values are generated by enumerating the IEnumerable returned by f.
/// </summary>
/// <param name="f">
/// A function that may synchronously use the provided IDatabaseConnection and returns
/// an IEnumerable of produced values that are published to the subscribed IObserver.
/// The returned IEnumerable may block. This allows the IEnumerable to provide the results of
/// enumerating a SQLite prepared statement for instance.
/// <note type="implement">
/// The IDatabaseConnection instance that f is called with is immutable. IDatabaseConnection events, setters and methods which
/// mutate the IDatabaseConnection throw <see cref="NotSupportedException"/>. The IDatabaseConnection may be used to prepare
/// statements and open database blobs, but these must not be captured or otherwise externally referenced unless their use is
/// scheduled on the connections's operation queue via future calls to <see cref="Use"/>.
/// </note>
/// </param>
/// <returns>A cold observable of the values produced by the function f.</returns>
IObservable<T> Use<T>(Func<IDatabaseConnection, IEnumerable<T>> f);
}
[ContractClass(typeof(IAsyncStatementContract))]
public interface IAsyncStatement : IDisposable
{
/// <summary>
/// Returns a cold IObservable which schedules the function f on the statement's database operation queue each
/// time it is is subscribed to. The published values are generated by enumerating the IEnumerable returned by f.
/// </summary>
/// <param name="f">
/// A function that may synchronously use the provided IStatement and returns
/// an IEnumerable of produced values that are published to the subscribed IObserver.
/// The returned IEnumerable may block. This allows the IEnumerable to provide the results of
/// enumerating the prepared statement for instance.
/// </param>
/// <returns>A cold observable of the values produced by the function f.</returns>
IObservable<T> Use<T>(Func<IStatement, IEnumerable<T>> f);
}
}
| /*
Copyright 2014 David Bordoley
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.Diagnostics.Contracts;
using System.Threading.Tasks;
namespace SQLitePCL.pretty
{
[ContractClass(typeof(IAsyncDatabaseConnectionContract))]
public interface IAsyncDatabaseConnection : IDisposable
{
IObservable<DatabaseTraceEventArgs> Trace { get; }
IObservable<DatabaseProfileEventArgs> Profile { get; }
IObservable<DatabaseUpdateEventArgs> Update { get; }
Task DisposeAsync();
IObservable<T> Use<T>(Func<IDatabaseConnection, IEnumerable<T>> f);
}
[ContractClass(typeof(IAsyncStatementContract))]
public interface IAsyncStatement : IDisposable
{
IObservable<T> Use<T>(Func<IStatement, IEnumerable<T>> f);
}
}
| apache-2.0 | C# |
49346a7863541f9a777cf60ddc170145e3b769bc | Update example | Intacct/intacct-sdk-net-examples | CreateCustomObjectExample/MyCustomObjectCreate.cs | CreateCustomObjectExample/MyCustomObjectCreate.cs | /**
* Copyright 2017 Intacct Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "LICENSE" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using Intacct.Sdk.Xml;
namespace CreateCustomObjectExample
{
class MyCustomObjectCreate : AbstractMyCustomObject
{
public MyCustomObjectCreate(string controlId = null) : base(controlId)
{
}
public override void WriteXml(ref IaXmlWriter xml)
{
xml.WriteStartElement("function");
xml.WriteAttribute("controlid", ControlId, true);
xml.WriteStartElement("create");
xml.WriteStartElement("test_object");
xml.WriteElement("name", Name, true);
xml.WriteElement("Description", Description, true);
xml.WriteEndElement(); //test_object
xml.WriteEndElement(); //create
xml.WriteEndElement(); //function
}
}
}
| /**
* Copyright 2017 Intacct Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "LICENSE" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using Intacct.Sdk.Xml;
namespace CreateCustomObjectExample
{
class MyCustomObjectCreate : AbstractMyCustomObject
{
public MyCustomObjectCreate(string controlId = null) : base(controlId)
{
}
public override void WriteXml(ref IaXmlWriter xml)
{
xml.WriteStartElement("function");
xml.WriteAttribute("controlid", ControlId, true);
xml.WriteStartElement("create");
xml.WriteStartElement("partner");
xml.WriteElement("name", Name, true);
xml.WriteElement("Description", Description, true);
xml.WriteEndElement(); //test_object
xml.WriteEndElement(); //create
xml.WriteEndElement(); //function
}
}
}
| apache-2.0 | C# |
1be0973640e8267c9e34c14d9ca1f722f63e6105 | create conditional approval from organization used wrong parameter | ucdavis/Purchasing,ucdavis/Purchasing,ucdavis/Purchasing | Purchasing.Web/Views/ConditionalApproval/ByOrg.cshtml | Purchasing.Web/Views/ConditionalApproval/ByOrg.cshtml | @model System.Linq.IQueryable<Purchasing.Core.Domain.ConditionalApproval>
@{
ViewBag.Title = "Conditional Approvals by Organization";
}
@section SubNav
{
<ul class="navigation">
<li>@Html.ActionLink("Back to Organization", "Details", "Organization", new { id = ViewBag.OrganizationId }, new { @class="button" })</li>
</ul>
}
<section class="display-form ui-corner-all">
<header class="ui-corner-top ui-widget-header">
</header>
<div class="section-contents">
<div class="col1"></div><div class="col2">@Html.ActionLink("Create Approval", "Create", "ConditionalApproval", new { orgId = ViewBag.OrganizationId }, new { @class = "button" })</div>
<table>
<thead>
<tr>
<th></th>
<th>Organization</th>
<th>Primary Approver</th>
<th>Secondary Approver</th>
<th>Question</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var ca in Model)
{
<tr>
<td><a href='@Url.Action("Edit", new { ca.Id })' class="ui-icon ui-icon-pencil" title="Edit approval"><img src='@Url.Image("edit.png")'></a></td>
<td>@ca.Organization.Name (@ca.Organization.Id)</td>
<td>@ca.PrimaryApprover.FullNameAndIdLastFirst</td>
<td>@(ca.SecondaryApprover == null ? "N/A" : ca.SecondaryApprover.FullNameAndIdLastFirst)</td>
<td>@ca.Question</td>
<td><a href='@Url.Action("Delete", new {ca.Id})' class="ui-icon ui-icon-trash" title="Delete approval"><img src='@Url.Image("delete.png")'></a></td>
</tr>
}
</tbody>
</table>
</div>
</section> | @model System.Linq.IQueryable<Purchasing.Core.Domain.ConditionalApproval>
@{
ViewBag.Title = "Conditional Approvals by Organization";
}
@section SubNav
{
<ul class="navigation">
<li>@Html.ActionLink("Back to Organization", "Details", "Organization", new { id = ViewBag.OrganizationId }, new { @class="button" })</li>
</ul>
}
<section class="display-form ui-corner-all">
<header class="ui-corner-top ui-widget-header">
</header>
<div class="section-contents">
<div class="col1"></div><div class="col2">@Html.ActionLink("Create Approval", "Create", "ConditionalApproval", new { id = ViewBag.OrganizationId }, new { @class = "button" })</div>
<table>
<thead>
<tr>
<th></th>
<th>Organization</th>
<th>Primary Approver</th>
<th>Secondary Approver</th>
<th>Question</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var ca in Model)
{
<tr>
<td><a href='@Url.Action("Edit", new { ca.Id })' class="ui-icon ui-icon-pencil" title="Edit approval"><img src='@Url.Image("edit.png")'></a></td>
<td>@ca.Organization.Name (@ca.Organization.Id)</td>
<td>@ca.PrimaryApprover.FullNameAndIdLastFirst</td>
<td>@(ca.SecondaryApprover == null ? "N/A" : ca.SecondaryApprover.FullNameAndIdLastFirst)</td>
<td>@ca.Question</td>
<td><a href='@Url.Action("Delete", new {ca.Id})' class="ui-icon ui-icon-trash" title="Delete approval"><img src='@Url.Image("delete.png")'></a></td>
</tr>
}
</tbody>
</table>
</div>
</section> | mit | C# |
7bd4ee2ec0674fb66f2d178648a44bde9841a26a | Include id and title on package version history items. | googol/NuGet.Lucene,themotleyfool/NuGet.Lucene,Stift/NuGet.Lucene | source/NuGet.Lucene.Web/Models/PackageVersionSummary.cs | source/NuGet.Lucene.Web/Models/PackageVersionSummary.cs | using System;
using AspNet.WebApi.HtmlMicrodataFormatter;
namespace NuGet.Lucene.Web.Models
{
public class PackageVersionSummary
{
private readonly string id;
private readonly string title;
private readonly StrictSemanticVersion version;
private readonly DateTimeOffset lastUpdated;
private readonly int versionDownloadCount;
private readonly Link link;
public string Id
{
get { return id; }
}
public string Title
{
get { return title; }
}
public StrictSemanticVersion Version
{
get { return version; }
}
public DateTimeOffset LastUpdated
{
get { return lastUpdated; }
}
public int VersionDownloadCount
{
get { return versionDownloadCount; }
}
public Link Link
{
get { return link; }
}
public PackageVersionSummary(LucenePackage package, Link link)
: this(package.Id, package.Title, package.Version, package.LastUpdated, package.VersionDownloadCount, link)
{
}
public PackageVersionSummary(string id, string title, StrictSemanticVersion version, DateTimeOffset lastUpdated, int versionDownloadCount, Link link)
{
this.id = id;
this.title = title;
this.version = version;
this.lastUpdated = lastUpdated;
this.versionDownloadCount = versionDownloadCount;
this.link = link;
}
}
} | using System;
using AspNet.WebApi.HtmlMicrodataFormatter;
namespace NuGet.Lucene.Web.Models
{
public class PackageVersionSummary
{
private readonly StrictSemanticVersion version;
private readonly DateTimeOffset lastUpdated;
private readonly int versionDownloadCount;
private readonly Link link;
public StrictSemanticVersion Version
{
get { return version; }
}
public DateTimeOffset LastUpdated
{
get { return lastUpdated; }
}
public int VersionDownloadCount
{
get { return versionDownloadCount; }
}
public Link Link
{
get { return link; }
}
public PackageVersionSummary(LucenePackage package, Link link)
: this(package.Version, package.LastUpdated, package.VersionDownloadCount, link)
{
}
public PackageVersionSummary(StrictSemanticVersion version, DateTimeOffset lastUpdated, int versionDownloadCount, Link link)
{
this.version = version;
this.lastUpdated = lastUpdated;
this.versionDownloadCount = versionDownloadCount;
this.link = link;
}
}
} | apache-2.0 | C# |
51aa900824e696441382c52f2b69e15422dee571 | test for pull | ytodorov/AntServices,ytodorov/AntServices,ytodorov/AntServices,ytodorov/AntServices,ytodorov/AntServices,ytodorov/AntServices,ytodorov/AntServices,ytodorov/AntServices | AdvancedNetToolsSolution/UnitTests/TraceRouteTests.cs | AdvancedNetToolsSolution/UnitTests/TraceRouteTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace UnitTests
{
public class TraceRouteTests
{
[Fact]
public void GetTraceRouteString()
{
using (HttpClient client = new HttpClient())
{
var encodedArgs = Uri.EscapeDataString($"--traceroute 92.247.12.80 -sn -T5");
string url = "http://antnortheu.cloudapp.net/home/exec?program=nmap&args=" + encodedArgs;
var res = client.GetStringAsync(url).Result;
// some test
int aTest = 123;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace UnitTests
{
public class TraceRouteTests
{
[Fact]
public void GetTraceRouteString()
{
using (HttpClient client = new HttpClient())
{
var encodedArgs = Uri.EscapeDataString($"--traceroute 92.247.12.80 -sn -T5");
string url = "http://antnortheu.cloudapp.net/home/exec?program=nmap&args=" + encodedArgs;
var res = client.GetStringAsync(url).Result;
}
}
}
}
| apache-2.0 | C# |
650c2e2eb72927fbb008f8912e7bf1a0efeb5fa1 | Remove redundant null check from WindowsUtils | chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck | Core/Utils/WindowsUtils.cs | Core/Utils/WindowsUtils.cs | using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Principal;
namespace TweetDck.Core.Utils{
static class WindowsUtils{
public static bool CheckFolderPermission(string path, FileSystemRights right){
try{
AuthorizationRuleCollection rules = Directory.GetAccessControl(path).GetAccessRules(true, true, typeof(SecurityIdentifier));
WindowsIdentity identity = WindowsIdentity.GetCurrent();
if (identity.Groups == null){
return false;
}
bool accessAllow = false, accessDeny = false;
foreach(FileSystemAccessRule rule in rules.Cast<FileSystemAccessRule>().Where(rule => identity.Groups.Contains(rule.IdentityReference) && (right & rule.FileSystemRights) == right)){
switch(rule.AccessControlType){
case AccessControlType.Allow: accessAllow = true; break;
case AccessControlType.Deny: accessDeny = true; break;
}
}
return accessAllow && !accessDeny;
}
catch{
return false;
}
}
}
}
| using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Principal;
namespace TweetDck.Core.Utils{
static class WindowsUtils{
public static bool CheckFolderPermission(string path, FileSystemRights right){
try{
AuthorizationRuleCollection rules = Directory.GetAccessControl(path).GetAccessRules(true, true, typeof(SecurityIdentifier));
WindowsIdentity identity = WindowsIdentity.GetCurrent();
if (identity == null || identity.Groups == null){
return false;
}
bool accessAllow = false, accessDeny = false;
foreach(FileSystemAccessRule rule in rules.Cast<FileSystemAccessRule>().Where(rule => identity.Groups.Contains(rule.IdentityReference) && (right & rule.FileSystemRights) == right)){
switch(rule.AccessControlType){
case AccessControlType.Allow: accessAllow = true; break;
case AccessControlType.Deny: accessDeny = true; break;
}
}
return accessAllow && !accessDeny;
}
catch{
return false;
}
}
}
}
| mit | C# |
2aea7d564c2153402547f8576e0f88b6e9fae9eb | Change version to 1.2 prior tagging. | iskiselev/moq4,cgourlay/moq4,madcapsoftware/moq4,ramanraghur/moq4,JohanLarsson/moq4,breyed/moq4,HelloKitty/moq4,RobSiklos/moq4,jeremymeng/moq4,ocoanet/moq4,kolomanschaft/moq4,Moq/moq4,AhmedAssaf/moq4,kulkarnisachin07/moq4,LeonidLevin/moq4,chkpnt/moq4,ericschultz/Moq,AhmedAssaf/moq4 | Source/Properties/AssemblyInfo.cs | Source/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("Moq")]
[assembly: AssemblyDescription("Mocking library for .NET 3.5 and C# 3.0, heavily based on Linq")]
[assembly: AssemblyCompany("Moq Project")]
[assembly: AssemblyProduct("Moq")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.2.*")]
[assembly: AssemblyFileVersion("1.2.0.0")]
[assembly: InternalsVisibleTo("Moq.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001009f7a95086500f8f66d892174803850fed9c22225c2ccfff21f39c8af8abfa5415b1664efd0d8e0a6f7f2513b1c11659bd84723dc7900c3d481b833a73a2bcf1ed94c16c4be64d54352c86956c89930444e9ac15124d3693e3f029818e8410f167399d6b995324b635e95353ba97bfab856abbaeb9b40c9b160070c6325e22ddc")] | using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("Moq")]
[assembly: AssemblyDescription("Mocking library for .NET 3.5 and C# 3.0, heavily based on Linq")]
[assembly: AssemblyCompany("Moq Project")]
[assembly: AssemblyProduct("Moq")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.*")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: InternalsVisibleTo("Moq.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001009f7a95086500f8f66d892174803850fed9c22225c2ccfff21f39c8af8abfa5415b1664efd0d8e0a6f7f2513b1c11659bd84723dc7900c3d481b833a73a2bcf1ed94c16c4be64d54352c86956c89930444e9ac15124d3693e3f029818e8410f167399d6b995324b635e95353ba97bfab856abbaeb9b40c9b160070c6325e22ddc")] | bsd-3-clause | C# |
c7eb0b6bead0d73d0534fba2b7e179fedcd24b7f | Create private and public key when saving a new product | dnauck/License.Manager-Light,dnauck/License.Manager-Light,dnauck/License.Manager-Light | src/License.Manager/Client/UserCode/CreateNewProduct.cs | src/License.Manager/Client/UserCode/CreateNewProduct.cs | using System;
using System.Linq;
using System.IO;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Framework.Client;
using Microsoft.LightSwitch.Presentation;
using Microsoft.LightSwitch.Presentation.Extensions;
namespace LightSwitchApplication
{
public partial class CreateNewProduct
{
partial void CreateNewProduct_InitializeDataWorkspace(global::System.Collections.Generic.List<global::Microsoft.LightSwitch.IDataService> saveChangesTo)
{
// Write your code here.
this.ProductProperty = new Product();
}
partial void CreateNewProduct_Saved()
{
// Write your code here.
this.Close(false);
Application.Current.ShowDefaultScreen(this.ProductProperty);
}
partial void CreateNewProduct_Saving(ref bool handled)
{
if (ProductProperty.KeyPair != null)
return;
ProductProperty.KeyPair = new KeyPair();
if (!string.IsNullOrWhiteSpace(ProductProperty.KeyPair.PrivateKey))
return;
var passPhrase = this.ShowInputBox("Please enter the pass phrase to encrypt the private key.",
"Private Key Generator");
if (string.IsNullOrWhiteSpace(passPhrase))
{
this.ShowMessageBox("Invalid pass phrase!", "Private Key Generator", MessageBoxOption.Ok);
handled = false;
return;
}
var keyPair = Portable.Licensing.Security.Cryptography.KeyGenerator.Create().GenerateKeyPair();
ProductProperty.KeyPair.PrivateKey = keyPair.ToEncryptedPrivateKeyString(passPhrase);
ProductProperty.KeyPair.PublicKey = keyPair.ToPublicKeyString();
}
}
} | using System;
using System.Linq;
using System.IO;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Framework.Client;
using Microsoft.LightSwitch.Presentation;
using Microsoft.LightSwitch.Presentation.Extensions;
namespace LightSwitchApplication
{
public partial class CreateNewProduct
{
partial void CreateNewProduct_InitializeDataWorkspace(global::System.Collections.Generic.List<global::Microsoft.LightSwitch.IDataService> saveChangesTo)
{
// Write your code here.
this.ProductProperty = new Product();
}
partial void CreateNewProduct_Saved()
{
// Write your code here.
this.Close(false);
Application.Current.ShowDefaultScreen(this.ProductProperty);
}
}
} | mit | C# |
026f2747aea2ede31e2e9634a78e36603452c76e | Remove popups from sharing buttons (attempt #1) | sdl/dxa-web-application-dotnet,sdl/dxa-web-application-dotnet | Site/Areas/Core/Views/Entity/SocialSharing.cshtml | Site/Areas/Core/Views/Entity/SocialSharing.cshtml | @model LinkList<TagLink>
@{
int i = 0;
var pageUrl = Url.Encode(Request.Url.ToString());
}
<div class="share-buttons clearfix" @Markup.Entity(Model)>
@Html.Resource("core.shareOnSocialCaption")
<ul>
@foreach(var link in Model.Links)
{
<li @Markup.Property(Model,"Links",i++)>
<!--<a class="popup-iframe popup-mobile-ignore" href="@String.Format(link.Url,pageUrl)" title="@Html.FormatResource("core.shareOnSocialLinkTitle",link.Tag.DisplayText)"> -->
<a href="@String.Format(link.Url,pageUrl)" title="@Html.FormatResource("core.shareOnSocialLinkTitle",link.Tag.DisplayText)">
<i class="fa fa-@link.Tag.Key"></i>
</a>
</li>
}
</ul>
</div> | @model LinkList<TagLink>
@{
int i = 0;
var pageUrl = Url.Encode(Request.Url.ToString());
}
<div class="share-buttons clearfix" @Markup.Entity(Model)>
@Html.Resource("core.shareOnSocialCaption")
<ul>
@foreach(var link in Model.Links)
{
<li @Markup.Property(Model,"Links",i++)>
<a class="popup-iframe popup-mobile-ignore" href="@String.Format(link.Url,pageUrl)" title="@Html.FormatResource("core.shareOnSocialLinkTitle",link.Tag.DisplayText)">
<i class="fa fa-@link.Tag.Key"></i>
</a>
</li>
}
</ul>
</div> | apache-2.0 | C# |
531b6740f6a486e6e3932903f79cf26d6ff33f67 | transform uses less memory - use values read for values transformed | ignatandrei/stankins,ignatandrei/stankins,ignatandrei/stankins,ignatandrei/stankins,ignatandrei/stankins,ignatandrei/stankins | Transformers/TransformAddField.cs | Transformers/TransformAddField.cs | using StankinsInterfaces;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Transformers
{
//replace with
//https://github.com/davideicardi/DynamicExpresso
public class TransformAddField<T,U> : ITransform
{
Func<T, U> transformFunc { get; set; }
public string OldField { get; set; }
public string NewField { get; set; }
public TransformAddField(Func<T,U> func, string oldField, string newField)
{
transformFunc = func;
OldField = oldField;
NewField = newField;
}
public IRow[] valuesRead { get; set; }
public IRow[] valuesTransformed { get; set; }
public async Task Run()
{
//var newVals = new List<IRow>();
foreach (var item in valuesRead)
{
var data = item.Values[OldField];
T convert = (T)Convert.ChangeType(data, typeof(T));
var val = transformFunc(convert);
if (item.Values.ContainsKey(NewField))
{
item.Values[NewField] = val;
}
else
{
item.Values.Add(NewField, val);
}
//newVals.Add(item);
}
valuesTransformed = valuesRead;
}
}
}
| using StankinsInterfaces;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Transformers
{
public class TransformAddField<T,U> : ITransform
{
Func<T, U> transformFunc { get; set; }
public string OldField { get; set; }
public string NewField { get; set; }
public TransformAddField(Func<T,U> func, string oldField, string newField)
{
transformFunc = func;
OldField = oldField;
NewField = newField;
}
public IRow[] valuesRead { get; set; }
public IRow[] valuesTransformed { get; set; }
public async Task Run()
{
var newVals = new List<IRow>();
foreach (var item in valuesRead)
{
var data = item.Values[OldField];
T convert = (T)Convert.ChangeType(data, typeof(T));
item.Values.Add(NewField, transformFunc(convert));
newVals.Add(item);
}
valuesTransformed = newVals.ToArray();
}
}
}
| mit | C# |
b59f23d0944a5aa512c2bf3096d4ef7390f32e72 | Implement hp increase for taiko | peppy/osu,UselessToucan/osu,EVAST9919/osu,ppy/osu,2yangk23/osu,2yangk23/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,EVAST9919/osu,ppy/osu,ZLima12/osu,smoogipoo/osu,smoogipoo/osu,ZLima12/osu,johnneijzen/osu,UselessToucan/osu,smoogipooo/osu,ppy/osu,peppy/osu-new,smoogipoo/osu,johnneijzen/osu | osu.Game.Rulesets.Taiko/Scoring/TaikoScoreProcessor.cs | osu.Game.Rulesets.Taiko/Scoring/TaikoScoreProcessor.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.Beatmaps;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.Taiko.Objects;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Taiko.Scoring
{
internal class TaikoScoreProcessor : ScoreProcessor<TaikoHitObject>
{
/// <summary>
/// A value used for calculating <see cref="hpMultiplier"/>.
/// </summary>
private const double object_count_factor = 3;
/// <summary>
/// Taiko fails at the end of the map if the player has not half-filled their HP bar.
/// </summary>
protected override bool DefaultFailCondition => JudgedHits == MaxHits && Health.Value <= 0.5;
/// <summary>
/// HP multiplier for a successful <see cref="HitResult"/>.
/// </summary>
private double hpMultiplier;
/// <summary>
/// HP multiplier for a <see cref="HitResult.Miss"/>.
/// </summary>
private double hpMissMultiplier;
public TaikoScoreProcessor(DrawableRuleset<TaikoHitObject> drawableRuleset)
: base(drawableRuleset)
{
}
protected override void ApplyBeatmap(Beatmap<TaikoHitObject> beatmap)
{
base.ApplyBeatmap(beatmap);
hpMultiplier = 1 / (object_count_factor * beatmap.HitObjects.FindAll(o => o is Hit).Count * BeatmapDifficulty.DifficultyRange(beatmap.BeatmapInfo.BaseDifficulty.DrainRate, 0.5, 0.75, 0.98));
hpMissMultiplier = BeatmapDifficulty.DifficultyRange(beatmap.BeatmapInfo.BaseDifficulty.DrainRate, 0.0018, 0.0075, 0.0120);
}
protected override double HpFactorFor(Judgement judgement, HitResult result)
=> result == HitResult.Miss ? hpMissMultiplier : hpMultiplier;
protected override void Reset(bool storeResults)
{
base.Reset(storeResults);
Health.Value = 0;
}
public override HitWindows CreateHitWindows() => new TaikoHitWindows();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.Taiko.Objects;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Taiko.Scoring
{
internal class TaikoScoreProcessor : ScoreProcessor<TaikoHitObject>
{
/// <summary>
/// A value used for calculating <see cref="hpMultiplier"/>.
/// </summary>
private const double object_count_factor = 3;
/// <summary>
/// Taiko fails at the end of the map if the player has not half-filled their HP bar.
/// </summary>
protected override bool DefaultFailCondition => JudgedHits == MaxHits && Health.Value <= 0.5;
/// <summary>
/// HP multiplier for a successful <see cref="HitResult"/>.
/// </summary>
private double hpMultiplier;
/// <summary>
/// HP multiplier for a <see cref="HitResult.Miss"/>.
/// </summary>
private double hpMissMultiplier;
public TaikoScoreProcessor(DrawableRuleset<TaikoHitObject> drawableRuleset)
: base(drawableRuleset)
{
}
protected override void ApplyBeatmap(Beatmap<TaikoHitObject> beatmap)
{
base.ApplyBeatmap(beatmap);
hpMultiplier = 1 / (object_count_factor * beatmap.HitObjects.FindAll(o => o is Hit).Count * BeatmapDifficulty.DifficultyRange(beatmap.BeatmapInfo.BaseDifficulty.DrainRate, 0.5, 0.75, 0.98));
hpMissMultiplier = BeatmapDifficulty.DifficultyRange(beatmap.BeatmapInfo.BaseDifficulty.DrainRate, 0.0018, 0.0075, 0.0120);
}
protected override void ApplyResult(JudgementResult result)
{
base.ApplyResult(result);
double hpIncrease = result.Judgement.HealthIncreaseFor(result);
if (result.Type == HitResult.Miss)
hpIncrease *= hpMissMultiplier;
else
hpIncrease *= hpMultiplier;
Health.Value += hpIncrease;
}
protected override void Reset(bool storeResults)
{
base.Reset(storeResults);
Health.Value = 0;
}
public override HitWindows CreateHitWindows() => new TaikoHitWindows();
}
}
| mit | C# |
c408b46a2158e251d82ce99997d65d2c58c7203f | Add AllowedMods to MultiplayerRoomSettings model | UselessToucan/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu-new | osu.Game/Online/Multiplayer/MultiplayerRoomSettings.cs | osu.Game/Online/Multiplayer/MultiplayerRoomSettings.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Game.Online.API;
namespace osu.Game.Online.Multiplayer
{
[Serializable]
public class MultiplayerRoomSettings : IEquatable<MultiplayerRoomSettings>
{
public int BeatmapID { get; set; }
public int RulesetID { get; set; }
public string BeatmapChecksum { get; set; } = string.Empty;
public string Name { get; set; } = "Unnamed room";
[NotNull]
public IEnumerable<APIMod> Mods { get; set; } = Enumerable.Empty<APIMod>();
[NotNull]
public IEnumerable<APIMod> AllowedMods { get; set; } = Enumerable.Empty<APIMod>();
public bool Equals(MultiplayerRoomSettings other)
=> BeatmapID == other.BeatmapID
&& BeatmapChecksum == other.BeatmapChecksum
&& Mods.SequenceEqual(other.Mods)
&& AllowedMods.SequenceEqual(other.AllowedMods)
&& RulesetID == other.RulesetID
&& Name.Equals(other.Name, StringComparison.Ordinal);
public override string ToString() => $"Name:{Name}"
+ $" Beatmap:{BeatmapID} ({BeatmapChecksum})"
+ $" Mods:{string.Join(',', Mods)}"
+ $" AllowedMods:{string.Join(',', AllowedMods)}"
+ $" Ruleset:{RulesetID}";
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Game.Online.API;
namespace osu.Game.Online.Multiplayer
{
[Serializable]
public class MultiplayerRoomSettings : IEquatable<MultiplayerRoomSettings>
{
public int BeatmapID { get; set; }
public int RulesetID { get; set; }
public string BeatmapChecksum { get; set; } = string.Empty;
public string Name { get; set; } = "Unnamed room";
[NotNull]
public IEnumerable<APIMod> Mods { get; set; } = Enumerable.Empty<APIMod>();
public bool Equals(MultiplayerRoomSettings other)
=> BeatmapID == other.BeatmapID
&& BeatmapChecksum == other.BeatmapChecksum
&& Mods.SequenceEqual(other.Mods)
&& RulesetID == other.RulesetID
&& Name.Equals(other.Name, StringComparison.Ordinal);
public override string ToString() => $"Name:{Name} Beatmap:{BeatmapID} ({BeatmapChecksum}) Mods:{string.Join(',', Mods)} Ruleset:{RulesetID}";
}
}
| mit | C# |
4b6f2f996205704d2c624c22684b6dca23bf618e | Fix incorrect ordering | Tom94/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework | osu.Framework/Graphics/Textures/TextureWithRefCount.cs | osu.Framework/Graphics/Textures/TextureWithRefCount.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using osu.Framework.Graphics.OpenGL.Textures;
namespace osu.Framework.Graphics.Textures
{
/// <summary>
/// A texture which updates the reference count of the underlying <see cref="TextureGL"/> on ctor and disposal.
/// </summary>
public class TextureWithRefCount : Texture
{
public TextureWithRefCount(TextureGL textureGl)
: base(textureGl)
{
TextureGL.Reference();
}
#region Disposal
~TextureWithRefCount()
{
// Finalizer implemented here rather than Texture to avoid GC overhead.
Dispose(false);
}
protected override void Dispose(bool isDisposing)
{
if (IsDisposed)
throw new ObjectDisposedException($"{nameof(TextureWithRefCount)} should never be disposed more than once");
base.Dispose(isDisposing);
TextureGL?.Dereference();
if (isDisposing) GC.SuppressFinalize(this);
}
#endregion
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using osu.Framework.Graphics.OpenGL.Textures;
namespace osu.Framework.Graphics.Textures
{
/// <summary>
/// A texture which updates the reference count of the underlying <see cref="TextureGL"/> on ctor and disposal.
/// </summary>
public class TextureWithRefCount : Texture
{
public TextureWithRefCount(TextureGL textureGl)
: base(textureGl)
{
TextureGL.Reference();
}
#region Disposal
~TextureWithRefCount()
{
// Finalizer implemented here rather than Texture to avoid GC overhead.
Dispose(false);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (IsDisposed)
throw new ObjectDisposedException($"{nameof(TextureWithRefCount)} should never be disposed more than once");
TextureGL?.Dereference();
if (isDisposing) GC.SuppressFinalize(this);
}
#endregion
}
}
| mit | C# |
1e6f19f981adcfc5cfd0101fd7919b14b6e50d66 | Throw ArgumentExceptions instead | EVAST9919/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework | osu.Framework/Input/StateChanges/TouchActivityInput.cs | osu.Framework/Input/StateChanges/TouchActivityInput.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Input.StateChanges.Events;
using osu.Framework.Input.States;
using osuTK.Input;
namespace osu.Framework.Input.StateChanges
{
/// <summary>
/// Denotes a change of the touch activity state (finger down, up).
/// Any provided touch source should always be in the range <see cref="MouseButton.Touch1"/>-<see cref="MouseButton.Touch10"/>.
/// </summary>
public class TouchActivityInput : ButtonInput<MouseButton>
{
public TouchActivityInput(IEnumerable<ButtonInputEntry<MouseButton>> entries)
: base(entries)
{
if (Entries.Any(e => e.Button < MouseButton.Touch1 || e.Button > MouseButton.Touch10))
throw new ArgumentException($"Invalid touch source entry provided in: {entries}", nameof(entries));
}
public TouchActivityInput(MouseButton button, bool isActive)
: base(button, isActive)
{
if (button < MouseButton.Touch1 || button > MouseButton.Touch10)
throw new ArgumentException($"Invalid touch source provided: {button}", nameof(button));
}
public TouchActivityInput(ButtonStates<MouseButton> current, ButtonStates<MouseButton> previous)
: base(current, previous)
{
if (Entries.Any(e => e.Button < MouseButton.Touch1 || e.Button > MouseButton.Touch10))
throw new ArgumentException("Invalid touch source entry provided.");
}
protected override ButtonStates<MouseButton> GetButtonStates(InputState state) => state.Touch.ActiveSources;
protected override ButtonStateChangeEvent<MouseButton> CreateEvent(InputState state, MouseButton button, ButtonStateChangeKind kind)
=> new TouchActivityChangeEvent(state, this, button, kind);
protected override void OnButtonStateChanged(InputState state, MouseButton button, bool isPressed)
{
if (isPressed == false)
state.Touch.TouchPositions.Remove(button);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using osu.Framework.Input.StateChanges.Events;
using osu.Framework.Input.States;
using osuTK.Input;
namespace osu.Framework.Input.StateChanges
{
/// <summary>
/// Denotes a change of the touch activity state (finger down, up).
/// Any provided touch source should always be in the range <see cref="MouseButton.Touch1"/>-<see cref="MouseButton.Touch10"/>.
/// </summary>
public class TouchActivityInput : ButtonInput<MouseButton>
{
public TouchActivityInput(IEnumerable<ButtonInputEntry<MouseButton>> entries)
: base(entries)
{
Trace.Assert(Entries.All(e => e.Button >= MouseButton.Touch1));
}
public TouchActivityInput(MouseButton button, bool isActive)
: base(button, isActive)
{
Trace.Assert(button >= MouseButton.Touch1);
}
public TouchActivityInput(ButtonStates<MouseButton> current, ButtonStates<MouseButton> previous)
: base(current, previous)
{
Trace.Assert(Entries.All(e => e.Button >= MouseButton.Touch1));
}
protected override ButtonStates<MouseButton> GetButtonStates(InputState state) => state.Touch.ActiveSources;
protected override ButtonStateChangeEvent<MouseButton> CreateEvent(InputState state, MouseButton button, ButtonStateChangeKind kind)
=> new TouchActivityChangeEvent(state, this, button, kind);
protected override void OnButtonStateChanged(InputState state, MouseButton button, bool isPressed)
{
if (isPressed == false)
state.Touch.TouchPositions.Remove(button);
}
}
}
| mit | C# |
5d74d92fcf030d6c98fb8941ea3159914b09a6dd | Revert `virtual` current bindable | ppy/osu,peppy/osu,peppy/osu,ppy/osu,peppy/osu,ppy/osu | osu.Game/Graphics/UserInterfaceV2/LabelledComponent.cs | osu.Game/Graphics/UserInterfaceV2/LabelledComponent.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.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.UserInterface;
namespace osu.Game.Graphics.UserInterfaceV2
{
public abstract class LabelledComponent<TDrawable, TValue> : LabelledDrawable<TDrawable>, IHasCurrentValue<TValue>
where TDrawable : Drawable, IHasCurrentValue<TValue>
{
protected LabelledComponent(bool padded)
: base(padded)
{
}
public Bindable<TValue> Current
{
get => Component.Current;
set => Component.Current = value;
}
}
}
| // 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.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.UserInterface;
namespace osu.Game.Graphics.UserInterfaceV2
{
public abstract class LabelledComponent<TDrawable, TValue> : LabelledDrawable<TDrawable>, IHasCurrentValue<TValue>
where TDrawable : Drawable, IHasCurrentValue<TValue>
{
protected LabelledComponent(bool padded)
: base(padded)
{
}
public virtual Bindable<TValue> Current
{
get => Component.Current;
set => Component.Current = value;
}
}
}
| mit | C# |
bcc904386842778c82d2689eb7613f569d45c9f8 | Update JailBreakGoogleEventsService.cs | fabianwilliams/JailBreakMobilePublic | jbb/jbb/ViewModel/JailBreakGoogleEventsService.cs | jbb/jbb/ViewModel/JailBreakGoogleEventsService.cs | using System;
using System.Net;
using System.Net.Http;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Threading.Tasks;
namespace jbb
{
public class JailBreakGoogleEventsService
{
public JailBreakGoogleEventsService ()
{
}
public async Task<JBEvent.RootObject> GetJBEventsAsync () {
var client = new System.Net.Http.HttpClient ();
var requestMessage = new HttpRequestMessage()
{
RequestUri = new Uri("YOUR URI END POINT FOR WEB API FOR GOOGLE CALENDAR"),
Method = HttpMethod.Get,
};
var response = await client.SendAsync (requestMessage);
var eventJson = response.Content.ReadAsStringAsync().Result;
var rootobject = JsonConvert.DeserializeObject<JBEvent.RootObject>(eventJson);
return rootobject;
}
public async Task<JBEvent.RootObject> GetJBFoodTrucksAsync () {
var client = new System.Net.Http.HttpClient ();
var requestMessage = new HttpRequestMessage()
{
RequestUri = new Uri("YOUR URI END POINT FOR WEB API FOR GOOGLE CALENDAR"),
Method = HttpMethod.Get,
};
var response = await client.SendAsync (requestMessage);
var eventJson = response.Content.ReadAsStringAsync().Result;
var rootobject = JsonConvert.DeserializeObject<JBEvent.RootObject>(eventJson);
return rootobject;
}
}
}
| using System;
using System.Net;
using System.Net.Http;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Threading.Tasks;
namespace jbb
{
public class JailBreakGoogleEventsService
{
public JailBreakGoogleEventsService ()
{
}
public async Task<JBEvent.RootObject> GetJBEventsAsync () {
var client = new System.Net.Http.HttpClient ();
var requestMessage = new HttpRequestMessage()
{
//RequestUri = new Uri("https://www.googleapis.com/calendar/v3/calendars/q1k3ll0bdkis2ceef447rthocs@group.calendar.google.com/events?key=AIzaSyAHLnznypEgj3IAWmDe04XCBpSqgKhikP4"),
RequestUri = new Uri("https://www.googleapis.com/calendar/v3/calendars/jailbreakbrewing.com_gqdh070qj7ajjt6rmas6ca5ju0@group.calendar.google.com/events?key=AIzaSyAHLnznypEgj3IAWmDe04XCBpSqgKhikP4"),
Method = HttpMethod.Get,
};
var response = await client.SendAsync (requestMessage);
var eventJson = response.Content.ReadAsStringAsync().Result;
var rootobject = JsonConvert.DeserializeObject<JBEvent.RootObject>(eventJson);
return rootobject;
}
public async Task<JBEvent.RootObject> GetJBFoodTrucksAsync () {
var client = new System.Net.Http.HttpClient ();
var requestMessage = new HttpRequestMessage()
{
RequestUri = new Uri("https://www.googleapis.com/calendar/v3/calendars/jailbreakbrewing.com_upiufesmmavkpud9t448q9i4q4@group.calendar.google.com/events?key=AIzaSyAHLnznypEgj3IAWmDe04XCBpSqgKhikP4"),
Method = HttpMethod.Get,
};
var response = await client.SendAsync (requestMessage);
var eventJson = response.Content.ReadAsStringAsync().Result;
var rootobject = JsonConvert.DeserializeObject<JBEvent.RootObject>(eventJson);
return rootobject;
}
}
}
| apache-2.0 | C# |
a001e4aa166675a81c8beacc065284aebc158871 | Fix web request failing if password is null | NeoAdonis/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipooo/osu,NeoAdonis/osu,ppy/osu,peppy/osu,UselessToucan/osu,peppy/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,peppy/osu-new,smoogipoo/osu,smoogipoo/osu | osu.Game/Online/Rooms/JoinRoomRequest.cs | osu.Game/Online/Rooms/JoinRoomRequest.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Net.Http;
using osu.Framework.IO.Network;
using osu.Game.Online.API;
namespace osu.Game.Online.Rooms
{
public class JoinRoomRequest : APIRequest
{
public readonly Room Room;
public readonly string Password;
public JoinRoomRequest(Room room, string password)
{
Room = room;
Password = password;
}
protected override WebRequest CreateWebRequest()
{
var req = base.CreateWebRequest();
req.Method = HttpMethod.Put;
if (!string.IsNullOrEmpty(Password))
req.AddParameter("password", Password);
return req;
}
protected override string Target => $"rooms/{Room.RoomID.Value}/users/{User.Id}";
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Net.Http;
using osu.Framework.IO.Network;
using osu.Game.Online.API;
namespace osu.Game.Online.Rooms
{
public class JoinRoomRequest : APIRequest
{
public readonly Room Room;
public readonly string Password;
public JoinRoomRequest(Room room, string password)
{
Room = room;
Password = password;
}
protected override WebRequest CreateWebRequest()
{
var req = base.CreateWebRequest();
req.Method = HttpMethod.Put;
req.AddParameter("password", Password);
return req;
}
protected override string Target => $"rooms/{Room.RoomID.Value}/users/{User.Id}";
}
}
| mit | C# |
fbb68d802df49cb7465ea591780e6bb2ead1545f | Remove useless properties from ItemPageViewModel.cs | wangjun/windows-app,wangjun/windows-app | wallabag/wallabag.Shared/ViewModel/ItemPageViewModel.cs | wallabag/wallabag.Shared/ViewModel/ItemPageViewModel.cs | using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Ioc;
using Windows.ApplicationModel.DataTransfer;
using Windows.UI.Xaml.Media;
using wallabag.Common;
namespace wallabag.ViewModel
{
public class ItemPageViewModel : viewModelBase
{
private ItemViewModel _Item;
public ItemViewModel Item
{
get { return _Item; }
set { Set(() => Item, ref _Item, value); }
}
public RelayCommand shareCommand { get; private set; }
[PreferredConstructor]
public ItemPageViewModel()
{
shareCommand = new RelayCommand(() => DataTransferManager.ShowShareUI());
}
public ItemPageViewModel(ItemViewModel item)
{
shareCommand = new RelayCommand(() => DataTransferManager.ShowShareUI());
Item = item;
}
}
}
| using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Ioc;
using Windows.ApplicationModel.DataTransfer;
using Windows.UI.Xaml.Media;
using wallabag.Common;
namespace wallabag.ViewModel
{
public class ItemPageViewModel : viewModelBase
{
private ItemViewModel _Item;
public ItemViewModel Item
{
get { return _Item; }
set { Set(() => Item, ref _Item, value); }
}
public SolidColorBrush Background
{
get { return new SettingsViewModel().Background; }
}
public SolidColorBrush textColor
{
get { return new SettingsViewModel().textColor; }
}
public RelayCommand shareCommand { get; private set; }
[PreferredConstructor]
public ItemPageViewModel()
{
shareCommand = new RelayCommand(() => DataTransferManager.ShowShareUI());
}
public ItemPageViewModel(ItemViewModel item)
{
shareCommand = new RelayCommand(() => DataTransferManager.ShowShareUI());
Item = item;
}
}
}
| mit | C# |
7269d71b659938ccbd6c73d9b35c3a0c5ecc48d6 | Disable example | mmoening/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,jlewin/MatterControl,mmoening/MatterControl,mmoening/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl | MatterControlLib/PartPreviewWindow/SceneViewer/TraceDataDrawable.cs | MatterControlLib/PartPreviewWindow/SceneViewer/TraceDataDrawable.cs | /*
Copyright (c) 2019, Lars Brubaker, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using MatterHackers.Agg.UI;
using MatterHackers.DataConverters3D;
using MatterHackers.RayTracer;
using MatterHackers.VectorMath;
namespace MatterHackers.MatterControl.PartPreviewWindow
{
public class TraceDataDrawable : IDrawable
{
private BedConfig sceneContext;
private InteractiveScene scene;
public TraceDataDrawable(BedConfig sceneContext)
{
this.sceneContext = sceneContext;
this.scene = sceneContext.Scene;
}
public void Draw(GuiWidget sender, DrawEventArgs e, Matrix4X4 itemMaxtrix, WorldView world)
{
return;
// RenderSceneTraceData
var bvhIterator = new BvhIterator(scene?.TraceData(), decentFilter: (x) =>
{
var center = x.Bvh.GetCenter();
var worldCenter = Vector3Ex.Transform(center, x.TransformToWorld);
if (worldCenter.Z > 0)
{
return true;
}
return false;
});
InteractionLayer.RenderBounds(e, world, bvhIterator);
}
}
} | /*
Copyright (c) 2019, Lars Brubaker, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using MatterHackers.Agg.UI;
using MatterHackers.DataConverters3D;
using MatterHackers.RayTracer;
using MatterHackers.VectorMath;
namespace MatterHackers.MatterControl.PartPreviewWindow
{
public class TraceDataDrawable : IDrawable
{
private BedConfig sceneContext;
private InteractiveScene scene;
public TraceDataDrawable(BedConfig sceneContext)
{
this.sceneContext = sceneContext;
this.scene = sceneContext.Scene;
}
public void Draw(GuiWidget sender, DrawEventArgs e, Matrix4X4 itemMaxtrix, WorldView world)
{
// RenderSceneTraceData
var bvhIterator = new BvhIterator(scene?.TraceData(), decentFilter: (x) =>
{
var center = x.Bvh.GetCenter();
var worldCenter = Vector3Ex.Transform(center, x.TransformToWorld);
if (worldCenter.Z > 0)
{
return true;
}
return false;
});
InteractionLayer.RenderBounds(e, world, bvhIterator);
}
}
} | bsd-2-clause | C# |
a1ffd84ff61a550bb58291d274b01f673ad2749e | use tables under DeepThought schema | spartanbeg/Beethoven | src/Beethoven/Beethoven.Plugins/Security/SecurityDataContext.cs | src/Beethoven/Beethoven.Plugins/Security/SecurityDataContext.cs | /*
* DeepThought.Account
*
* Written for .NET 4.0 in C#
*
* Copyright (C) 2009, 2010, 2011. All Right Reserved, Spartansoft L.L.C.
* http://spartansoft.org
*
* Proprietary and Confidential information of Spartansoft L.L.C.
* Redistribution and use in source and binary forms, with or without modification,
* without the authorization of Spartansoft L.L.C. is prohibited. *
*
* "Whatever happens SPARTAN's code must stand ... or at least crash responsibly."
*
* File Name: DeepThoughtDataContext.cs
*
* File Authors:
* Mehmetali N. Shaqiri, m.shaqiri@spartansoft.org
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Beethoven.Configuration;
using System.Configuration;
using System.Data.Entity;
namespace Beethoven.Plugins.Security
{
public class SecurityDataContext : DbContext
{
private readonly BeethovenConfiguration _configuration = ConfigurationManager.GetSection("BeethovenConfiguration") as BeethovenConfiguration;
public SecurityDataContext()
{
base.Database.Connection.ConnectionString = _configuration.DataSource.ConnectionString;
}
public IDbSet<Capability> Capabilities { get; set; }
public IDbSet<RoleCapability> RoleCapabilities { get; set; }
public IDbSet<Role> Roles { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Capability>().ToTable("DeepThought.Capabilities");
modelBuilder.Entity<RoleCapability>().ToTable("DeepThought.RoleCapabilities");
modelBuilder.Entity<Role>().ToTable("aspnet_Roles");
base.OnModelCreating(modelBuilder);
}
}
}
| /*
* DeepThought.Account
*
* Written for .NET 4.0 in C#
*
* Copyright (C) 2009, 2010, 2011. All Right Reserved, Spartansoft L.L.C.
* http://spartansoft.org
*
* Proprietary and Confidential information of Spartansoft L.L.C.
* Redistribution and use in source and binary forms, with or without modification,
* without the authorization of Spartansoft L.L.C. is prohibited. *
*
* "Whatever happens SPARTAN's code must stand ... or at least crash responsibly."
*
* File Name: DeepThoughtDataContext.cs
*
* File Authors:
* Mehmetali N. Shaqiri, m.shaqiri@spartansoft.org
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Beethoven.Configuration;
using System.Configuration;
using System.Data.Entity;
namespace Beethoven.Plugins.Security
{
public class SecurityDataContext : DbContext
{
private readonly BeethovenConfiguration _configuration = ConfigurationManager.GetSection("BeethovenConfiguration") as BeethovenConfiguration;
public SecurityDataContext()
{
base.Database.Connection.ConnectionString = _configuration.DataSource.ConnectionString;
}
public IDbSet<Capability> Capabilities { get; set; }
public IDbSet<RoleCapability> RoleCapabilities { get; set; }
public IDbSet<Role> Roles { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Capability>().ToTable("Capabilities");
modelBuilder.Entity<RoleCapability>().ToTable("RoleCapabilities");
modelBuilder.Entity<Role>().ToTable("aspnet_Roles");
base.OnModelCreating(modelBuilder);
}
}
}
| mit | C# |
5e6d28a3027f1cf4dac32cbd0cd21dcbe0c9e6e2 | Fix fleet ship list not update | amatukaze/HeavenlyWind | src/ViewModels/Sakuno.ING.ViewModels/Homeport/FleetViewModel.cs | src/ViewModels/Sakuno.ING.ViewModels/Homeport/FleetViewModel.cs | using DynamicData;
using DynamicData.Aggregation;
using DynamicData.Binding;
using ReactiveUI;
using Sakuno.ING.Game.Models;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
namespace Sakuno.ING.ViewModels.Homeport
{
public sealed class FleetViewModel : ReactiveObject, IHomeportTabViewModel
{
public PlayerFleet Model { get; }
public IReadOnlyCollection<ShipViewModel> Ships { get; }
private readonly ObservableAsPropertyHelper<int> _totalLevel;
public int TotalLevel => _totalLevel.Value;
private readonly ObservableAsPropertyHelper<int> _speed;
public ShipSpeed Speed => (ShipSpeed)_speed.Value;
private bool _isSelected;
public bool IsSelected
{
get => _isSelected;
set => this.RaiseAndSetIfChanged(ref _isSelected, value);
}
public FleetViewModel(PlayerFleet fleet)
{
Model = fleet;
var ships = fleet.Ships.ToObservableChangeSet();
Ships = ships.Transform(r => new ShipViewModel(r)).Bind();
_totalLevel = ships.Sum(r => r.Leveling.Level).ObserveOn(RxApp.MainThreadScheduler).ToProperty(this, nameof(TotalLevel), deferSubscription: true);
_speed = ships.Minimum(r => (int)r.Speed).ObserveOn(RxApp.MainThreadScheduler).ToProperty(this, nameof(ShipSpeed));
}
}
}
| using DynamicData;
using DynamicData.Aggregation;
using ReactiveUI;
using Sakuno.ING.Game.Models;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
namespace Sakuno.ING.ViewModels.Homeport
{
public sealed class FleetViewModel : ReactiveObject, IHomeportTabViewModel
{
public PlayerFleet Model { get; }
public IReadOnlyCollection<ShipViewModel> Ships { get; }
private readonly ObservableAsPropertyHelper<int> _totalLevel;
public int TotalLevel => _totalLevel.Value;
private readonly ObservableAsPropertyHelper<int> _speed;
public ShipSpeed Speed => (ShipSpeed)_speed.Value;
private bool _isSelected;
public bool IsSelected
{
get => _isSelected;
set => this.RaiseAndSetIfChanged(ref _isSelected, value);
}
public FleetViewModel(PlayerFleet fleet)
{
Model = fleet;
var ships = fleet.Ships.AsObservableChangeSet();
Ships = ships.Transform(r => new ShipViewModel(r)).Bind();
_totalLevel = ships.Sum(r => r.Leveling.Level).ObserveOn(RxApp.MainThreadScheduler).ToProperty(this, nameof(TotalLevel), deferSubscription: true);
_speed = ships.Minimum(r => (int)r.Speed).ObserveOn(RxApp.MainThreadScheduler).ToProperty(this, nameof(ShipSpeed));
}
}
}
| mit | C# |
d313de18e1b36a448e10961034a4e9fcacd5a127 | Fix constructor layout in DerAsnBitStringTests | huysentruitw/pem-utils | tests/DerConverter.Tests/Asn/KnownTypes/DerAsnBitStringTests.cs | tests/DerConverter.Tests/Asn/KnownTypes/DerAsnBitStringTests.cs | using System.Collections;
using DerConverter.Asn;
using DerConverter.Asn.KnownTypes;
using NUnit.Framework;
namespace DerConverter.Tests.Asn.KnownTypes
{
[TestFixture]
public class DerAsnBitStringTests : Base<DerAsnBitString, BitArray>
{
public DerAsnBitStringTests() : base(DerAsnIdentifiers.Primitive.BitString) { }
[TestCase(new bool[0], 0x00)]
[TestCase(new[] { false, true, false, true, true, false, true, false }, 0x00, 0x5A)]
[TestCase(new[] { true, false, true, false, false, false, true, true, false, true }, 0x06, 0xA3, 0x40)]
[TestCase(new[] { true, false, true, false, false, false, true, true, false, false, false }, 0x05, 0xA3, 0x00)]
public void DecodeConstructor_ShouldDecodeCorrectly(bool[] expectedValue, params int[] rawData)
{
base.DecodeConstructor_ShouldDecodeCorrectly(new BitArray(expectedValue), rawData);
}
[TestCase(new bool[0], 0x00)]
[TestCase(new[] { false, true, false, true, true, false, true, false }, 0x00, 0x5A)]
[TestCase(new[] { true, false, true, false, false, false, true, true, false, true }, 0x06, 0xA3, 0x40)]
[TestCase(new[] { true, false, true, false, false, false, true, true, false, false, false }, 0x05, 0xA3, 0x00)]
public void Encode_ShouldEncodeCorrectly(bool[] value, params int[] expectedRawData)
{
base.Encode_ShouldEncodeCorrectly(new BitArray(value), expectedRawData);
}
}
}
| using System.Collections;
using DerConverter.Asn;
using DerConverter.Asn.KnownTypes;
using NUnit.Framework;
namespace DerConverter.Tests.Asn.KnownTypes
{
[TestFixture]
public class DerAsnBitStringTests : Base<DerAsnBitString, BitArray>
{
public DerAsnBitStringTests()
: base(DerAsnIdentifiers.Primitive.BitString)
{
}
[TestCase(new bool[0], 0x00)]
[TestCase(new[] { false, true, false, true, true, false, true, false }, 0x00, 0x5A)]
[TestCase(new[] { true, false, true, false, false, false, true, true, false, true }, 0x06, 0xA3, 0x40)]
[TestCase(new[] { true, false, true, false, false, false, true, true, false, false, false }, 0x05, 0xA3, 0x00)]
public void DecodeConstructor_ShouldDecodeCorrectly(bool[] expectedValue, params int[] rawData)
{
base.DecodeConstructor_ShouldDecodeCorrectly(new BitArray(expectedValue), rawData);
}
[TestCase(new bool[0], 0x00)]
[TestCase(new[] { false, true, false, true, true, false, true, false }, 0x00, 0x5A)]
[TestCase(new[] { true, false, true, false, false, false, true, true, false, true }, 0x06, 0xA3, 0x40)]
[TestCase(new[] { true, false, true, false, false, false, true, true, false, false, false }, 0x05, 0xA3, 0x00)]
public void Encode_ShouldEncodeCorrectly(bool[] value, params int[] expectedRawData)
{
base.Encode_ShouldEncodeCorrectly(new BitArray(value), expectedRawData);
}
}
}
| apache-2.0 | C# |
1feb9fa14d9dc465f8f9a238294d975799261333 | fix test | Fody/Validar | Fody/AssemblyTests/GenericExternalTests.cs | Fody/AssemblyTests/GenericExternalTests.cs | using System.IO;
using System.Reflection;
using NUnit.Framework;
[TestFixture]
public class GenericExternalTests
{
string afterAssemblyPath;
Assembly assembly;
public GenericExternalTests()
{
AppDomainAssemblyFinder.Attach();
var beforeAssemblyPath = Path.GetFullPath(@"..\..\..\WithGenericExternal\bin\Debug\WithGenericExternal.dll");
#if (!DEBUG)
beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release");
#endif
afterAssemblyPath = WeaverHelper.Weave(beforeAssemblyPath);
assembly = Assembly.LoadFile(afterAssemblyPath);
}
[Test]
public void DataErrorInfo()
{
var instance = assembly.GetInstance("WithGenericExternal.MyModel");
ValidationTester.TestDataErrorInfo(instance);
}
[Test]
public void DataErrorInfoWithImplementation()
{
var instance = assembly.GetInstance("WithGenericExternal.ModelWithImplementation");
ValidationTester.TestDataErrorInfo(instance);
}
#if(DEBUG)
[Test]
public void PeVerify()
{
Verifier.Verify(afterAssemblyPath);
}
#endif
[Test]
public void NotifyDataErrorInfo()
{
var instance = assembly.GetInstance("WithGenericExternal.MyModel");
ValidationTester.TestNotifyDataErrorInfo(instance);
}
[Test]
public void NotifyDataErrorInfoWithImplementation()
{
var instance = assembly.GetInstance("WithGenericExternal.ModelWithImplementation");
ValidationTester.TestNotifyDataErrorInfo(instance);
}
} | using System.IO;
using System.Reflection;
using NUnit.Framework;
[TestFixture]
public class GenericExternalTests
{
string afterAssemblyPath;
Assembly assembly;
public GenericExternalTests()
{
AppDomainAssemblyFinder.Attach();
var beforeAssemblyPath = Path.GetFullPath(@"..\..\..\WithGenericExternal\bin\Debug\WithGenericExternal.dll");
#if (!DEBUG)
beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release");
#endif
afterAssemblyPath = WeaverHelper.Weave(beforeAssemblyPath);
assembly = Assembly.LoadFile(afterAssemblyPath);
}
[Test]
public void DataErrorInfo()
{
var instance = assembly.GetInstance("WithGenericExternal.Model");
ValidationTester.TestDataErrorInfo(instance);
}
[Test]
public void DataErrorInfoWithImplementation()
{
var instance = assembly.GetInstance("WithGenericExternal.ModelWithImplementation");
ValidationTester.TestDataErrorInfo(instance);
}
#if(DEBUG)
[Test]
public void PeVerify()
{
Verifier.Verify(afterAssemblyPath);
}
#endif
[Test]
public void NotifyDataErrorInfo()
{
var instance = assembly.GetInstance("WithGenericExternal.Model");
ValidationTester.TestNotifyDataErrorInfo(instance);
}
[Test]
public void NotifyDataErrorInfoWithImplementation()
{
var instance = assembly.GetInstance("WithGenericExternal.ModelWithImplementation");
ValidationTester.TestNotifyDataErrorInfo(instance);
}
} | mit | C# |
2a31739302c818e32444a0e4608b627acb179613 | Update doc comment for RazorInjectAttribute (#11554) | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Mvc/Mvc.Razor/src/Internal/RazorInjectAttribute.cs | src/Mvc/Mvc.Razor/src/Internal/RazorInjectAttribute.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Microsoft.AspNetCore.Mvc.Razor.Internal
{
/// <summary>
/// Specifies that the attributed property should be bound using request services.
/// <para>
/// This attribute is used as the backing attribute for the <code>@inject</code>
/// Razor directive.
/// </para>
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class RazorInjectAttribute : Attribute
{
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Microsoft.AspNetCore.Mvc.Razor.Internal
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class RazorInjectAttribute : Attribute
{
}
} | apache-2.0 | C# |
551b663f78da91aba94083b200299d5cfeee52aa | Fix for display of hours | Red-Folder/red-folder.com,Red-Folder/red-folder.com,Red-Folder/red-folder.com | src/Red-Folder.com/Views/Shared/_PodcastMetrics.cshtml | src/Red-Folder.com/Views/Shared/_PodcastMetrics.cshtml | @model RedFolder.Podcast.Models.PodcastMetrics
<div class="podcast-metrics">
<div>
<h3 class="title">Number of episodes</h3>
<p class="metric">
@Model.NumberOfEpisodes
</p>
</div>
<div>
<h3 class="title">Total duration</h3>
<p class="metric">
@Model.TotalDuration.TotalHours.ToString("###") Hours, @Model.TotalDuration.Minutes Minutes
</p>
</div>
</div> | @model RedFolder.Podcast.Models.PodcastMetrics
<div class="podcast-metrics">
<div>
<h3 class="title">Number of episodes</h3>
<p class="metric">
@Model.NumberOfEpisodes
</p>
</div>
<div>
<h3 class="title">Total duration</h3>
<p class="metric">
@Model.TotalDuration.Hours Hours, @Model.TotalDuration.Minutes Minutes
</p>
</div>
</div> | mit | C# |
9e0b9ec9eb5a29a510428e05d5c16d5500b5dd70 | Increment assembly version | Sunlighter/AsyncQueues | AsyncQueueLib/Properties/AssemblyInfo.cs | AsyncQueueLib/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("AsyncQueueLib")]
[assembly: AssemblyDescription("Asynchronous Queuing Library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Sunlighter")]
[assembly: AssemblyProduct("AsyncQueueLib")]
[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("81b20c3a-e64a-4f60-8f87-8f67160a63c1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.1.0")]
[assembly: AssemblyFileVersion("1.0.1.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("AsyncQueueLib")]
[assembly: AssemblyDescription("Asynchronous Queuing Library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Sunlighter")]
[assembly: AssemblyProduct("AsyncQueueLib")]
[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("81b20c3a-e64a-4f60-8f87-8f67160a63c1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
8352cb7313302e869dcd9bc56078a2aa22d3ab2f | Check if property has setter | davidsonsousa/CMSEngine,davidsonsousa/CMSEngine,davidsonsousa/CMSEngine,davidsonsousa/CMSEngine | CMSEngine/Extensions/ObjectExtensions.cs | CMSEngine/Extensions/ObjectExtensions.cs | using System.Linq;
namespace CmsEngine.Extensions
{
public static class ObjectExtensions
{
public static object MapTo(this object source, object target)
{
foreach (var sourceProp in source.GetType().GetProperties())
{
var targetProp = target.GetType().GetProperties().Where(p => p.Name == sourceProp.Name).FirstOrDefault();
if (targetProp != null && targetProp.CanWrite && targetProp.GetSetMethod() != null && targetProp.GetType().Name == sourceProp.GetType().Name)
{
targetProp.SetValue(target, sourceProp.GetValue(source));
}
}
return target;
}
}
}
| using System.Linq;
namespace CmsEngine.Extensions
{
public static class ObjectExtensions
{
public static object MapTo(this object source, object target)
{
foreach (var sourceProp in source.GetType().GetProperties())
{
var targetProp = target.GetType().GetProperties().Where(p => p.Name == sourceProp.Name).FirstOrDefault();
if (targetProp != null && targetProp.GetType().Name == sourceProp.GetType().Name)
{
targetProp.SetValue(target, sourceProp.GetValue(source));
}
}
return target;
}
}
}
| mit | C# |
3158f700748a6724865820901174cbfacd0670b1 | Trim leading slash on AdminUrlPrefix (#5193) | petedavis/Orchard2,xkproject/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,stevetayloruk/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,petedavis/Orchard2 | src/OrchardCore/OrchardCore.Admin.Abstractions/AdminOptions.cs | src/OrchardCore/OrchardCore.Admin.Abstractions/AdminOptions.cs | namespace OrchardCore.Admin
{
public class AdminOptions
{
private string _adminUrlPrefix = "Admin";
public string AdminUrlPrefix
{
get => _adminUrlPrefix;
set => _adminUrlPrefix = value.Trim(' ', '/');
}
}
}
| namespace OrchardCore.Admin
{
public class AdminOptions
{
public string AdminUrlPrefix { get; set; } = "Admin";
}
}
| bsd-3-clause | C# |
2649c4d57cb1e4d9d940350acd1260f4717898a3 | Check if the syntax list has any elements before calling .First() | dotnet/roslyn-analyzers,mavasani/roslyn-analyzers,genlu/roslyn-analyzers,mattwar/roslyn-analyzers,bkoelman/roslyn-analyzers,pakdev/roslyn-analyzers,mavasani/roslyn-analyzers,Anniepoh/roslyn-analyzers,natidea/roslyn-analyzers,SpotLabsNET/roslyn-analyzers,heejaechang/roslyn-analyzers,jinujoseph/roslyn-analyzers,dotnet/roslyn-analyzers,srivatsn/roslyn-analyzers,pakdev/roslyn-analyzers,qinxgit/roslyn-analyzers,jasonmalinowski/roslyn-analyzers | src/Roslyn/Core/Documentation/DoNotUseVerbatimCrefsAnalyzer.cs | src/Roslyn/Core/Documentation/DoNotUseVerbatimCrefsAnalyzer.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Roslyn.Diagnostics.Analyzers.Documentation
{
public abstract class DoNotUseVerbatimCrefsAnalyzer : DiagnosticAnalyzer
{
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(RoslynDiagnosticsResources.UseProperCrefTagsTitle), RoslynDiagnosticsResources.ResourceManager, typeof(RoslynDiagnosticsResources));
private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(RoslynDiagnosticsResources.UseProperCrefTagsMessage), RoslynDiagnosticsResources.ResourceManager, typeof(RoslynDiagnosticsResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(RoslynDiagnosticsResources.UseProperCrefTagsDescription), RoslynDiagnosticsResources.ResourceManager, typeof(RoslynDiagnosticsResources));
internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(
RoslynDiagnosticIds.DoNotUseVerbatimCrefsRuleId,
title: s_localizableTitle,
messageFormat: s_localizableMessage,
category: "Documentation",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
customTags: WellKnownDiagnosticTags.Telemetry,
description: s_localizableDescription);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(Rule);
}
}
protected void ProcessAttribute(SyntaxNodeAnalysisContext context, SyntaxTokenList textTokens)
{
if (!textTokens.Any())
{
return;
}
var token = textTokens.First();
if (token.Span.Length >= 2)
{
var text = token.Text;
if (text[1] == ':')
{
var location = Location.Create(token.SyntaxTree, textTokens.Span);
context.ReportDiagnostic(Diagnostic.Create(Rule, location, text.Substring(0, 2)));
}
}
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Roslyn.Diagnostics.Analyzers.Documentation
{
public abstract class DoNotUseVerbatimCrefsAnalyzer : DiagnosticAnalyzer
{
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(RoslynDiagnosticsResources.UseProperCrefTagsTitle), RoslynDiagnosticsResources.ResourceManager, typeof(RoslynDiagnosticsResources));
private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(RoslynDiagnosticsResources.UseProperCrefTagsMessage), RoslynDiagnosticsResources.ResourceManager, typeof(RoslynDiagnosticsResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(RoslynDiagnosticsResources.UseProperCrefTagsDescription), RoslynDiagnosticsResources.ResourceManager, typeof(RoslynDiagnosticsResources));
internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(
RoslynDiagnosticIds.DoNotUseVerbatimCrefsRuleId,
title: s_localizableTitle,
messageFormat: s_localizableMessage,
category: "Documentation",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
customTags: WellKnownDiagnosticTags.Telemetry,
description: s_localizableDescription);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(Rule);
}
}
protected void ProcessAttribute(SyntaxNodeAnalysisContext context, SyntaxTokenList textTokens)
{
var token = textTokens.First();
if (token.Span.Length >= 2)
{
var text = token.Text;
if (text[1] == ':')
{
var location = Location.Create(token.SyntaxTree, textTokens.Span);
context.ReportDiagnostic(Diagnostic.Create(Rule, location, text.Substring(0, 2)));
}
}
}
}
}
| mit | C# |
094c339159ebbbf75e3165b6ccdeb5b7071c74d9 | Fix threading issue with GetRolesForProperty. | rockfordlhotka/csla,ronnymgm/csla-light,JasonBock/csla,jonnybee/csla,rockfordlhotka/csla,JasonBock/csla,jonnybee/csla,MarimerLLC/csla,ronnymgm/csla-light,jonnybee/csla,MarimerLLC/csla,BrettJaner/csla,MarimerLLC/csla,JasonBock/csla,BrettJaner/csla,rockfordlhotka/csla,BrettJaner/csla,ronnymgm/csla-light | cslacs/Csla/Security/AuthorizationRulesManager.cs | cslacs/Csla/Security/AuthorizationRulesManager.cs | using System;
using System.Collections.Generic;
using System.Security.Principal;
namespace Csla.Security
{
/// <summary>
/// Maintains authorization roles for a business object
/// or business object type.
/// </summary>
public class AuthorizationRulesManager
{
private Dictionary<string, RolesForProperty> _rules;
internal Dictionary<string, RolesForProperty> RulesList
{
get
{
if (_rules == null)
_rules = new Dictionary<string, RolesForProperty>();
return _rules;
}
}
#region Get Roles
private static object _rolesLock = new object();
internal RolesForProperty GetRolesForProperty(string propertyName)
{
RolesForProperty currentRoles = null;
if (!RulesList.TryGetValue(propertyName, out currentRoles))
{
lock (_rolesLock)
{
if (!RulesList.TryGetValue(propertyName, out currentRoles))
{
currentRoles = new RolesForProperty();
RulesList.Add(propertyName, currentRoles);
}
}
}
return currentRoles;
}
#endregion
#region IsInRole
internal static bool PrincipalRoleInList(IPrincipal principal, List<string> roleList)
{
bool result = false;
foreach (string role in roleList)
{
if (IsInRole(principal, role))
{
result = true;
break;
}
}
return result;
}
private static IsInRoleProvider mIsInRoleProvider;
private static bool IsInRole(IPrincipal principal, string role)
{
if (mIsInRoleProvider == null)
{
string provider = ApplicationContext.IsInRoleProvider;
if (string.IsNullOrEmpty(provider))
mIsInRoleProvider = IsInRoleDefault;
else
{
string[] items = provider.Split(',');
Type containingType = Type.GetType(items[0] + "," + items[1]);
mIsInRoleProvider = (IsInRoleProvider)(Delegate.CreateDelegate(typeof(IsInRoleProvider), containingType, items[2]));
}
}
return mIsInRoleProvider(principal, role);
}
private static bool IsInRoleDefault(IPrincipal principal, string role)
{
return principal.IsInRole(role);
}
#endregion
}
/// <summary>
/// Delegate for the method called when the a role
/// needs to be checked for the current user.
/// </summary>
/// <param name="principal">
/// The current security principal object.
/// </param>
/// <param name="role">
/// The role to be checked.
/// </param>
/// <returns>
/// True if the current user is in the specified role.
/// </returns>
public delegate bool IsInRoleProvider(IPrincipal principal, string role);
}
| using System;
using System.Collections.Generic;
using System.Security.Principal;
namespace Csla.Security
{
/// <summary>
/// Maintains authorization roles for a business object
/// or business object type.
/// </summary>
public class AuthorizationRulesManager
{
private Dictionary<string, RolesForProperty> _rules;
internal Dictionary<string, RolesForProperty> RulesList
{
get
{
if (_rules == null)
_rules = new Dictionary<string, RolesForProperty>();
return _rules;
}
}
#region Get Roles
internal RolesForProperty GetRolesForProperty(string propertyName)
{
RolesForProperty currentRoles = null;
if (!RulesList.TryGetValue(propertyName, out currentRoles))
{
currentRoles = new RolesForProperty();
RulesList.Add(propertyName, currentRoles);
}
return currentRoles;
}
#endregion
#region IsInRole
internal static bool PrincipalRoleInList(IPrincipal principal, List<string> roleList)
{
bool result = false;
foreach (string role in roleList)
{
if (IsInRole(principal, role))
{
result = true;
break;
}
}
return result;
}
private static IsInRoleProvider mIsInRoleProvider;
private static bool IsInRole(IPrincipal principal, string role)
{
if (mIsInRoleProvider == null)
{
string provider = ApplicationContext.IsInRoleProvider;
if (string.IsNullOrEmpty(provider))
mIsInRoleProvider = IsInRoleDefault;
else
{
string[] items = provider.Split(',');
Type containingType = Type.GetType(items[0] + "," + items[1]);
mIsInRoleProvider = (IsInRoleProvider)(Delegate.CreateDelegate(typeof(IsInRoleProvider), containingType, items[2]));
}
}
return mIsInRoleProvider(principal, role);
}
private static bool IsInRoleDefault(IPrincipal principal, string role)
{
return principal.IsInRole(role);
}
#endregion
}
/// <summary>
/// Delegate for the method called when the a role
/// needs to be checked for the current user.
/// </summary>
/// <param name="principal">
/// The current security principal object.
/// </param>
/// <param name="role">
/// The role to be checked.
/// </param>
/// <returns>
/// True if the current user is in the specified role.
/// </returns>
public delegate bool IsInRoleProvider(IPrincipal principal, string role);
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.