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 |
|---|---|---|---|---|---|---|---|---|
656fb955969774f28c3086a4aced7450aceacf40 | Add TouchingWall condition to BodyCollider. | jguarShark/Unity2D-Components,cmilr/Unity2D-Components | Actor/BodyCollider.cs | Actor/BodyCollider.cs | using UnityEngine;
using System.Collections;
using Matcha.Lib;
[RequireComponent(typeof(BoxCollider2D))]
public class BodyCollider : CacheBehaviour
{
private bool alreadyCollided;
private PickupEntity pickupEntity;
private EntityBehaviour entityBehaviour;
// private CharacterEntity charEntity;
void Start()
{
base.CacheComponents();
MLib2D.IgnoreLayerCollisionWith(gameObject, "One-Way Platform", true);
MLib2D.IgnoreLayerCollisionWith(gameObject, "Platform", true);
}
void OnTriggerEnter2D(Collider2D coll)
{
GetColliderComponents(coll);
if (coll.tag == "Prize" && !alreadyCollided)
{
Messenger.Broadcast<int>("prize collected", pickupEntity.worth);
pickupEntity.React();
}
if (coll.tag == "Enemy" && !alreadyCollided)
{
Messenger.Broadcast<string, Collider2D>("player dead", "StruckDown", coll);
}
if (coll.tag == "Water" && !alreadyCollided)
{
Messenger.Broadcast<string, Collider2D>("player dead", "Drowned", coll);
}
if (coll.tag == "Wall" && !alreadyCollided)
{
Debug.Log("Hit Wall!!");
}
}
void GetColliderComponents(Collider2D coll)
{
pickupEntity = coll.GetComponent<PickupEntity>() as PickupEntity;
// charEntity = coll.GetComponent<CharacterEntity>() as CharacterEntity;
if (coll.GetComponent<EntityBehaviour>())
{
entityBehaviour = coll.GetComponent<EntityBehaviour>();
alreadyCollided = entityBehaviour.alreadyCollided;
}
}
} | using UnityEngine;
using System.Collections;
using Matcha.Lib;
[RequireComponent(typeof(BoxCollider2D))]
public class BodyCollider : CacheBehaviour
{
private bool alreadyCollided;
private PickupEntity pickupEntity;
private EntityBehaviour entityBehaviour;
// private CharacterEntity charEntity;
void Start()
{
base.CacheComponents();
MLib2D.IgnoreLayerCollisionWith(gameObject, "One-Way Platform", true);
MLib2D.IgnoreLayerCollisionWith(gameObject, "Platform", true);
}
void OnTriggerEnter2D(Collider2D coll)
{
GetColliderComponents(coll);
if (coll.tag == "Prize" && !alreadyCollided)
{
Messenger.Broadcast<int>("prize collected", pickupEntity.worth);
pickupEntity.React();
}
if (coll.tag == "Enemy" && !alreadyCollided)
{
Messenger.Broadcast<string, Collider2D>("player dead", "StruckDown", coll);
}
if (coll.tag == "Water" && !alreadyCollided)
{
Messenger.Broadcast<string, Collider2D>("player dead", "Drowned", coll);
}
}
void GetColliderComponents(Collider2D coll)
{
pickupEntity = coll.GetComponent<PickupEntity>() as PickupEntity;
// charEntity = coll.GetComponent<CharacterEntity>() as CharacterEntity;
if (coll.GetComponent<EntityBehaviour>())
{
entityBehaviour = coll.GetComponent<EntityBehaviour>();
alreadyCollided = entityBehaviour.alreadyCollided;
}
}
} | mit | C# |
79826b0632960774e9d580fa4d6fe318b94e12cc | Update AdUnitSelectorOptions.cs | tiksn/TIKSN-Framework | TIKSN.Core/Advertising/AdUnitSelectorOptions.cs | TIKSN.Core/Advertising/AdUnitSelectorOptions.cs | namespace TIKSN.Advertising
{
public class AdUnitSelectorOptions
{
public AdUnitSelectorOptions()
{
IsDebuggerSensitive = true;
IsDebug = false;
}
public bool IsDebuggerSensitive { get; set; }
public bool IsDebug { get; set; }
}
} | namespace TIKSN.Advertising
{
public class AdUnitSelectorOptions
{
public AdUnitSelectorOptions()
{
IsDebuggerSensitive = true;
IsDebug = false;
}
public bool IsDebuggerSensitive { get; set; }
public bool IsDebug { get; set; }
}
} | mit | C# |
f0bb424d5c93fc0844bf04a0676675d941976f46 | Fix condition | bartlomiejwolk/OnCollisionActivate | GameObjectActivate.cs | GameObjectActivate.cs | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace GameObjectActivator {
/// Enable child game object on collision with
/// other game object.
public class GameObjectActivate : MonoBehaviour {
private List<ObjectToEnable> objsToEnable = new List<ObjectToEnable>();
public List<ObjectToEnable> ObjsToEnable {
get { return objsToEnable; }
set { objsToEnable = value; }
}
/// Handle collision.
// todo refactor
public void OnCollisionEnable(RaycastHit hitInfo) {
var hitGOTag = hitInfo.transform.gameObject.tag;
foreach (ObjectToEnable obj in ObjsToEnable) {
switch (obj.TagOption) {
case TagOptions.Include:
if (hitGOTag != obj.ExcludeTag) {
break;
}
obj.ObjToEnable.SetActive(true);
break;
case TagOptions.Exclude:
// Don't enable target object when hit a GO
// with excluded tag.
if (hitGOTag == obj.ExcludeTag) {
break;
}
obj.ObjToEnable.SetActive(true);
break;
}
}
}
}
}
| using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace GameObjectActivator {
/// Enable child game object on collision with
/// other game object.
public class GameObjectActivate : MonoBehaviour {
private List<ObjectToEnable> objsToEnable = new List<ObjectToEnable>();
public List<ObjectToEnable> ObjsToEnable {
get { return objsToEnable; }
set { objsToEnable = value; }
}
/// Handle collision.
// todo refactor
public void OnCollisionEnable(RaycastHit hitInfo) {
var hitGOTag = hitInfo.transform.gameObject.tag;
foreach (ObjectToEnable obj in ObjsToEnable) {
switch (obj.TagOption) {
case TagOptions.Include:
if (tag != obj.ExcludeTag) {
break;
}
obj.ObjToEnable.SetActive(true);
break;
case TagOptions.Exclude:
// Don't enable target object when hit a GO
// with excluded tag.
if (tag == obj.ExcludeTag) {
break;
}
obj.ObjToEnable.SetActive(true);
break;
}
}
}
}
}
| mit | C# |
45be368da834e07905777adb87343cb9504adbcc | Update SumOfSelfPowers.cs | DuckBoss/Programming-Challenges,DuckBoss/Programming-Challenges,DuckBoss/Programming-Challenges,DuckBoss/Programming-Challenges | Sum_Of_Self_Powers/SumOfSelfPowers.cs | Sum_Of_Self_Powers/SumOfSelfPowers.cs | using System;
namespace SumOfSelfPowers
{
class MainClass
{
public static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("This program requires 1 integer input");
Environment.Exit(0);
}
long totalSum = 0;
int inputtedNum = Convert.ToInt32(args[0]);
for (int i = 1; i <= inputtedNum; i++)
{
long val = (long)Math.Pow(i, i);
totalSum += val;
Console.WriteLine(val);
}
Console.WriteLine("Total Sum - " + totalSum);
Console.WriteLine();
Console.ReadKey();
}
}
}
| using System;
namespace SumOfSelfPowers
{
class MainClass
{
public static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("This program requires 1 integer input");
Environment.Exit(0);
}
long totalSum = 0;
int inputtedNum = Convert.ToInt32(args[0]);
for (int i = 1; i <= inputtedNum; i++)
{
long val = (long)Math.Pow(i, i);
totalSum += val;
Console.WriteLine(val);
}
Console.WriteLine("Total Sum - " + totalSum);
Console.WriteLine();
Console.ReadKey();
}
}
}
| unlicense | C# |
580b0a9b9fc15b026b02dfbc029c91535fbc838e | Allow negative GAF frame offsets | MHeasell/TAUtil,MHeasell/TAUtil | TAUtil/Gaf/Structures/GafFrameData.cs | TAUtil/Gaf/Structures/GafFrameData.cs | namespace TAUtil.Gaf.Structures
{
using System.IO;
internal struct GafFrameData
{
public ushort Width;
public ushort Height;
public short XPos;
public short YPos;
public byte TransparencyIndex;
public bool Compressed;
public ushort FramePointers;
public uint Unknown2;
public uint PtrFrameData;
public uint Unknown3;
public static void Read(BinaryReader b, ref GafFrameData e)
{
e.Width = b.ReadUInt16();
e.Height = b.ReadUInt16();
e.XPos = b.ReadInt16();
e.YPos = b.ReadInt16();
e.TransparencyIndex = b.ReadByte();
e.Compressed = b.ReadBoolean();
e.FramePointers = b.ReadUInt16();
e.Unknown2 = b.ReadUInt32();
e.PtrFrameData = b.ReadUInt32();
e.Unknown3 = b.ReadUInt32();
}
}
}
| namespace TAUtil.Gaf.Structures
{
using System.IO;
internal struct GafFrameData
{
public ushort Width;
public ushort Height;
public ushort XPos;
public ushort YPos;
public byte TransparencyIndex;
public bool Compressed;
public ushort FramePointers;
public uint Unknown2;
public uint PtrFrameData;
public uint Unknown3;
public static void Read(BinaryReader b, ref GafFrameData e)
{
e.Width = b.ReadUInt16();
e.Height = b.ReadUInt16();
e.XPos = b.ReadUInt16();
e.YPos = b.ReadUInt16();
e.TransparencyIndex = b.ReadByte();
e.Compressed = b.ReadBoolean();
e.FramePointers = b.ReadUInt16();
e.Unknown2 = b.ReadUInt32();
e.PtrFrameData = b.ReadUInt32();
e.Unknown3 = b.ReadUInt32();
}
}
}
| mit | C# |
7d57e1a2691b0cb23184265727ac0dbffc50a77b | bump version | Fody/Validar | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Validar")]
[assembly: AssemblyProduct("Validar")]
[assembly: AssemblyVersion("1.4.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")]
| using System.Reflection;
[assembly: AssemblyTitle("Validar")]
[assembly: AssemblyProduct("Validar")]
[assembly: AssemblyVersion("1.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
| mit | C# |
67e1a83ae843830a75fad1566ca968fa66ef514a | Create completed pomodoro in db async | YetAnotherPomodoroApp/YAPA-2 | YAPA.Shared/Common/DashboardPlugin.cs | YAPA.Shared/Common/DashboardPlugin.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YAPA.Shared.Contracts;
namespace YAPA.Shared.Common
{
public class Dashboard : IPlugin
{
private readonly IPomodoroRepository _itemRepository;
public Dashboard(IPomodoroEngine engine, IPomodoroRepository itemRepository)
{
_itemRepository = itemRepository;
engine.OnPomodoroCompleted += _engine_OnPomodoroCompleted;
}
public IEnumerable<PomodoroEntity> GetPomodoros()
{
//last 4 full months + current
var date = DateTime.Now.Date.AddMonths(-4);
var fromDate = new DateTime(date.Year, date.Month, 01, 0, 0, 0, 0, DateTimeKind.Utc);
var totalDays = (int)(DateTime.Now.Date - fromDate).TotalDays;
var emptyPomodoros = Enumerable.Range(0, totalDays + 1).Select(x => new PomodoroEntity() { Count = 0, DateTime = fromDate.AddDays(x) }).ToList();
var capturedPomodoros = _itemRepository.Pomodoros.Where(x => x.DateTime >= fromDate).ToList();
var joinedPomodoros = capturedPomodoros.Union(emptyPomodoros)
.GroupBy(c => c.DateTime.Date, c => c.Count,
(time, ints) => new PomodoroEntity() { DateTime = time, Count = ints.Sum(x => x) });
return joinedPomodoros.OrderBy(x => x.DateTime.Date);
}
public int CompletedToday()
{
var today = DateTime.Now.Date;
return _itemRepository.Pomodoros.Where(x => x.DateTime == today).Select(a => a.Count).DefaultIfEmpty(0).Sum();
}
private void _engine_OnPomodoroCompleted()
{
Task.Run(() =>
{
_itemRepository.Add(new PomodoroEntity { Count = 1, DateTime = DateTime.UtcNow.Date });
});
}
}
public class DashboardSettings : IPluginSettings
{
private readonly ISettingsForComponent _settings;
public DashboardSettings(ISettings settings)
{
_settings = settings.GetSettingsForComponent(nameof(Dashboard));
}
public void DeferChanges()
{
_settings.DeferChanges();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using YAPA.Shared.Contracts;
namespace YAPA.Shared.Common
{
public class Dashboard : IPlugin
{
private readonly IPomodoroRepository _itemRepository;
public Dashboard(IPomodoroEngine engine, IPomodoroRepository itemRepository)
{
_itemRepository = itemRepository;
engine.OnPomodoroCompleted += _engine_OnPomodoroCompleted;
}
public IEnumerable<PomodoroEntity> GetPomodoros()
{
//last 4 full months + current
var date = DateTime.Now.Date.AddMonths(-4);
var fromDate = new DateTime(date.Year, date.Month, 01, 0, 0, 0, 0, DateTimeKind.Utc);
var totalDays = (int)(DateTime.Now.Date - fromDate).TotalDays;
var emptyPomodoros = Enumerable.Range(0, totalDays + 1).Select(x => new PomodoroEntity() { Count = 0, DateTime = fromDate.AddDays(x) }).ToList();
var capturedPomodoros = _itemRepository.Pomodoros.Where(x => x.DateTime >= fromDate).ToList();
var joinedPomodoros = capturedPomodoros.Union(emptyPomodoros)
.GroupBy(c => c.DateTime.Date, c => c.Count,
(time, ints) => new PomodoroEntity() { DateTime = time, Count = ints.Sum(x => x) });
return joinedPomodoros.OrderBy(x => x.DateTime.Date);
}
public int CompletedToday()
{
var today = DateTime.Now.Date;
return _itemRepository.Pomodoros.Where(x => x.DateTime == today).Select(a => a.Count).DefaultIfEmpty(0).Sum();
}
private void _engine_OnPomodoroCompleted()
{
_itemRepository.Add(new PomodoroEntity { Count = 1, DateTime = DateTime.UtcNow.Date });
}
}
public class DashboardSettings : IPluginSettings
{
private readonly ISettingsForComponent _settings;
public DashboardSettings(ISettings settings)
{
_settings = settings.GetSettingsForComponent(nameof(Dashboard));
}
public void DeferChanges()
{
_settings.DeferChanges();
}
}
}
| mit | C# |
b635c564061eb1deee4eb0bb20b67ad9adc9fbd8 | Fix bitmap serialization with indexed format bitmaps | MHeasell/TAUtil,MHeasell/TAUtil | TAUtil.Gdi/Bitmap/BitmapSerializer.cs | TAUtil.Gdi/Bitmap/BitmapSerializer.cs | namespace TAUtil.Gdi.Bitmap
{
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using TAUtil.Gdi.Palette;
/// <summary>
/// Serializes a 32-bit Bitmap instance into raw 8-bit indexed color data.
/// The mapping from color to index is done according to the given
/// reverse palette lookup.
/// </summary>
public class BitmapSerializer
{
private readonly IPalette palette;
public BitmapSerializer(IPalette palette)
{
this.palette = palette;
}
public byte[] ToBytes(Bitmap bitmap)
{
int length = bitmap.Width * bitmap.Height;
byte[] output = new byte[length];
this.Serialize(new MemoryStream(output, true), bitmap);
return output;
}
public void Serialize(Stream output, Bitmap bitmap)
{
Rectangle r = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
BitmapData data = bitmap.LockBits(r, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
int length = bitmap.Width * bitmap.Height;
unsafe
{
int* pointer = (int*)data.Scan0;
for (int i = 0; i < length; i++)
{
Color c = Color.FromArgb(pointer[i]);
output.WriteByte((byte)this.palette.LookUp(c));
}
}
bitmap.UnlockBits(data);
}
}
} | namespace TAUtil.Gdi.Bitmap
{
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using TAUtil.Gdi.Palette;
/// <summary>
/// Serializes a 32-bit Bitmap instance into raw 8-bit indexed color data.
/// The mapping from color to index is done according to the given
/// reverse palette lookup.
/// </summary>
public class BitmapSerializer
{
private readonly IPalette palette;
public BitmapSerializer(IPalette palette)
{
this.palette = palette;
}
public byte[] ToBytes(Bitmap bitmap)
{
int length = bitmap.Width * bitmap.Height;
byte[] output = new byte[length];
this.Serialize(new MemoryStream(output, true), bitmap);
return output;
}
public void Serialize(Stream output, Bitmap bitmap)
{
Rectangle r = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
BitmapData data = bitmap.LockBits(r, ImageLockMode.ReadOnly, bitmap.PixelFormat);
int length = bitmap.Width * bitmap.Height;
unsafe
{
int* pointer = (int*)data.Scan0;
for (int i = 0; i < length; i++)
{
Color c = Color.FromArgb(pointer[i]);
output.WriteByte((byte)this.palette.LookUp(c));
}
}
bitmap.UnlockBits(data);
}
}
} | mit | C# |
4be2577c802c54093f22fa6b7d422a0a53b0f56f | Increment minor -> 0.11.0 | awseward/Bugsnag.NET,awseward/Bugsnag.NET | SharedAssemblyInfo.cs | SharedAssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("0.11.0.0")]
[assembly: AssemblyFileVersion("0.11.0.0")]
[assembly: AssemblyInformationalVersion("0.11.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("0.10.0.0")]
[assembly: AssemblyFileVersion("0.10.0.0")]
[assembly: AssemblyInformationalVersion("0.10.0")]
| mit | C# |
0041f1bdf9c8d64fae0fb5512351f5be4fec757c | update version | DevExpress/AjaxControlToolkit,DevExpress/AjaxControlToolkit,DevExpress/AjaxControlToolkit | SharedAssemblyInfo.cs | SharedAssemblyInfo.cs | using System.Reflection;
using System.Resources;
// WARNING this file is shared accross multiple projects
[assembly: AssemblyProduct("ASP.NET AJAX Control Toolkit")]
[assembly: AssemblyCopyright("Copyright © CodePlex Foundation 2012-2017")]
[assembly: AssemblyCompany("CodePlex Foundation")]
[assembly: AssemblyVersion("18.1.0.0")]
[assembly: AssemblyFileVersion("18.1.0.0")]
[assembly: NeutralResourcesLanguage("en-US")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
| using System.Reflection;
using System.Resources;
// WARNING this file is shared accross multiple projects
[assembly: AssemblyProduct("ASP.NET AJAX Control Toolkit")]
[assembly: AssemblyCopyright("Copyright © CodePlex Foundation 2012-2017")]
[assembly: AssemblyCompany("CodePlex Foundation")]
[assembly: AssemblyVersion("17.1.2.0")]
[assembly: AssemblyFileVersion("17.1.2.0")]
[assembly: NeutralResourcesLanguage("en-US")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
| bsd-3-clause | C# |
cd8b61486f5e0851fdeeee7b7508e3a8cc79c69e | fix build | jhgbrt/joincs | JoinCSharp/Program.cs | JoinCSharp/Program.cs | using System;
using System.IO;
using System.Linq;
namespace JoinCSharp
{
class Program
{
static int Main(string[] args)
{
if (args.Length < 1 || args.Length > 2)
{
Console.WriteLine("usage: joincs inputfolder [outputfile]");
return 1;
}
var inputDirectory = args[0];
if (!Directory.Exists(inputDirectory))
{
Console.WriteLine("{0}: directory not found", inputDirectory);
return 1;
}
var files = Directory.GetFiles(inputDirectory, "*.cs", SearchOption.AllDirectories);
if (!files.Any())
{
Console.WriteLine("No .cs files found in folder {0}", inputDirectory);
return 1;
}
try
{
var sources = files.Select(File.ReadAllText);
var output = Joiner.Join(sources);
if (args.Length == 2)
{
File.WriteAllText(args[1], output);
}
else
{
Console.WriteLine(output);
}
return 0;
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
return 1;
}
}
}
}
| using System;
using System.IO;
using System.Linq;
namespace JoinCSharp
{
class Program
{
static int Main(string[] args)
{
if (args.Length < 1 || args.Length > 2)
{
Console.WriteLine("usage: joincs inputfolder [outputfile]");
return 1;
}
var inputDirectory = args[0];
if (!Directory.Exists(inputDirectory))
{
Console.WriteLine($"{inputDirectory}: directory not found");
return 1;
}
var files = Directory.GetFiles(inputDirectory, "*.cs", SearchOption.AllDirectories);
if (!files.Any())
{
Console.WriteLine($"No .cs files found in folder {inputDirectory}");
return 1;
}
try
{
var sources = files.Select(File.ReadAllText);
var output = Joiner.Join(sources);
if (args.Length == 2)
{
File.WriteAllText(args[1], output);
}
else
{
Console.WriteLine(output);
}
return 0;
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
return 1;
}
}
}
}
| mit | C# |
18251debc7562dcb2890d2b0bfe7a418c194951f | Increment patch -> 0.8.1 | awseward/Bugsnag.NET,awseward/Bugsnag.NET | SharedAssemblyInfo.cs | SharedAssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("0.8.1.0")]
[assembly: AssemblyFileVersion("0.8.1.0")]
[assembly: AssemblyInformationalVersion("0.8.1")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("0.8.0.0")]
[assembly: AssemblyFileVersion("0.8.0.0")]
[assembly: AssemblyInformationalVersion("0.8.0")]
| mit | C# |
bbcf10b3981ef07108a9119542ba8ff36655967a | fix random error on kerrb page titles | andrewconnell/aci-orchardcms,andrewconnell/aci-orchardcms,andrewconnell/aci-orchardcms,andrewconnell/aci-orchardcms | Themes/Kerrb/Views/Parts.Title.cshtml | Themes/Kerrb/Views/Parts.Title.cshtml | @{
Layout.Title = Model.Title;
// figure out if this is a search bot
var searchBots = new List<string>() {"teoma", "alexa", "froogle", "gigabot", "inktomi", "looksmart", "url_spider_sql", "firefly", "nationaldirectory", "ask jeeves", "tecnoseek", "infoseek", "webfindbot", "girafabot", "crawler", "www.galaxy.com", "googlebot", "scooter", "slurp", "msnbot", "appie", "fast", "webbug", "spade", "zyborg", "rabaz", "baiduspider", "feedfetcher-google", "technoratisnoop", "rankivabot", "mediapartners-google", "sogou web spider", "webalta crawler", "facebookexternalhit"};
var requesterIsBot = false;
try{
foreach (var bot in searchBots){
if (Request.UserAgent.ToLower().Contains(bot))
{
requesterIsBot = true;
break;
}
}
} finally{
// swallow error... let requester is bot = default
}
}
@if(requesterIsBot){
<h1>@Model.Title</h1>
} else {
<script type="text/javascript">
$(document).ready(function($){
$("div.titleBox .container").prepend("<h1 class=\"big pull-left\">@(Model.Title)</h1>");
});
</script>
} | @{
Layout.Title = Model.Title;
// figure out if this is a search bot
var searchBots = new List<string>() {"teoma", "alexa", "froogle", "gigabot", "inktomi", "looksmart", "url_spider_sql", "firefly", "nationaldirectory", "ask jeeves", "tecnoseek", "infoseek", "webfindbot", "girafabot", "crawler", "www.galaxy.com", "googlebot", "scooter", "slurp", "msnbot", "appie", "fast", "webbug", "spade", "zyborg", "rabaz", "baiduspider", "feedfetcher-google", "technoratisnoop", "rankivabot", "mediapartners-google", "sogou web spider", "webalta crawler", "facebookexternalhit"};
var requesterIsBot = false;
foreach (var bot in searchBots){
if (Request.UserAgent.ToLower().Contains(bot))
{
requesterIsBot = true;
break;
}
}
}
@if(requesterIsBot){
<h1>@Model.Title</h1>
} else {
<script type="text/javascript">
$(document).ready(function($){
$("div.titleBox .container").prepend("<h1 class=\"big pull-left\">@(Model.Title)</h1>");
});
</script>
} | bsd-3-clause | C# |
e30e976acb717616d5e51157fb51a17434401c2c | fix endings | gregoryjscott/Simpler,gregoryjscott/Simpler,ResourceDataInc/Simpler.Data,ResourceDataInc/Simpler.Data,ResourceDataInc/Simpler.Data | app/Simpler/Data/Tasks/BuildDynamic.cs | app/Simpler/Data/Tasks/BuildDynamic.cs | using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
namespace Simpler.Data.Tasks
{
public class BuildDynamic : InOutTask<BuildDynamic.Input, BuildDynamic.Output>
{
public class Input
{
public IDataRecord DataRecord { get; set; }
}
public class Output
{
public dynamic Object { get; set; }
}
class Dynamic : DynamicObject
{
readonly Dictionary<string, object> _members = new Dictionary<string, object>();
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return _members.TryGetValue(binder.Name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_members[binder.Name.ToLower()] = value;
return true;
}
public void AddMember(string memberName, object memberValue)
{
_members[memberName] = memberValue;
}
}
public override void Execute()
{
Out.Object = new ExpandoObject();
var OutObject = Out.Object as IDictionary<string, Object>;
for (var i = 0; i < In.DataRecord.FieldCount; i++)
{
var columnName = In.DataRecord.GetName(i);
var columnValue = In.DataRecord[columnName];
if (columnValue.GetType() != typeof(System.DBNull))
{
OutObject.Add(columnName, columnValue);
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
namespace Simpler.Data.Tasks
{
public class BuildDynamic : InOutTask<BuildDynamic.Input, BuildDynamic.Output>
{
public class Input
{
public IDataRecord DataRecord { get; set; }
}
public class Output
{
public dynamic Object { get; set; }
}
class Dynamic : DynamicObject
{
readonly Dictionary<string, object> _members = new Dictionary<string, object>();
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return _members.TryGetValue(binder.Name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_members[binder.Name.ToLower()] = value;
return true;
}
public void AddMember(string memberName, object memberValue)
{
_members[memberName] = memberValue;
}
}
public override void Execute()
{
Out.Object = new ExpandoObject();
var OutObject = Out.Object as IDictionary<string, Object>;
for (var i = 0; i < In.DataRecord.FieldCount; i++)
{
var columnName = In.DataRecord.GetName(i);
var columnValue = In.DataRecord[columnName];
if (columnValue.GetType() != typeof(System.DBNull))
{
OutObject.Add(columnName, columnValue);
}
}
}
}
}
| mit | C# |
74ca335171d8fdf9e8b639c204a6f04e40435a4e | Document PoEItemFrameType | jcmoyer/Yeena | Yeena/PathOfExile/PoEItemFrameType.cs | Yeena/PathOfExile/PoEItemFrameType.cs | // Copyright 2013 J.C. Moyer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Yeena.PathOfExile {
/// <summary>
/// Represents an item's rarity.
/// </summary>
enum PoEItemFrameType {
Normal = 0,
Magic = 1,
Rare = 2,
Unique = 3,
}
}
| // Copyright 2013 J.C. Moyer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Yeena.PathOfExile {
enum PoEItemFrameType {
Normal = 0,
Magic = 1,
Rare = 2,
Unique = 3,
}
}
| apache-2.0 | C# |
73a63ce4b61e181da0f72443c5f1e029f3a0563f | Add copyright information | BinaryKits/ZPLUtility | ZPLUtility/Properties/AssemblyInfo.cs | ZPLUtility/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("ZPLUtility")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Binary Kits Pte. Ltd.")]
[assembly: AssemblyProduct("ZPLUtility")]
[assembly: AssemblyCopyright("BinaryKits Pte. Ltd. 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a836ca9d-cf58-4289-85f7-781eff51e091")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| 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("ZPLUtility")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Binary Kits Pte. Ltd.")]
[assembly: AssemblyProduct("ZPLUtility")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a836ca9d-cf58-4289-85f7-781eff51e091")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| mit | C# |
fab09575ec30d2cec7aef5487f59b6b8fa10732a | Add full testing flow for `BeatmapOffsetControl` | NeoAdonis/osu,NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu | osu.Game.Tests/Visual/Gameplay/TestSceneBeatmapOffsetControl.cs | osu.Game.Tests/Visual/Gameplay/TestSceneBeatmapOffsetControl.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.Linq;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Overlays.Settings;
using osu.Game.Scoring;
using osu.Game.Screens.Play.PlayerSettings;
using osu.Game.Tests.Visual.Ranking;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneBeatmapOffsetControl : OsuTestScene
{
private BeatmapOffsetControl offsetControl;
[SetUpSteps]
public void SetUpSteps()
{
AddStep("Create control", () =>
{
Child = new PlayerSettingsGroup("Some settings")
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
offsetControl = new BeatmapOffsetControl()
}
};
});
}
[Test]
public void TestDisplay()
{
const double average_error = -4.5;
AddAssert("Offset is neutral", () => offsetControl.Current.Value == 0);
AddAssert("No calibration button", () => !offsetControl.ChildrenOfType<SettingsButton>().Any());
AddStep("Set reference score", () =>
{
offsetControl.ReferenceScore.Value = new ScoreInfo
{
HitEvents = TestSceneHitEventTimingDistributionGraph.CreateDistributedHitEvents(average_error)
};
});
AddAssert("Has calibration button", () => offsetControl.ChildrenOfType<SettingsButton>().Any());
AddStep("Press button", () => offsetControl.ChildrenOfType<SettingsButton>().Single().TriggerClick());
AddAssert("Offset is adjusted", () => offsetControl.Current.Value == average_error);
AddStep("Remove reference score", () => offsetControl.ReferenceScore.Value = null);
AddAssert("No calibration button", () => !offsetControl.ChildrenOfType<SettingsButton>().Any());
}
}
}
| // 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 NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Screens.Play.PlayerSettings;
using osu.Game.Tests.Visual.Ranking;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneBeatmapOffsetControl : OsuTestScene
{
[Test]
public void TestDisplay()
{
Child = new PlayerSettingsGroup("Some settings")
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
new BeatmapOffsetControl(TestSceneHitEventTimingDistributionGraph.CreateDistributedHitEvents(-4.5))
}
};
}
}
}
| mit | C# |
fa76028679aa71e70ef4ba4c67450bc360cbba82 | Fix sendind admin msgs | gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer | Client/Systems/Admin/AdminMessageSender.cs | Client/Systems/Admin/AdminMessageSender.cs | using LunaClient.Base;
using LunaClient.Base.Interface;
using LunaClient.Network;
using LunaCommon.Message.Client;
using LunaCommon.Message.Data.Admin;
using LunaCommon.Message.Interface;
namespace LunaClient.Systems.Admin
{
public class AdminMessageSender : SubSystem<AdminSystem>, IMessageSender
{
public void SendMessage(IMessageData msg)
{
TaskFactory.StartNew(() => NetworkSender.QueueOutgoingMessage(MessageFactory.CreateNew<AdminCliMsg>(msg)));
}
public void SendBanPlayerMsg(string playerName)
{
var msgData = NetworkMain.CliMsgFactory.CreateNewMessageData<AdminBanMsgData>();
msgData.AdminPassword = System.AdminPassword;
msgData.PlayerName = playerName;
SendMessage(msgData);
}
public void SendKickPlayerMsg(string playerName)
{
var msgData = NetworkMain.CliMsgFactory.CreateNewMessageData<AdminKickMsgData>();
msgData.AdminPassword = System.AdminPassword;
msgData.PlayerName = playerName;
SendMessage(msgData);
}
public void SendNukeMsg()
{
var msgData = NetworkMain.CliMsgFactory.CreateNewMessageData<AdminNukeMsgData>();
msgData.AdminPassword = System.AdminPassword;
SendMessage(msgData);
}
public void SendDekesslerMsg()
{
var msgData = NetworkMain.CliMsgFactory.CreateNewMessageData<AdminDekesslerMsgData>();
msgData.AdminPassword = System.AdminPassword;
SendMessage(msgData);
}
}
}
| using LunaClient.Base;
using LunaClient.Base.Interface;
using LunaClient.Network;
using LunaCommon.Message.Client;
using LunaCommon.Message.Data.Admin;
using LunaCommon.Message.Interface;
namespace LunaClient.Systems.Admin
{
public class AdminMessageSender : SubSystem<AdminSystem>, IMessageSender
{
public void SendMessage(IMessageData msg)
{
TaskFactory.StartNew(() => NetworkSender.QueueOutgoingMessage(MessageFactory.CreateNew<HandshakeCliMsg>(msg)));
}
public void SendBanPlayerMsg(string playerName)
{
var msgData = NetworkMain.CliMsgFactory.CreateNewMessageData<AdminBanMsgData>();
msgData.AdminPassword = System.AdminPassword;
msgData.PlayerName = playerName;
SendMessage(msgData);
}
public void SendKickPlayerMsg(string playerName)
{
var msgData = NetworkMain.CliMsgFactory.CreateNewMessageData<AdminKickMsgData>();
msgData.AdminPassword = System.AdminPassword;
msgData.PlayerName = playerName;
SendMessage(msgData);
}
public void SendNukeMsg()
{
var msgData = NetworkMain.CliMsgFactory.CreateNewMessageData<AdminNukeMsgData>();
msgData.AdminPassword = System.AdminPassword;
SendMessage(msgData);
}
public void SendDekesslerMsg()
{
var msgData = NetworkMain.CliMsgFactory.CreateNewMessageData<AdminDekesslerMsgData>();
msgData.AdminPassword = System.AdminPassword;
SendMessage(msgData);
}
}
}
| mit | C# |
2bf101e26146fcb272e6731921823cc78985f0e1 | Fix summary | AMDL/CommonMark.NET,AMDL/CommonMark.NET | CommonMark/CommonMarkAdditionalFeatures.cs | CommonMark/CommonMarkAdditionalFeatures.cs | using System;
namespace CommonMark
{
/// <summary>
/// Lists additional features that can be enabled in <see cref="CommonMarkSettings"/>.
/// These features are not part of the standard and should not be used if interoperability with other
/// CommonMark implementations is required.
/// </summary>
[Flags]
public enum CommonMarkAdditionalFeatures
{
/// <summary>
/// No additional features are enabled. This is the default.
/// </summary>
None = 0,
/// <summary>
/// The parser will recognize syntax <c>~~foo~~</c> that will be rendered as <c><del>foo</del></c>.
/// </summary>
StrikethroughTilde = 1,
/// <summary>
/// The parser will recognize syntax <c>~foo~</c> that will be rendered as <c><sub>foo</sub></c>.
/// </summary>
SubscriptTilde = 2,
/// <summary>
/// The parser will recognize syntax <c>^foo^</c> that will be rendered as <c><sup>foo</sup></c>.
/// </summary>
SuperscriptCaret = 4,
/// <summary>
/// The parser will recognize syntax <c>$foo$</c> that will be rendered as <span class="math">foo</span></c>.
/// </summary>
MathDollar = 8,
/// <summary>
/// The parser will recognize emphasis in indented code.
/// </summary>
EmphasisInIndentedCode = 32,
/// <summary>
/// The parser will recognize <c>:::foo<br/>bar<br/>:::</c> that will be rendered as <c><div class="foo">bar</div></c>
/// </summary>
CustomContainers = 128,
/// <summary>
/// The parser will treat reference labels as case sensitive.
/// </summary>
RespectReferenceCase = 0x100,
/// <summary>
/// All additional features are enabled.
/// </summary>
All = 0x7FFFFFFF
}
}
| using System;
namespace CommonMark
{
/// <summary>
/// Lists additional features that can be enabled in <see cref="CommonMarkSettings"/>.
/// These features are not part of the standard and should not be used if interoperability with other
/// CommonMark implementations is required.
/// </summary>
[Flags]
public enum CommonMarkAdditionalFeatures
{
/// <summary>
/// No additional features are enabled. This is the default.
/// </summary>
None = 0,
/// <summary>
/// The parser will recognize syntax <c>~~foo~~</c> that will be rendered as <c><del>foo</del></c>.
/// </summary>
StrikethroughTilde = 1,
/// <summary>
/// The parser will recognize syntax <c>~foo~</c> that will be rendered as <c><sub>foo</sub></c>.
/// </summary>
SubscriptTilde = 2,
/// <summary>
/// The parser will recognize syntax <c>^foo^</c> that will be rendered as <c><sup>foo</sup></c>.
/// </summary>
SuperscriptCaret = 4,
/// <summary>
/// The parser will recognize syntax <c>$foo$</c> that will be rendered as <span class="math">foo</span></c>.
/// </summary>
MathDollar = 8,
/// The parser will recognize emphasis in indented code.
/// </summary>
EmphasisInIndentedCode = 32,
/// <summary>
/// The parser will recognize <c>:::foo<br/>bar<br/>:::</c> that will be rendered as <c><div class="foo">bar</div></c>
/// </summary>
CustomContainers = 128,
/// <summary>
/// The parser will treat reference labels as case sensitive.
/// </summary>
RespectReferenceCase = 0x100,
/// <summary>
/// All additional features are enabled.
/// </summary>
All = 0x7FFFFFFF
}
}
| bsd-3-clause | C# |
29ba866ddc7dbd11e7eb0103c2744366ffc2701d | Add "Search" widget no base url warning | danielchalmers/DesktopWidgets | DesktopWidgets/Widgets/Search/ViewModel.cs | DesktopWidgets/Widgets/Search/ViewModel.cs | using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
using DesktopWidgets.Classes;
using DesktopWidgets.Helpers;
using DesktopWidgets.ViewModelBase;
using GalaSoft.MvvmLight.Command;
namespace DesktopWidgets.Widgets.Search
{
public class ViewModel : WidgetViewModelBase
{
private string _searchText;
public ViewModel(WidgetId id) : base(id)
{
Settings = id.GetSettings() as Settings;
if (Settings == null)
return;
Go = new RelayCommand(GoExecute);
OnKeyUp = new RelayCommand<KeyEventArgs>(OnKeyUpExecute);
}
public Settings Settings { get; }
public ICommand Go { get; set; }
public ICommand OnKeyUp { get; set; }
public string SearchText
{
get { return _searchText; }
set
{
if (_searchText != value)
{
_searchText = value;
RaisePropertyChanged(nameof(SearchText));
}
}
}
private void GoExecute()
{
if (string.IsNullOrWhiteSpace(Settings.BaseUrl))
{
Popup.Show("You must setup a base url first.", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
var searchText = SearchText;
SearchText = string.Empty;
Process.Start($"{Settings.BaseUrl}{searchText}");
}
private void OnKeyUpExecute(KeyEventArgs args)
{
if (args.Key == Key.Enter)
GoExecute();
}
}
} | using System.Diagnostics;
using System.Windows.Input;
using DesktopWidgets.Classes;
using DesktopWidgets.Helpers;
using DesktopWidgets.ViewModelBase;
using GalaSoft.MvvmLight.Command;
namespace DesktopWidgets.Widgets.Search
{
public class ViewModel : WidgetViewModelBase
{
private string _searchText;
public ViewModel(WidgetId id) : base(id)
{
Settings = id.GetSettings() as Settings;
if (Settings == null)
return;
Go = new RelayCommand(GoExecute);
OnKeyUp = new RelayCommand<KeyEventArgs>(OnKeyUpExecute);
}
public Settings Settings { get; }
public ICommand Go { get; set; }
public ICommand OnKeyUp { get; set; }
public string SearchText
{
get { return _searchText; }
set
{
if (_searchText != value)
{
_searchText = value;
RaisePropertyChanged(nameof(SearchText));
}
}
}
private void GoExecute()
{
var searchText = SearchText;
SearchText = string.Empty;
Process.Start($"{Settings.BaseUrl}{searchText}");
}
private void OnKeyUpExecute(KeyEventArgs args)
{
if (args.Key == Key.Enter)
GoExecute();
}
}
} | apache-2.0 | C# |
a0f020cbcacf4b4ff227ccadbde9e5da0a184e2f | Add rationale. | PenguinF/sandra-three | Eutherion/Win/Storage/ITypeErrorBuilder.cs | Eutherion/Win/Storage/ITypeErrorBuilder.cs | #region License
/*********************************************************************************
* ITypeErrorBuilder.cs
*
* Copyright (c) 2004-2022 Henk Nicolai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
#endregion
using Eutherion.Localization;
namespace Eutherion.Win.Storage
{
/// <summary>
/// Contains information to build an error message caused by a value being of a different type than expected.
/// </summary>
// The idea of this design is that both ITypeErrorBuilders and actual PTypeErrors both allocate little memory,
// because:
//
// a) There are only very few ITypeErrorBuilder instances, one for each PType, plus a few indexed type error
// builders, which in turn are small too.
// b) PTypeErrors contain only what's necessary to display the error somewhere, i.e. a source position and range,
// and most of the time a property key and a value display string.
// c) No references are kept to any syntax structures, they are only given as arguments to methods of this
// interface to transform an error into a meaningful message in various stages.
//
// The ITypeErrorBuilder is generated from a typecheck of a single value, regardless of where it occurs in
// the source. The builder is then used to generate a proper (unlocalized) PTypeError in the context of the source.
public interface ITypeErrorBuilder
{
/// <summary>
/// Gets the localized, context sensitive message for this error.
/// </summary>
/// <param name="localizer">
/// The localizer to use.
/// </param>
/// <param name="actualValueString">
/// A string representation of the value in the source code.
/// </param>
/// <returns>
/// The localized error message.
/// </returns>
string GetLocalizedTypeErrorMessage(Localizer localizer, string actualValueString);
/// <summary>
/// Gets the localized, context sensitive message for this error.
/// </summary>
/// <param name="localizer">
/// The localizer to use.
/// </param>
/// <param name="actualValueString">
/// A string representation of the value in the source code.
/// </param>
/// <param name="propertyKey">
/// The property key for which the error occurred.
/// </param>
/// <returns>
/// The localized error message.
/// </returns>
string GetLocalizedTypeErrorAtPropertyKeyMessage(Localizer localizer, string actualValueString, string propertyKey);
}
}
| #region License
/*********************************************************************************
* ITypeErrorBuilder.cs
*
* Copyright (c) 2004-2020 Henk Nicolai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
#endregion
using Eutherion.Localization;
namespace Eutherion.Win.Storage
{
/// <summary>
/// Contains information to build an error message caused by a value being of a different type than expected.
/// </summary>
public interface ITypeErrorBuilder
{
/// <summary>
/// Gets the localized, context sensitive message for this error.
/// </summary>
/// <param name="localizer">
/// The localizer to use.
/// </param>
/// <param name="actualValueString">
/// A string representation of the value in the source code.
/// </param>
/// <returns>
/// The localized error message.
/// </returns>
string GetLocalizedTypeErrorMessage(Localizer localizer, string actualValueString);
/// <summary>
/// Gets the localized, context sensitive message for this error.
/// </summary>
/// <param name="localizer">
/// The localizer to use.
/// </param>
/// <param name="actualValueString">
/// A string representation of the value in the source code.
/// </param>
/// <param name="propertyKey">
/// The property key for which the error occurred.
/// </param>
/// <returns>
/// The localized error message.
/// </returns>
string GetLocalizedTypeErrorAtPropertyKeyMessage(Localizer localizer, string actualValueString, string propertyKey);
}
}
| apache-2.0 | C# |
042442b7d1fdbf864e0fd7cffa4a08102ebbce85 | Document UshortExtensions | izik1/JAGBE | JAGBE/GB/UShortExtensions.cs | JAGBE/GB/UShortExtensions.cs | namespace JAGBE.GB
{
/// <summary>
/// Provides extension methods for <see cref="ushort"/>
/// </summary>
internal static class UShortExtensions
{
/// <summary>
/// determines weather adding two ushorts would produce a half carry.
/// </summary>
/// <param name="u">The first value.</param>
/// <param name="val">The second value.</param>
/// <returns></returns>
public static bool GetHalfCarry(this ushort u, ushort val) => (((u & 0xFFF) + (val & 0xFFF)) & 0x1000) == 0x1000;
}
}
| namespace JAGBE.GB
{
internal static class UShortExtensions
{
public static bool GetHalfCarry(this ushort a, ushort b) => (((a & 0xFFF) + (b & 0xFFF)) & 0x1000) == 0x1000;
}
}
| mit | C# |
a5c8a01ded505d14b71cb1338a986dabddc7f3b6 | Make hit test based on the image optional | k-t/SharpHaven | MonoHaven.Client/UI/Widgets/ImageButton.cs | MonoHaven.Client/UI/Widgets/ImageButton.cs | using System;
using MonoHaven.Graphics;
using MonoHaven.Input;
namespace MonoHaven.UI.Widgets
{
public class ImageButton : Widget
{
private bool isPressed;
public ImageButton(Widget parent)
: base(parent)
{
IsFocusable = true;
}
public event Action Click;
public bool ImageHitTest
{
get;
set;
}
public Drawable Image
{
get;
set;
}
public Drawable PressedImage
{
get;
set;
}
public Drawable HoveredImage
{
get;
set;
}
protected override void OnDraw(DrawingContext dc)
{
Drawable image = null;
if (isPressed && PressedImage != null)
image = PressedImage;
else if (IsHovered && HoveredImage != null)
image = HoveredImage;
else
image = Image;
if (image != null)
dc.Draw(image, 0, 0);
}
protected override bool CheckHit(int x, int y)
{
if (ImageHitTest)
return Image != null && Image.CheckHit(x - X, y - Y);
return base.CheckHit(x, y);
}
protected override void OnMouseButtonDown(MouseButtonEvent e)
{
Host.GrabMouse(this);
isPressed = true;
e.Handled = true;
}
protected override void OnMouseButtonUp(MouseButtonEvent e)
{
Host.ReleaseMouse();
isPressed = false;
// button released outside of borders?
var p = MapFromScreen(e.Position);
if (CheckHit(p.X + X, p.Y + Y))
Click.Raise();
e.Handled = true;
}
}
}
| using System;
using MonoHaven.Graphics;
using MonoHaven.Input;
namespace MonoHaven.UI.Widgets
{
public class ImageButton : Widget
{
private bool isPressed;
public ImageButton(Widget parent)
: base(parent)
{
IsFocusable = true;
}
public event Action Click;
public Drawable Image
{
get;
set;
}
public Drawable PressedImage
{
get;
set;
}
public Drawable HoveredImage
{
get;
set;
}
protected override void OnDraw(DrawingContext dc)
{
Drawable image = null;
if (isPressed && PressedImage != null)
image = PressedImage;
else if (IsHovered && HoveredImage != null)
image = HoveredImage;
else
image = Image;
if (image != null)
dc.Draw(image, 0, 0);
}
protected override bool CheckHit(int x, int y)
{
return Image != null && Image.CheckHit(x - X, y - Y);
}
protected override void OnMouseButtonDown(MouseButtonEvent e)
{
Host.GrabMouse(this);
isPressed = true;
e.Handled = true;
}
protected override void OnMouseButtonUp(MouseButtonEvent e)
{
Host.ReleaseMouse();
isPressed = false;
// button released outside of borders?
var p = MapFromScreen(e.Position);
if (CheckHit(p.X + X, p.Y + Y))
Click.Raise();
e.Handled = true;
}
}
}
| mit | C# |
505d36dd8b8ea3d12ff351b611581c79066f9bc9 | Update run.csx | vunvulear/Stuff,vunvulear/Stuff,vunvulear/Stuff | Azure/azure-function-extractgpslocation-onedrive-drawwatermark/run.csx | Azure/azure-function-extractgpslocation-onedrive-drawwatermark/run.csx | #r "Microsoft.Azure.WebJobs.Extensions.ApiHub"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExifLib;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
public static void Run(Stream inputFile, Stream outputFile, TraceWriter log)
{
log.Info("Image Process Starts");
string locationText = GetCoordinate(inputFile, log);
log.Info($"Text to be written: '{locationText}'");
// Reset position. After Exif operations the cursor location is not on position 0 anymore;
inputFile.Position = 0;
WriteWatermark(locationText, inputFile, outputFile, log);
log.Info("Image Process Ends");
}
private static string GetCoordinate(Stream image, TraceWriter log)
{
log.Info("Extract location information");
ExifReader exifReader = new ExifReader(image);
double[] latitudeComponents;
exifReader.GetTagValue(ExifTags.GPSLatitude, out latitudeComponents);
double[] longitudeComponents;
exifReader.GetTagValue(ExifTags.GPSLongitude, out longitudeComponents);
log.Info("Prepare string content");
string location = string.Empty;
if (latitudeComponents == null ||
longitudeComponents == null)
{
location = "No GPS location";
}
else
{
double latitude = 0;
double longitude = 0;
latitude = latitudeComponents[0] + latitudeComponents[1] / 60 + latitudeComponents[2] / 3600;
longitude = longitudeComponents[0] + longitudeComponents[1] / 60 + longitudeComponents[2] / 3600;
location = $"Latitude: '{latitude}' | Longitude: '{longitude}'";
}
return location;
}
private static void WriteWatermark(string watermarkContent, Stream originalImage, Stream newImage, TraceWriter log)
{
log.Info("Write text to picture");
using (Image inputImage = Image.FromStream(originalImage, true))
{
using (Graphics graphic = Graphics.FromImage(inputImage))
{
graphic.SmoothingMode = SmoothingMode.HighQuality;
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphic.DrawString(watermarkContent, new Font("Tahoma", 100, FontStyle.Bold), Brushes.Red, 200, 200);
graphic.Flush();
log.Info("Write to the output stream");
inputImage.Save(newImage, ImageFormat.Jpeg);
}
}
}
| #r "Microsoft.Azure.WebJobs.Extensions.ApiHub" // Don't forget to blog about it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExifLib;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
public static void Run(Stream inputFile, TraceWriter log, Stream outputFile)
{
log.Info("Image Process Starts");
log.Info("Extract location information");
ExifReader exifReader = new ExifReader(inputFile);
double[] latitudeComponents;
exifReader.GetTagValue(ExifTags.GPSLatitude, out latitudeComponents);
double[] longitudeComponents;
exifReader.GetTagValue(ExifTags.GPSLongitude, out longitudeComponents);
log.Info("Prepare string content");
string location = string.Empty;
if (latitudeComponents == null ||
longitudeComponents == null)
{
location = "No GPS location";
}
else
{
double latitude = 0;
double longitude = 0;
latitude = latitudeComponents[0] + latitudeComponents[1] / 60 + latitudeComponents[2] / 3600;
longitude = longitudeComponents[0] + longitudeComponents[1] / 60 + longitudeComponents[2] / 3600;
location = $"Latitude: '{latitude}' | Longitude: '{longitude}'";
}
log.Info($"Text to be written: '{location}'");
// Reset position. After Exif operations the cursor location is not on position 0 anymore;
inputFile.Position = 0;
log.Info("Write text to picture");
using (Image inputImage = Image.FromStream(inputFile, true))
{
using (Graphics graphic = Graphics.FromImage(inputImage))
{
graphic.SmoothingMode = SmoothingMode.HighQuality;
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphic.DrawString(location, new Font("Tahoma", 100, FontStyle.Bold), Brushes.Red, 200, 200);
graphic.Flush();
log.Info("Write to the output stream");
inputImage.Save(outputFile, ImageFormat.Jpeg);
}
}
log.Info("Image Process Ends");
}
| apache-2.0 | C# |
151a92f6208427f114944dac8743176025db5504 | Fix failing test | Xeeynamo/KingdomHearts | OpenKh.Tests/Bbs/PmpTests.cs | OpenKh.Tests/Bbs/PmpTests.cs | using OpenKh.Common;
using OpenKh.Bbs;
using System.IO;
using Xunit;
using System;
using System.Collections.Generic;
using System.Text;
namespace OpenKh.Tests.Bbs
{
public class PmpTests
{
private static readonly string FileName = "Bbs/res/bbs-testmap.pmp";
[Fact]
public void ReadCorrectHeader() => File.OpenRead(FileName).Using(stream =>
{
var TestPmo = Pmp.Read(stream);
Assert.Equal(0x504D50, (int)TestPmo.header.MagicCode);
Assert.Equal(1, TestPmo.header.ObjectCount);
});
[Fact]
public void WritesBackCorrectly() => File.OpenRead(FileName).Using(stream =>
Helpers.AssertStream(stream, x =>
{
var outStream = new MemoryStream();
Pmp.Write(outStream, Pmp.Read(stream));
return outStream;
}));
}
}
| using OpenKh.Common;
using OpenKh.Bbs;
using System.IO;
using Xunit;
using System;
using System.Collections.Generic;
using System.Text;
namespace OpenKh.Tests.Bbs
{
public class PmpTests
{
private static readonly string FileName = "Bbs/res/jb_23.pmp";
[Fact]
public void ReadCorrectHeader() => File.OpenRead(FileName).Using(stream =>
{
var TestPmo = Pmp.Read(stream);
Assert.Equal(0x504D50, (int)TestPmo.header.MagicCode);
Assert.Equal(4, (int)TestPmo.header.ObjectCount);
});
[Fact]
public void WritesBackCorrectly()
{
Stream input = File.OpenRead(FileName);
var TestPmp = Pmp.Read(input);
Stream output = File.Open("Bbs/res/jb_23_TEST.pmp", FileMode.Create);
Pmp.Write(output, TestPmp);
input.Position = 0;
output.Position = 0;
// Check all bytes.
for (int i = 0; i < output.Length; i++)
{
if (input.ReadByte() != output.ReadByte())
{
long position = output.Position;
Assert.False(true);
}
}
Assert.True(true);
}
}
}
| mit | C# |
1682adc3f51a2a95b8d01135fb8d426b4bdd1563 | Remove useless argument. | ivarboms/PasswordGenerator | PasswordGenerator/Program.cs | PasswordGenerator/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace PasswordGenerator
{
class Program
{
private const string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private const string numerical = "0123456789";
private const string symbols = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿";
private static char[] GenerateCharacterSelection(bool includeSymbols)
{
char[] chars = alphabet.Union(numerical).ToArray();
if (includeSymbols)
{
chars = chars.Union(symbols).ToArray();
}
return chars;
}
private static int ParseLength(string[] args)
{
foreach (string arg in args)
{
if (Regex.IsMatch(arg, @"^\d+$"))
{
return int.Parse(arg);
}
}
return 42;
}
private static string GeneratePassword(char[] sourceSymbols, int length)
{
Random rng = new Random();
List<char> password = new List<char>();
for (int i = 0; i < length; ++i)
{
char c = sourceSymbols[rng.Next(0, sourceSymbols.Length)];
password.Add(c);
}
return new string(password.ToArray());
}
private static void OutputPassword(string password)
{
Console.WriteLine(password);
Clipboard.SetText(password);
}
//STAThread needed to access clipboard.
[STAThread]
private static void Main(string[] args)
{
bool includeSymbols = !args.Any(arg => arg == "no-symbols");
char[] chars = GenerateCharacterSelection(includeSymbols);
int passwordLength = ParseLength(args);
string password = GeneratePassword(chars, passwordLength);
OutputPassword(password);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace PasswordGenerator
{
class Program
{
private const string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private const string numerical = "0123456789";
private const string symbols = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿";
private static char[] GenerateCharacterSelection(bool includeSymbols)
{
char[] chars = alphabet.Union(numerical).ToArray();
if (includeSymbols)
{
chars = chars.Union(symbols).ToArray();
}
return chars;
}
private static int ParseLength(string[] args)
{
foreach (string arg in args)
{
if (Regex.IsMatch(arg, @"^\d+$"))
{
return int.Parse(arg);
}
if (arg == "short")
{
return 14;
}
}
return 42;
}
private static string GeneratePassword(char[] sourceSymbols, int length)
{
Random rng = new Random();
List<char> password = new List<char>();
for (int i = 0; i < length; ++i)
{
char c = sourceSymbols[rng.Next(0, sourceSymbols.Length)];
password.Add(c);
}
return new string(password.ToArray());
}
private static void OutputPassword(string password)
{
Console.WriteLine(password);
Clipboard.SetText(password);
}
//STAThread needed to access clipboard.
[STAThread]
private static void Main(string[] args)
{
bool includeSymbols = !args.Any(arg => arg == "no-symbols");
char[] chars = GenerateCharacterSelection(includeSymbols);
int passwordLength = ParseLength(args);
string password = GeneratePassword(chars, passwordLength);
OutputPassword(password);
}
}
}
| mit | C# |
fd0c2594a6264e82b91121e1b401ed27dbebc101 | Remove setter | bartlomiejwolk/AnimationPathAnimator | PathEvents/PathEventsData.cs | PathEvents/PathEventsData.cs | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace ATP.SimplePathAnimator.Events {
public class PathEventsData : ScriptableObject {
[SerializeField]
private List<NodeEvent> nodeEvents;
public List<NodeEvent> NodeEvents {
get { return nodeEvents; }
}
public void ResetEvents() {
NodeEvents.Clear();
}
private void OnEnable() {
if (nodeEvents == null) {
nodeEvents = new List<NodeEvent>();
}
}
}
}
| using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace ATP.SimplePathAnimator.Events {
public class PathEventsData : ScriptableObject {
[SerializeField]
private List<NodeEvent> nodeEvents;
public List<NodeEvent> NodeEvents {
get { return nodeEvents; }
set { nodeEvents = value; }
}
public void ResetEvents() {
NodeEvents.Clear();
}
private void OnEnable() {
if (nodeEvents == null) {
nodeEvents = new List<NodeEvent>();
}
}
}
}
| mit | C# |
c91b74e74ecc1a7a765a420db7b1b525b5770464 | Update Product_MenuFunctions.cs | NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework | Test/AdventureWorksFunctionalModel/Production/Product_MenuFunctions.cs | Test/AdventureWorksFunctionalModel/Production/Product_MenuFunctions.cs | // Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// 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.Linq;
using NakedFunctions;
using AW.Types;
using static AW.Helpers;
using System.Collections.Generic;
namespace AW.Functions
{
[Named("Products")]
public static class Product_MenuFunctions
{
[MemberOrder(1)]
[TableView(true, nameof(Product.ProductNumber), nameof(Product.ProductSubcategory), nameof(Product.ListPrice))]
public static IQueryable<Product> FindProductByName(string searchString, IContext context) =>
context.Instances<Product>().Where(x => x.Name.ToUpper().Contains(searchString.ToUpper())).OrderBy(x => x.Name);
[MemberOrder(2)]
public static Product RandomProduct(IContext context) => Random<Product>(context);
[MemberOrder(3)]
public static Product FindProductByNumber(string number, IContext context) =>
context.Instances<Product>().Where(x => x.ProductNumber == number).FirstOrDefault();
[MemberOrder(4)]
public static IQueryable<Product> AllProducts(IContext context) => context.Instances<Product>();
[MemberOrder(5)]
public static IQueryable<Product> ListProductsByCategory(
ProductCategory category, [Optionally] ProductSubcategory subCategory, IContext context)
{
int catId = category.ProductCategoryID;
int subId = subCategory is null ? 0 : subCategory.ProductSubcategoryID;
return context.Instances<Product>().Where(p => p.ProductSubcategory.ProductCategoryID == catId
&& (subId == 0 || p.ProductSubcategoryID.Value == subId));
}
public static List<ProductSubcategory> Choices1ListProductsByCategory(ProductCategory category) =>
category.ProductSubcategory.ToList();
}
} | // Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// 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.Linq;
using NakedFunctions;
using AW.Types;
using static AW.Helpers;
namespace AW.Functions
{
[Named("Products")]
public static class Product_MenuFunctions
{
[MemberOrder(1)]
[TableView(true, nameof(Product.ProductNumber), nameof(Product.ProductSubcategory), nameof(Product.ListPrice))]
public static IQueryable<Product> FindProductByName(string searchString, IContext context) =>
context.Instances<Product>().Where(x => x.Name.ToUpper().Contains(searchString.ToUpper())).OrderBy(x => x.Name);
[MemberOrder(2)]
public static Product RandomProduct(IContext context) => Random<Product>(context);
[MemberOrder(3)]
public static Product FindProductByNumber(string number, IContext context) =>
context.Instances<Product>().Where(x => x.ProductNumber == number).FirstOrDefault();
[MemberOrder(4)]
public static IQueryable<Product> AllProducts(IContext context) => context.Instances<Product>();
}
} | apache-2.0 | C# |
e45c7e72e6fe5ee95ae94c243d0f1f7116754bb9 | Update Box.cs | dimmpixeye/Unity3dTools | Runtime/LibProcessors/Box.cs | Runtime/LibProcessors/Box.cs | // Project : ACTORS
// Contacts : Pixeye - ask@pixeye.games
using System;
using System.Collections.Generic;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Pixeye.Framework
{
/// <summary>
/// <para>Caches / return assets that Developer takes from the Resources folder.
/// Box cleans cache when scene reloads.</para>
/// </summary>
public class Box : IKernel, IDisposable
{
/// <summary>
/// <para>Caches / return assets that Developer takes from the Resources folder.
/// Box cleans cache when scene reloads.</para>
/// </summary>
public static Box Default = new Box();
public static readonly string path = "/{0}";
internal Dictionary<int, Object> items = new Dictionary<int, Object>(20, FastComparable.Default);
Dictionary<int, string> itemsPaths = new Dictionary<int, string>(20, FastComparable.Default);
public static int StringToHash(string val)
{
var hash = val.GetHashCode();
Default.itemsPaths.Add(hash, val);
return hash;
}
public static T Load<T>(string id) where T : Object
{
return Resources.Load<T>(id);
}
public static T[] LoadAll<T>(string id) where T : Object
{
return Resources.LoadAll<T>(id);
}
public static T Get<T>(string id) where T : Object
{
Object obj;
var key = id.GetHashCode();
var hasValue = Default.items.TryGetValue(key, out obj);
if (hasValue == false)
{
obj = Resources.Load<T>(id);
Default.items.Add(key, obj);
}
return obj as T;
}
public static T Get<T>(int id) where T : Object
{
Object obj;
if (Default.items.TryGetValue(id, out obj))
return obj as T;
obj = Resources.Load(Default.itemsPaths[id]);
Default.items.Add(id, obj);
return obj as T;
}
public void Dispose()
{
items.Clear();
itemsPaths.Clear();
}
}
} | // Project : ACTORS
// Contacts : Pixeye - ask@pixeye.games
using System;
using System.Collections.Generic;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Pixeye.Framework
{
/// <summary>
/// <para>Caches / return assets that Developer takes from the Resources folder.
/// Box cleans cache when scene reloads.</para>
/// </summary>
public class Box : IKernel, IDisposable
{
/// <summary>
/// <para>Caches / return assets that Developer takes from the Resources folder.
/// Box cleans cache when scene reloads.</para>
/// </summary>
public static Box Default = new Box();
public static readonly string path = "/{0}";
internal Dictionary<int, Object> items = new Dictionary<int, Object>(20, FastComparable.Default);
Dictionary<int, string> itemsPaths = new Dictionary<int, string>(20, FastComparable.Default);
public static int StringToHash(string val)
{
var hash = val.GetHashCode();
Default.itemsPaths.Add(hash, val);
return hash;
}
public static T Load<T>(string id) where T : Object
{
return Resources.Load<T>(id);
}
public static T Get<T>(string id) where T : Object
{
Object obj;
var key = id.GetHashCode();
var hasValue = Default.items.TryGetValue(key, out obj);
if (hasValue == false)
{
obj = Resources.Load<T>(id);
Default.items.Add(key, obj);
}
return obj as T;
}
public static T Get<T>(int id) where T : Object
{
Object obj;
if (Default.items.TryGetValue(id, out obj))
return obj as T;
obj = Resources.Load(Default.itemsPaths[id]);
Default.items.Add(id, obj);
return obj as T;
}
public void Dispose()
{
items.Clear();
itemsPaths.Clear();
}
}
} | mit | C# |
31a51426cc4360cddc0de5837e9936be76ef5bf6 | Update stockMarketScreen.cs | IanMcT/StockMarketGame | SMG/SMG/stockMarketScreen.cs | SMG/SMG/stockMarketScreen.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SMG
{
public partial class stockMarketScreen : Form
{
//Global Variables
List<Stock> stocks = new List<Stock>();
Bitmap bmpUp = new Bitmap("up.bmp");
Bitmap bmpDown = new Bitmap("down.bmp");
public stockMarketScreen()
{
InitializeComponent();
}
/// <summary>
/// Runs when screen loads
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void stockMarketScreen_Load(object sender, EventArgs e)
{
//load stocks
stocks.Add(new Stock("Guugle"));
stocks.Add(new Stock("Pear"));
stocks.Add(new Stock("Skybucks"));
//adds rows
int currentRow = 0;
foreach (Stock s in stocks)
{
dgvStockList.Rows.Add();
dgvStockList.Rows[currentRow].Cells[0].Value = s.StockName;
dgvStockList.Rows[currentRow].Cells[1].Value = s.StockReturn;
dgvStockList.Rows[currentRow].Cells[2].Value = bmpUp;
currentRow++;
}
}
/// <summary>
/// Runs when stock list clicked.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dgvStockList_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
//is a row clicked?
if (e.RowIndex >= 0 && e.RowIndex < dgvStockList.RowCount)
{
MessageBox.Show("You clicked " +
dgvStockList.Rows[e.RowIndex].Cells[0].Value);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SMG
{
public partial class stockMarketScreen : Form
{
//Global Variables
List<Stock> stocks = new List<Stock>();
Bitmap bmpUp = new Bitmap("up.bmp");
Bitmap bmpDown = new Bitmap("down.bmp");
public stockMarketScreen()
{
InitializeComponent();
}
/// <summary>
/// Runs when screen loads
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void stockMarketScreen_Load(object sender, EventArgs e)
{
//load stocks
//adds a row
dgvStockList.Rows.Add();
dgvStockList.Rows[dgvStockList.RowCount - 1].Cells[0].Value = "Google";
dgvStockList.Rows[dgvStockList.RowCount - 1].Cells[1].Value = 99.98;
dgvStockList.Rows[dgvStockList.RowCount - 1].Cells[2].Value = bmpUp;
}
/// <summary>
/// Runs when stock list clicked.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dgvStockList_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
//is a row clicked?
if (e.RowIndex >= 0 && e.RowIndex < dgvStockList.RowCount)
{
MessageBox.Show("You clicked " +
dgvStockList.Rows[e.RowIndex].Cells[0].Value);
}
}
}
}
| apache-2.0 | C# |
e52400f7561e4932efe06857c2889e43a54a01e1 | Use string instead of String | mirajavora/sendgrid-webhooks | Sendgrid.Webhooks/Converters/WebhookCategoryConverter.cs | Sendgrid.Webhooks/Converters/WebhookCategoryConverter.cs | using System;
using System.ComponentModel;
using Newtonsoft.Json;
using Sendgrid.Webhooks.Converters;
namespace Sendgrid.Webhooks.Service
{
public class WebhookCategoryConverter : GenericListCreationJsonConverter<string>
{
}
}
| using System;
using System.ComponentModel;
using Newtonsoft.Json;
using Sendgrid.Webhooks.Converters;
namespace Sendgrid.Webhooks.Service
{
public class WebhookCategoryConverter : GenericListCreationJsonConverter<String>
{
}
} | apache-2.0 | C# |
14b21ed05b63d833ebe17115548e1aafa6118463 | make exception serializable | ThuCommix/Sharpex2D | Sharpex.GameLibrary/Framework/Plugins/PluginException.cs | Sharpex.GameLibrary/Framework/Plugins/PluginException.cs | using System;
namespace SharpexGL.Framework.Plugins
{
[Serializable]
public class PluginException : Exception
{
private readonly string _message = "";
public override string Message
{
get
{
return _message;
}
}
/// <summary>
/// Initializes a new PluginException.
/// </summary>
public PluginException()
{
}
/// <summary>
/// Initializes a new PluginException.
/// </summary>
/// <param name="message">The Message.</param>
public PluginException(string message)
{
_message = message;
}
}
}
| using System;
namespace SharpexGL.Framework.Plugins
{
public class PluginException : Exception
{
private string _message = "";
public override string Message
{
get
{
return _message;
}
}
/// <summary>
/// Initializes a new PluginException.
/// </summary>
public PluginException()
{
}
/// <summary>
/// Initializes a new PluginException.
/// </summary>
/// <param name="message">The Message.</param>
public PluginException(string message)
{
_message = message;
}
}
}
| mit | C# |
847b30641fa0209e81456c68f8770d872acfc075 | Hide Guid prop on SalesTaxRate | NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework | Test/AdventureWorksFunctionalModel/Sales/SalesTaxRate.cs | Test/AdventureWorksFunctionalModel/Sales/SalesTaxRate.cs | // Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// 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 NakedFunctions;
using static AW.Utilities;
namespace AW.Types
{
public record SalesTaxRate
{
[Hidden]
public virtual int SalesTaxRateID { get; init; }
public virtual byte TaxType { get; init; }
public virtual decimal TaxRate { get; init; }
public virtual string Name { get; init; }
[Hidden]
public virtual int StateProvinceID { get; init; }
public virtual StateProvince StateProvince { get; init; }
[MemberOrder(99)]
[Versioned]
public virtual DateTime ModifiedDate { get; init; }
[Hidden]
public virtual Guid rowguid { get; init; }
public override string ToString() => $"{TaxRate}";
public override int GetHashCode() => HashCode(this, SalesTaxRateID);
public virtual bool Equals(SalesTaxRate other) => ReferenceEquals(this, other);
}
} | // Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// 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 NakedFunctions;
using static AW.Utilities;
namespace AW.Types
{
public record SalesTaxRate
{
[Hidden]
public virtual int SalesTaxRateID { get; init; }
public virtual byte TaxType { get; init; }
public virtual decimal TaxRate { get; init; }
public virtual string Name { get; init; }
[Hidden]
public virtual int StateProvinceID { get; init; }
public virtual StateProvince StateProvince { get; init; }
[MemberOrder(99)]
[Versioned]
public virtual DateTime ModifiedDate { get; init; }
public virtual Guid rowguid { get; init; }
public override string ToString() => $"{TaxRate}";
public override int GetHashCode() => HashCode(this, SalesTaxRateID);
public virtual bool Equals(SalesTaxRate other) => ReferenceEquals(this, other);
}
} | apache-2.0 | C# |
83497221cd0b86710f57db152493c1fcf5420f82 | Remove unused usings. | jcheng31/WundergroundAutocomplete.NET | WundergroundClient/Autocomplete/RawAutocompleteResult.cs | WundergroundClient/Autocomplete/RawAutocompleteResult.cs | using System;
using System.Runtime.Serialization;
namespace WundergroundClient.Autocomplete
{
// ReSharper disable InconsistentNaming
[DataContract]
internal class RawAutocompleteResult
{
[DataMember] internal RawResult[] RESULTS;
}
[DataContract]
internal class RawResult
{
[DataMember] internal String name;
[DataMember] internal String type;
[DataMember] internal String l;
// Hurricane Fields
[DataMember] internal String date;
[DataMember] internal String strmnum;
[DataMember] internal String basin;
[DataMember] internal String damage;
[DataMember] internal String start_epoch;
[DataMember] internal String end_epoch;
[DataMember] internal String sw_lat;
[DataMember] internal String sw_lon;
[DataMember] internal String ne_lat;
[DataMember] internal String ne_lon;
[DataMember] internal String maxcat;
// City Fields
[DataMember] internal String c;
[DataMember] internal String zmw;
[DataMember] internal String tz;
[DataMember] internal String tzs;
[DataMember] internal String ll;
[DataMember] internal String lat;
[DataMember] internal String lon;
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
namespace WundergroundClient.Autocomplete
{
// ReSharper disable InconsistentNaming
[DataContract]
internal class RawAutocompleteResult
{
[DataMember] internal RawResult[] RESULTS;
}
[DataContract]
internal class RawResult
{
[DataMember] internal String name;
[DataMember] internal String type;
[DataMember] internal String l;
// Hurricane Fields
[DataMember] internal String date;
[DataMember] internal String strmnum;
[DataMember] internal String basin;
[DataMember] internal String damage;
[DataMember] internal String start_epoch;
[DataMember] internal String end_epoch;
[DataMember] internal String sw_lat;
[DataMember] internal String sw_lon;
[DataMember] internal String ne_lat;
[DataMember] internal String ne_lon;
[DataMember] internal String maxcat;
// City Fields
[DataMember] internal String c;
[DataMember] internal String zmw;
[DataMember] internal String tz;
[DataMember] internal String tzs;
[DataMember] internal String ll;
[DataMember] internal String lat;
[DataMember] internal String lon;
}
} | mit | C# |
1fec6ec2127de08cf234aaa61843bab899a69eb3 | Add back incorrectly removed parameter | ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework | osu.Framework/Host.cs | osu.Framework/Host.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.Platform;
using osu.Framework.Platform.Linux;
using osu.Framework.Platform.MacOS;
using osu.Framework.Platform.Windows;
using System;
namespace osu.Framework
{
public static class Host
{
public static DesktopGameHost GetSuitableHost(string gameName, bool bindIPC = false, bool portableInstallation = false)
{
switch (RuntimeInfo.OS)
{
case RuntimeInfo.Platform.macOS:
return new MacOSGameHost(gameName, bindIPC, portableInstallation);
case RuntimeInfo.Platform.Linux:
return new LinuxGameHost(gameName, bindIPC, portableInstallation);
case RuntimeInfo.Platform.Windows:
return new WindowsGameHost(gameName, bindIPC, portableInstallation);
default:
throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({Enum.GetName(typeof(RuntimeInfo.Platform), RuntimeInfo.OS)}).");
}
}
}
}
| // 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.Platform;
using osu.Framework.Platform.Linux;
using osu.Framework.Platform.MacOS;
using osu.Framework.Platform.Windows;
using System;
namespace osu.Framework
{
public static class Host
{
public static DesktopGameHost GetSuitableHost(string gameName, bool bindIPC = false, bool portableInstallation = false)
{
switch (RuntimeInfo.OS)
{
case RuntimeInfo.Platform.macOS:
return new MacOSGameHost(gameName, bindIPC);
case RuntimeInfo.Platform.Linux:
return new LinuxGameHost(gameName, bindIPC);
case RuntimeInfo.Platform.Windows:
return new WindowsGameHost(gameName, bindIPC);
default:
throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({Enum.GetName(typeof(RuntimeInfo.Platform), RuntimeInfo.OS)}).");
}
}
}
}
| mit | C# |
38c8de0ff07be3d856ea10bc4c9846c230ed92dd | set parameter type attribute | LagoVista/DeviceAdmin | src/LagoVista.IoT.DeviceAdmin/Models/InputCommandParameter.cs | src/LagoVista.IoT.DeviceAdmin/Models/InputCommandParameter.cs | using LagoVista.Core.Attributes;
using LagoVista.Core.Models;
using LagoVista.IoT.DeviceAdmin.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LagoVista.IoT.DeviceAdmin.Models
{
[EntityDescription(DeviceAdminDomain.DeviceAdmin, DeviceLibraryResources.Names.InputCommandParameter_Title, DeviceLibraryResources.Names.InputCommandParameter_Help, DeviceLibraryResources.Names.InputCommandParamter_Description, EntityDescriptionAttribute.EntityTypes.SimpleModel, typeof(DeviceLibraryResources))]
public class InputCommandParameter
{
public enum InputCommandParameterTypes
{
[EnumLabel("string", DeviceLibraryResources.Names.Parameter_Types_String, typeof(DeviceLibraryResources))]
String,
[EnumLabel("integer", DeviceLibraryResources.Names.Parameter_Types_Integer, typeof(DeviceLibraryResources))]
Integer,
[EnumLabel("decimal", DeviceLibraryResources.Names.Parameter_Types_Decimal, typeof(DeviceLibraryResources))]
Decimal,
[EnumLabel("true-false", DeviceLibraryResources.Names.Parameter_Types_TrueFalse, typeof(DeviceLibraryResources))]
TrueFalse,
[EnumLabel("geolocation", DeviceLibraryResources.Names.Parameter_Types_GeoLocation, typeof(DeviceLibraryResources), DeviceLibraryResources.Names.WorkflowInput_Type_GeoLocation_Help)]
GeoLocation,
}
[FormField(LabelResource: Resources.DeviceLibraryResources.Names.Common_IsRequired, ResourceType: typeof(DeviceLibraryResources))]
public bool IsRequired { get; set; }
[FormField(LabelResource: Resources.DeviceLibraryResources.Names.Common_Name, ResourceType: typeof(DeviceLibraryResources), IsRequired: true)]
public String Name { get; set; }
[FormField(LabelResource: Resources.DeviceLibraryResources.Names.Common_Key, HelpResource: Resources.DeviceLibraryResources.Names.Common_Key_Help, FieldType: FieldTypes.Key, RegExValidationMessageResource: Resources.DeviceLibraryResources.Names.Common_Key_Validation, ResourceType: typeof(DeviceLibraryResources), IsRequired: true)]
public String Key { get; set; }
[FormField(LabelResource: Resources.DeviceLibraryResources.Names.InputCommandParameter_Type, FieldType: FieldTypes.Picker, ResourceType: typeof(DeviceLibraryResources), IsRequired: true, EnumType:typeof(InputCommandParameterTypes), WaterMark: DeviceLibraryResources.Names.Parameter_Type_Watermark)]
public EntityHeader ParameterType { get; set; }
[FormField(LabelResource: Resources.DeviceLibraryResources.Names.Common_Description, FieldType: FieldTypes.MultiLineText, ResourceType: typeof(DeviceLibraryResources))]
public String Description { get; set; }
}
}
| using LagoVista.Core.Attributes;
using LagoVista.Core.Models;
using LagoVista.IoT.DeviceAdmin.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LagoVista.IoT.DeviceAdmin.Models
{
[EntityDescription(DeviceAdminDomain.DeviceAdmin, DeviceLibraryResources.Names.InputCommandParameter_Title, DeviceLibraryResources.Names.InputCommandParameter_Help, DeviceLibraryResources.Names.InputCommandParamter_Description, EntityDescriptionAttribute.EntityTypes.SimpleModel, typeof(DeviceLibraryResources))]
public class InputCommandParameter
{
public enum InputCommandParameterTypes
{
[EnumLabel("string", DeviceLibraryResources.Names.Parameter_Types_String, typeof(DeviceLibraryResources))]
String,
[EnumLabel("integer", DeviceLibraryResources.Names.Parameter_Types_Integer, typeof(DeviceLibraryResources))]
Integer,
[EnumLabel("decimal", DeviceLibraryResources.Names.Parameter_Types_Decimal, typeof(DeviceLibraryResources))]
Decimal,
[EnumLabel("true-false", DeviceLibraryResources.Names.Parameter_Types_TrueFalse, typeof(DeviceLibraryResources))]
TrueFalse,
[EnumLabel("geolocation", DeviceLibraryResources.Names.Parameter_Types_GeoLocation, typeof(DeviceLibraryResources), DeviceLibraryResources.Names.WorkflowInput_Type_GeoLocation_Help)]
GeoLocation,
}
[FormField(LabelResource: Resources.DeviceLibraryResources.Names.Common_IsRequired, ResourceType: typeof(DeviceLibraryResources))]
public bool IsRequired { get; set; }
[FormField(LabelResource: Resources.DeviceLibraryResources.Names.Common_Name, ResourceType: typeof(DeviceLibraryResources), IsRequired: true)]
public String Name { get; set; }
[FormField(LabelResource: Resources.DeviceLibraryResources.Names.Common_Key, HelpResource: Resources.DeviceLibraryResources.Names.Common_Key_Help, FieldType: FieldTypes.Key, RegExValidationMessageResource: Resources.DeviceLibraryResources.Names.Common_Key_Validation, ResourceType: typeof(DeviceLibraryResources), IsRequired: true)]
public String Key { get; set; }
[FormField(LabelResource: Resources.DeviceLibraryResources.Names.InputCommandParameter_Type, ResourceType: typeof(DeviceLibraryResources), IsRequired: true, WaterMark: DeviceLibraryResources.Names.Parameter_Type_Watermark)]
public EntityHeader ParameterType { get; set; }
[FormField(LabelResource: Resources.DeviceLibraryResources.Names.Common_Description, FieldType: FieldTypes.MultiLineText, ResourceType: typeof(DeviceLibraryResources))]
public String Description { get; set; }
}
}
| mit | C# |
15021065997ebb9fae3459b1ad172631cce51a6e | bump version | alecgorge/adzerk-dot-net | Adzerk.Api/Properties/AssemblyInfo.cs | Adzerk.Api/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("Adzerk.Api")]
[assembly: AssemblyDescription("Unofficial Adzerk API client.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Stack Exchange")]
[assembly: AssemblyProduct("Adzerk.Api")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d05e1e25-d95d-43d6-a74b-3cb38492fa7e")]
// 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.0.0.13")]
[assembly: AssemblyFileVersion("0.0.0.13")]
| 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("Adzerk.Api")]
[assembly: AssemblyDescription("Unofficial Adzerk API client.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Stack Exchange")]
[assembly: AssemblyProduct("Adzerk.Api")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d05e1e25-d95d-43d6-a74b-3cb38492fa7e")]
// 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.0.0.12")]
[assembly: AssemblyFileVersion("0.0.0.12")]
| mit | C# |
5722460b5180df68a955b3875fb66c16048c9622 | fix async calls | lvermeulen/Equalizer | src/Equalizer.Middleware.Core/RegistryClient.cs | src/Equalizer.Middleware.Core/RegistryClient.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Equalizer.Core;
using Nanophone.Core;
namespace Equalizer.Middleware.Core
{
public class RegistryClient
{
private readonly IRouter<RegistryInformation> _router;
private readonly List<IRegistryHost> _registryHosts = new List<IRegistryHost>();
public string PrefixName { get; }
public RegistryClient(string prefixName, IRouter<RegistryInformation> router)
{
PrefixName = prefixName;
_router = router;
}
public void AddRegistryHost(IRegistryHost registryHost)
{
_registryHosts.Add(registryHost);
}
public void RemoveRegistryHost(IRegistryHost registryHost)
{
_registryHosts.Remove(registryHost);
}
public async Task<IList<RegistryInformation>> FindServiceInstancesAsync()
{
var allInstances = new List<RegistryInformation>();
foreach (var registryHost in _registryHosts)
{
var instances = await registryHost.FindServiceInstancesAsync().ConfigureAwait(false);
allInstances.AddRange(instances);
}
return allInstances;
}
public IList<RegistryInformation> FindServiceInstances(Uri uri, IEnumerable<RegistryInformation> instances)
{
var results = instances
.Where(x => x.Tags.Any(tag => tag.StartsWith(PrefixName, StringComparison.OrdinalIgnoreCase)
&& uri.StartsWithSegments(tag.Substring(PrefixName.Length))))
.ToList();
return results;
}
public async Task<IList<RegistryInformation>> FindServiceInstancesAsync(Uri uri)
{
var instances = await FindServiceInstancesAsync().ConfigureAwait(false);
return FindServiceInstances(uri, instances);
}
public RegistryInformation Choose(IList<RegistryInformation> instances)
{
return _router.Choose(instances);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Equalizer.Core;
using Nanophone.Core;
namespace Equalizer.Middleware.Core
{
public class RegistryClient
{
private readonly IRouter<RegistryInformation> _router;
private readonly List<IRegistryHost> _registryHosts = new List<IRegistryHost>();
public string PrefixName { get; }
public RegistryClient(string prefixName, IRouter<RegistryInformation> router)
{
PrefixName = prefixName;
_router = router;
}
public void AddRegistryHost(IRegistryHost registryHost)
{
_registryHosts.Add(registryHost);
}
public void RemoveRegistryHost(IRegistryHost registryHost)
{
_registryHosts.Remove(registryHost);
}
public async Task<IList<RegistryInformation>> FindServiceInstancesAsync()
{
var allInstances = new List<RegistryInformation>();
foreach (var registryHost in _registryHosts)
{
var instances = await registryHost.FindServiceInstancesAsync().ConfigureAwait(false);
allInstances.AddRange(instances);
}
return allInstances;
}
public IList<RegistryInformation> FindServiceInstances(Uri uri, IEnumerable<RegistryInformation> instances)
{
var results = instances
.Where(x => x.Tags.Any(tag => tag.StartsWith(PrefixName, StringComparison.OrdinalIgnoreCase)
&& uri.StartsWithSegments(tag.Substring(PrefixName.Length))))
.ToList();
return results;
}
public async Task<IList<RegistryInformation>> FindServiceInstancesAsync(Uri uri)
{
var instances = await FindServiceInstancesAsync();
return FindServiceInstances(uri, instances);
}
public RegistryInformation Choose(IList<RegistryInformation> instances)
{
return _router.Choose(instances);
}
}
}
| mit | C# |
c9468cb0bcd3841d602b4a7b7bbf42176d730fcd | Check the environment variable for the license key | kylebjones/CertiPay.Services.PDF | CertiPay.Services.PDF/Bootstrapper.cs | CertiPay.Services.PDF/Bootstrapper.cs | using CertiPay.PDF;
using Nancy;
using Nancy.TinyIoc;
using System;
using System.Configuration;
namespace CertiPay.Services.PDF
{
public class Bootstrapper : DefaultNancyBootstrapper
{
private static String ABCPdfLicense
{
get
{
// Check the environment variables for the license key
String key = "ABCPDF-License";
if (!String.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(key, EnvironmentVariableTarget.User)))
{
return Environment.GetEnvironmentVariable(key, EnvironmentVariableTarget.User);
}
return ConfigurationManager.AppSettings[key];
}
}
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
container.Register<IPDFService>(new PDFService(ABCPdfLicense));
}
}
} | using CertiPay.PDF;
using Nancy;
using Nancy.TinyIoc;
using System;
using System.Configuration;
namespace CertiPay.Services.PDF
{
public class Bootstrapper : DefaultNancyBootstrapper
{
private static String ABCPdfLicense
{
get { return ConfigurationManager.AppSettings["ABCPDF-License"]; }
}
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
container.Register<IPDFService>(new PDFService(ABCPdfLicense));
}
}
} | mit | C# |
6cf0dc0024f6f76d157892394d69b3d48387e129 | Add enum member into LuryExceptionType | nokok/lury,HaiTo/lury,lury-lang/lury | src/Lury/Runtime/Exception/LuryExceptionType.cs | src/Lury/Runtime/Exception/LuryExceptionType.cs | //
// LuryExceptionType.cs
//
// Author:
// Tomona Nanase <nanase@users.noreply.github.com>
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Tomona Nanase
//
// 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 Lury.Runtime
{
public enum LuryExceptionType
{
Unknown = -1,
NilReference,
DivideByZero,
NotSupportedOperation,
NotEnoughFunctionArgumentNumber,
WrongBreak,
ConditionValueIsNotBoolean,
AttributeIsNotFound,
WrongLValue,
}
}
| //
// LuryExceptionType.cs
//
// Author:
// Tomona Nanase <nanase@users.noreply.github.com>
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Tomona Nanase
//
// 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 Lury
{
public enum LuryExceptionType
{
}
}
| mit | C# |
0661cddb296073958df12cfe56449a2f49ed2e81 | Add French language into LanguageSelector | larsbrubaker/MatterControl,rytz/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,ddpruitt/MatterControl,rytz/MatterControl,tellingmachine/MatterControl,unlimitedbacon/MatterControl,ddpruitt/MatterControl,jlewin/MatterControl,mmoening/MatterControl,MatterHackers/MatterControl,MatterHackers/MatterControl,unlimitedbacon/MatterControl,mmoening/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,CodeMangler/MatterControl,MatterHackers/MatterControl,CodeMangler/MatterControl,CodeMangler/MatterControl,tellingmachine/MatterControl,ddpruitt/MatterControl,mmoening/MatterControl,rytz/MatterControl,larsbrubaker/MatterControl | ConfigurationPage/LanguageSelector.cs | ConfigurationPage/LanguageSelector.cs | using MatterHackers.VectorMath;
using System.Collections.Generic;
namespace MatterHackers.MatterControl
{
public class LanguageSelector : StyledDropDownList
{
private Dictionary<string, string> languageDict;
public LanguageSelector()
: base("Default")
{
this.MinimumSize = new Vector2(this.LocalBounds.Width, this.LocalBounds.Height);
CreateLanguageDict();
string languageCode = UserSettings.Instance.get("Language");
foreach (KeyValuePair<string, string> entry in languageDict)
{
AddItem(entry.Key, entry.Value);
}
foreach (KeyValuePair<string, string> entry in languageDict)
{
if (languageCode == entry.Value)
{
SelectedLabel = entry.Key;
break;
}
}
}
private void CreateLanguageDict()
{
languageDict = new Dictionary<string, string>();
languageDict["Default"] = "EN";
languageDict["English"] = "EN";
languageDict["Español"] = "ES";
languageDict["Français"] = "FR";
languageDict["Deutsch"] = "DE";
languageDict["Polski"] = "PL";
languageDict["Türkçe"] = "TR";
}
}
} | using MatterHackers.VectorMath;
using System.Collections.Generic;
namespace MatterHackers.MatterControl
{
public class LanguageSelector : StyledDropDownList
{
private Dictionary<string, string> languageDict;
public LanguageSelector()
: base("Default")
{
this.MinimumSize = new Vector2(this.LocalBounds.Width, this.LocalBounds.Height);
CreateLanguageDict();
string languageCode = UserSettings.Instance.get("Language");
foreach (KeyValuePair<string, string> entry in languageDict)
{
AddItem(entry.Key, entry.Value);
}
foreach (KeyValuePair<string, string> entry in languageDict)
{
if (languageCode == entry.Value)
{
SelectedLabel = entry.Key;
break;
}
}
}
private void CreateLanguageDict()
{
languageDict = new Dictionary<string, string>();
languageDict["Default"] = "EN";
languageDict["English"] = "EN";
languageDict["Español"] = "ES";
//languageDict["Français"] = "FR";
languageDict["Deutsch"] = "DE";
languageDict["Polski"] = "PL";
languageDict["Türkçe"] = "TR";
}
}
} | bsd-2-clause | C# |
08f440c57b87fe5a3f7fb0b617cfd73cc9fd6c11 | improve timer test ranges | CoreAPM/DotNetAgent | CoreAPM.NET.Agent.Tests/TimerTests.cs | CoreAPM.NET.Agent.Tests/TimerTests.cs | using System.Diagnostics;
using System.Threading;
using NSubstitute;
using Xunit;
namespace CoreAPM.NET.Agent.Tests
{
public class TimerTests
{
[Fact]
public void TimerCanStartStopwatch()
{
//arrange
var stopwatch = Substitute.For<Stopwatch>();
var timer = new Timer(stopwatch);
//act
timer.Start();
//assert
stopwatch.Received().Start();
}
[Fact]
public void TimerCanStopStopwatch()
{
//arrange
var stopwatch = Substitute.For<Stopwatch>();
var timer = new Timer(stopwatch);
//act
timer.Stop();
//assert
stopwatch.Received().Stop();
}
[Fact]
public void TimerCanGetTimeFromStopwatch()
{
//arrange
var stopwatch = Substitute.For<Stopwatch>();
var timer = new Timer(stopwatch);
timer.Start();
Thread.Sleep(1);
timer.Stop();
//act
var result = timer.CurrentTime;
//assert
Assert.InRange(result, 1, 10);
}
[Fact]
public void TimerCanTimeAction()
{
//arrange
var stopwatch = Substitute.For<Stopwatch>();
var timer = new Timer(stopwatch);
//act
var result = timer.Time(() => Thread.Sleep(1));
//assert
Assert.InRange(result, 1, 10);
}
}
}
| using System.Diagnostics;
using System.Threading;
using NSubstitute;
using Xunit;
namespace CoreAPM.NET.Agent.Tests
{
public class TimerTests
{
[Fact]
public void TimerCanStartStopwatch()
{
//arrange
var stopwatch = Substitute.For<Stopwatch>();
var timer = new Timer(stopwatch);
//act
timer.Start();
//assert
stopwatch.Received().Start();
}
[Fact]
public void TimerCanStopStopwatch()
{
//arrange
var stopwatch = Substitute.For<Stopwatch>();
var timer = new Timer(stopwatch);
//act
timer.Stop();
//assert
stopwatch.Received().Stop();
}
[Fact]
public void TimerCanGetTimeFromStopwatch()
{
//arrange
var stopwatch = Substitute.For<Stopwatch>();
var timer = new Timer(stopwatch);
timer.Start();
Thread.Sleep(5);
timer.Stop();
//act
var result = timer.CurrentTime;
//assert
Assert.InRange(result, 5, 10);
}
[Fact]
public void TimerCanTimeAction()
{
//arrange
var stopwatch = Substitute.For<Stopwatch>();
var timer = new Timer(stopwatch);
//act
var result = timer.Time(() => Thread.Sleep(5));
//assert
Assert.InRange(result, 5, 10);
}
}
} | mit | C# |
cfce111383cedd5709c0237a976fd45e8fd3aacd | Handle drag and drop of folder. Fix #15 | aloisdg/Doccou,aloisdg/CountPages,saidmarouf/Doccou | CountPages/ViewModel/MainViewModel.cs | CountPages/ViewModel/MainViewModel.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using Counter;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
namespace CountPages.ViewModel
{
public class MainViewModel : ViewModelBase
{
public uint PageCount { get; set; }
public Visibility LoaderVisibility { get; set; }
public RelayCommand<object> Dropped { get; private set; }
public MainViewModel()
{
////if (IsInDesignMode)
////{
//// // Code runs in Blend --> create design time data.
////}
////else
////{
//// // Code runs "for real"
Dropped = new RelayCommand<object>(ExecuteDropped);
////}
SwitchLoaderVisibility();
}
private async void ExecuteDropped(object o)
{
var e = o as DragEventArgs;
if (e != null && e.Data.GetDataPresent(DataFormats.FileDrop, false))
await ReadFiles((string[])e.Data.GetData(DataFormats.FileDrop));
}
private async Task ReadFiles(IEnumerable<string> droppedPaths)
{
//try
//{
var paths = droppedPaths.SelectMany(path => path.GetAllFiles()).ToArray();
var tasks = new Task<Document>[paths.Length];
for (var i = 0; i < paths.Length; i++)
{
var path = paths[i];
var stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
tasks[i] = Task.Run(() => new Document(path, stream));
}
var documents = await Task.WhenAll(tasks);
PageCount = Convert.ToUInt32(documents.Sum(doc => doc.Count));
RaisePropertyChanged("PageCount");
//SwitchLoaderVisibility();
//}
//catch (Exception ex)
//{
// MessageBox.Show(ex.Message);
//}
}
private void SwitchLoaderVisibility()
{
LoaderVisibility = LoaderVisibility.Equals(Visibility.Visible)
? Visibility.Hidden : Visibility.Visible;
RaisePropertyChanged("LoaderVisibility");
}
}
public static class TreeReader
{
public static IEnumerable<string> GetAllFiles(this string path)
{
var queue = new Queue<string>();
queue.Enqueue(path);
while (queue.Count > 0)
{
path = queue.Dequeue();
if (String.IsNullOrEmpty(Path.GetExtension(path)))
{
try
{
foreach (var subDir in Directory.GetDirectories(path))
queue.Enqueue(subDir);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
}
string[] files = null;
try
{
files = Directory.GetFiles(path);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
}
if (files != null)
foreach (var t in files)
yield return t;
}
else
yield return path;
}
}
}
} | using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using Counter;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
namespace CountPages.ViewModel
{
public class MainViewModel : ViewModelBase
{
public uint PageCount { get; set; }
public Visibility LoaderVisibility { get; set; }
public RelayCommand<object> Dropped { get; private set; }
public MainViewModel()
{
////if (IsInDesignMode)
////{
//// // Code runs in Blend --> create design time data.
////}
////else
////{
//// // Code runs "for real"
Dropped = new RelayCommand<object>(ExecuteDropped);
////}
SwitchLoaderVisibility();
}
private async void ExecuteDropped(object o)
{
var e = o as DragEventArgs;
if (e != null)
await ReadFiles(e);
}
private async Task ReadFiles(DragEventArgs e)
{
if (!e.Data.GetDataPresent(DataFormats.FileDrop)) return;
//try
//{
var paths = (string[])e.Data.GetData(DataFormats.FileDrop);
var tasks = new Task<Document>[paths.Length];
for (var i = 0; i < paths.Length; i++)
{
var path = paths[i];
var stream = new FileStream(path, FileMode.Open);
tasks[i] = Task.Run<Document>(() =>
new Document(path, stream));
}
var documents = await Task.WhenAll(tasks);
PageCount = Convert.ToUInt32(documents.Sum(doc => doc.Count));
RaisePropertyChanged("PageCount");
//SwitchLoaderVisibility();
//}
//catch (Exception ex)
//{
// MessageBox.Show(ex.Message);
//}
}
private void SwitchLoaderVisibility()
{
LoaderVisibility = LoaderVisibility.Equals(Visibility.Visible)
? Visibility.Hidden : Visibility.Visible;
RaisePropertyChanged("LoaderVisibility");
}
}
} | mit | C# |
0b970b3de194463f81cb007fc3db74a40fc6dcd8 | Add skips to prime factors test suite | ErikSchierboom/xcsharp,ErikSchierboom/xcsharp,robkeim/xcsharp,exercism/xcsharp,robkeim/xcsharp,GKotfis/csharp,exercism/xcsharp,GKotfis/csharp | exercises/prime-factors/PrimeFactorsTest.cs | exercises/prime-factors/PrimeFactorsTest.cs | // This file was auto-generated based on version 1.0.0 of the canonical data.
using Xunit;
public class PrimeFactorsTest
{
[Fact]
public void No_factors()
{
Assert.Empty(PrimeFactors.Factors(1));
}
[Fact(Skip = "Remove to run test")]
public void Prime_number()
{
Assert.Equal(new[] { 2 }, PrimeFactors.Factors(2));
}
[Fact(Skip = "Remove to run test")]
public void Square_of_a_prime()
{
Assert.Equal(new[] { 3, 3 }, PrimeFactors.Factors(9));
}
[Fact(Skip = "Remove to run test")]
public void Cube_of_a_prime()
{
Assert.Equal(new[] { 2, 2, 2 }, PrimeFactors.Factors(8));
}
[Fact(Skip = "Remove to run test")]
public void Product_of_primes_and_non_primes()
{
Assert.Equal(new[] { 2, 2, 3 }, PrimeFactors.Factors(12));
}
[Fact(Skip = "Remove to run test")]
public void Product_of_primes()
{
Assert.Equal(new[] { 5, 17, 23, 461 }, PrimeFactors.Factors(901255));
}
[Fact(Skip = "Remove to run test")]
public void Factors_include_a_large_prime()
{
Assert.Equal(new[] { 11, 9539, 894119 }, PrimeFactors.Factors(93819012551));
}
} | // This file was auto-generated based on version 1.0.0 of the canonical data.
using Xunit;
public class PrimeFactorsTest
{
[Fact]
public void No_factors()
{
Assert.Empty(PrimeFactors.Factors(1));
}
[Fact]
public void Prime_number()
{
Assert.Equal(new[] { 2 }, PrimeFactors.Factors(2));
}
[Fact]
public void Square_of_a_prime()
{
Assert.Equal(new[] { 3, 3 }, PrimeFactors.Factors(9));
}
[Fact]
public void Cube_of_a_prime()
{
Assert.Equal(new[] { 2, 2, 2 }, PrimeFactors.Factors(8));
}
[Fact]
public void Product_of_primes_and_non_primes()
{
Assert.Equal(new[] { 2, 2, 3 }, PrimeFactors.Factors(12));
}
[Fact]
public void Product_of_primes()
{
Assert.Equal(new[] { 5, 17, 23, 461 }, PrimeFactors.Factors(901255));
}
[Fact]
public void Factors_include_a_large_prime()
{
Assert.Equal(new[] { 11, 9539, 894119 }, PrimeFactors.Factors(93819012551));
}
} | mit | C# |
cd16236bf6b9472234c3fdc5365f96e6307f206e | add basic logic for MockServerLoopNode | DarkCaster/DotNetBlocks,DarkCaster/DotNetBlocks | Tests/Mocks/DataLoop/MockServerLoopNode.cs | Tests/Mocks/DataLoop/MockServerLoopNode.cs | // MockServerLoopNode.cs
//
// The MIT License (MIT)
//
// Copyright (c) 2017 DarkCaster <dark.caster@outlook.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
using System;
using System.Threading;
using System.Threading.Tasks;
using DarkCaster.Async;
using DarkCaster.DataTransfer.Server;
using DarkCaster.DataTransfer.Config;
namespace Tests.Mocks.DataLoop
{
public sealed class MockServerLoopNode : INode
{
private readonly Random random;
private readonly AsyncRunner newConnRunner = new AsyncRunner();
private readonly ITunnelConfigFactory configFactory;
private readonly INode upstreamNode;
private volatile INode downstreamNode;
private readonly int minBlockSize;
private readonly int maxBlockSize;
private readonly int readTimeout;
private readonly float nodeFailProb;
private int noFailOpsCount;
private int initCount;
private int ncCount;
private int regDsCount;
private int shutdownCount;
private int disposeCount;
public MockServerLoopNode(ITunnelConfig serverConfig, INode upstream, ITunnelConfigFactory configFactory,
int defaultMinBlockSize = 16, int defaultMaxBlockSize = 4096, int defaultReadTimeout = 5000,
int defaultNoFailOpsCount = 1, float defaultNodeFailProb = 0.0f)
{
minBlockSize = serverConfig.Get<int>("mock_min_block_size");
maxBlockSize = serverConfig.Get<int>("mock_max_block_size");
readTimeout = serverConfig.Get<int>("mock_read_timeout");
nodeFailProb = serverConfig.Get<float>("mock_fail_prob");
noFailOpsCount = serverConfig.Get<int>("mock_nofail_ops_count");
if(minBlockSize <= 0)
minBlockSize = defaultMinBlockSize;
if(maxBlockSize <= 0)
maxBlockSize = defaultMaxBlockSize;
if(readTimeout <= 0)
readTimeout = defaultReadTimeout;
if(nodeFailProb <= 0.001f)
nodeFailProb = defaultNodeFailProb;
if(noFailOpsCount <= 0)
noFailOpsCount = defaultNoFailOpsCount;
this.upstreamNode = upstream;
this.configFactory = configFactory;
this.random = new Random();
}
public void NewConnection(Storage clientReadStorage, Storage clientWriteStorage)
{
Interlocked.Increment(ref ncCount);
//simulate fail
if(--noFailOpsCount <= 0 && (float)random.NextDouble() < nodeFailProb)
{
newConnRunner.ExecuteTask(() => downstreamNode.NodeFailAsync(new Exception("Expected fail")));
throw new Exception("Expected fail triggered");
}
var tunnel = new MockServerLoopTunnel(minBlockSize, maxBlockSize, clientWriteStorage, readTimeout, clientReadStorage);
var config = configFactory.CreateNew();
newConnRunner.ExecuteTask(() => downstreamNode.OpenTunnelAsync(config, tunnel));
}
public Task InitAsync()
{
Interlocked.Increment(ref initCount);
return Task.FromResult(true);
}
public void RegisterDownstream(INode downstream)
{
Interlocked.Increment(ref regDsCount);
this.downstreamNode = downstream;
}
public Task OpenTunnelAsync(ITunnelConfig config, ITunnel upstream)
{
throw new NotSupportedException("THIS IS A ROOT SERVER NODE");
}
public Task NodeFailAsync(Exception ex)
{
throw new NotSupportedException("THIS IS A ROOT SERVER NODE");
}
public Task ShutdownAsync()
{
Interlocked.Increment(ref shutdownCount);
return Task.FromResult(true);
}
public void Dispose()
{
Interlocked.Increment(ref disposeCount);
}
}
}
| // MockServerLoopNode.cs
//
// The MIT License (MIT)
//
// Copyright (c) 2017 DarkCaster <dark.caster@outlook.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
using System;
using System.Threading.Tasks;
using DarkCaster.DataTransfer.Server;
using DarkCaster.DataTransfer.Config;
namespace Tests.Mocks.DataLoop
{
public sealed class MockServerLoopNode : INode
{
public void NewConnection(Storage readStorage, Storage writeStorage)
{
}
public Task InitAsync()
{
throw new NotImplementedException("TODO");
}
public void RegisterDownstream(INode downstream)
{
throw new NotImplementedException("TODO");
}
public Task OpenTunnelAsync(ITunnelConfig config, ITunnel upstream)
{
throw new NotImplementedException("TODO");
}
public Task NodeFailAsync(Exception ex)
{
throw new NotImplementedException("TODO");
}
public Task ShutdownAsync()
{
throw new NotImplementedException("TODO");
}
public void Dispose()
{
}
}
}
| mit | C# |
84c51bf650ec82351184ffebc684e616503df3f8 | Remove ToList | anthonychu/slack-user-change-alerts | src/SlackUserChangeAlerts.Function/CheckUserListChanges/run.csx | src/SlackUserChangeAlerts.Function/CheckUserListChanges/run.csx | #r "Newtonsoft.Json"
using Newtonsoft.Json;
static HttpClient httpClient = new HttpClient();
static MemberComparer comparer = new MemberComparer();
public static async Task<string> Run(TimerInfo myTimer, string previousUsersJson, TraceWriter log)
{
var currentUsersJson = await httpClient.GetStringAsync($"https://slack.com/api/users.list?token={Env("SlackApiToken")}&pretty=1");
if (!string.IsNullOrEmpty(previousUsersJson))
{
var currentUsers = DeserializeMembers(currentUsersJson);
var previousUsers = DeserializeMembers(previousUsersJson);
var deletedUsers = previousUsers.Except(currentUsers, comparer).ToList();
var newUsers = currentUsers.Except(previousUsers, comparer).ToList();
await SendMessage("These users just got deleted: ", deletedUsers, log);
await SendMessage("These users just got added: ", newUsers, log);
}
return currentUsersJson;
}
private static async Task SendMessage(string message, IEnumerable<Member> users, TraceWriter log)
{
if (users.Any())
{
var slackMessage = message + string.Join(", ", users.Select(u => $"{u.Name}({u.Real_name ?? ""})"));
log.Info($"Sending to {Env("ChannelsToNotify")}:\n{slackMessage}");
var channels = Env("ChannelsToNotify").Split(',');
foreach (var channel in channels)
{
await httpClient.PostAsync($"{Env("SlackbotUrl")}&channel={channel.Trim()}", new StringContent(slackMessage));
}
}
}
private static IEnumerable<Member> DeserializeMembers(string json) =>
JsonConvert.DeserializeObject<UserCollection>(json).Members.Where(m => !m.Deleted);
private static string Env(string name) => System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
public class UserCollection
{
public IEnumerable<Member> Members { get; set; } = new List<Member>();
}
public class Member
{
public string Name { get; set; }
public string Real_name { get; set; }
public bool Deleted { get; set; }
}
public class MemberComparer : IEqualityComparer<Member>
{
public bool Equals(Member x, Member y) => x.Name == y.Name;
public int GetHashCode(Member m) => 0;
} | #r "Newtonsoft.Json"
using Newtonsoft.Json;
static HttpClient httpClient = new HttpClient();
static MemberComparer comparer = new MemberComparer();
public static async Task<string> Run(TimerInfo myTimer, string previousUsersJson, TraceWriter log)
{
var currentUsersJson = await httpClient.GetStringAsync($"https://slack.com/api/users.list?token={Env("SlackApiToken")}&pretty=1");
if (!string.IsNullOrEmpty(previousUsersJson))
{
var currentUsers = DeserializeMembers(currentUsersJson);
var previousUsers = DeserializeMembers(previousUsersJson);
var deletedUsers = previousUsers.Except(currentUsers, comparer).ToList();
var newUsers = currentUsers.Except(previousUsers, comparer).ToList();
await SendMessage("These users just got deleted: ", deletedUsers, log);
await SendMessage("These users just got added: ", newUsers, log);
}
return currentUsersJson;
}
private static async Task SendMessage(string message, IEnumerable<Member> users, TraceWriter log)
{
if (users.Any())
{
var slackMessage = message + string.Join(", ", users.Select(u => $"{u.Name}({u.Real_name ?? ""})"));
log.Info($"Sending to {Env("ChannelsToNotify")}:\n{slackMessage}");
var channels = Env("ChannelsToNotify").Split(',');
foreach (var channel in channels)
{
await httpClient.PostAsync($"{Env("SlackbotUrl")}&channel={channel.Trim()}", new StringContent(slackMessage));
}
}
}
private static IEnumerable<Member> DeserializeMembers(string json) =>
JsonConvert.DeserializeObject<UserCollection>(json).Members.Where(m => !m.Deleted).ToList();
private static string Env(string name) => System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
public class UserCollection
{
public IEnumerable<Member> Members { get; set; } = new List<Member>();
}
public class Member
{
public string Name { get; set; }
public string Real_name { get; set; }
public bool Deleted { get; set; }
}
public class MemberComparer : IEqualityComparer<Member>
{
public bool Equals(Member x, Member y) => x.Name == y.Name;
public int GetHashCode(Member m) => 0;
} | apache-2.0 | C# |
193d84b2fdc1b41069d7bc2c96e7f86aff0c1347 | Clean up using directives | Microsoft/ApplicationInsights-SDK-Labs,frackleton/ApplicationInsights-SDK-Labs | WCF/Shared/ClientIpTelemetryInitializer.cs | WCF/Shared/ClientIpTelemetryInitializer.cs | using System;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.Extensibility.Implementation;
using System.ServiceModel.Channels;
using Microsoft.ApplicationInsights.Wcf.Implementation;
namespace Microsoft.ApplicationInsights.Wcf
{
/// <summary>
/// Collects the IP of the client calling the WCF service
/// </summary>
public sealed class ClientIpTelemetryInitializer : WcfTelemetryInitializer
{
/// <summary>
/// Initialize the telemetry event with the client IP if available
/// </summary>
/// <param name="telemetry">The telemetry event</param>
/// <param name="operation">The WCF operation context</param>
protected override void OnInitialize(ITelemetry telemetry, IOperationContext operation)
{
if ( String.IsNullOrEmpty(telemetry.Context.Location.Ip) )
{
var location = operation.Request.Context.Location;
if ( String.IsNullOrEmpty(location.Ip) )
{
UpdateClientIp(location, operation);
}
telemetry.Context.Location.Ip = location.Ip;
}
}
private void UpdateClientIp(LocationContext location, IOperationContext operation)
{
if ( operation.HasIncomingMessageProperty(RemoteEndpointMessageProperty.Name) )
{
var property = (RemoteEndpointMessageProperty)
operation.GetIncomingMessageProperty(RemoteEndpointMessageProperty.Name);
location.Ip = property.Address;
WcfEventSource.Log.LocationIdSet(location.Ip);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.Extensibility.Implementation;
using System.ServiceModel.Channels;
using Microsoft.ApplicationInsights.Wcf.Implementation;
namespace Microsoft.ApplicationInsights.Wcf
{
/// <summary>
/// Collects the IP of the client calling the WCF service
/// </summary>
public sealed class ClientIpTelemetryInitializer : WcfTelemetryInitializer
{
/// <summary>
/// Initialize the telemetry event with the client IP if available
/// </summary>
/// <param name="telemetry">The telemetry event</param>
/// <param name="operation">The WCF operation context</param>
protected override void OnInitialize(ITelemetry telemetry, IOperationContext operation)
{
if ( String.IsNullOrEmpty(telemetry.Context.Location.Ip) )
{
var location = operation.Request.Context.Location;
if ( String.IsNullOrEmpty(location.Ip) )
{
UpdateClientIp(location, operation);
}
telemetry.Context.Location.Ip = location.Ip;
}
}
private void UpdateClientIp(LocationContext location, IOperationContext operation)
{
if ( operation.HasIncomingMessageProperty(RemoteEndpointMessageProperty.Name) )
{
var property = (RemoteEndpointMessageProperty)
operation.GetIncomingMessageProperty(RemoteEndpointMessageProperty.Name);
location.Ip = property.Address;
WcfEventSource.Log.LocationIdSet(location.Ip);
}
}
}
}
| mit | C# |
1fe933437a944e471677db8f6d7a8942a378a5ff | exclude another Unit test | sachatrauwaen/OpenApp,sachatrauwaen/OpenApp,sachatrauwaen/OpenApp,sachatrauwaen/OpenApp,sachatrauwaen/OpenApp,sachatrauwaen/OpenApp | test/Satrabel.OpenApp.Tests/Sessions/SessionAppService_Tests.cs | test/Satrabel.OpenApp.Tests/Sessions/SessionAppService_Tests.cs | using System.Threading.Tasks;
using Satrabel.OpenApp.Sessions;
using Shouldly;
using Xunit;
namespace Satrabel.OpenApp.Tests.Sessions
{
public class SessionAppService_Tests : StarterTestBase
{
private readonly ISessionAppService _sessionAppService;
public SessionAppService_Tests()
{
_sessionAppService = Resolve<ISessionAppService>();
}
//[MultiTenantFact]
//public async Task Should_Get_Current_User_When_Logged_In_As_Host()
//{
// //Arrange
// LoginAsHostAdmin();
// //Act
// var output = await _sessionAppService.GetCurrentLoginInformations();
// //Assert
// var currentUser = await GetCurrentUserAsync();
// output.User.ShouldNotBe(null);
// output.User.Name.ShouldBe(currentUser.Name);
// output.User.Surname.ShouldBe(currentUser.Surname);
// output.Tenant.ShouldBe(null);
//}
//[Fact]
//public async Task Should_Get_Current_User_And_Tenant_When_Logged_In_As_Tenant()
//{
// //Act
// var output = await _sessionAppService.GetCurrentLoginInformations();
// //Assert
// var currentUser = await GetCurrentUserAsync();
// var currentTenant = await GetCurrentTenantAsync();
// output.User.ShouldNotBe(null);
// output.User.Name.ShouldBe(currentUser.Name);
// output.Tenant.ShouldNotBe(null);
// output.Tenant.Name.ShouldBe(currentTenant.Name);
//}
}
}
| using System.Threading.Tasks;
using Satrabel.OpenApp.Sessions;
using Shouldly;
using Xunit;
namespace Satrabel.OpenApp.Tests.Sessions
{
public class SessionAppService_Tests : StarterTestBase
{
private readonly ISessionAppService _sessionAppService;
public SessionAppService_Tests()
{
_sessionAppService = Resolve<ISessionAppService>();
}
//[MultiTenantFact]
//public async Task Should_Get_Current_User_When_Logged_In_As_Host()
//{
// //Arrange
// LoginAsHostAdmin();
// //Act
// var output = await _sessionAppService.GetCurrentLoginInformations();
// //Assert
// var currentUser = await GetCurrentUserAsync();
// output.User.ShouldNotBe(null);
// output.User.Name.ShouldBe(currentUser.Name);
// output.User.Surname.ShouldBe(currentUser.Surname);
// output.Tenant.ShouldBe(null);
//}
[Fact]
public async Task Should_Get_Current_User_And_Tenant_When_Logged_In_As_Tenant()
{
//Act
var output = await _sessionAppService.GetCurrentLoginInformations();
//Assert
var currentUser = await GetCurrentUserAsync();
var currentTenant = await GetCurrentTenantAsync();
output.User.ShouldNotBe(null);
output.User.Name.ShouldBe(currentUser.Name);
output.Tenant.ShouldNotBe(null);
output.Tenant.Name.ShouldBe(currentTenant.Name);
}
}
}
| mit | C# |
6601d97619fcf7b14ae90f6bc4e410fb5829bf37 | Improve LogAnalysis tests (#1696) | exercism/xcsharp,exercism/xcsharp | exercises/concept/log-analysis/LogAnalysisTests.cs | exercises/concept/log-analysis/LogAnalysisTests.cs | using Xunit;
using Exercism.Tests;
using System;
public class LogAnalysisTests
{
[Fact]
public void SubstringAfter_WithDelimeterOfLength1()
{
Assert.Equal(" am the 1st test", "I am the 1st test".SubstringAfter("I"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void SubstringAfter_WithDelimeterOfLengthLongerThan1()
{
Assert.Equal(" test", "I am the 2nd test".SubstringAfter("2nd"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void SubstringBetween()
{
Assert.Equal("INFO", "[INFO]: File Deleted.".SubstringBetween("[", "]"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void SubstringBetweenLongerDelimiters()
{
Assert.Equal("SOMETHING", "FIND >>> SOMETHING <===< HERE".SubstringBetween(">>> ", " <===<"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Message()
{
var log = "[WARNING]: Library is deprecated.";
Assert.Equal("Library is deprecated.", log.Message());
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void LogLevel()
{
var log = "[WARNING]: Library is deprecated.";
Assert.Equal("WARNING", log.LogLevel());;
}
}
| using Xunit;
using Exercism.Tests;
using System;
public class LogAnalysisTests
{
[Fact]
public void SubstringAfter_WithDelimeterOfLength1()
{
Assert.Equal(" am the 1st test", "I am the 1st test".SubstringAfter("I"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void SubstringAfter_WithDelimeterOfLengthLongerThan1()
{
Assert.Equal(" test", "I am the 2nd test".SubstringAfter("2nd"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void SubstringBetween()
{
Assert.Equal("INFO", "[INFO]: File Deleted.".SubstringBetween("[", "]"));
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Message()
{
var log = "[WARNING]: Library is deprecated.";
Assert.Equal("Library is deprecated.", log.Message());
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void LogLevel()
{
var log = "[WARNING]: Library is deprecated.";
Assert.Equal("WARNING", log.LogLevel());;
}
}
| mit | C# |
07e144147d17a8cf3bb0d27cdffc75312b15ee58 | Update ShapeStyleDragAndDropListBox.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D | Core2D.Wpf/Controls/Custom/Lists/ShapeStyleDragAndDropListBox.cs | Core2D.Wpf/Controls/Custom/Lists/ShapeStyleDragAndDropListBox.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Immutable;
using System.Windows.Controls;
namespace Core2D.Wpf.Controls.Custom.Lists
{
/// <summary>
/// The <see cref="ListBox"/> control for <see cref="ShapeStyle"/> items with drag and drop support.
/// </summary>
public class ShapeStyleDragAndDropListBox : DragAndDropListBox<ShapeStyle>
{
/// <summary>
/// Initializes a new instance of the <see cref="ShapeStyleDragAndDropListBox"/> class.
/// </summary>
public ShapeStyleDragAndDropListBox()
: base()
{
this.Initialized += (s, e) => base.Initialize();
}
/// <summary>
/// Updates DataContext binding to ImmutableArray collection property.
/// </summary>
/// <param name="array">The updated immutable array.</param>
public override void UpdateDataContext(ImmutableArray<ShapeStyle> array)
{
var editor = (Core2D.Editor)this.Tag;
var sg = editor.Project.CurrentStyleLibrary;
var previous = sg.Items;
var next = array;
editor.Project?.History?.Snapshot(previous, next, (p) => sg.Items = p);
sg.Items = next;
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Immutable;
using System.Windows.Controls;
namespace Core2D.Wpf.Controls.Custom.Lists
{
/// <summary>
/// The <see cref="ListBox"/> control for <see cref="ShapeStyle"/> items with drag and drop support.
/// </summary>
public class ShapeStyleDragAndDropListBox : DragAndDropListBox<ShapeStyle>
{
/// <summary>
/// Initializes a new instance of the <see cref="ShapeStyleDragAndDropListBox"/> class.
/// </summary>
public ShapeStyleDragAndDropListBox()
: base()
{
this.Initialized += (s, e) => base.Initialize();
}
/// <summary>
/// Updates DataContext binding to ImmutableArray collection property.
/// </summary>
/// <param name="array">The updated immutable array.</param>
public override void UpdateDataContext(ImmutableArray<ShapeStyle> array)
{
var editor = (Core2D.Editor)this.Tag;
var sg = editor.Project.CurrentStyleLibrary;
var previous = sg.Items;
var next = array;
editor.project?.History?.Snapshot(previous, next, (p) => sg.Items = p);
sg.Items = next;
}
}
}
| mit | C# |
7240367e34a7465ea8c94c011aa41aa9fd9a4b44 | Update WikipediaHandler to use new method | IvionSauce/MeidoBot | UrlTitling/WebIrc/WikipediaHandler.cs | UrlTitling/WebIrc/WikipediaHandler.cs | using System;
using IvionWebSoft;
namespace WebIrc
{
public class WikipediaHandler
{
public int MaxCharacters { get; set; }
public string ContinuationSymbol { get; set; }
public TitlingResult WikipediaSummarize(TitlingRequest req, string htmlDoc)
{
WikipediaArticle article = WikipediaTools.Parse(htmlDoc);
// The paragraph to be summarized.
string p = null;
// Check if the URL has an anchor to a specific section in the article.
int anchorIndex = req.Url.IndexOf("#", StringComparison.OrdinalIgnoreCase);
if (anchorIndex >= 0 && (anchorIndex + 1) < req.Url.Length)
{
var anchorId = req.Url.Substring(anchorIndex + 1);
p = article.GetFirstParagraph(anchorId);
}
// If no anchor or if we couldn't extract a paragraph for the specific anchor,
// get first paragraph of the article.
if (p == null && article.SummaryParagraphs.Length > 0)
p = article.SummaryParagraphs[0];
if (!string.IsNullOrWhiteSpace(p))
{
string summary;
if (MaxCharacters > 0 && p.Length <= MaxCharacters)
summary = p;
else
summary = p.Substring(0, MaxCharacters) + ContinuationSymbol;
req.IrcTitle.SetFormat("[ {0} ]", summary);
}
return req.CreateResult(true);
}
}
} | using System;
using IvionWebSoft;
namespace WebIrc
{
public class WikipediaHandler
{
public int MaxCharacters { get; set; }
public string ContinuationSymbol { get; set; }
public TitlingResult WikipediaSummarize(TitlingRequest req, string htmlDoc)
{
WikipediaArticle article = WikipediaTools.Parse(htmlDoc);
// The paragraph to be summarized.
string p = null;
// Check if the URL has an anchor to a specific section in the article.
int anchorIndex = req.Url.IndexOf("#", StringComparison.OrdinalIgnoreCase);
if (anchorIndex >= 0 && (anchorIndex + 1) < req.Url.Length)
{
var anchorId = req.Url.Substring(anchorIndex + 1);
p = GetFirstParagraph(article, anchorId);
}
// If no anchor or if we couldn't extract a paragraph for the specific anchor,
// get first paragraph of the article.
if (p == null && article.SummaryParagraphs.Length > 0)
p = article.SummaryParagraphs[0];
if (!string.IsNullOrWhiteSpace(p))
{
string summary;
if (MaxCharacters > 0 && p.Length <= MaxCharacters)
summary = p;
else
summary = p.Substring(0, MaxCharacters) + ContinuationSymbol;
req.IrcTitle.SetFormat("[ {0} ]", summary);
}
return req.CreateResult(true);
}
// Keep searching, from anchor forward, for a section with paragraphs.
// Returns null in case it couldn't find any.
static string GetFirstParagraph(WikipediaArticle article, string anchorId)
{
int sectionIndex = article.IndexOf(anchorId);
if (sectionIndex >= 0)
{
while (sectionIndex < article.SectionCount)
{
var section = article[sectionIndex];
if (section.Paragraphs.Length > 0)
return section.Paragraphs[0];
else
sectionIndex++;
}
}
return null;
}
}
} | bsd-2-clause | C# |
44e264f8e19c3412b6224c8a9f645a7552532fa5 | Upgrade assembly version to 2.4.0 | transistor1/dockpanelsuite,joelbyren/dockpanelsuite,angelapper/dockpanelsuite,ArsenShnurkov/dockpanelsuite,shintadono/dockpanelsuite,rohitlodha/dockpanelsuite,RadarNyan/dockpanelsuite,modulexcite/O2_Fork_dockpanelsuite,15070217668/dockpanelsuite,jorik041/dockpanelsuite,xo-energy/dockpanelsuite,thijse/dockpanelsuite,dockpanelsuite/dockpanelsuite,15070217668/dockpanelsuite,compborg/dockpanelsuite,Romout/dockpanelsuite,elnomade/dockpanelsuite | WinFormsUI/Properties/AssemblyInfo.cs | WinFormsUI/Properties/AssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
[assembly: AssemblyTitle("DockPanel Suite for .Net 2.0")]
[assembly: AssemblyDescription(".Net Docking Library for Windows Forms")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Weifen Luo")]
[assembly: AssemblyProduct("DockPanel Suite")]
[assembly: AssemblyCopyright("Copyright © Weifen Luo 2007")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: Guid("9d690ef9-ce19-4c69-874c-e24d8eb36aff")]
[assembly: AssemblyVersion("2.4.0.*")]
[assembly: AssemblyFileVersion("2.4.0.0")]
[module: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "namespace", Target = "WeifenLuo.WinFormsUI.Docking", MessageId = "Weifen")]
[module: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "namespace", Target = "WeifenLuo.WinFormsUI.Docking", MessageId = "Luo")]
[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Weifen")]
[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Luo")]
[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Dockable")] | using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
[assembly: AssemblyTitle("DockPanel Suite for .Net 2.0")]
[assembly: AssemblyDescription(".Net Docking Library for Windows Forms")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Weifen Luo")]
[assembly: AssemblyProduct("DockPanel Suite")]
[assembly: AssemblyCopyright("Copyright © Weifen Luo 2007")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: Guid("9d690ef9-ce19-4c69-874c-e24d8eb36aff")]
[assembly: AssemblyVersion("2.3.1.*")]
[assembly: AssemblyFileVersion("2.3.1.0")]
[module: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "namespace", Target = "WeifenLuo.WinFormsUI.Docking", MessageId = "Weifen")]
[module: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "namespace", Target = "WeifenLuo.WinFormsUI.Docking", MessageId = "Luo")]
[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Weifen")]
[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Luo")]
[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Dockable")] | mit | C# |
9371e709cecb50421c42eaa3efb99eba0a63dac0 | Update build.cake | xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents | XPlat/ExposureNotification/build.cake | XPlat/ExposureNotification/build.cake | var TARGET = Argument("t", Argument("target", "ci"));
var SRC_COMMIT = "0453ef280effd21903f3920fba57b58695cf60ab";
var SRC_URL = $"https://github.com/xamarin/xamarin.exposurenotification/archive/{SRC_COMMIT}.zip";
var OUTPUT_PATH = (DirectoryPath)"./output/";
var NUGET_VERSION = "0.2.1-preview";
Task("externals")
.Does(() =>
{
DownloadFile(SRC_URL, "./src.zip");
Unzip("./src.zip", "./");
MoveDirectory($"./xamarin.exposurenotification-{SRC_COMMIT}", "./src");
});
Task("libs")
.IsDependentOn("externals")
.Does(() =>
{
EnsureDirectoryExists(OUTPUT_PATH);
MSBuild($"./src/Xamarin.ExposureNotification/Xamarin.ExposureNotification.csproj", c => c
.SetConfiguration("Release")
.WithRestore()
.WithTarget("Build")
.WithTarget("Pack")
.WithProperty("PackageVersion", NUGET_VERSION)
.WithProperty("PackageOutputPath", MakeAbsolute(OUTPUT_PATH).FullPath));
});
Task("nuget")
.IsDependentOn("libs");
Task("samples")
.IsDependentOn("nuget");
Task("clean")
.Does(() =>
{
CleanDirectories("./externals/");
});
Task("ci")
.IsDependentOn("nuget");
RunTarget(TARGET);
| var TARGET = Argument("t", Argument("target", "ci"));
var SRC_COMMIT = "1dbccda04f9adb511b422125ebdb2eb3aae8329b";
var SRC_URL = $"https://github.com/xamarin/xamarin.exposurenotification/archive/{SRC_COMMIT}.zip";
var OUTPUT_PATH = (DirectoryPath)"./output/";
var NUGET_VERSION = "0.2.0-preview01";
Task("externals")
.Does(() =>
{
DownloadFile(SRC_URL, "./src.zip");
Unzip("./src.zip", "./");
MoveDirectory($"./xamarin.exposurenotification-{SRC_COMMIT}", "./src");
});
Task("libs")
.IsDependentOn("externals")
.Does(() =>
{
EnsureDirectoryExists(OUTPUT_PATH);
MSBuild($"./src/Xamarin.ExposureNotification/Xamarin.ExposureNotification.csproj", c => c
.SetConfiguration("Release")
.WithRestore()
.WithTarget("Build")
.WithTarget("Pack")
.WithProperty("PackageVersion", NUGET_VERSION)
.WithProperty("PackageOutputPath", MakeAbsolute(OUTPUT_PATH).FullPath));
});
Task("nuget")
.IsDependentOn("libs");
Task("samples")
.IsDependentOn("nuget");
Task("clean")
.Does(() =>
{
CleanDirectories("./externals/");
});
Task("ci")
.IsDependentOn("nuget");
RunTarget(TARGET);
| mit | C# |
6be18f4aeebca49f4fde6f24b628b04d4276a26e | Fix float-double conversion | Xenopathic/spatial-evolution,Xenopathic/spatial-evolution | workers/unity/Assets/Gamelogic/Behaviours/OrganismMovement.cs | workers/unity/Assets/Gamelogic/Behaviours/OrganismMovement.cs | using UnityEngine;
using System;
using Random = UnityEngine.Random;
using Improbable.Math;
using System.Collections;
using Evolution.Organism;
using Improbable.Unity;
using Improbable.Unity.Visualizer;
namespace Assets.Gamelogic.Organisms {
public class OrganismMovement : MonoBehaviour {
[Require]
private Mover.Writer OrganismMoverWriter;
int ticksTravelled = 0;
int maxTicks;
float tickDelay = Time.deltaTime; //time between Update calls.
public void OnEnable() {
changeDirection();
moveOrganism();
}
public void Update() {
moveOrganism();
}
public void moveOrganism()
{
maxTicks = OrganismMoverWriter.Data.timeConstant;
if ((float)ticksTravelled / maxTicks > Random.Range(0, 1) * 2)
{
changeDirection();
ticksTravelled = 0;
}
var currentSpeed = OrganismMoverWriter.Data.speed;
var currentAngle = OrganismMoverWriter.Data.angle;
var xTranslation = currentSpeed * tickDelay * Mathf.Cos(currentAngle);
var yTranslation = currentSpeed * tickDelay * Mathf.Sin(currentAngle);
transform.Translate(xTranslation, yTranslation, 0, Space.World);
Coordinates oldCoordinates = OrganismMoverWriter.Data.position;
Coordinates newCoordinates = new Coordinates(Mathf.Clamp((float)oldCoordinates.X + xTranslation, 0, 1000),
Mathf.Clamp((float)oldCoordinates.Y + yTranslation, 0, 1000),
oldCoordinates.Z);
OrganismMoverWriter.Send(new Mover.Update().SetPosition(newCoordinates));
ticksTravelled++;
}
public void changeDirection() {
OrganismMoverWriter.Send(new Mover.Update().SetAngle(Random.Range(0f, 2 * Mathf.PI)));
}
}
}
| using UnityEngine;
using System;
using Random = UnityEngine.Random;
using Improbable.Math;
using System.Collections;
using Evolution.Organism;
using Improbable.Unity;
using Improbable.Unity.Visualizer;
namespace Assets.Gamelogic.Organisms {
public class OrganismMovement : MonoBehaviour {
[Require]
private Mover.Writer OrganismMoverWriter;
int gridBorderX = 990;
int gridBorderY = 990;
int ticksTravelled = 0;
int maxTicks;
float tickDelay = Time.deltaTime; //time between Update calls.
public void OnEnable() {
changeDirection();
moveOrganism();
}
public void Update() {
moveOrganism();
}
public void moveOrganism()
{
maxTicks = OrganismMoverWriter.Data.timeConstant;
if (ticksTravelled / maxTicks > Random.Range(0, 1) * 2)
{
changeDirection();
ticksTravelled = 0;
}
var currentSpeed = OrganismMoverWriter.Data.speed;
var currentAngle = OrganismMoverWriter.Data.angle;
var xTranslation = currentSpeed * tickDelay * Mathf.Cos(currentAngle);
var yTranslation = currentSpeed * tickDelay * Mathf.Sin(currentAngle);
transform.Translate(xTranslation, yTranslation, 0, Space.World);
Coordinates oldCoordinates = OrganismMoverWriter.Data.position;
Coordinates newCoordinates = new Coordinates(Mathf.Clamp(oldCoordinates.X + xTranslation, 0, 1000),
Mathf.Clamp(oldCoordinates.Y + yTranslation, 0, 1000),
oldCoordinates.Z);
OrganismMoverWriter.Send(new Mover.Update().SetPosition(newCoordinates));
ticksTravelled++;
}
public void changeDirection() {
OrganismMoverWriter.Send(new Mover.Update().SetAngle(Random.Range(0f, 2 * Mathf.PI)));
}
}
} | mit | C# |
e057ea96228d18b5f286cff9ec78b23958b7fdec | add closing method | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/CrashReporter/Views/CrashReportWindow.xaml.cs | WalletWasabi.Gui/CrashReporter/Views/CrashReportWindow.xaml.cs | using System;
using System.ComponentModel;
using Avalonia;
using Avalonia.Markup.Xaml;
using AvalonStudio.Shell.Controls;
using Splat;
namespace WalletWasabi.Gui.CrashReporter.Views
{
public class CrashReportWindow : MetroWindow
{
public CrashReportWindow()
{
InitializeComponent();
#if DEBUG
this.AttachDevTools();
#endif
Closing += CrashReportWindow_ClosingAsync;
}
private void CrashReportWindow_ClosingAsync(object sender, CancelEventArgs e)
{
Environment.Exit(0);
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
| using Avalonia;
using Avalonia.Markup.Xaml;
using AvalonStudio.Shell.Controls;
using Splat;
namespace WalletWasabi.Gui.CrashReporter.Views
{
public class CrashReportWindow : MetroWindow
{
public CrashReportWindow()
{
InitializeComponent();
#if DEBUG
this.AttachDevTools();
#endif
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
| mit | C# |
f53f14f69577abf25f2aa97f41f10aaa5f273f6e | add some more scenario tests for Experiment.AutoFixture. | jwChung/Experimentalism,jwChung/Experimentalism | test/Experiment.AutoFixtureUnitTest/Scenario.cs | test/Experiment.AutoFixtureUnitTest/Scenario.cs | using System;
using System.Collections.Generic;
using System.Reflection;
using Xunit;
using Xunit.Extensions;
namespace Jwc.Experiment
{
public class Scenario
{
[Theorem]
public void TheoremSupportsNonParameterizedTest()
{
Assert.True(true, "excuted.");
}
[Theorem]
[InlineData("expected", 1234)]
[ParameterizedTestData]
public void TheoremSupportsParameterizedTest(string arg1, int arg2)
{
Assert.Equal("expected", arg1);
Assert.Equal(1234, arg2);
}
[Theorem]
public void TheoremSupportsParameterizedTestWithAutoData(
string arg1, Type arg2)
{
Assert.NotNull(arg1);
Assert.NotNull(arg2);
}
[Theorem]
[InlineData("expected")]
public void TheoremSupportsParameterizedTestWithMixedData(
string arg1, object arg2)
{
Assert.Equal("expected", arg1);
Assert.NotNull(arg2);
}
private class ParameterizedTestDataAttribute : DataAttribute
{
public override IEnumerable<object[]> GetData(MethodInfo methodUnderTest, Type[] parameterTypes)
{
yield return new object[] { "expected", 1234 };
}
}
}
} | using System;
using Xunit;
namespace Jwc.Experiment
{
public class Scenario
{
[Theorem]
public void TheoremSupportsParameterizedTestWithAutoData(
string arg1, Type arg2)
{
Assert.NotNull(arg1);
Assert.NotNull(arg2);
}
}
} | mit | C# |
41451127a0279038df297889f3f4c7708af47399 | Break up bulk operations that can't be batched. | SilkStack/Silk.Data.SQL.ORM | Silk.Data.SQL.ORM/Operations/BulkOperation.cs | Silk.Data.SQL.ORM/Operations/BulkOperation.cs | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Silk.Data.SQL.Expressions;
using Silk.Data.SQL.ORM.Operations.Expressions;
using Silk.Data.SQL.Queries;
namespace Silk.Data.SQL.ORM.Operations
{
public class BulkOperation
{
private readonly DataOperation[] _operations;
public BulkOperation(DataOperation[] operations)
{
var bulkOperations = new List<DataOperation>();
var currentOperations = new List<DataOperation>();
foreach (var operation in operations)
{
if (!operation.CanBeBatched)
{
bulkOperations.Add(new BulkDataOperation(currentOperations.ToArray()));
currentOperations.Clear();
}
currentOperations.Add(operation);
}
if (currentOperations.Count > 0)
{
bulkOperations.Add(new BulkDataOperation(currentOperations.ToArray()));
}
_operations = bulkOperations.ToArray();
}
public DataOperation[] GetOperations() => _operations;
private class BulkDataOperation : DataOperation
{
private readonly DataOperation[] _operations;
public override bool CanBeBatched => _operations.All(q => q.CanBeBatched);
public BulkDataOperation(DataOperation[] operations)
{
_operations = operations;
}
public override QueryExpression GetQuery()
{
return new CompositeQueryExpression(
_operations.Select(q => q.GetQuery()).ToArray()
);
}
public override void ProcessResult(QueryResult queryResult)
{
foreach (var operation in _operations)
operation.ProcessResult(queryResult);
}
public override async Task ProcessResultAsync(QueryResult queryResult)
{
foreach (var operation in _operations)
await operation.ProcessResultAsync(queryResult);
}
}
}
}
| using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Silk.Data.SQL.Expressions;
using Silk.Data.SQL.ORM.Operations.Expressions;
using Silk.Data.SQL.Queries;
namespace Silk.Data.SQL.ORM.Operations
{
public class BulkOperation
{
private readonly DataOperation[] _operations;
public BulkOperation(DataOperation[] operations)
{
var bulkOperations = new List<DataOperation>();
var currentOperations = new List<DataOperation>();
foreach (var operation in operations)
{
if (operation.CanBeBatched)
{
currentOperations.Add(operation);
}
}
if (currentOperations.Count > 0)
{
bulkOperations.Add(new BulkDataOperation(currentOperations.ToArray()));
}
_operations = bulkOperations.ToArray();
}
public DataOperation[] GetOperations() => _operations;
private class BulkDataOperation : DataOperation
{
private readonly DataOperation[] _operations;
public override bool CanBeBatched => _operations.All(q => q.CanBeBatched);
public BulkDataOperation(DataOperation[] operations)
{
_operations = operations;
}
public override QueryExpression GetQuery()
{
return new CompositeQueryExpression(
_operations.Select(q => q.GetQuery()).ToArray()
);
}
public override void ProcessResult(QueryResult queryResult)
{
foreach (var operation in _operations)
operation.ProcessResult(queryResult);
}
public override async Task ProcessResultAsync(QueryResult queryResult)
{
foreach (var operation in _operations)
await operation.ProcessResultAsync(queryResult);
}
}
}
}
| mit | C# |
21191d15f30d8a29305d83c4d6b4ded1670f7cfa | Add namespace for MassSetTags tool | petereichinger/unity-helpers | Assets/Scripts/EditorTools/Editor/MassSetTags.cs | Assets/Scripts/EditorTools/Editor/MassSetTags.cs | using System.Collections;
using UnityEditor;
using UnityEngine;
namespace UnityHelpers.EditorTools.Editor {
/// <summary>
/// Tool that applies a tag to the currently selected objects and all their child objects.
/// </summary>
public class MassSetTags : EditorWindow {
private string _tag;
[MenuItem("UnityHelpers/Mass Set Tags")]
public static void Init() {
MassSetTags window = GetWindow<MassSetTags>();
window.Show();
}
private void OnGUI() {
EditorGUILayout.HelpBox("Applies the selected tag to all selected objects and their child objects", MessageType.Info);
_tag = EditorGUILayout.TagField("Tag", _tag);
if (GUILayout.Button("Apply")) {
foreach (GameObject go in Selection.gameObjects) {
Undo.RegisterFullObjectHierarchyUndo(go, "Mass set tag '" + _tag + "' for " + go.name);
SetTagRecursively(go, _tag);
}
}
}
private void SetTagRecursively(GameObject go, string tag) {
go.tag = tag;
foreach (Transform t in go.transform) {
SetTagRecursively(t.gameObject, tag);
}
}
}
}
| using System.Collections;
using UnityEditor;
using UnityEngine;
/// <summary>Tool that applies a tag to the currently selected objects and all their child objects.</summary>
public class MassSetTags : EditorWindow {
private string _tag;
[MenuItem("UnityHelpers/Mass Set Tags")]
public static void Init() {
MassSetTags window = GetWindow<MassSetTags>();
window.Show();
}
private void OnGUI() {
EditorGUILayout.HelpBox("Applies the selected tag to all selected objects and their child objects", MessageType.Info);
_tag = EditorGUILayout.TagField("Tag", _tag);
if (GUILayout.Button("Apply")) {
foreach (GameObject go in Selection.gameObjects) {
Undo.RegisterFullObjectHierarchyUndo(go, "Mass set tag '" + _tag + "' for " + go.name);
SetTagRecursively(go, _tag);
}
}
}
private void SetTagRecursively(GameObject go, string tag) {
go.tag = tag;
foreach (Transform t in go.transform) {
SetTagRecursively(t.gameObject, tag);
}
}
}
| mit | C# |
e8532f0ec8b72f94bf700d7d712d8d9a98f0a89b | Add Test for SemVer Parsing | nikeee/HolzShots | src/HolzShots.Core.Tests/Net/Custom/CustomUploaderLoaderTests.cs | src/HolzShots.Core.Tests/Net/Custom/CustomUploaderLoaderTests.cs | using HolzShots.Net.Custom;
using Xunit;
namespace HolzShots.Core.Tests.Net.Custom
{
public class CustomUploaderLoaderTests
{
[Theory]
[FileStringContentData("Files/DirectUpload.net.hsjson")]
[FileStringContentData("Files/FotosHochladen.hsjson")]
public void ValidateTest(string content)
{
var parseResult = CustomUploader.TryParse(content, out var result);
Assert.True(parseResult);
Assert.NotNull(result);
Assert.NotNull(result.CustomData);
Assert.NotNull(result.CustomData.Info);
Assert.NotNull(result.CustomData.Uploader);
Assert.NotNull(result.CustomData.SchemaVersion);
Assert.True(result.CustomData.Info.Version == new Semver.SemVersion(1, 0, 0));
}
}
}
| using HolzShots.Net.Custom;
using Xunit;
namespace HolzShots.Core.Tests.Net.Custom
{
public class CustomUploaderLoaderTests
{
[Theory]
[FileStringContentData("Files/DirectUpload.net.hsjson")]
[FileStringContentData("Files/FotosHochladen.hsjson")]
public void ValidateTest(string content)
{
var parseResult = CustomUploader.TryParse(content, out var result);
Assert.True(parseResult);
Assert.NotNull(result);
Assert.NotNull(result.CustomData);
Assert.NotNull(result.CustomData.Info);
Assert.NotNull(result.CustomData.Uploader);
Assert.NotNull(result.CustomData.SchemaVersion);
}
}
}
| agpl-3.0 | C# |
f78d35ed1b94855ee1dcb3ed8dd4d709310600f0 | Remove old test theory | nikeee/HolzShots | src/HolzShots.Core.Tests/Net/Custom/CustomUploaderLoaderTests.cs | src/HolzShots.Core.Tests/Net/Custom/CustomUploaderLoaderTests.cs | using HolzShots.Net.Custom;
using Xunit;
namespace HolzShots.Core.Tests.Net.Custom
{
public class CustomUploaderLoaderTests
{
[Theory]
[FileStringContentData("Files/DirectUpload.net.hsjson")]
public void ValidateTest(string content)
{
var parseResult = CustomUploader.TryParse(content, out var result);
Assert.True(parseResult);
Assert.NotNull(result);
Assert.NotNull(result.UploaderInfo);
Assert.NotNull(result.UploaderInfo.Meta);
Assert.NotNull(result.UploaderInfo.Uploader);
Assert.NotNull(result.UploaderInfo.SchemaVersion);
Assert.True(result.UploaderInfo.Meta.Version == new Semver.SemVersion(1, 0, 0));
}
}
}
| using HolzShots.Net.Custom;
using Xunit;
namespace HolzShots.Core.Tests.Net.Custom
{
public class CustomUploaderLoaderTests
{
[Theory]
[FileStringContentData("Files/DirectUpload.net.hsjson")]
[FileStringContentData("Files/FotosHochladen.hsjson")]
public void ValidateTest(string content)
{
var parseResult = CustomUploader.TryParse(content, out var result);
Assert.True(parseResult);
Assert.NotNull(result);
Assert.NotNull(result.UploaderInfo);
Assert.NotNull(result.UploaderInfo.Meta);
Assert.NotNull(result.UploaderInfo.Uploader);
Assert.NotNull(result.UploaderInfo.SchemaVersion);
Assert.True(result.UploaderInfo.Meta.Version == new Semver.SemVersion(1, 0, 0));
}
}
}
| agpl-3.0 | C# |
7333fd119f180ca66ff3885562fc26815ce5fbe9 | clean up | asipe/SupaCharge | src/SupaCharge.Core/ThreadingAbstractions/ThreadPoolWorkQueue.cs | src/SupaCharge.Core/ThreadingAbstractions/ThreadPoolWorkQueue.cs | using System;
using System.Threading;
namespace SupaCharge.Core.ThreadingAbstractions {
public class ThreadPoolWorkQueue : IWorkQueue {
public EmptyFuture Enqueue(Action work) {
var future = new EmptyFuture();
ThreadPool.QueueUserWorkItem(o => DoWork(work, future));
return future;
}
public EmptyFuture Enqueue<T>(T data, Action<T> work) {
var future = new EmptyFuture();
ThreadPool.QueueUserWorkItem(o => DoWork((T)o, work, future), data);
return future;
}
public ResultFuture<T> Enqueue<T>(Func<T> work) {
var future = new ResultFuture<T>();
ThreadPool.QueueUserWorkItem(o => DoWork(work, future));
return future;
}
public ResultFuture<TResult> Enqueue<T, TResult>(T data, Func<T, TResult> work) {
var future = new ResultFuture<TResult>();
ThreadPool.QueueUserWorkItem(o => DoWork((T)o, work, future), data);
return future;
}
private static void DoWork<T, TResult>(T data, Func<T, TResult> work, ResultFuture<TResult> future) {
try {
future.Set(work(data));
} catch (Exception e) {
future.Failed(e);
}
}
private static void DoWork<T>(Func<T> work, ResultFuture<T> future) {
try {
future.Set(work());
} catch (Exception e) {
future.Failed(e);
}
}
private static void DoWork(Action work, EmptyFuture future) {
try {
work();
future.Set();
} catch (Exception e) {
future.Failed(e);
}
}
private static void DoWork<T>(T data, Action<T> work, EmptyFuture future) {
try {
work(data);
future.Set();
} catch (Exception e) {
future.Failed(e);
}
}
}
} | using System;
using System.Threading;
namespace SupaCharge.Core.ThreadingAbstractions {
public class ThreadPoolWorkQueue : IWorkQueue {
public EmptyFuture Enqueue(Action work) {
var future = new EmptyFuture();
ThreadPool.QueueUserWorkItem(w => DoWork(work, future));
return future;
}
public EmptyFuture Enqueue<T>(T data, Action<T> work) {
var future = new EmptyFuture();
ThreadPool.QueueUserWorkItem(o => DoWork((T)o, work, future), data);
return future;
}
public ResultFuture<T> Enqueue<T>(Func<T> work) {
var future = new ResultFuture<T>();
ThreadPool.QueueUserWorkItem(w => DoWork(work, future));
return future;
}
public ResultFuture<TResult> Enqueue<T, TResult>(T data, Func<T, TResult> work) {
var future = new ResultFuture<TResult>();
ThreadPool.QueueUserWorkItem(o => DoWork((T)o, work, future), data);
return future;
}
private static void DoWork<T, TResult>(T data, Func<T, TResult> work, ResultFuture<TResult> future) {
try {
future.Set(work(data));
} catch (Exception e) {
future.Failed(e);
}
}
private static void DoWork<T>(Func<T> work, ResultFuture<T> future) {
try {
future.Set(work());
} catch (Exception e) {
future.Failed(e);
}
}
private static void DoWork(Action work, EmptyFuture future) {
try {
work();
future.Set();
} catch (Exception e) {
future.Failed(e);
}
}
private static void DoWork<T>(T data, Action<T> work, EmptyFuture future) {
try {
work(data);
future.Set();
} catch (Exception e) {
future.Failed(e);
}
}
}
} | mit | C# |
5fc845c32ccbf2b7e8a6c9186d3cd6382d9ae430 | fix for CS1998: This async method lacks 'await' in tests. (#606) | JoeMighty/shouldly | src/Shouldly.Tests/ShouldThrow/FuncOfTaskWhichThrowsDirectlyScenario.cs | src/Shouldly.Tests/ShouldThrow/FuncOfTaskWhichThrowsDirectlyScenario.cs | using System;
using System.Threading.Tasks;
using Xunit;
namespace Shouldly.Tests.ShouldThrow
{
public class FuncOfTaskWhichThrowsDirectlyScenario
{
[Fact]
public void ShouldPass()
{
// ReSharper disable once RedundantDelegateCreation
var task = new Func<Task>(() => { throw new InvalidOperationException(); });
task.ShouldThrow<InvalidOperationException>();
}
[Fact]
public void ShouldPass_ExceptionTypePassedIn()
{
// ReSharper disable once RedundantDelegateCreation
var task = new Func<Task>(() => { throw new InvalidOperationException(); });
task.ShouldThrow(typeof(InvalidOperationException));
}
[Fact]
public void ShouldPassTimeoutException()
{
var task = new Func<Task>(() => { throw new TimeoutException(); });
task.ShouldThrow<TimeoutException>();
}
[Fact]
public void ShouldPassTimeoutException_ExceptionTypePassedIn()
{
var task = new Func<Task>(() => { throw new TimeoutException(); });
task.ShouldThrow(typeof(TimeoutException));
}
[Fact]
public async Task ShouldPassTimeoutExceptionAsync()
{
var task = new Func<Task>(async () => { await Task.FromException(new TimeoutException()); });
await Task.FromResult(task.ShouldThrow<TimeoutException>());
}
[Fact]
public async Task ShouldPassTimeoutExceptionAsync_ExceptionTypePassedIn()
{
var task = new Func<Task>(async () => { await Task.FromException(new TimeoutException()); });
await Task.FromResult(task.ShouldThrow(typeof(TimeoutException)));
}
}
} | using System;
using System.Threading.Tasks;
using Xunit;
namespace Shouldly.Tests.ShouldThrow
{
public class FuncOfTaskWhichThrowsDirectlyScenario
{
[Fact]
public void ShouldPass()
{
// ReSharper disable once RedundantDelegateCreation
var task = new Func<Task>(() => { throw new InvalidOperationException(); });
task.ShouldThrow<InvalidOperationException>();
}
[Fact]
public void ShouldPass_ExceptionTypePassedIn()
{
// ReSharper disable once RedundantDelegateCreation
var task = new Func<Task>(() => { throw new InvalidOperationException(); });
task.ShouldThrow(typeof(InvalidOperationException));
}
[Fact]
public void ShouldPassTimeoutException()
{
var task = new Func<Task>(() => { throw new TimeoutException(); });
task.ShouldThrow<TimeoutException>();
}
[Fact]
public void ShouldPassTimeoutException_ExceptionTypePassedIn()
{
var task = new Func<Task>(() => { throw new TimeoutException(); });
task.ShouldThrow(typeof(TimeoutException));
}
[Fact]
public void ShouldPassTimeoutExceptionAsync()
{
var task = new Func<Task>(async () => { throw new TimeoutException(); });
task.ShouldThrow<TimeoutException>();
}
[Fact]
public void ShouldPassTimeoutExceptionAsync_ExceptionTypePassedIn()
{
var task = new Func<Task>(async () => { throw new TimeoutException(); });
task.ShouldThrow(typeof(TimeoutException));
}
}
} | bsd-3-clause | C# |
07add3c59cac788c79322da3b5b4872e2654cc85 | Update PoolID.cs | cdrandin/Simple-Object-Pooling | PoolingSystem_Demo/Assets/Demo/Scripts/PoolID.cs | PoolingSystem_Demo/Assets/Demo/Scripts/PoolID.cs | using UnityEngine;
using System.Collections;
public class PoolID : MonoBehaviour
{
private int _id;
private bool _init;
public int id
{
get { return _id; }
}
void Awake()
{
_init = false;
}
public void GenerateID(GameObject obj)
{
if(_init) return; // called only once
_id = obj.transform.GetInstanceID();
_init = true;
}
// This ensures objects that we are caching don't get polluted with our tag script, so destroy on exit
// Also, in case PoolingSystem misses removing it
void OnApplicationQuit()
{
Component.DestroyImmediate(this, true);
}
}
| using UnityEngine;
using System.Collections;
public class PoolID : MonoBehaviour {
[SerializeField]private int _id;
private bool _init;
public int id
{
get { return _id; }
}
void Awake()
{
_init = false;
}
public void GenerateID(GameObject obj)
{
if(_init) return; // called only once
_id = obj.transform.GetInstanceID();
_init = true;
}
}
| mit | C# |
d48ef5eef8cc33ad586efe70af73cab71e88da19 | Fix breaking test | Hammerstad/Moya | TestMoya/Extensions/DictionaryExtensionsTests.cs | TestMoya/Extensions/DictionaryExtensionsTests.cs | namespace TestMoya.Extensions
{
using System;
using System.Collections.Generic;
using Xunit;
using Moya.Extensions;
public class DictionaryExtensionsTests
{
public Dictionary<string, string> originalDictionary = new Dictionary<string, string>
{
{ "key1", "value1" },
{ "key2", "value2" }
};
[Fact]
public void AddingSeveralUniqueElementsWithAddRangeWorks()
{
var otherDictionary = new Dictionary<string, string>
{
{ "key3", "value3" },
{ "key4", "value4" }
};
otherDictionary.AddRange(originalDictionary);
Assert.Equal(4, otherDictionary.Count);
Assert.Equal("value1", otherDictionary["key1"]);
Assert.Equal("value2", otherDictionary["key2"]);
Assert.Equal("value3", otherDictionary["key3"]);
Assert.Equal("value4", otherDictionary["key4"]);
}
[Fact]
public void TryingToAddRangeWithNullShouldThrowArgumentException()
{
var exception = Record.Exception(() => originalDictionary.AddRange(null));
Assert.Equal(typeof(ArgumentNullException), exception.GetType());
Assert.Equal("Argument cannot be null.\r\nParameter name: collection", exception.Message);
}
[Fact]
public void AddingSeveralEqualElementsWithAddRangeIgnoresDuplicates()
{
var otherDictionary = new Dictionary<string, string>
{
{ "key1", "value3" },
{ "key2", "value4" },
};
otherDictionary.AddRange(originalDictionary);
Assert.Equal(2, otherDictionary.Count);
Assert.Equal("value3", otherDictionary["key1"]);
Assert.Equal("value4", otherDictionary["key2"]);
}
}
} | namespace TestMoya.Extensions
{
using System;
using System.Collections.Generic;
using Xunit;
using Moya.Extensions;
public class DictionaryExtensionsTests
{
public Dictionary<string, string> originalDictionary = new Dictionary<string, string>
{
{ "key1", "value1" },
{ "key2", "value2" }
};
[Fact]
public void AddingSeveralUniqueElementsWithAddRangeWorks()
{
var otherDictionary = new Dictionary<string, string>
{
{ "key3", "value3" },
{ "key4", "value4" }
};
otherDictionary.AddRange(originalDictionary);
Assert.Equal(4, otherDictionary.Count);
Assert.Equal("value1", otherDictionary["key1"]);
Assert.Equal("value2", otherDictionary["key2"]);
Assert.Equal("value3", otherDictionary["key3"]);
Assert.Equal("value4", otherDictionary["key4"]);
}
[Fact]
public void TryingToAddRangeWithNullShouldThrowArgumentException()
{
var exception = Record.Exception(() => originalDictionary.AddRange(null));
Assert.Equal(typeof(ArgumentNullException), exception.GetType());
Assert.Equal("Value cannot be null.\r\nParameter name: collection", exception.Message);
}
[Fact]
public void AddingSeveralEqualElementsWithAddRangeIgnoresDuplicates()
{
var otherDictionary = new Dictionary<string, string>
{
{ "key1", "value3" },
{ "key2", "value4" },
};
otherDictionary.AddRange(originalDictionary);
Assert.Equal(2, otherDictionary.Count);
Assert.Equal("value3", otherDictionary["key1"]);
Assert.Equal("value4", otherDictionary["key2"]);
}
}
} | mit | C# |
a26b0915b4047d61032dc7c0e9fc893502ac70ae | Fix scheduled tasks not being cleaned up between test steps | smoogipoo/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,peppy/osu-new,smoogipooo/osu,peppy/osu,UselessToucan/osu,peppy/osu,ppy/osu | osu.Game.Rulesets.Osu.Tests/TestSceneShaking.cs | osu.Game.Rulesets.Osu.Tests/TestSceneShaking.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Diagnostics;
using osu.Framework.Threading;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Osu.Tests
{
public class TestSceneShaking : TestSceneHitCircle
{
private readonly List<ScheduledDelegate> scheduledTasks = new List<ScheduledDelegate>();
protected override IBeatmap CreateBeatmapForSkinProvider()
{
// best way to run cleanup before a new step is run
foreach (var task in scheduledTasks)
task.Cancel();
scheduledTasks.Clear();
return base.CreateBeatmapForSkinProvider();
}
protected override TestDrawableHitCircle CreateDrawableHitCircle(HitCircle circle, bool auto)
{
var drawableHitObject = base.CreateDrawableHitCircle(circle, auto);
Debug.Assert(drawableHitObject.HitObject.HitWindows != null);
double delay = drawableHitObject.HitObject.StartTime - (drawableHitObject.HitObject.HitWindows.WindowFor(HitResult.Miss) + RNG.Next(0, 300)) - Time.Current;
scheduledTasks.Add(Scheduler.AddDelayed(() => drawableHitObject.TriggerJudgement(), delay));
return drawableHitObject;
}
}
}
| // 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.Diagnostics;
using osu.Framework.Utils;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Osu.Tests
{
public class TestSceneShaking : TestSceneHitCircle
{
protected override TestDrawableHitCircle CreateDrawableHitCircle(HitCircle circle, bool auto)
{
var drawableHitObject = base.CreateDrawableHitCircle(circle, auto);
Debug.Assert(drawableHitObject.HitObject.HitWindows != null);
double delay = drawableHitObject.HitObject.StartTime - (drawableHitObject.HitObject.HitWindows.WindowFor(HitResult.Miss) + RNG.Next(0, 300)) - Time.Current;
Scheduler.AddDelayed(() => drawableHitObject.TriggerJudgement(), delay);
return drawableHitObject;
}
}
}
| mit | C# |
0f002fe68b8d6ee4ebdd0327300407fbc4aee7b2 | Update FindInScopeAttribute | atata-framework/atata,YevgeniyShunevych/Atata,atata-framework/atata,YevgeniyShunevych/Atata | src/Atata/Attributes/FindInScopeAttribute.cs | src/Atata/Attributes/FindInScopeAttribute.cs | using System;
namespace Atata
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class | AttributeTargets.Assembly, Inherited = true)]
public class FindInScopeAttribute : Attribute
{
public FindInScopeAttribute(ScopeSource scope = ScopeSource.Inherit)
{
Scope = scope;
}
public ScopeSource Scope { get; private set; }
}
}
| using System;
namespace Atata
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class | AttributeTargets.Assembly, Inherited = true)]
public class FindInScopeAttribute : Attribute
{
public FindInScopeAttribute(ScopeSource scope = ScopeSource.Inherit)
{
Scope = scope;
}
public ScopeSource Scope { get; set; }
}
}
| apache-2.0 | C# |
b08f1b01fc96a94526b4bb0e30e88c437cf4e87b | Make CriHcaConstants public | Thealexbarney/VGAudio,Thealexbarney/LibDspAdpcm,Thealexbarney/LibDspAdpcm,Thealexbarney/VGAudio | src/VGAudio/Codecs/CriHca/CriHcaConstants.cs | src/VGAudio/Codecs/CriHca/CriHcaConstants.cs | namespace VGAudio.Codecs.CriHca
{
public static class CriHcaConstants
{
public const int SubframesPerFrame = 8;
public const int SubFrameSamplesBits = 7;
public const int SamplesPerSubFrame = 1 << SubFrameSamplesBits;
public const int SamplesPerFrame = SubframesPerFrame * SamplesPerSubFrame;
}
}
| namespace VGAudio.Codecs.CriHca
{
internal static class CriHcaConstants
{
public const int SubframesPerFrame = 8;
public const int SubFrameSamplesBits = 7;
public const int SamplesPerSubFrame = 1 << SubFrameSamplesBits;
public const int SamplesPerFrame = SubframesPerFrame * SamplesPerSubFrame;
}
}
| mit | C# |
9c71504092bca44bc15da47bb445e7bafca0889b | Modify "http.uri" to "http.url" | criteo/zipkin4net,criteo/zipkin4net | zipkin4net-owin/Criteo.Profiling.Tracing.Middleware/ZipkinMiddleware.cs | zipkin4net-owin/Criteo.Profiling.Tracing.Middleware/ZipkinMiddleware.cs | using Criteo.Profiling.Tracing.Transport;
using Microsoft.Owin;
using System.Threading.Tasks;
namespace Criteo.Profiling.Tracing.Middleware
{
class ZipkinMiddleware : OwinMiddleware
{
private readonly string serviceName;
private readonly ITraceExtractor traceExtractor;
public ZipkinMiddleware(
OwinMiddleware next,
string serviceName,
ITraceExtractor traceExtractor) : base(next)
{
this.serviceName = serviceName;
this.traceExtractor = traceExtractor;
}
public override async Task Invoke(IOwinContext context)
{
Trace trace;
if (!this.traceExtractor.TryExtract(context.Request.Headers, (dic, k) => string.Join(",", dic[k]), out trace))
{
trace = Trace.Create();
}
Trace.Current = trace;
using (var serverTrace = new ServerTrace(this.serviceName, context.Request.Method))
{
trace.Record(Annotations.Tag("http.host", context.Request.Host.Value));
trace.Record(Annotations.Tag("http.url", context.Request.Uri.AbsoluteUri));
trace.Record(Annotations.Tag("http.path", context.Request.Uri.AbsolutePath));
await serverTrace.TracedActionAsync(Next.Invoke(context));
}
}
}
}
| using Criteo.Profiling.Tracing.Transport;
using Microsoft.Owin;
using System.Threading.Tasks;
namespace Criteo.Profiling.Tracing.Middleware
{
class ZipkinMiddleware : OwinMiddleware
{
private readonly string serviceName;
private readonly ITraceExtractor traceExtractor;
public ZipkinMiddleware(
OwinMiddleware next,
string serviceName,
ITraceExtractor traceExtractor) : base(next)
{
this.serviceName = serviceName;
this.traceExtractor = traceExtractor;
}
public override async Task Invoke(IOwinContext context)
{
Trace trace;
if (!this.traceExtractor.TryExtract(context.Request.Headers, (dic, k) => string.Join(",", dic[k]), out trace))
{
trace = Trace.Create();
}
Trace.Current = trace;
using (var serverTrace = new ServerTrace(this.serviceName, context.Request.Method))
{
trace.Record(Annotations.Tag("http.host", context.Request.Host.Value));
trace.Record(Annotations.Tag("http.uri", context.Request.Uri.AbsoluteUri));
trace.Record(Annotations.Tag("http.path", context.Request.Uri.AbsolutePath));
await serverTrace.TracedActionAsync(Next.Invoke(context));
}
}
}
}
| apache-2.0 | C# |
47ee16fc374228461837a32138fb6abc23b01389 | add dns ip settings to HFTRuntimeOptions for server | greggman/hft-unity3d,greggman/hft-unity3d,greggman/hft-unity3d,greggman/hft-unity3d | hft-server/hft-server/HFTRuntimeOptions.cs | hft-server/hft-server/HFTRuntimeOptions.cs | using System;
namespace HappyFunTimes
{
public class HFTRuntimeOptions
{
public string dataPath = "";
public string url = "";
public string id = "";
public string name = "";
public string gameId = "HFTUnity"; // this is kind of left over from when one server supported mutiple games
public string controllerFilename = "";
public bool disconnectPlayersIfGameDisconnects = true;
public bool installationMode = false;
public bool master = false;
public bool showInList = true;
public bool showMessages;
public string debug = "";
public bool startServer;
public bool dns;
public bool captivePortal;
public string serverPort = "";
public string rendezvousUrl;
public string ipv4DnsAddress = "";
public string ipv6DnsAddress = "";
public string args;
}
}
| using System;
namespace HappyFunTimes
{
public class HFTRuntimeOptions
{
public string dataPath = "";
public string url = "";
public string id = "";
public string name = "";
public string gameId = "HFTUnity"; // this is kind of left over from when one server supported mutiple games
public string controllerFilename = "";
public bool disconnectPlayersIfGameDisconnects = true;
public bool installationMode = false;
public bool master = false;
public bool showInList = true;
public bool showMessages;
public string debug = "";
public bool startServer;
public bool dns;
public bool captivePortal;
public string serverPort = "";
public string rendezvousUrl;
public string args;
}
}
| bsd-3-clause | C# |
107ca5f7aa55448e0f19c46427841b525411c09b | Patch #27 Fix fetch messages example | AfricasTalkingLtd/africastalking.Net | Examples/FetchMessages/Program.cs | Examples/FetchMessages/Program.cs | using System;
using AfricasTalkingCS;
namespace FetchMessages
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
const string Username = "sandbox";
const string ApiKey = "afd635a4f295dd936312836c0b944d55f2a836e8ff2b63987da5e717cd5ff745";
var gateway = new AfricasTalkingGateway(Username,ApiKey);
int msgId = 0;
try
{
var res = gateway.FetchMessages(msgId);
Console.WriteLine(res);
}
catch (AfricasTalkingGatewayException e)
{
Console.WriteLine("We had an Error: " + e.Message);
}
Console.ReadLine();
}
}
}
| using System;
using AfricasTalkingCS;
namespace FetchMessages
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
const string Username = "sandbox";
const string ApiKey = "afd635a4f295dd936312836c0b944d55f2a836e8ff2b63987da5e717cd5ff745";
const string Env = "sandbox";
var gateway = new AfricasTalkingGateway(Username,ApiKey);
int msgId = 0;
try
{
var res = gateway.FetchMessages(0);
Console.WriteLine(res);
}
catch (AfricasTalkingGatewayException e)
{
Console.WriteLine("We had an Error: " + e.Message);
}
Console.ReadLine();
}
}
}
| mit | C# |
b9944cce53442e8dc34bf55c49b22fc55ccbd9a9 | Add an optional timeout for connection attempts. | izrik/NDeproxy | SocketHelper.cs | SocketHelper.cs | using System;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace NDeproxy
{
public static class SocketHelper
{
static readonly Logger log = new Logger("SocketHelper");
public static Socket Server(int port, int listenQueue=5)
{
var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Bind(new IPEndPoint(IPAddress.Any, port));
s.Listen(listenQueue);
return s;
}
public static Socket Client(string remoteHost, int port, int timeout=Timeout.Infinite)
{
var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
if (timeout == Timeout.Infinite)
{
s.Connect(remoteHost, port);
return s;
}
else
{
var result = s.BeginConnect(remoteHost, port, (_result) => { s.EndConnect(_result); }, s);
if (result.AsyncWaitHandle.WaitOne(timeout))
{
return s;
}
else
{
throw new SocketException((int)SocketError.TimedOut);
}
}
}
public static int GetLocalPort(this Socket socket)
{
return ((IPEndPoint)socket.LocalEndPoint).Port;
}
public static int GetRemotePort(this Socket socket)
{
return ((IPEndPoint)socket.RemoteEndPoint).Port;
}
}
}
| using System;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace NDeproxy
{
public static class SocketHelper
{
static readonly Logger log = new Logger("SocketHelper");
public static Socket Server(int port, int listenQueue=5)
{
var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Bind(new IPEndPoint(IPAddress.Any, port));
s.Listen(listenQueue);
return s;
}
public static Socket Client(string remoteHost, int port)
{
var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Connect(remoteHost, port);
return s;
}
public static int GetLocalPort(this Socket socket)
{
return ((IPEndPoint)socket.LocalEndPoint).Port;
}
public static int GetRemotePort(this Socket socket)
{
return ((IPEndPoint)socket.RemoteEndPoint).Port;
}
}
}
| mit | C# |
0d9d8cc3b8e88b333faa204854cd3aea04ff6ba1 | Fix help command (#19) | Sitecore/Sitecore-Instance-Manager,Brad-Christie/Sitecore-Instance-Manager,sergeyshushlyapin/Sitecore-Instance-Manager | src/SIM.Client/ParseArgumentsCommand.cs | src/SIM.Client/ParseArgumentsCommand.cs | namespace SIM.Client
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CommandLine;
using JetBrains.Annotations;
using Sitecore.Diagnostics.Base;
using SIM.Client.Commands;
using SIM.Core.Common;
public class ParseArgumentsCommand
{
public IReadOnlyList<string> Args { get; set; }
public bool Autocomplete { get; set; }
public TextWriter HelpWriter { get; set; }
[CanBeNull]
public ICommand Execute()
{
Assert.ArgumentNotNull(Args, nameof(Args));
var parser = new Parser(with =>
{
Assert.ArgumentNotNull(with, nameof(with));
if (HelpWriter != null)
{
with.HelpWriter = HelpWriter;
}
});
Assert.IsNotNull(parser, nameof(parser));
if (Autocomplete == true)
{
var ensureAutocomplete = new EnsureAutocompleteCommand();
ensureAutocomplete.Execute();
}
var result = Execute(parser);
ICommand selectedCommand = null;
result.WithParsed(x => selectedCommand = (ICommand)x);
return selectedCommand;
}
private ParserResult<object> Execute(Parser parser)
{
var result = parser.ParseArguments<
BrowseCommandFacade,
ConfigCommandFacade,
DeleteCommandFacade,
InstallCommandFacade,
InstallModuleCommandFacade,
ListCommandFacade,
LoginCommandFacade,
ProfileCommandFacade,
RepositoryCommandFacade,
StartCommandFacade,
StateCommandFacade,
StopCommandFacade,
SyncCommandFacade
>(Args);
return result;
}
}
} | namespace SIM.Client
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CommandLine;
using JetBrains.Annotations;
using Sitecore.Diagnostics.Base;
using SIM.Client.Commands;
using SIM.Core.Common;
public class ParseArgumentsCommand
{
public IReadOnlyList<string> Args { get; set; }
public bool Autocomplete { get; set; }
public TextWriter HelpWriter { get; set; }
[CanBeNull]
public ICommand Execute()
{
Assert.ArgumentNotNull(Args, nameof(Args));
var parser = new Parser(with =>
{
Assert.ArgumentNotNull(with, nameof(with));
if (HelpWriter != null)
{
with.HelpWriter = HelpWriter;
}
});
Assert.IsNotNull(parser, nameof(parser));
if (Autocomplete == true)
{
var ensureAutocomplete = new EnsureAutocompleteCommand();
ensureAutocomplete.Execute();
}
var result = Execute(parser);
ICommand selectedCommand = null;
result.WithParsed(x => selectedCommand = (ICommand)x);
return selectedCommand;
}
private ParserResult<object> Execute(Parser parser)
{
var result = parser.ParseArguments<
BrowseCommandFacade,
ConfigCommandFacade,
DeleteCommandFacade,
InstallModuleCommandFacade,
InstallModuleCommandFacade,
ListCommandFacade,
LoginCommandFacade,
ProfileCommandFacade,
RepositoryCommandFacade,
StartCommandFacade,
StateCommandFacade,
StopCommandFacade,
SyncCommandFacade
>(Args);
return result;
}
}
} | mit | C# |
5753a45b86fb396b4424544452f17de6edd0ce15 | Improve documentation of LongLivedMarshalByRefObject. | EliotJones/fixie,JakeGinnivan/fixie,fixie/fixie,Duohong/fixie,KevM/fixie | src/Fixie/Execution/LongLivedMarshalByRefObject.cs | src/Fixie/Execution/LongLivedMarshalByRefObject.cs | using System;
using System.Runtime.Remoting;
namespace Fixie.Execution
{
/// <summary>
/// Simplifies the definition of MarshalByRefObject classes whose
/// instances need to live longer than the default lease lifetime
/// allows, such as implementations of Listener provided by test
/// runners.
///
/// Instances of LongLivedMarshalByRefObject have an infinite
/// lease lifetime so that they won't become defective after
/// several minutes. As a consequence, instances must be disposed
/// to free up all resources.
/// </summary>
public class LongLivedMarshalByRefObject : MarshalByRefObject, IDisposable
{
public override sealed object InitializeLifetimeService()
{
// MarshalByRefObjects have lifetimes unlike normal objects.
// The default implementation of InitializeLifetimeService()
// causes instances to throw runtime exceptions when the
// instance lives for several minutes.
//
// This fact poses a problem for long-lived MarshalByRefObjects
// used in the cross-AppDomain communication between a Fixie
// runner and the running test assembly. Long-lived tests could
// cause a MarshalByRefObject Listener, for instance, to become
// defective when the running test finally finishes.
//
// This class provides a more familiar lifetime for such long-
// lived MarshalByRefObjects. Instances claim an infinite
// lease lifetime by returning null here. To prevent memory leaks
// as a side effect, Dispose() in order to explicitly end the
// lifetime.
return null;
}
public void Dispose()
{
RemotingServices.Disconnect(this);
}
}
} | using System;
using System.Runtime.Remoting;
namespace Fixie.Execution
{
/// <summary>
/// Normally, inheriting from MarshalByRefObject introduces an unexpected defect
/// in which your instances cease to exist after they get a few minutes old.
///
/// For instance, when a runner provides a MarshalByRefObject to act as the test
/// Listener, that Listener may disappear after a long-running test finally finishes,
/// causing a runtime exception that interrupts the run. The Listener would no longer
/// be available to receive the test's results.
///
/// Inheriting from this alternative to MarshalByRefObject allows the instance
/// to be kept alive indefinitely, but you must Dispose() of it yourself when
/// its natural lifetime has been reached.
/// </summary>
public class LongLivedMarshalByRefObject : MarshalByRefObject, IDisposable
{
public override sealed object InitializeLifetimeService()
{
//Returning null here causes the instance to live indefinitely.
//A consequence of keeping a MarshalByRefObject alive like this is that
//it must be explicitly cleaned up with a call to RemotingServices.Disconnect(this).
//See Dispose().
return null;
}
public void Dispose()
{
RemotingServices.Disconnect(this);
}
}
} | mit | C# |
a2e855eb6029841873543c730a93b14608cd8901 | Improve GitVersionAttribute to issue a warning on UNIX systems. | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Common/Tools/GitVersion/GitVersionAttribute.cs | source/Nuke.Common/Tools/GitVersion/GitVersionAttribute.cs | // Copyright Matthias Koch 2017.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Core;
using Nuke.Core.Injection;
using Nuke.Core.Tooling;
namespace Nuke.Common.Tools.GitVersion
{
/// <inheritdoc/>
[PublicAPI]
[UsedImplicitly(ImplicitUseKindFlags.Default)]
public class GitVersionAttribute : StaticInjectionAttributeBase
{
public static GitVersion Value { get; private set; }
public override Type InjectionType => typeof(GitVersion);
[CanBeNull]
public override object GetStaticValue ()
{
// TODO: https://github.com/GitTools/GitVersion/issues/1097
if (EnvironmentInfo.IsUnix)
{
Logger.Warn($"{nameof(GitVersion)} does not work in UNIX environments.");
return null;
}
return Value = Value ??
GitVersionTasks.GitVersion(
s => GitVersionTasks.DefaultGitVersion,
new ProcessSettings().EnableRedirectOutput());
}
}
}
| // Copyright Matthias Koch 2017.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Core;
using Nuke.Core.Injection;
using Nuke.Core.Tooling;
namespace Nuke.Common.Tools.GitVersion
{
/// <inheritdoc/>
[PublicAPI]
[UsedImplicitly(ImplicitUseKindFlags.Default)]
public class GitVersionAttribute : StaticInjectionAttributeBase
{
public static GitVersion Value { get; private set; }
public override Type InjectionType => typeof(GitVersion);
[CanBeNull]
public override object GetStaticValue ()
{
return Value = Value ??
(EnvironmentInfo.IsWin && GitVersionTasks.DefaultGitVersion.HasValidToolPath()
? GitVersionTasks.GitVersion(s => GitVersionTasks.DefaultGitVersion, new ProcessSettings().EnableRedirectOutput())
: null);
}
}
}
| mit | C# |
52e0efb1120ca34c5e6411dc286f0d2599afdb3f | Fix bug in EnsureIndexesShouldDropAndRetry | rapidcore/rapidcore,rapidcore/rapidcore | src/Internal/MongoCommandExceptionExtensions.cs | src/Internal/MongoCommandExceptionExtensions.cs | using System;
using MongoDB.Driver;
namespace RapidCore.Mongo.Internal
{
public static class MongoCommandExceptionExtensions
{
public static bool EnsureIndexesShouldDropAndRetry(this MongoCommandException ex, IndexDefinition index)
{
//
// index already exists, but with different options
// Check using the error code - all error codes are defined here and have been stable over time, with only new codes added:
// https://github.com/mongodb/mongo/blob/v3.4/src/mongo/base/error_codes.err
//
if (ex.Code == 86)
{
return true;
}
//
// index already exists
//
else if (ex.Message.StartsWith("Command createIndexes failed: Index must have unique name.The existing index:"))
{
// check if the existing and the requested index are different
var indexes = ex.Message
.Remove(0, "Command createIndexes failed: Index must have unique name.The existing index: ".Length)
.Split(new string[] { " has the same name as the requested index: " }, StringSplitOptions.None);
return !indexes[0].Trim().Equals(indexes[1].Trim());
}
return false;
}
}
} | using System;
using MongoDB.Driver;
namespace RapidCore.Mongo.Internal
{
public static class MongoCommandExceptionExtensions
{
public static bool EnsureIndexesShouldDropAndRetry(this MongoCommandException ex, IndexDefinition index)
{
//
// index already exists, but with different options
//
if (ex.Message.Equals($"Command createIndexes failed: Index with name: {index.Name} already exists with different options."))
{
return true;
}
//
// index already exists
//
else if (ex.Message.StartsWith("Command createIndexes failed: Index must have unique name.The existing index:"))
{
// check if the existing and the requested index are different
var indexes = ex.Message
.Remove(0, "Command createIndexes failed: Index must have unique name.The existing index: ".Length)
.Split(new string[] { " has the same name as the requested index: " }, StringSplitOptions.None);
return !indexes[0].Trim().Equals(indexes[1].Trim());
}
return false;
}
}
} | mit | C# |
b9a2b8183e5469447e0ee7ddde8e0e37dc6ed6b4 | Improve ${callsite} when filtering is used. | NLog/NLog.Framework.Logging,NLog/NLog.Framework.Logging,NLog/NLog.Extensions.Logging | src/NLog.Extensions.Logging/AspNetExtensions.cs | src/NLog.Extensions.Logging/AspNetExtensions.cs | using System;
using System.IO;
using System.Reflection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Config;
namespace NLog.Extensions.Logging
{
/// <summary>
/// Helpers for ASP.NET Core
/// </summary>
public static class AspNetExtensions
{
/// <summary>
/// Enable NLog as logging provider in ASP.NET Core.
/// </summary>
/// <param name="factory"></param>
/// <returns></returns>
public static ILoggerFactory AddNLog(this ILoggerFactory factory)
{
//ignore this
LogManager.AddHiddenAssembly(Assembly.Load(new AssemblyName("Microsoft.Extensions.Logging")));
LogManager.AddHiddenAssembly(Assembly.Load(new AssemblyName("Microsoft.Extensions.Logging.Abstractions")));
try
{
//try the Filter extensin
var filterAssembly = Assembly.Load(new AssemblyName("Microsoft.Extensions.Logging.Filter"));
LogManager.AddHiddenAssembly(filterAssembly);
}
catch (Exception)
{
//ignore
}
LogManager.AddHiddenAssembly(typeof(AspNetExtensions).GetTypeInfo().Assembly);
using (var provider = new NLogLoggerProvider())
{
factory.AddProvider(provider);
}
return factory;
}
/// <summary>
/// Apply NLog configuration from XML config.
/// </summary>
/// <param name="env"></param>
/// <param name="configFileRelativePath">relative path to NLog configuration file.</param>
public static void ConfigureNLog(this IHostingEnvironment env, string configFileRelativePath)
{
var fileName = Path.Combine(env.ContentRootPath, configFileRelativePath);
ConfigureNLog(fileName);
}
/// <summary>
/// Apply NLog configuration from XML config.
/// </summary>
/// <param name="fileName">absolute path NLog configuration file.</param>
private static void ConfigureNLog(string fileName)
{
LogManager.Configuration = new XmlLoggingConfiguration(fileName, true);
}
}
}
| using System.IO;
using System.Reflection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Config;
namespace NLog.Extensions.Logging
{
/// <summary>
/// Helpers for ASP.NET Core
/// </summary>
public static class AspNetExtensions
{
/// <summary>
/// Enable NLog as logging provider in ASP.NET Core.
/// </summary>
/// <param name="factory"></param>
/// <returns></returns>
public static ILoggerFactory AddNLog(this ILoggerFactory factory)
{
//ignore this
LogManager.AddHiddenAssembly(Assembly.Load(new AssemblyName("Microsoft.Extensions.Logging")));
LogManager.AddHiddenAssembly(Assembly.Load(new AssemblyName("Microsoft.Extensions.Logging.Abstractions")));
LogManager.AddHiddenAssembly(typeof(AspNetExtensions).GetTypeInfo().Assembly);
using (var provider = new NLogLoggerProvider())
{
factory.AddProvider(provider);
}
return factory;
}
/// <summary>
/// Apply NLog configuration from XML config.
/// </summary>
/// <param name="env"></param>
/// <param name="configFileRelativePath">relative path to NLog configuration file.</param>
public static void ConfigureNLog(this IHostingEnvironment env, string configFileRelativePath)
{
var fileName = Path.Combine(env.ContentRootPath, configFileRelativePath);
ConfigureNLog(fileName);
}
/// <summary>
/// Apply NLog configuration from XML config.
/// </summary>
/// <param name="fileName">absolute path NLog configuration file.</param>
private static void ConfigureNLog(string fileName)
{
LogManager.Configuration = new XmlLoggingConfiguration(fileName, true);
}
}
}
| bsd-2-clause | C# |
f114fbd3c662ea3f29130159a51dca3aa1883177 | Add XMLDoc to IFileStreamCaptureHandler. | techyian/MMALSharp | src/MMALSharp.Processing/Handlers/IFileStreamCaptureHandler.cs | src/MMALSharp.Processing/Handlers/IFileStreamCaptureHandler.cs | // <copyright file="IFileStreamCaptureHandler.cs" company="Techyian">
// Copyright (c) Ian Auty. All rights reserved.
// Licensed under the MIT License. Please see LICENSE.txt for License info.
// </copyright>
namespace MMALSharp.Handlers
{
/// <summary>
/// Represents a FileStreamCaptureHandler.
/// </summary>
public interface IFileStreamCaptureHandler : IOutputCaptureHandler
{
/// <summary>
/// Creates a new File (FileStream), assigns it to the Stream instance of this class and disposes of any existing stream.
/// </summary>
void NewFile();
/// <summary>
/// Gets the filepath that a FileStream points to.
/// </summary>
/// <returns>The filepath.</returns>
string GetFilepath();
/// <summary>
/// Gets the filename that a FileStream points to.
/// </summary>
/// <returns>The filename.</returns>
string GetFilename();
}
}
|
namespace MMALSharp.Handlers
{
public interface IFileStreamCaptureHandler : IOutputCaptureHandler
{
/// <summary>
/// Creates a new File (FileStream), assigns it to the Stream instance of this class and disposes of any existing stream.
/// </summary>
void NewFile();
/// <summary>
/// Gets the filepath that a FileStream points to.
/// </summary>
/// <returns>The filepath.</returns>
string GetFilepath();
/// <summary>
/// Gets the filename that a FileStream points to.
/// </summary>
/// <returns>The filename.</returns>
string GetFilename();
}
}
| mit | C# |
6b58aa03211e43b970967cad44f83808ac336ab1 | bump 0.1.1 release | g0t4/Rx-FileSystemWatcher,g0t4/Rx-FileSystemWatcher | src/RxFileSystemWatcher/Properties/AssemblyInfo.cs | src/RxFileSystemWatcher/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RxFileSystemWatcher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RxFileSystemWatcher")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8ac26a3f-ea94-44ca-8131-e3a63ad35bfa")]
[assembly: AssemblyVersion("0.1.1")]
[assembly: AssemblyFileVersion("0.1.1")] | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RxFileSystemWatcher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RxFileSystemWatcher")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8ac26a3f-ea94-44ca-8131-e3a63ad35bfa")]
[assembly: AssemblyVersion("0.1.0")]
[assembly: AssemblyFileVersion("0.1.0")] | mit | C# |
b3287e7b0d51023c57ffe07665b7e35de6880cf6 | Add support for builtins directory from the assembly folder/_meta | lunet-io/lunet,lunet-io/lunet | src/Lunet/Core/MetaManager.cs | src/Lunet/Core/MetaManager.cs | // Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace Lunet.Core
{
/// <summary>
/// Manages the meta information associated to a site (from the `_meta` directory and `.lunet` directory)
/// </summary>
/// <seealso cref="ManagerBase" />
public class MetaManager : ManagerBase
{
public const string MetaDirectoryName = "_meta";
/// <summary>
/// Initializes a new instance of the <see cref="MetaManager"/> class.
/// </summary>
/// <param name="site">The site.</param>
public MetaManager(SiteObject site) : base(site)
{
Directory = Site.BaseDirectory.GetSubFolder(MetaDirectoryName);
PrivateDirectory = Site.PrivateBaseDirectory.GetSubFolder(MetaDirectoryName);
BuiltinDirectory = Path.GetDirectoryName(typeof(MetaManager).GetTypeInfo().Assembly.Location);
}
public FolderInfo Directory { get; }
public FolderInfo BuiltinDirectory { get; }
public FolderInfo PrivateDirectory { get; }
public IEnumerable<FolderInfo> Directories
{
get
{
yield return Directory;
foreach (var theme in Site.Extends.CurrentList)
{
yield return theme.Directory.GetSubFolder(MetaDirectoryName);
}
// Last one is the builtin directory
yield return new DirectoryInfo(Path.Combine(BuiltinDirectory, MetaDirectoryName));
}
}
}
} | // Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using System.Collections.Generic;
namespace Lunet.Core
{
/// <summary>
/// Manages the meta information associated to a site (from the `_meta` directory and `.lunet` directory)
/// </summary>
/// <seealso cref="ManagerBase" />
public class MetaManager : ManagerBase
{
public const string MetaDirectoryName = "_meta";
/// <summary>
/// Initializes a new instance of the <see cref="MetaManager"/> class.
/// </summary>
/// <param name="site">The site.</param>
public MetaManager(SiteObject site) : base(site)
{
Directory = Site.BaseDirectory.GetSubFolder(MetaDirectoryName);
PrivateDirectory = Site.PrivateBaseDirectory.GetSubFolder(MetaDirectoryName);
}
public FolderInfo Directory { get; }
public FolderInfo PrivateDirectory { get; }
public IEnumerable<FolderInfo> Directories
{
get
{
yield return Directory;
foreach (var theme in Site.Extends.CurrentList)
{
yield return theme.Directory.GetSubFolder(MetaDirectoryName);
}
}
}
}
} | bsd-2-clause | C# |
37cac765834fc16c159fa46bcadb05060e7d85a0 | Fix image | dona1312/AcademyEF,dona1312/AcademyEF | AcademyEF/AcademyEF/Views/Courses/List.cshtml | AcademyEF/AcademyEF/Views/Courses/List.cshtml | @model AcademyEF.ViewModels.CoursesVM.CourseListVM
@{
ViewBag.Title = "Courses";
ViewBag.Description = "Our current courses";
}
@if (AcademyEF.Services.AuthenticationService.LoggedUser != null &&
AcademyEF.Services.AuthenticationService.LoggedUser.IsAdmin)
{
<p class="row" style="margin-left:17px;">
@Html.ActionLink("Create New", "Edit", null, new { @class = "btn btn-info" })
</p>
}
@if (Model.Courses.Count == 0)
{
<p>No courses found !!!</p>
}
else
{
foreach (var item in Model.Courses)
{
<div class="col-md-4">
<div class="card" style="width: 30rem;">
<img class="card-img-top" src="..\..\Uploads\@item.ImagePath" alt="Card image cap" style="width:300px;height:300px;">
<div class="card-block">
<h4 class="card-title">@Html.DisplayFor(modelItem => item.Name)</h4>
<p class="card-text">@Html.DisplayFor(modelItem => item.Description)</p>
@if (AcademyEF.Services.AuthenticationService.LoggedUser != null &&
AcademyEF.Services.AuthenticationService.LoggedUser.IsAdmin)
{
@Html.ActionLink("Edit", "Edit", new { id = item.ID }, new { @class = "btn btn-primary" }) @Html.Raw(" ")
@Html.ActionLink("Delete", "Delete", new { id = item.ID }, new { @class = "btn btn-danger" })
}
@if (AcademyEF.Services.AuthenticationService.LoggedUser != null &&
!AcademyEF.Services.AuthenticationService.LoggedUser.Courses.Select(c=>c.ID).Contains(item.ID))
{
@Html.ActionLink("Assign", "Assign", new { id = item.ID }, new { @class = "btn btn-success" })
}
</div>
</div>
</div>
}
} | @model AcademyEF.ViewModels.CoursesVM.CourseListVM
@{
ViewBag.Title = "Courses";
ViewBag.Description = "Our current courses";
}
@if (AcademyEF.Services.AuthenticationService.LoggedUser != null &&
AcademyEF.Services.AuthenticationService.LoggedUser.IsAdmin)
{
<p class="row" style="margin-left:17px;">
@Html.ActionLink("Create New", "Edit", null, new { @class = "btn btn-info" })
</p>
}
@if (Model.Courses.Count == 0)
{
<p>No courses found !!!</p>
}
else
{
foreach (var item in Model.Courses)
{
<div class="col-md-4">
<div class="card" style="width: 30rem;">
<img class="card-img-top" src="/Uploads/@item.ImagePath" alt="Card image cap" style="width:300px;height:300px;">
<div class="card-block">
<h4 class="card-title">@Html.DisplayFor(modelItem => item.Name)</h4>
<p class="card-text">@Html.DisplayFor(modelItem => item.Description)</p>
@if (AcademyEF.Services.AuthenticationService.LoggedUser != null &&
AcademyEF.Services.AuthenticationService.LoggedUser.IsAdmin)
{
@Html.ActionLink("Edit", "Edit", new { id = item.ID }, new { @class = "btn btn-primary" }) @Html.Raw(" ")
@Html.ActionLink("Delete", "Delete", new { id = item.ID }, new { @class = "btn btn-danger" })
}
@if (AcademyEF.Services.AuthenticationService.LoggedUser != null &&
!AcademyEF.Services.AuthenticationService.LoggedUser.Courses.Select(c=>c.ID).Contains(item.ID))
{
@Html.ActionLink("Assign", "Assign", new { id = item.ID }, new { @class = "btn btn-success" })
}
</div>
</div>
</div>
}
} | mit | C# |
cdb74803a87d3d2ccf05947540c48fe77e78dcfc | Store actions as their object representation | DrabWeb/osu-framework,default0/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,paparony03/osu-framework,paparony03/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,default0/osu-framework,Nabile-Rahmani/osu-framework,ZLima12/osu-framework,Tom94/osu-framework,smoogipooo/osu-framework,Nabile-Rahmani/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,ZLima12/osu-framework | osu.Framework/Input/Bindings/KeyBinding.cs | osu.Framework/Input/Bindings/KeyBinding.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
namespace osu.Framework.Input.Bindings
{
/// <summary>
/// A binding of a <see cref="Bindings.KeyCombination"/> to an action.
/// </summary>
public class KeyBinding
{
/// <summary>
/// The combination of keys which will trigger this binding.
/// </summary>
public KeyCombination KeyCombination;
/// <summary>
/// The resultant action which is triggered by this binding.
/// </summary>
public object Action;
/// <summary>
/// Construct a new instance.
/// </summary>
/// <param name="keys">The combination of keys which will trigger this binding.</param>
/// <param name="action">The resultant action which is triggered by this binding. Usually an enum type.</param>
public KeyBinding(KeyCombination keys, object action)
{
KeyCombination = keys;
Action = action;
}
/// <summary>
/// Constructor for derived classes that may require serialisation.
/// </summary>
public KeyBinding()
{
}
/// <summary>
/// Get the action associated with this binding, cast to the required enum type.
/// </summary>
/// <typeparam name="T">The enum type.</typeparam>
/// <returns>A cast <see cref="T"/> representation of <see cref="Action"/>.</returns>
public virtual T GetAction<T>() => (T)Action;
public override string ToString() => $"{KeyCombination}=>{Action}";
}
} | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
namespace osu.Framework.Input.Bindings
{
/// <summary>
/// A binding of a <see cref="Bindings.KeyCombination"/> to an action.
/// </summary>
public class KeyBinding
{
/// <summary>
/// The combination of keys which will trigger this binding.
/// </summary>
public KeyCombination KeyCombination;
/// <summary>
/// The resultant action which is triggered by this binding.
/// This is an <see cref="int"/> representation of an enum type.
/// </summary>
public int Action;
/// <summary>
/// Construct a new instance.
/// </summary>
/// <param name="keys">The combination of keys which will trigger this binding.</param>
/// <param name="action">The resultant action which is triggered by this binding. Usually an enum type.</param>
public KeyBinding(KeyCombination keys, object action)
{
KeyCombination = keys;
Action = (int)action;
}
/// <summary>
/// Constructor for derived classes that may require serialisation.
/// </summary>
public KeyBinding()
{
}
/// <summary>
/// Get the action associated with this binding, cast to the required enum type.
/// </summary>
/// <typeparam name="T">The enum type.</typeparam>
/// <returns>A cast <see cref="T"/> representation of <see cref="Action"/>.</returns>
public virtual T GetAction<T>() => (T)(object)Action;
public override string ToString() => $"{KeyCombination}=>{Action}";
}
} | mit | C# |
77e74c3a10556ec5900db50e03c08a0e06f85a81 | Set `Content-Length` in the `hello` sample | bbaia/connect-owin,sebgod/connect-owin,sebgod/connect-owin,bbaia/connect-owin | examples/hello/Startup.cs | examples/hello/Startup.cs | using System;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;
using Owin;
namespace Connect.Owin.Examples.Hello
{
// OWIN application delegate
using AppFunc = Func<IDictionary<string, object>, Task>;
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Use(new Func<AppFunc, AppFunc>(next => async env =>
{
env["owin.ResponseStatusCode"] = 200;
((IDictionary<string, string[]>)env["owin.ResponseHeaders"]).Add(
"Content-Length", new string[] { "53" });
((IDictionary<string, string[]>)env["owin.ResponseHeaders"]).Add(
"Content-Type", new string[] { "text/html" });
StreamWriter w = new StreamWriter((Stream)env["owin.ResponseBody"]);
w.Write("Hello, from C#. Time on server is " + DateTime.Now.ToString());
await w.FlushAsync();
}));
}
}
}
| using System;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;
using Owin;
namespace Connect.Owin.Examples.Hello
{
// OWIN application delegate
using AppFunc = Func<IDictionary<string, object>, Task>;
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Use(new Func<AppFunc, AppFunc>(next => async env =>
{
env["owin.ResponseStatusCode"] = 200;
((IDictionary<string, string[]>)env["owin.ResponseHeaders"]).Add(
"Content-Type", new string[] { "text/html" });
StreamWriter w = new StreamWriter((Stream)env["owin.ResponseBody"]);
w.Write("Hello, from C#. Time on server is " + DateTime.Now.ToString());
await w.FlushAsync();
}));
}
}
}
| apache-2.0 | C# |
706fef3567d4c25e5154238018c0634d3805f68b | Add boolean to figure out is the uow is made with the session | generik0/Smooth.IoC.Dapper.Repository.UnitOfWork,generik0/Smooth.IoC.Dapper.Repository.UnitOfWork | src/Smooth.IoC.Dapper.Repository.UnitOfWork/Data/UnitOfWork.cs | src/Smooth.IoC.Dapper.Repository.UnitOfWork/Data/UnitOfWork.cs | using System;
using System.Data;
using Dapper.FastCrud;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data
{
public class UnitOfWork : DbTransaction, IUnitOfWork
{
public SqlDialect SqlDialect { get; set; }
private readonly Guid _guid = Guid.NewGuid();
public UnitOfWork(IDbFactory factory, ISession session,
IsolationLevel isolationLevel = IsolationLevel.Serializable, bool sessionOnlyForThisUnitOfWork = false) : base(factory)
{
if (sessionOnlyForThisUnitOfWork)
{
Session = session;
}
Transaction = session.BeginTransaction(isolationLevel);
}
protected bool Equals(UnitOfWork other)
{
return _guid.Equals(other._guid);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((UnitOfWork) obj);
}
public override int GetHashCode()
{
return _guid.GetHashCode();
}
public static bool operator ==(UnitOfWork left, UnitOfWork right)
{
return Equals(left, right);
}
public static bool operator !=(UnitOfWork left, UnitOfWork right)
{
return !Equals(left, right);
}
}
}
| using System;
using System.Data;
using Dapper.FastCrud;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data
{
public class UnitOfWork : DbTransaction, IUnitOfWork
{
public SqlDialect SqlDialect { get; set; }
private readonly Guid _guid = Guid.NewGuid();
public UnitOfWork(IDbFactory factory, ISession session, IsolationLevel isolationLevel = IsolationLevel.Serializable) : base(factory)
{
Transaction = session.BeginTransaction(isolationLevel);
}
protected bool Equals(UnitOfWork other)
{
return _guid.Equals(other._guid);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((UnitOfWork) obj);
}
public override int GetHashCode()
{
return _guid.GetHashCode();
}
public static bool operator ==(UnitOfWork left, UnitOfWork right)
{
return Equals(left, right);
}
public static bool operator !=(UnitOfWork left, UnitOfWork right)
{
return !Equals(left, right);
}
}
}
| mit | C# |
9725d1f19e2e1439d0bebd3dfc128647299ed500 | Update AssemblyInfo.cs | NLog/NLog.Etw | NLog.Etw/Properties/AssemblyInfo.cs | NLog.Etw/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("NLog.Etw")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NLog.Etw")]
[assembly: AssemblyCopyright("Copyright © 2014-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("88ca6063-6b65-471f-8a53-9cf9caf39dc0")]
// 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")]
| 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("NLog.Etw")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NLog.Etw")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("88ca6063-6b65-471f-8a53-9cf9caf39dc0")]
// 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# |
1c42b83ab758d3bc3052915edce6218caf4e8d48 | Change assertion method | pardeike/Harmony | HarmonyTests/Extras/RetrieveOriginalMethod.cs | HarmonyTests/Extras/RetrieveOriginalMethod.cs | using HarmonyLib;
using NUnit.Framework;
using System.Diagnostics;
using System.Reflection;
namespace HarmonyLibTests.Extras
{
[TestFixture]
class RetrieveOriginalMethod : TestLogger
{
[Test]
public void Test0()
{
var harmony = new Harmony("test-original-method");
var originalMethod = AccessTools.Method(typeof(RetrieveOriginalMethod), nameof(RetrieveOriginalMethod.PatchTarget));
var dummyPrefix = AccessTools.Method(typeof(RetrieveOriginalMethod), nameof(RetrieveOriginalMethod.DummyPrefix));
_ = harmony.Patch(originalMethod, new HarmonyMethod(dummyPrefix));
PatchTarget();
}
private static void ChecksStackTrace()
{
var st = new StackTrace(1, false);
var method = Harmony.GetMethodFromStackframe(st.GetFrame(0));
// Replacement will be HarmonyLibTests.Extras.RetrieveOriginalMethod.PatchTarget_Patch1
// We should be able to go from this method, back to HarmonyLibTests.Extras.PatchTarget
if (method is MethodInfo replacement)
{
var original = Harmony.GetOriginalMethod(replacement);
Assert.NotNull(original);
Assert.AreEqual(original, AccessTools.Method(typeof(RetrieveOriginalMethod), nameof(RetrieveOriginalMethod.PatchTarget)));
}
}
internal static void PatchTarget()
{
ChecksStackTrace();
}
internal static void DummyPrefix()
{
}
}
}
| using HarmonyLib;
using NUnit.Framework;
using System.Diagnostics;
using System.Reflection;
namespace HarmonyLibTests.Extras
{
[TestFixture]
class RetrieveOriginalMethod : TestLogger
{
[Test]
public void Test0()
{
var harmony = new Harmony("test-original-method");
var originalMethod = AccessTools.Method(typeof(RetrieveOriginalMethod), nameof(RetrieveOriginalMethod.PatchTarget));
var dummyPrefix = AccessTools.Method(typeof(RetrieveOriginalMethod), nameof(RetrieveOriginalMethod.DummyPrefix));
_ = harmony.Patch(originalMethod, new HarmonyMethod(dummyPrefix));
PatchTarget();
}
private static void ChecksStackTrace()
{
var st = new StackTrace(1, false);
var method = Harmony.GetMethodFromStackframe(st.GetFrame(0));
// Replacement will be HarmonyLibTests.Extras.RetrieveOriginalMethod.PatchTarget_Patch1
// We should be able to go from this method, back to HarmonyLibTests.Extras.PatchTarget
if (method is MethodInfo replacement)
{
var original = Harmony.GetOriginalMethod(replacement);
Assert.NotNull(original);
Assert.Equals(original, AccessTools.Method(typeof(RetrieveOriginalMethod), nameof(RetrieveOriginalMethod.PatchTarget)));
}
}
internal static void PatchTarget()
{
ChecksStackTrace();
}
internal static void DummyPrefix()
{
}
}
}
| mit | C# |
b7158de1917eff5c2fb96abd4e1142c7c1d95842 | add fallback for serial port lister | martin2250/OpenCNCPilot | OpenCNCPilot/SettingsWindow.xaml.cs | OpenCNCPilot/SettingsWindow.xaml.cs | using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Management;
using System.Windows;
using System.Windows.Controls;
namespace OpenCNCPilot
{
/// <summary>
/// Interaction logic for SettingsWindow.xaml
/// </summary>
public partial class SettingsWindow : Window
{
public SettingsWindow()
{
InitializeComponent();
ComboBoxSerialPort_DropDownOpened(null, null);
}
private void ComboBoxSerialPort_DropDownOpened(object sender, EventArgs e)
{
ComboBoxSerialPort.Items.Clear();
Dictionary<string, string> ports = new Dictionary<string, string>();
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_SerialPort");
foreach (ManagementObject queryObj in searcher.Get())
{
string id = queryObj["DeviceID"] as string;
string name = queryObj["Name"] as string;
ports.Add(id, name);
}
}
catch (ManagementException ex)
{
MessageBox.Show("An error occurred while querying for WMI data: " + ex.Message);
}
// fix error of some boards not being listed properly
foreach (string port in SerialPort.GetPortNames())
{
if (!ports.ContainsKey(port))
{
ports.Add(port, port);
}
}
foreach (var port in ports)
{
ComboBoxSerialPort.Items.Add(new ComboBoxItem() { Content = port.Value, Tag = port.Key });
}
}
private void Window_Closed(object sender, EventArgs e)
{
Properties.Settings.Default.Save();
}
}
}
| using System;
using System.Management;
using System.Windows;
using System.Windows.Controls;
namespace OpenCNCPilot
{
/// <summary>
/// Interaction logic for SettingsWindow.xaml
/// </summary>
public partial class SettingsWindow : Window
{
public SettingsWindow()
{
InitializeComponent();
ComboBoxSerialPort_DropDownOpened(null, null);
}
private void ComboBoxSerialPort_DropDownOpened(object sender, EventArgs e)
{
ComboBoxSerialPort.Items.Clear();
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_SerialPort");
foreach (ManagementObject queryObj in searcher.Get())
{
string id = queryObj["DeviceID"] as string;
string name = queryObj["Name"] as string;
ComboBoxSerialPort.Items.Add(new ComboBoxItem() { Content = name, Tag = id });
}
}
catch (ManagementException ex)
{
MessageBox.Show("An error occurred while querying for WMI data: " + ex.Message);
}
}
private void Window_Closed(object sender, EventArgs e)
{
Properties.Settings.Default.Save();
}
}
}
| mit | C# |
04dd4be2c85a86a0d6863fc6089d7b90f50de7a4 | Fix CSS bundles | vtfuture/BForms,vtfuture/BForms,vtfuture/BForms | BForms.Docs/App_Start/BundleConfig.cs | BForms.Docs/App_Start/BundleConfig.cs | using System.Web;
using System.Web.Optimization;
namespace BForms.Docs
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new StyleBundle("~/css")
.Include("~/Scripts/BForms/Components/Bootstrap/css/*.css", new CssRewriteUrlTransform())
.Include("~/Scripts/BForms/Plugins/Select2/css/*.css", new CssRewriteUrlTransform())
.Include("~/Scripts/BForms/Stylesheets/*.css", new CssRewriteUrlTransform())
.Include("~/Content/Stylesheets/*.css", new CssRewriteUrlTransform())
);
}
}
} | using System.Web;
using System.Web.Optimization;
namespace BForms.Docs
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new StyleBundle("~/css")
.Include("~/Scripts/BForms/Components/Bootstrap/css/*.css", new CssRewriteUrlTransform())
.Include("~/Scripts/BForms/Plugins/Select2/css/*.css", new CssRewriteUrlTransform())
.Include("~/Scripts/BForms/Plugins/Datepicker/css/*.css", new CssRewriteUrlTransform())
.Include("~/Scripts/BForms/Stylesheets/*.css", new CssRewriteUrlTransform())
.Include("~/Content/Stylesheets/*.css", new CssRewriteUrlTransform())
);
}
}
} | mit | C# |
01742e17eeed5eb63d5bef5f77db80e73fbeda08 | modify IExchangeRatesProvider to provide support for ExchangeRates from previous years | 180254/KursyWalut | KursyWalut/Provider/IExchangeRatesProvider.cs | KursyWalut/Provider/IExchangeRatesProvider.cs | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace KursyWalut.Provider
{
internal interface IExchangeRatesProvider : IObservable<int>
{
Task<IList<int>> GetAvailableYears();
Task<IList<DateTime>> GetAvailableDates(int year);
Task<IList<ExchangeRate>> GetExchangeRates(DateTime day);
Task<ExchangeRate> GetExchangeRate(Currency currency, DateTime day);
Task<IList<ExchangeRate>> GetExchangeRateHistory(Currency currency, DateTime startDay, DateTime stopDay);
}
} | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace KursyWalut.Provider
{
internal interface IExchangeRatesProvider : IObservable<int>
{
Task<IList<DateTime>> GetAvailableDates();
Task<IList<ExchangeRate>> GetExchangeRates(DateTime day);
Task<IList<ExchangeRate>> GetExchangeRatesHistory(Currency currency, DateTime startDay, DateTime stopDay);
}
} | mit | C# |
3621e9fc550dd8dcd00bf9955cf276a66459bda5 | Save chart/plot in var. | joshuadeleon/typingclassifier,joshuadeleon/typingclassifier,joshuadeleon/typingclassifier | ML.TypingClassifier/Views/Home/Results.cshtml | ML.TypingClassifier/Views/Home/Results.cshtml | @{
ViewBag.Title = "Typing Profile Results";
}
@section scripts
{
<script type="text/javascript">
$(function() {
var points
, features
, plot;
$.getJSON('/sink/points', function(data) {
points = data;
features = {
wpm: ['WPM'].concat(points[0].Values),
backspaces: ['Backspaces'].concat(points[1].Values),
deletes: ['Deletes'].concat(points[2].Values),
averageKeyPressDuration: ['AverageKeyPressDuration'].concat(points[3].Values),
averageTimeBetweenKeystrokes: ['AverageTimeBetweenKeystrokes'].concat(points[4].Values)
};
console.log(data);
console.log(features);
plot = render();
});
function render() {
return c3.generate({
bindto: '#chart',
data: {
columns: [features.wpm, features.averageKeyPressDuration],
type: 'scatter'
},
});
}
});
</script>
}
<main class="container body-content">
<h4>Results</h4>
<div id="chart"></div>
<section>
<span>I want to see</span>
<select id="dropdown-1">
<option value="setosa">Total Time</option>
<option value="versicolor">Spaces</option>
<option value="setosa">Deletion Key Frequency</option>
<option value="setosa">Keypress Duration</option>
<option value="setosa">Words Per Minute</option>
</select>
<span>combined with</span>
<select id="dropdown-2">
<option value="setosa">Total Time</option>
<option value="versicolor">Spaces</option>
<option value="setosa">Deletion Key Frequency</option>
<option value="setosa">Keypress Duration</option>
<option value="setosa">Words Per Minute</option>
</select>
</section>
</main> | @{
ViewBag.Title = "Typing Profile Results";
}
@section scripts
{
<script type="text/javascript">
$(function() {
var points
, features;
$.getJSON('/sink/points', function(data) {
points = data;
features = {
wpm: ['WPM'].concat(points[0].Values),
backspaces: ['Backspaces'].concat(points[1].Values),
deletes: ['Deletes'].concat(points[2].Values),
averageKeyPressDuration: ['AverageKeyPressDuration'].concat(points[3].Values),
averageTimeBetweenKeystrokes: ['AverageTimeBetweenKeystrokes'].concat(points[4].Values)
};
console.log(data);
console.log(features);
render();
});
function render() {
c3.generate({
bindto: '#chart',
data: {
columns: [features.wpm, features.averageKeyPressDuration],
type: 'scatter'
},
});
}
});
</script>
}
<main class="container body-content">
<h4>Results</h4>
<div id="chart"></div>
<section>
<span>I want to see</span>
<select id="dropdown-1">
<option value="setosa">Total Time</option>
<option value="versicolor">Spaces</option>
<option value="setosa">Deletion Key Frequency</option>
<option value="setosa">Keypress Duration</option>
<option value="setosa">Words Per Minute</option>
</select>
<span>combined with</span>
<select id="dropdown-2">
<option value="setosa">Total Time</option>
<option value="versicolor">Spaces</option>
<option value="setosa">Deletion Key Frequency</option>
<option value="setosa">Keypress Duration</option>
<option value="setosa">Words Per Minute</option>
</select>
</section>
</main> | mit | C# |
73c40996ff3fc4e84383b4e2b159faf82b554d58 | Clean up DisplayMode struct | smoogipooo/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework | osu.Framework/Platform/DisplayMode.cs | osu.Framework/Platform/DisplayMode.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Drawing;
namespace osu.Framework.Platform
{
/// <summary>
/// Represents a display mode on a given <see cref="Display"/>.
/// </summary>
public readonly struct DisplayMode
{
/// <summary>
/// The pixel format of the display mode, if available.
/// </summary>
public readonly string Format;
/// <summary>
/// The dimensions of the screen resolution in pixels.
/// </summary>
public readonly Size Size;
/// <summary>
/// The number of bits that represent the colour value for each pixel.
/// </summary>
public readonly int BitsPerPixel;
/// <summary>
/// The refresh rate in hertz.
/// </summary>
public readonly int RefreshRate;
/// <summary>
/// The index of the display mode as determined by the windowing backend.
/// </summary>
public readonly int Index;
/// <summary>
/// The index of the display this mode belongs to as determined by the windowing backend.
/// </summary>
public readonly int DisplayIndex;
public DisplayMode(string format, Size size, int bitsPerPixel, int refreshRate, int index, int displayIndex)
{
Format = format ?? "Unknown";
Size = size;
BitsPerPixel = bitsPerPixel;
RefreshRate = refreshRate;
Index = index;
DisplayIndex = displayIndex;
}
public override string ToString() => $"Size: {Size}, BitsPerPixel: {BitsPerPixel}, RefreshRate: {RefreshRate}, Format: {Format}, Index: {Index}, DisplayIndex: {DisplayIndex}";
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Drawing;
namespace osu.Framework.Platform
{
/// <summary>
/// Represents a display mode on a given <see cref="Display"/>.
/// </summary>
public readonly struct DisplayMode : IEquatable<DisplayMode>
{
/// <summary>
/// The pixel format of the display mode, if available.
/// </summary>
public readonly string Format;
/// <summary>
/// The dimensions of the screen resolution in pixels.
/// </summary>
public readonly Size Size;
/// <summary>
/// The number of bits that represent the colour value for each pixel.
/// </summary>
public readonly int BitsPerPixel;
/// <summary>
/// The refresh rate in hertz.
/// </summary>
public readonly int RefreshRate;
public readonly int Index;
public readonly int DisplayIndex;
public DisplayMode(string format, Size size, int bitsPerPixel, int refreshRate, int index, int displayIndex)
{
Format = format ?? "Unknown";
Size = size;
BitsPerPixel = bitsPerPixel;
RefreshRate = refreshRate;
Index = index;
DisplayIndex = displayIndex;
}
public override string ToString() => $"Size: {Size}, BitsPerPixel: {BitsPerPixel}, RefreshRate: {RefreshRate}, Format: {Format}";
public bool Equals(DisplayMode other) => Index == other.Index && DisplayIndex == other.DisplayIndex;
}
}
| mit | C# |
623ab1ef3be8f3ef21b71797622894690b21d735 | Update time ramp preview on setting change | 2yangk23/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,EVAST9919/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu-new,peppy/osu,johnneijzen/osu,NeoAdonis/osu,ppy/osu,smoogipooo/osu,EVAST9919/osu,peppy/osu,2yangk23/osu,johnneijzen/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,peppy/osu | osu.Game/Rulesets/Mods/ModTimeRamp.cs | osu.Game/Rulesets/Mods/ModTimeRamp.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.Linq;
using osu.Framework.Audio;
using osu.Framework.Audio.Track;
using osu.Framework.Bindables;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Rulesets.UI;
using osu.Game.Rulesets.Objects;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModTimeRamp : Mod, IUpdatableByPlayfield, IApplicableToBeatmap, IApplicableToTrack
{
/// <summary>
/// The point in the beatmap at which the final ramping rate should be reached.
/// </summary>
private const double final_rate_progress = 0.75f;
[SettingSource("Final rate", "The final speed to ramp to")]
public abstract BindableNumber<double> FinalRate { get; }
private double finalRateTime;
private double beginRampTime;
public BindableNumber<double> SpeedChange { get; } = new BindableDouble
{
Default = 1,
Value = 1,
Precision = 0.01,
};
private Track track;
public ModTimeRamp()
{
// for preview purpose at song select. eventually we'll want to be able to update every frame.
FinalRate.BindValueChanged(val => applyAdjustment(1), true);
}
public void ApplyToTrack(Track track)
{
this.track = track;
track.AddAdjustment(AdjustableProperty.Frequency, SpeedChange);
}
public virtual void ApplyToBeatmap(IBeatmap beatmap)
{
HitObject lastObject = beatmap.HitObjects.LastOrDefault();
SpeedChange.SetDefault();
beginRampTime = beatmap.HitObjects.FirstOrDefault()?.StartTime ?? 0;
finalRateTime = final_rate_progress * (lastObject?.GetEndTime() ?? 0);
}
public virtual void Update(Playfield playfield)
{
applyAdjustment((track.CurrentTime - beginRampTime) / finalRateTime);
}
/// <summary>
/// Adjust the rate along the specified ramp
/// </summary>
/// <param name="amount">The amount of adjustment to apply (from 0..1).</param>
private void applyAdjustment(double amount) =>
SpeedChange.Value = 1 + (Math.Sign(FinalRate.Value) * Math.Clamp(amount, 0, 1) * Math.Abs(FinalRate.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 System;
using System.Linq;
using osu.Framework.Audio;
using osu.Framework.Audio.Track;
using osu.Framework.Bindables;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Rulesets.UI;
using osu.Game.Rulesets.Objects;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModTimeRamp : Mod, IUpdatableByPlayfield, IApplicableToBeatmap, IApplicableToTrack
{
/// <summary>
/// The point in the beatmap at which the final ramping rate should be reached.
/// </summary>
private const double final_rate_progress = 0.75f;
[SettingSource("Final rate", "The final speed to ramp to")]
public abstract BindableNumber<double> FinalRate { get; }
private double finalRateTime;
private double beginRampTime;
public BindableNumber<double> SpeedChange { get; } = new BindableDouble
{
Default = 1,
Value = 1,
Precision = 0.01,
};
private Track track;
public void ApplyToTrack(Track track)
{
this.track = track;
track.AddAdjustment(AdjustableProperty.Frequency, SpeedChange);
}
public virtual void ApplyToBeatmap(IBeatmap beatmap)
{
HitObject lastObject = beatmap.HitObjects.LastOrDefault();
SpeedChange.SetDefault();
beginRampTime = beatmap.HitObjects.FirstOrDefault()?.StartTime ?? 0;
finalRateTime = final_rate_progress * (lastObject?.GetEndTime() ?? 0);
}
public virtual void Update(Playfield playfield)
{
applyAdjustment((track.CurrentTime - beginRampTime) / finalRateTime);
}
/// <summary>
/// Adjust the rate along the specified ramp
/// </summary>
/// <param name="amount">The amount of adjustment to apply (from 0..1).</param>
private void applyAdjustment(double amount) =>
SpeedChange.Value = 1 + (Math.Sign(FinalRate.Value) * Math.Clamp(amount, 0, 1) * Math.Abs(FinalRate.Value));
}
}
| mit | C# |
caca9834ce5ee24e03404a91edeb9b6f4064b5e9 | Fix MySqlQuoterTest quote value char | fluentmigrator/fluentmigrator,FabioNascimento/fluentmigrator,schambers/fluentmigrator,igitur/fluentmigrator,mstancombe/fluentmig,jogibear9988/fluentmigrator,mstancombe/fluentmig,MetSystem/fluentmigrator,modulexcite/fluentmigrator,stsrki/fluentmigrator,IRlyDontKnow/fluentmigrator,wolfascu/fluentmigrator,dealproc/fluentmigrator,barser/fluentmigrator,drmohundro/fluentmigrator,istaheev/fluentmigrator,eloekset/fluentmigrator,amroel/fluentmigrator,modulexcite/fluentmigrator,alphamc/fluentmigrator,mstancombe/fluentmigrator,tommarien/fluentmigrator,vgrigoriu/fluentmigrator,tommarien/fluentmigrator,eloekset/fluentmigrator,amroel/fluentmigrator,lcharlebois/fluentmigrator,KaraokeStu/fluentmigrator,istaheev/fluentmigrator,itn3000/fluentmigrator,alphamc/fluentmigrator,MetSystem/fluentmigrator,igitur/fluentmigrator,jogibear9988/fluentmigrator,mstancombe/fluentmigrator,drmohundro/fluentmigrator,daniellee/fluentmigrator,daniellee/fluentmigrator,wolfascu/fluentmigrator,barser/fluentmigrator,spaccabit/fluentmigrator,mstancombe/fluentmig,daniellee/fluentmigrator,akema-fr/fluentmigrator,FabioNascimento/fluentmigrator,lcharlebois/fluentmigrator,spaccabit/fluentmigrator,KaraokeStu/fluentmigrator,bluefalcon/fluentmigrator,akema-fr/fluentmigrator,bluefalcon/fluentmigrator,IRlyDontKnow/fluentmigrator,fluentmigrator/fluentmigrator,schambers/fluentmigrator,itn3000/fluentmigrator,istaheev/fluentmigrator,stsrki/fluentmigrator,dealproc/fluentmigrator,vgrigoriu/fluentmigrator | src/FluentMigrator.Tests/Unit/Generators/MySql/MySqlQuoterTest.cs | src/FluentMigrator.Tests/Unit/Generators/MySql/MySqlQuoterTest.cs | using System;
using System.Globalization;
using System.Threading;
using FluentMigrator.Model;
using FluentMigrator.Runner.Generators;
using FluentMigrator.Runner.Generators.Generic;
using FluentMigrator.Runner.Generators.Jet;
using FluentMigrator.Runner.Generators.MySql;
using FluentMigrator.Runner.Generators.Oracle;
using FluentMigrator.Runner.Generators.SQLite;
using FluentMigrator.Runner.Generators.SqlServer;
using NUnit.Framework;
using NUnit.Should;
namespace FluentMigrator.Tests.Unit.Generators.MySql
{
[TestFixture]
public class MySqlQuoterTest
{
private IQuoter quoter = default(MySqlQuoter);
private readonly CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
[SetUp]
public void SetUp()
{
quoter = new MySqlQuoter();
}
[Test]
public void TimeSpanIsFormattedQuotes()
{
quoter.QuoteValue(new TimeSpan(1,2, 13, 65))
.ShouldBe("'26:14:05'");
}
}
}
| using System;
using System.Globalization;
using System.Threading;
using FluentMigrator.Model;
using FluentMigrator.Runner.Generators;
using FluentMigrator.Runner.Generators.Generic;
using FluentMigrator.Runner.Generators.Jet;
using FluentMigrator.Runner.Generators.MySql;
using FluentMigrator.Runner.Generators.Oracle;
using FluentMigrator.Runner.Generators.SQLite;
using FluentMigrator.Runner.Generators.SqlServer;
using NUnit.Framework;
using NUnit.Should;
namespace FluentMigrator.Tests.Unit.Generators.MySql
{
[TestFixture]
public class MySqlQuoterTest
{
private IQuoter quoter = default(MySqlQuoter);
private readonly CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
[SetUp]
public void SetUp()
{
quoter = new MySqlQuoter();
}
[Test]
public void TimeSpanIsFormattedQuotes()
{
quoter.QuoteValue(new TimeSpan(1,2, 13, 65))
.ShouldBe("`26:14:05`");
}
}
}
| apache-2.0 | C# |
0a3ef1d0e2f27a63d0f9a1e893cf674ea4e37faa | Add service ServiceKnownTypes for object[] and Dictionary<string, object> so that basic arrays can be passed two and from functions | NumbersInternational/CefSharp,ruisebastiao/CefSharp,zhangjingpu/CefSharp,jamespearce2006/CefSharp,jamespearce2006/CefSharp,joshvera/CefSharp,joshvera/CefSharp,twxstar/CefSharp,ITGlobal/CefSharp,illfang/CefSharp,rover886/CefSharp,rlmcneary2/CefSharp,yoder/CefSharp,haozhouxu/CefSharp,battewr/CefSharp,rlmcneary2/CefSharp,Haraguroicha/CefSharp,battewr/CefSharp,yoder/CefSharp,Livit/CefSharp,battewr/CefSharp,Haraguroicha/CefSharp,illfang/CefSharp,twxstar/CefSharp,ruisebastiao/CefSharp,AJDev77/CefSharp,Livit/CefSharp,rover886/CefSharp,AJDev77/CefSharp,jamespearce2006/CefSharp,dga711/CefSharp,VioletLife/CefSharp,windygu/CefSharp,haozhouxu/CefSharp,Haraguroicha/CefSharp,yoder/CefSharp,Livit/CefSharp,VioletLife/CefSharp,AJDev77/CefSharp,illfang/CefSharp,windygu/CefSharp,VioletLife/CefSharp,rover886/CefSharp,ruisebastiao/CefSharp,dga711/CefSharp,wangzheng888520/CefSharp,gregmartinhtc/CefSharp,wangzheng888520/CefSharp,jamespearce2006/CefSharp,jamespearce2006/CefSharp,windygu/CefSharp,rlmcneary2/CefSharp,zhangjingpu/CefSharp,ITGlobal/CefSharp,rover886/CefSharp,wangzheng888520/CefSharp,ITGlobal/CefSharp,gregmartinhtc/CefSharp,NumbersInternational/CefSharp,Livit/CefSharp,dga711/CefSharp,dga711/CefSharp,yoder/CefSharp,rlmcneary2/CefSharp,joshvera/CefSharp,zhangjingpu/CefSharp,ITGlobal/CefSharp,Haraguroicha/CefSharp,ruisebastiao/CefSharp,joshvera/CefSharp,twxstar/CefSharp,gregmartinhtc/CefSharp,illfang/CefSharp,AJDev77/CefSharp,gregmartinhtc/CefSharp,NumbersInternational/CefSharp,NumbersInternational/CefSharp,Haraguroicha/CefSharp,wangzheng888520/CefSharp,rover886/CefSharp,zhangjingpu/CefSharp,haozhouxu/CefSharp,VioletLife/CefSharp,twxstar/CefSharp,battewr/CefSharp,windygu/CefSharp,haozhouxu/CefSharp | CefSharp/Internals/IBrowserProcess.cs | CefSharp/Internals/IBrowserProcess.cs | // Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System.Collections.Generic;
using System.ServiceModel;
namespace CefSharp.Internals
{
[ServiceContract(CallbackContract = typeof(IRenderProcess), SessionMode = SessionMode.Required)]
[ServiceKnownType(typeof(object[]))]
[ServiceKnownType(typeof(Dictionary<string, object>))]
public interface IBrowserProcess
{
[OperationContract]
BrowserProcessResponse CallMethod(long objectId, string name, object[] parameters);
[OperationContract]
BrowserProcessResponse GetProperty(long objectId, string name);
[OperationContract]
BrowserProcessResponse SetProperty(long objectId, string name, object value);
[OperationContract]
JavascriptRootObject GetRegisteredJavascriptObjects();
[OperationContract]
void Connect();
}
} | // Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System.ServiceModel;
namespace CefSharp.Internals
{
[ServiceContract(CallbackContract = typeof(IRenderProcess), SessionMode = SessionMode.Required)]
public interface IBrowserProcess
{
[OperationContract]
BrowserProcessResponse CallMethod(long objectId, string name, object[] parameters);
[OperationContract]
BrowserProcessResponse GetProperty(long objectId, string name);
[OperationContract]
BrowserProcessResponse SetProperty(long objectId, string name, object value);
[OperationContract]
JavascriptRootObject GetRegisteredJavascriptObjects();
[OperationContract]
void Connect();
}
} | bsd-3-clause | C# |
910f49764db7c9aa42116090b801cd6d8aac1440 | Tidy up sum a bit by moving where we cast and negate to the line below. | lukedrury/super-market-kata | supermarketkata/engine/rules/PercentageDiscount.cs | supermarketkata/engine/rules/PercentageDiscount.cs | using System;
using engine.core;
namespace engine.rules
{
public class PercentageDiscount : Rule
{
private readonly string m_ApplicableItemName;
private readonly double m_Percentage;
public PercentageDiscount(string applicableItemName, int percentage)
{
m_ApplicableItemName = applicableItemName;
m_Percentage = percentage;
}
public override Basket Apply(Basket basket)
{
var discountedBasket = new Basket();
foreach (var item in basket)
{
discountedBasket.Add(item);
if (item.Name.Equals(m_ApplicableItemName) && !item.UsedInOffer)
{
var discountToApply = Math.Ceiling(item.Price * m_Percentage / 100);
discountedBasket.Add(string.Format("{0}:{1}% discount", m_ApplicableItemName, m_Percentage), (int) -discountToApply);
}
}
return discountedBasket;
}
}
} | using System;
using engine.core;
namespace engine.rules
{
public class PercentageDiscount : Rule
{
private readonly string m_ApplicableItemName;
private readonly double m_Percentage;
public PercentageDiscount(string applicableItemName, int percentage)
{
m_ApplicableItemName = applicableItemName;
m_Percentage = percentage;
}
public override Basket Apply(Basket basket)
{
var discountedBasket = new Basket();
foreach (var item in basket)
{
discountedBasket.Add(item);
if (item.Name.Equals(m_ApplicableItemName) && !item.UsedInOffer)
{
var discountToApply = -(int) Math.Ceiling(item.Price * m_Percentage / 100);
discountedBasket.Add(string.Format("{0}:{1}% discount", m_ApplicableItemName, m_Percentage), discountToApply);
}
}
return discountedBasket;
}
}
} | mit | C# |
7900b333ea4b03a7df461252948fc77a60ae8e29 | Fix modifier of ANTLR parser. | exKAZUu/Code2Xml,exKAZUu/Code2Xml,exKAZUu/Code2Xml,exKAZUu/Code2Xml | Code2Xml.Tools/AntlrHelper/Program.cs | Code2Xml.Tools/AntlrHelper/Program.cs | #region License
// Copyright (C) 2011-2013 Kazunori Sakamoto
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Code2Xml.Tools.AntlrHelper {
internal class Program {
private static void Main(string[] args) {
if (args.Length == 0) {
Console.WriteLine("Find 'Code2Xml.Languages' directory due to no arguments.");
var dir = new FileInfo(Assembly.GetEntryAssembly().Location).Directory;
while (true) {
var dirs = dir.GetDirectories("Code2Xml.Languages", SearchOption.AllDirectories);
if (dirs.Length > 0) {
args = new[] { dirs[0].FullName };
break;
}
dir = dir.Parent;
if (dir == null) {
Console.WriteLine("Can't find 'Code2Xml.Languages' directory.");
args = new[] { Console.In.ReadLine() };
break;
}
}
}
foreach (var arg in args) {
var path = Path.GetFullPath(arg);
var dir = Directory.Exists(path) ? path : Path.GetDirectoryName(path);
var grammarFiles = Directory.GetFiles(dir, "*.g", SearchOption.AllDirectories);
foreach (var grammarFile in grammarFiles) {
Console.WriteLine(grammarFile);
var info = new ProcessStartInfo {
FileName = "Antlr3",
Arguments = '"' + grammarFile + '"',
CreateNoWindow = true,
UseShellExecute = true,
WorkingDirectory = Path.GetDirectoryName(grammarFile),
};
using (var p = Process.Start(info)) {
p.WaitForExit();
}
}
var csFiles = grammarFiles
.Select(Path.GetDirectoryName)
.SelectMany(d => Directory.GetFiles(d, "*.cs", SearchOption.AllDirectories));
foreach (var file in csFiles) {
if (file.EndsWith("Parser.cs")) {
Console.WriteLine(file);
ParserModifier.Modify(file);
} else if (file.EndsWith("Lexer.cs")) {
Console.WriteLine(file);
LexerModifier.Modify(file);
}
}
}
}
}
} | #region License
// Copyright (C) 2011-2013 Kazunori Sakamoto
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Code2Xml.Tools.AntlrHelper {
internal class Program {
private static void Main(string[] args) {
if (args.Length == 0) {
Console.WriteLine("Find 'Code2Xml.Languages' directory due to no arguments.");
var dir = new FileInfo(Assembly.GetEntryAssembly().Location).Directory;
while (true) {
var dirs = dir.GetDirectories("Code2Xml.Languages", SearchOption.AllDirectories);
if (dirs.Length > 0) {
args = new[] { dirs[0].FullName };
break;
}
dir = dir.Parent;
if (dir == null) {
Console.WriteLine("Can't find 'Code2Xml.Languages' directory.");
args = new[] { Console.In.ReadLine() };
break;
}
}
}
foreach (var arg in args) {
var path = Path.GetFullPath(arg);
var dir = Directory.Exists(path) ? path : Path.GetDirectoryName(path);
var grammarFiles = Directory.GetFiles(dir, "php.g", SearchOption.AllDirectories);
foreach (var grammarFile in grammarFiles) {
Console.WriteLine(grammarFile);
var info = new ProcessStartInfo {
FileName = "Antlr3",
Arguments = '"' + grammarFile + '"',
CreateNoWindow = true,
UseShellExecute = true,
WorkingDirectory = Path.GetDirectoryName(grammarFile),
};
using (var p = Process.Start(info)) {
p.WaitForExit();
}
}
var csFiles = grammarFiles
.Select(Path.GetDirectoryName)
.SelectMany(d => Directory.GetFiles(d, "*.cs", SearchOption.AllDirectories));
foreach (var file in csFiles) {
if (file.EndsWith("Parser.cs")) {
Console.WriteLine(file);
ParserModifier.Modify(file);
} else if (file.EndsWith("Lexer.cs")) {
Console.WriteLine(file);
LexerModifier.Modify(file);
}
}
}
}
}
} | apache-2.0 | C# |
827c6d4a3e35ae85ee8fe01627c31db06735bb45 | Use withPrecomilation variable | reactjs/React.NET,reactjs/React.NET,reactjs/React.NET,reactjs/React.NET,reactjs/React.NET,reactjs/React.NET | tests/React.Tests.Integration/ServerRenderTests.cs | tests/React.Tests.Integration/ServerRenderTests.cs | using System;
using System.IO;
using System.Text;
using JavaScriptEngineSwitcher.ChakraCore;
using JavaScriptEngineSwitcher.Core;
using Xunit;
namespace React.Tests.Integration
{
public class ServerRenderTests : IDisposable
{
public ServerRenderTests()
{
Initializer.Initialize(registration => registration.AsSingleton());
JsEngineSwitcher.Current.EngineFactories.Add(new ChakraCoreJsEngineFactory());
JsEngineSwitcher.Current.DefaultEngineName = ChakraCoreJsEngine.EngineName;
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void RendersSuccessfullyWithBundledReact(bool withPrecompilation)
{
#if NET461
AssemblyRegistration.Container.Register<ICache, MemoryFileCache>();
AssemblyRegistration.Container.Register<IFileSystem, PhysicalFileSystem>();
#else
AssemblyRegistration.Container.Register<ICache, MemoryFileCacheCore>();
AssemblyRegistration.Container.Register<IFileSystem, SimpleFileSystem>();
#endif
ReactSiteConfiguration.Configuration
.SetReuseJavaScriptEngines(false)
.SetAllowJavaScriptPrecompilation(withPrecompilation)
.AddScript("Sample.jsx");
var stringWriter = new StringWriter(new StringBuilder(128));
ReactEnvironment.GetCurrentOrThrow.CreateComponent("HelloWorld", new { name = "Tester" }, serverOnly: true).RenderHtml(stringWriter, renderServerOnly: true);
Assert.Equal("<div>Hello Tester!</div>", stringWriter.ToString());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void RendersSuccessfullyWithExternalReact(bool withPrecompilation)
{
#if NET461
AssemblyRegistration.Container.Register<ICache, MemoryFileCache>();
AssemblyRegistration.Container.Register<IFileSystem, PhysicalFileSystem>();
#else
AssemblyRegistration.Container.Register<ICache, MemoryFileCacheCore>();
AssemblyRegistration.Container.Register<IFileSystem, SimpleFileSystem>();
#endif
ReactSiteConfiguration.Configuration
.SetReuseJavaScriptEngines(false)
.SetAllowJavaScriptPrecompilation(withPrecompilation)
.SetLoadReact(false)
.AddScriptWithoutTransform("react.generated.js")
.AddScript("Sample.jsx");
var stringWriter = new StringWriter(new StringBuilder(128));
ReactEnvironment.GetCurrentOrThrow.CreateComponent("HelloWorld", new { name = "Tester" }, serverOnly: true).RenderHtml(stringWriter, renderServerOnly: true);
Assert.Equal("<div>Hello Tester!</div>", stringWriter.ToString());
}
public void Dispose()
{
JsEngineSwitcher.Current.DefaultEngineName = string.Empty;
JsEngineSwitcher.Current.EngineFactories.Clear();
ReactSiteConfiguration.Configuration = new ReactSiteConfiguration();
AssemblyRegistration.Container.Unregister<ICache>();
AssemblyRegistration.Container.Unregister<IFileSystem>();
}
}
}
| using System;
using System.IO;
using System.Text;
using JavaScriptEngineSwitcher.ChakraCore;
using JavaScriptEngineSwitcher.Core;
using Xunit;
namespace React.Tests.Integration
{
public class ServerRenderTests : IDisposable
{
public ServerRenderTests()
{
Initializer.Initialize(registration => registration.AsSingleton());
JsEngineSwitcher.Current.EngineFactories.Add(new ChakraCoreJsEngineFactory());
JsEngineSwitcher.Current.DefaultEngineName = ChakraCoreJsEngine.EngineName;
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void RendersSuccessfullyWithBundledReact(bool withPrecompilation)
{
#if NET461
AssemblyRegistration.Container.Register<ICache, MemoryFileCache>();
AssemblyRegistration.Container.Register<IFileSystem, PhysicalFileSystem>();
#else
AssemblyRegistration.Container.Register<ICache, MemoryFileCacheCore>();
AssemblyRegistration.Container.Register<IFileSystem, SimpleFileSystem>();
#endif
ReactSiteConfiguration.Configuration
.SetReuseJavaScriptEngines(false)
.SetAllowJavaScriptPrecompilation(withPrecompilation)
.AddScript("Sample.jsx");
var stringWriter = new StringWriter(new StringBuilder(128));
ReactEnvironment.GetCurrentOrThrow.CreateComponent("HelloWorld", new { name = "Tester" }, serverOnly: true).RenderHtml(stringWriter, renderServerOnly: true);
Assert.Equal("<div>Hello Tester!</div>", stringWriter.ToString());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void RendersSuccessfullyWithExternalReact(bool withPrecompilation)
{
#if NET461
AssemblyRegistration.Container.Register<ICache, MemoryFileCache>();
AssemblyRegistration.Container.Register<IFileSystem, PhysicalFileSystem>();
#else
AssemblyRegistration.Container.Register<ICache, MemoryFileCacheCore>();
AssemblyRegistration.Container.Register<IFileSystem, SimpleFileSystem>();
#endif
ReactSiteConfiguration.Configuration
.SetReuseJavaScriptEngines(false)
.SetAllowJavaScriptPrecompilation(false)
.SetLoadReact(false)
.AddScriptWithoutTransform("react.generated.js")
.AddScript("Sample.jsx");
var stringWriter = new StringWriter(new StringBuilder(128));
ReactEnvironment.GetCurrentOrThrow.CreateComponent("HelloWorld", new { name = "Tester" }, serverOnly: true).RenderHtml(stringWriter, renderServerOnly: true);
Assert.Equal("<div>Hello Tester!</div>", stringWriter.ToString());
}
public void Dispose()
{
JsEngineSwitcher.Current.DefaultEngineName = string.Empty;
JsEngineSwitcher.Current.EngineFactories.Clear();
ReactSiteConfiguration.Configuration = new ReactSiteConfiguration();
AssemblyRegistration.Container.Unregister<ICache>();
AssemblyRegistration.Container.Unregister<IFileSystem>();
}
}
}
| mit | C# |
3039fbe43b193d57beb9b099c0a44d42e74e51ee | Increase AssemblyVersion | inputfalken/Sharpy | Sharpy/Properties/AssemblyInfo.cs | Sharpy/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("Sharpy")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Sharpy")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//Makes my internal items visibile to the test project
[assembly: InternalsVisibleTo("Tests")]
// 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("e4c60589-e7ce-471c-82e3-28c356cd1191")]
// 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("3.3.0.0")]
[assembly: AssemblyInformationalVersion("3.3.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("Sharpy")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Sharpy")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//Makes my internal items visibile to the test project
[assembly: InternalsVisibleTo("Tests")]
// 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("e4c60589-e7ce-471c-82e3-28c356cd1191")]
// 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("3.2.0.0")]
[assembly: AssemblyInformationalVersion("3.2.0")]
| mit | C# |
f3ac49474c9f354c399e8f9d1b487829770b29aa | Use the same reference for all method calls | jmptrader/WampSharp,jmptrader/WampSharp,jmptrader/WampSharp | src/net45/WampSharp.Default/WAMP2/V2/DefaultWampChannelFactory.cs | src/net45/WampSharp.Default/WAMP2/V2/DefaultWampChannelFactory.cs | using WampSharp.Binding;
using WampSharp.V2.Binding;
using WampSharp.V2.Client;
using WampSharp.WebSocket4Net;
namespace WampSharp.V2
{
public class DefaultWampChannelFactory : WampChannelFactory
{
private readonly MessagePackObjectBinding mMsgpackBinding = new MessagePackObjectBinding();
private readonly JTokenBinding mJsonBinding = new JTokenBinding();
public IWampChannel CreateChannel<TMessage>(string address,
string realm,
IWampTextBinding<TMessage> binding)
{
var connection =
new WebSocket4NetTextConnection<TMessage>(address, binding);
return this.CreateChannel(realm, connection, binding);
}
public IWampChannel CreateChannel<TMessage>(string address,
string realm,
IWampBinaryBinding<TMessage> binding)
{
var connection =
new WebSocket4NetBinaryConnection<TMessage>(address, binding);
return this.CreateChannel(realm, connection, binding);
}
public IWampChannel CreateJsonChannel(string address,
string realm)
{
return this.CreateChannel(address, realm, mJsonBinding);
}
public IWampChannel CreateMsgpackChannel(string address,
string realm)
{
return this.CreateChannel(address, realm, mMsgpackBinding);
}
}
} | using WampSharp.Binding;
using WampSharp.V2.Binding;
using WampSharp.V2.Client;
using WampSharp.WebSocket4Net;
namespace WampSharp.V2
{
public class DefaultWampChannelFactory : WampChannelFactory
{
public IWampChannel CreateChannel<TMessage>(string address,
string realm,
IWampTextBinding<TMessage> binding)
{
var connection =
new WebSocket4NetTextConnection<TMessage>(address, binding);
return this.CreateChannel(realm, connection, binding);
}
public IWampChannel CreateChannel<TMessage>(string address,
string realm,
IWampBinaryBinding<TMessage> binding)
{
var connection =
new WebSocket4NetBinaryConnection<TMessage>(address, binding);
return this.CreateChannel(realm, connection, binding);
}
public IWampChannel CreateJsonChannel(string address,
string realm)
{
JTokenBinding binding = new JTokenBinding();
return this.CreateChannel(address, realm, binding);
}
public IWampChannel CreateMsgpackChannel(string address,
string realm)
{
MessagePackObjectBinding binding = new MessagePackObjectBinding();
return this.CreateChannel(address, realm, binding);
}
}
} | bsd-2-clause | C# |
65159771a8fb3d9885cabd12a57dd94d5a036151 | Fix build error in LoggerMock | SAEnergy/Infrastructure,SAEnergy/Superstructure,SAEnergy/Infrastructure | Src/Test/Test.Mocks/LoggerMock.cs | Src/Test/Test.Mocks/LoggerMock.cs | using Core.Interfaces.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
namespace Test.Mocks
{
public class LoggerMock : ILogger
{
public bool IsRunning { get; private set; }
public void AddLogDestination(ILogDestination logDestination)
{
throw new NotImplementedException();
}
public void Log(LogMessage logMessage, [CallerMemberName] string callerName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
{
throw new NotImplementedException();
}
public void Log(LogMessageSeverity severity, string message, [CallerMemberName] string callerName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
{
throw new NotImplementedException();
}
public void RemoveLogDestination(ILogDestination logDestination)
{
throw new NotImplementedException();
}
public void Start()
{
throw new NotImplementedException();
}
public void Stop()
{
throw new NotImplementedException();
}
}
}
| using Core.Interfaces.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
namespace Test.Mocks
{
public class LoggerMock : ILogger
{
public bool IsRunning { get; }
public void AddLogDestination(ILogDestination logDestination)
{
throw new NotImplementedException();
}
public void Log(LogMessage logMessage, [CallerMemberName] string callerName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
{
throw new NotImplementedException();
}
public void Log(LogMessageSeverity severity, string message, [CallerMemberName] string callerName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
{
throw new NotImplementedException();
}
public void RemoveLogDestination(ILogDestination logDestination)
{
throw new NotImplementedException();
}
public void Start()
{
throw new NotImplementedException();
}
public void Stop()
{
throw new NotImplementedException();
}
}
}
| mit | C# |
85461855a3fd94254d13e524eb7dd448763311b0 | fix log message | AdamsLair/duality | Test/Core/InitDualityAttribute.cs | Test/Core/InitDualityAttribute.cs | using System;
using Duality.Launcher;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
namespace Duality.Tests
{
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public class InitDualityAttribute : Attribute, ITestAction
{
private string oldEnvDir = null;
private CorePlugin unitTestPlugin = null;
public ActionTargets Targets
{
get { return ActionTargets.Suite; }
}
private DualityLauncher launcher;
public InitDualityAttribute() {}
public void BeforeTest(ITest details)
{
Console.WriteLine("----- Beginning Duality environment setup -----");
// Set environment directory to Duality binary directory
this.oldEnvDir = Environment.CurrentDirectory;
Console.WriteLine("Testing in working directory: {0}", TestContext.CurrentContext.TestDirectory);
Environment.CurrentDirectory = TestContext.CurrentContext.TestDirectory;
if (this.launcher == null)
{
this.launcher = new DualityLauncher();
}
// Manually register pseudo-plugin for the Unit Testing Assembly
this.unitTestPlugin = DualityApp.PluginManager.LoadPlugin(
typeof(DualityTestsPlugin).Assembly,
typeof(DualityTestsPlugin).Assembly.Location);
Console.WriteLine("----- Duality environment setup complete -----");
}
public void AfterTest(ITest details)
{
Console.WriteLine("----- Beginning Duality environment teardown -----");
if (this.launcher != null)
{
this.launcher.Dispose();
}
Environment.CurrentDirectory = this.oldEnvDir;
Console.WriteLine("----- Duality environment teardown complete -----");
}
}
}
| using System;
using Duality.Launcher;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
namespace Duality.Tests
{
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public class InitDualityAttribute : Attribute, ITestAction
{
private string oldEnvDir = null;
private CorePlugin unitTestPlugin = null;
public ActionTargets Targets
{
get { return ActionTargets.Suite; }
}
private DualityLauncher launcher;
public InitDualityAttribute() {}
public void BeforeTest(ITest details)
{
Console.WriteLine("----- Beginning Duality environment setup -----");
// Set environment directory to Duality binary directory
this.oldEnvDir = Environment.CurrentDirectory;
Console.WriteLine("Testing Core Assembly: {0}", TestContext.CurrentContext.TestDirectory);
Environment.CurrentDirectory = TestContext.CurrentContext.TestDirectory;
if (this.launcher == null)
{
this.launcher = new DualityLauncher();
}
// Manually register pseudo-plugin for the Unit Testing Assembly
this.unitTestPlugin = DualityApp.PluginManager.LoadPlugin(
typeof(DualityTestsPlugin).Assembly,
typeof(DualityTestsPlugin).Assembly.Location);
Console.WriteLine("----- Duality environment setup complete -----");
}
public void AfterTest(ITest details)
{
Console.WriteLine("----- Beginning Duality environment teardown -----");
if (this.launcher != null)
{
this.launcher.Dispose();
}
Environment.CurrentDirectory = this.oldEnvDir;
Console.WriteLine("----- Duality environment teardown complete -----");
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.