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 |
|---|---|---|---|---|---|---|---|---|
3b9bcd16db2f1f61f4e6b2133a0523ec5c82cfce
|
Change hard-coded IP address
|
jskeet/DemoCode,jskeet/DemoCode,jskeet/DemoCode,jskeet/DemoCode
|
XTouchMini/XTouchMini.MixerControl/Program.cs
|
XTouchMini/XTouchMini.MixerControl/Program.cs
|
// Copyright 2021 Jon Skeet. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using OscMixerControl;
using System;
using System.Threading;
using System.Threading.Tasks;
using XTouchMini.Model;
namespace XTouchMini.MixerControl
{
class Program
{
static async Task Main()
{
// MIDI input name hard-coded as I think the chances of anyone else running this are slim...
await using (var controller = await XTouchMiniMackieController.ConnectAsync("X-TOUCH MINI"))
{
Console.WriteLine("Connected to controller");
using (var mixer = new Mixer())
{
// IP address hard-coded as I think the chances of anyone else running this are slim...
mixer.Connect("192.168.1.41", 10024);
mixer.RegisterHandler("/info", (sender, message) => Console.WriteLine($"Mixer info response: {string.Join("/", message)}"));
await mixer.SendInfoAsync();
using (var connector = new MixerConnector(controller, mixer))
{
await connector.StartAsync();
await Task.Delay(Timeout.Infinite);
}
}
}
}
}
}
|
// Copyright 2021 Jon Skeet. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using OscMixerControl;
using System;
using System.Threading;
using System.Threading.Tasks;
using XTouchMini.Model;
namespace XTouchMini.MixerControl
{
class Program
{
static async Task Main()
{
// MIDI input name hard-coded as I think the chances of anyone else running this are slim...
await using (var controller = await XTouchMiniMackieController.ConnectAsync("X-TOUCH MINI"))
{
Console.WriteLine("Connected to controller");
using (var mixer = new Mixer())
{
// IP address hard-coded as I think the chances of anyone else running this are slim...
mixer.Connect("192.168.1.172", 10024);
mixer.RegisterHandler("/info", (sender, message) => Console.WriteLine($"Mixer info response: {string.Join("/", message)}"));
await mixer.SendInfoAsync();
using (var connector = new MixerConnector(controller, mixer))
{
await connector.StartAsync();
await Task.Delay(Timeout.Infinite);
}
}
}
}
}
}
|
apache-2.0
|
C#
|
b79fc889eb0bdf83828dfe474e722b04f806435a
|
Fix duplicate 'CollectionBehavior' attribute
|
wieslawsoltes/Perspex,akrisiun/Perspex,jazzay/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,MrDaedra/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,Perspex/Perspex,MrDaedra/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,grokys/Perspex,jkoritzinsky/Avalonia,grokys/Perspex,jkoritzinsky/Avalonia,Perspex/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex
|
tests/Avalonia.Markup.UnitTests/Properties/AssemblyInfo.cs
|
tests/Avalonia.Markup.UnitTests/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Xunit;
// 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("Avalonia.Markup.UnitTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Avalonia.Markup.UnitTests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8ef392d5-1416-45aa-9956-7cbbc3229e8a")]
// 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")]
// Don't run tests in parallel.
[assembly: CollectionBehavior(MaxParallelThreads = 1)]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Xunit;
// 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("Avalonia.Markup.UnitTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Avalonia.Markup.UnitTests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8ef392d5-1416-45aa-9956-7cbbc3229e8a")]
// 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")]
// Don't run tests in parallel.
[assembly: CollectionBehavior(DisableTestParallelization = true)]
[assembly: CollectionBehavior(MaxParallelThreads = 1)]
|
mit
|
C#
|
d46c1d7a286ca73285a7e1b63e60ec77e84de15f
|
Use different parameter for nameof operator.
|
PenguinF/sandra-three
|
Sandra.UI.WF.Chess/SettingsTextBox.UIActions.cs
|
Sandra.UI.WF.Chess/SettingsTextBox.UIActions.cs
|
/*********************************************************************************
* SettingsTextBox.UIActions.cs
*
* Copyright (c) 2004-2018 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.
*
*********************************************************************************/
using System;
using System.IO;
namespace Sandra.UI.WF
{
public partial class SettingsTextBox
{
public const string SettingsTextBoxUIActionPrefix = nameof(SettingsTextBox) + ".";
public static readonly DefaultUIActionBinding SaveToFile = new DefaultUIActionBinding(
new UIAction(SettingsTextBoxUIActionPrefix + nameof(SaveToFile)),
new UIActionBinding()
{
ShowInMenu = true,
IsFirstInGroup = true,
MenuCaptionKey = LocalizedStringKeys.Save,
Shortcuts = new ShortcutKeys[] { new ShortcutKeys(KeyModifiers.Control, ConsoleKey.S), },
});
public UIActionState TrySaveToFile(bool perform)
{
if (ReadOnly) return UIActionVisibility.Hidden;
if (perform) File.WriteAllText(settingsFile.AbsoluteFilePath, Text);
return UIActionVisibility.Enabled;
}
}
}
|
/*********************************************************************************
* SettingsTextBox.UIActions.cs
*
* Copyright (c) 2004-2018 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.
*
*********************************************************************************/
using System;
using System.IO;
namespace Sandra.UI.WF
{
public partial class SettingsTextBox
{
public const string SettingsTextBoxUIActionPrefix = nameof(RichTextBoxBase) + ".";
public static readonly DefaultUIActionBinding SaveToFile = new DefaultUIActionBinding(
new UIAction(SettingsTextBoxUIActionPrefix + nameof(SaveToFile)),
new UIActionBinding()
{
ShowInMenu = true,
IsFirstInGroup = true,
MenuCaptionKey = LocalizedStringKeys.Save,
Shortcuts = new ShortcutKeys[] { new ShortcutKeys(KeyModifiers.Control, ConsoleKey.S), },
});
public UIActionState TrySaveToFile(bool perform)
{
if (ReadOnly) return UIActionVisibility.Hidden;
if (perform) File.WriteAllText(settingsFile.AbsoluteFilePath, Text);
return UIActionVisibility.Enabled;
}
}
}
|
apache-2.0
|
C#
|
c744bcdd8bb1d7e74a92037de790affd884ff5e0
|
Update SettingWidthOfColumn.cs
|
maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET
|
Examples/CSharp/RowsColumns/HeightAndWidth/SettingWidthOfColumn.cs
|
Examples/CSharp/RowsColumns/HeightAndWidth/SettingWidthOfColumn.cs
|
using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.RowsColumns.HeightAndWidth
{
public class SettingWidthOfColumn
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Creating a file stream containing the Excel file to be opened
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open);
//Instantiating a Workbook object
//Opening the Excel file through the file stream
Workbook workbook = new Workbook(fstream);
//Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.Worksheets[0];
//Setting the width of the second column to 17.5
worksheet.Cells.SetColumnWidth(1, 17.5);
//Saving the modified Excel file
workbook.Save(dataDir + "output.out.xls");
//Closing the file stream to free all resources
fstream.Close();
//ExEnd:1
}
}
}
|
using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.RowsColumns.HeightAndWidth
{
public class SettingWidthOfColumn
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Creating a file stream containing the Excel file to be opened
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open);
//Instantiating a Workbook object
//Opening the Excel file through the file stream
Workbook workbook = new Workbook(fstream);
//Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.Worksheets[0];
//Setting the width of the second column to 17.5
worksheet.Cells.SetColumnWidth(1, 17.5);
//Saving the modified Excel file
workbook.Save(dataDir + "output.out.xls");
//Closing the file stream to free all resources
fstream.Close();
}
}
}
|
mit
|
C#
|
de4aad6e1b40b3c4481f7ee1dfb66d046196cad2
|
Deploy as well as trim
|
Smartrak/Smartrak.Library
|
NugetPackageTrimmer/Program.cs
|
NugetPackageTrimmer/Program.cs
|
using System;
using System.Globalization;
using System.IO;
using NuGet;
namespace NugetPackageTrimmer
{
class Program
{
static void Main(string[] args)
{
var repoUrl = args.Length > 3 ? args[2] : "https://packages.nuget.org/api/v2";
Console.WriteLine($"Checking if packages in [{args[0]}] exist in {repoUrl} and deleting any that dont need deploying...");
var repo = PackageRepositoryFactory.Default.CreateRepository(repoUrl);
var packageServer = new PackageServer(repoUrl, "NuGet Command Line");
packageServer.SendingRequest += (sender, e) =>
{
Console.WriteLine(String.Format(CultureInfo.CurrentCulture, "{0} {1}", e.Request.Method, e.Request.RequestUri));
};
foreach (var nupkg in Directory.EnumerateFiles(args[0], "*.nupkg"))
{
Console.WriteLine($"Checking nuget package : {nupkg}");
var package = new OptimizedZipPackage(nupkg);
if (repo.Exists(package))
{
Console.WriteLine("That package already exists, skipping...");
File.Delete(nupkg);
}
else
{
Console.WriteLine("That package isnt in nuget yet, pushing...");
// Push the package to the server
var sourceUri = new Uri(repoUrl);
packageServer.PushPackage(
args[1],
package,
new FileInfo(nupkg).Length,
Convert.ToInt32(new TimeSpan(0, 0, 1, 0, 0).TotalMilliseconds),
false);
Console.WriteLine("Pushed");
}
}
}
}
}
|
using System;
using System.IO;
using NuGet;
namespace NugetPackageTrimmer
{
class Program
{
static void Main(string[] args)
{
var repoUrl = args.Length > 2 ? args[1] : "https://packages.nuget.org/api/v2";
Console.WriteLine($"Checking if packages in [{args[0]}] exist in {repoUrl} and deleting any that dont need deploying...");
var repo = PackageRepositoryFactory.Default.CreateRepository(repoUrl);
foreach (var nupkg in Directory.EnumerateFiles(args[0], "*.nupkg"))
{
Console.WriteLine($"Checking nuget package : {nupkg}");
var package = new ZipPackage(nupkg);
if (repo.Exists(package))
{
Console.WriteLine("That package already exists, deleting...");
File.Delete(nupkg);
}
else
{
Console.WriteLine("That package isnt in nuget yet, skipping...");
}
}
}
}
}
|
mit
|
C#
|
debb0891d7f33b182511ea12789bf6d589367b0b
|
Use deprecated method for older Unity support
|
Visagalis/Oxide,bawNg/Oxide,bawNg/Oxide,ApocDev/Oxide,LaserHydra/Oxide,ApocDev/Oxide,Nogrod/Oxide-2,Nogrod/Oxide-2,Visagalis/Oxide,MSylvia/Oxide,MSylvia/Oxide,LaserHydra/Oxide
|
Oxide.Ext.Unity/UnityScript.cs
|
Oxide.Ext.Unity/UnityScript.cs
|
using Oxide.Core;
using UnityEngine;
namespace Oxide.Unity
{
/// <summary>
/// The main MonoBehaviour which calls OxideMod.OnFrame
/// </summary>
public class UnityScript : MonoBehaviour
{
public static GameObject Instance { get; private set; }
public static void Create()
{
Instance = new GameObject("Oxide.Ext.Unity");
Object.DontDestroyOnLoad(Instance);
Instance.AddComponent<UnityScript>();
}
private OxideMod oxideMod;
void Awake()
{
oxideMod = Interface.GetMod();
Application.RegisterLogCallback(HandleException);
}
void Update()
{
oxideMod.OnFrame(Time.deltaTime);
}
void OnDestroy()
{
if (oxideMod.IsShuttingDown) return;
oxideMod.LogWarning("The Oxide Unity Script was destroyed (creating a new instance)");
oxideMod.NextTick(Create);
}
void HandleException(string message, string stack_trace, LogType type)
{
if (type == LogType.Exception && stack_trace.Contains("Oxide"))
RemoteLogger.Exception(message, stack_trace);
}
}
}
|
using Oxide.Core;
using UnityEngine;
namespace Oxide.Unity
{
/// <summary>
/// The main MonoBehaviour which calls OxideMod.OnFrame
/// </summary>
public class UnityScript : MonoBehaviour
{
public static GameObject Instance { get; private set; }
public static void Create()
{
Instance = new GameObject("Oxide.Ext.Unity");
Object.DontDestroyOnLoad(Instance);
Instance.AddComponent<UnityScript>();
}
private OxideMod oxideMod;
void Awake()
{
oxideMod = Interface.GetMod();
Application.logMessageReceived += HandleException;
}
void Update()
{
oxideMod.OnFrame(Time.deltaTime);
}
void OnDestroy()
{
if (oxideMod.IsShuttingDown) return;
oxideMod.LogWarning("The Oxide Unity Script was destroyed (creating a new instance)");
oxideMod.NextTick(Create);
}
void HandleException(string message, string stack_trace, LogType type)
{
if (type == LogType.Exception && stack_trace.Contains("Oxide"))
RemoteLogger.Exception(message, stack_trace);
}
}
}
|
mit
|
C#
|
4509392adb2efffd6256ec923f6d36bfb95800dd
|
update assembly info
|
ms-iot/onedrive-connector,mwmckee/onedrive-connector
|
OnedriveRESTWrapper/OnedriveRESTWrapper/Properties/AssemblyInfo.cs
|
OnedriveRESTWrapper/OnedriveRESTWrapper/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("OnedriveRESTWrapper")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("OnedriveRESTWrapper")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)]
|
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("OnedriveRESTWrapper")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OnedriveRESTWrapper")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)]
|
mit
|
C#
|
8cd99beb622532290ce34ef39ae3000a3992831e
|
Unify ShardedCommandContext with SocketCommandContext (#739)
|
RogueException/Discord.Net,AntiTcb/Discord.Net,Confruggy/Discord.Net
|
src/Discord.Net.WebSocket/Commands/ShardedCommandContext.cs
|
src/Discord.Net.WebSocket/Commands/ShardedCommandContext.cs
|
using Discord.WebSocket;
namespace Discord.Commands
{
public class ShardedCommandContext : SocketCommandContext, ICommandContext
{
public new DiscordShardedClient Client { get; }
public ShardedCommandContext(DiscordShardedClient client, SocketUserMessage msg)
: base(client.GetShard(GetShardId(client, (msg.Channel as SocketGuildChannel)?.Guild)), msg)
{
Client = client;
}
private static int GetShardId(DiscordShardedClient client, IGuild guild)
=> guild == null ? 0 : client.GetShardIdFor(guild);
//ICommandContext
IDiscordClient ICommandContext.Client => Client;
}
}
|
using Discord.WebSocket;
namespace Discord.Commands
{
public class ShardedCommandContext : ICommandContext
{
public DiscordShardedClient Client { get; }
public SocketGuild Guild { get; }
public ISocketMessageChannel Channel { get; }
public SocketUser User { get; }
public SocketUserMessage Message { get; }
public bool IsPrivate => Channel is IPrivateChannel;
public ShardedCommandContext(DiscordShardedClient client, SocketUserMessage msg)
{
Client = client;
Guild = (msg.Channel as SocketGuildChannel)?.Guild;
Channel = msg.Channel;
User = msg.Author;
Message = msg;
}
//ICommandContext
IDiscordClient ICommandContext.Client => Client;
IGuild ICommandContext.Guild => Guild;
IMessageChannel ICommandContext.Channel => Channel;
IUser ICommandContext.User => User;
IUserMessage ICommandContext.Message => Message;
}
}
|
mit
|
C#
|
a52fa8eb8b9a769b1fc481cc33052f881c76e367
|
Rename const
|
ppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu
|
osu.Game.Rulesets.Mania/Objects/Drawables/DrawableBarLine.cs
|
osu.Game.Rulesets.Mania/Objects/Drawables/DrawableBarLine.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osuTK;
namespace osu.Game.Rulesets.Mania.Objects.Drawables
{
/// <summary>
/// Visualises a <see cref="BarLine"/>. Although this derives DrawableManiaHitObject,
/// this does not handle input/sound like a normal hit object.
/// </summary>
public class DrawableBarLine : DrawableManiaHitObject<BarLine>
{
public DrawableBarLine(BarLine barLine)
: base(barLine)
{
RelativeSizeAxes = Axes.X;
Height = barLine.Major ? 1.7f : 1.2f;
AddInternal(new Box
{
Name = "Bar line",
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre,
RelativeSizeAxes = Axes.Both,
Alpha = barLine.Major ? 0.5f : 0.2f
});
if (barLine.Major)
{
Vector2 size = new Vector2(22, 6);
const float line_offset = 4;
AddInternal(new Circle
{
Name = "Left line",
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreRight,
Size = size,
X = -line_offset,
});
AddInternal(new Circle
{
Name = "Right line",
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreLeft,
Size = size,
X = line_offset,
});
}
}
protected override void UpdateInitialTransforms()
{
}
protected override void UpdateStartTimeStateTransforms() => this.FadeOut(150);
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osuTK;
namespace osu.Game.Rulesets.Mania.Objects.Drawables
{
/// <summary>
/// Visualises a <see cref="BarLine"/>. Although this derives DrawableManiaHitObject,
/// this does not handle input/sound like a normal hit object.
/// </summary>
public class DrawableBarLine : DrawableManiaHitObject<BarLine>
{
public DrawableBarLine(BarLine barLine)
: base(barLine)
{
RelativeSizeAxes = Axes.X;
Height = barLine.Major ? 1.7f : 1.2f;
AddInternal(new Box
{
Name = "Bar line",
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre,
RelativeSizeAxes = Axes.Both,
Alpha = barLine.Major ? 0.5f : 0.2f
});
if (barLine.Major)
{
Vector2 size = new Vector2(22, 6);
const float triangle_offset = 4;
AddInternal(new Circle
{
Name = "Left line",
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreRight,
Size = size,
X = -triangle_offset,
});
AddInternal(new Circle
{
Name = "Right line",
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreLeft,
Size = size,
X = triangle_offset,
});
}
}
protected override void UpdateInitialTransforms()
{
}
protected override void UpdateStartTimeStateTransforms() => this.FadeOut(150);
}
}
|
mit
|
C#
|
ab2cbe26837c89ba6bcaa7533a47ec81bf5a585c
|
Remove a few hacks from NSAsyncActionDispatcher which are no longer necessary
|
mono/maccore,cwensley/maccore
|
src/Foundation/NSAction.cs
|
src/Foundation/NSAction.cs
|
//
// Copyright 2009-2010, Novell, Inc.
// Copyright 2012 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
namespace MonoMac.Foundation {
public delegate void NSAction ();
// Use this for synchronous operations
[Register ("__MonoMac_NSActionDispatcher")]
internal sealed class NSActionDispatcher : NSObject {
public static readonly Selector Selector = new Selector ("apply");
readonly NSAction action;
public NSActionDispatcher (NSAction action)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
[Export ("apply")]
[Preserve (Conditional = true)]
public void Apply ()
{
action ();
}
}
// Use this for asynchronous operations
[Register ("__MonoMac_NSAsyncActionDispatcher")]
internal class NSAsyncActionDispatcher : NSObject {
GCHandle gch;
NSAction action;
#if !MONOTOUCH
// This ctor is so that the runtime can create a new instance of this class
// if ObjC wants to call release on an instance we've already called Dispose on.
// Since we detach the handle from the managed instance when Dispose is called,
// there is no way we can get the existing managed instance (which has possibly
// been freed anyway) when ObjC calls release (which ends up in NSObject.NativeRelease).
[Obsolete ("Do not use, this method is only used internally")]
public NSAsyncActionDispatcher (IntPtr handle)
: base (handle)
{
}
#endif
public NSAsyncActionDispatcher (NSAction action)
{
this.action = action;
gch = GCHandle.Alloc (this);
}
[Export ("apply")]
[Preserve (Conditional = true)]
public void Apply ()
{
try {
action ();
} finally {
action = null; // this is a one-shot dispatcher
gch.Free ();
//
// Although I would like to call Dispose here, to
// reduce the load on the GC, we have some useful diagnostic
// code in our runtime that is useful to track down
// problems, so we are removing the Dispose and letting
// the GC and our pipeline do their job.
//
#if MONOTOUCH
// MonoTouch has fixed the above problems, and we can call
// Dispose here.
Dispose ();
#endif
}
}
}
}
|
//
// Copyright 2009-2010, Novell, Inc.
// Copyright 2012 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
namespace MonoMac.Foundation {
public delegate void NSAction ();
// Use this for synchronous operations
[Register ("__MonoMac_NSActionDispatcher")]
internal sealed class NSActionDispatcher : NSObject {
public static readonly Selector Selector = new Selector ("apply");
readonly NSAction action;
public NSActionDispatcher (NSAction action)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
[Export ("apply")]
[Preserve (Conditional = true)]
public void Apply ()
{
action ();
}
}
// Use this for asynchronous operations
[Register ("__MonoMac_NSAsyncActionDispatcher")]
internal class NSAsyncActionDispatcher : NSObject {
GCHandle gch;
NSAction action;
// This ctor is so that the runtime can create a new instance of this class
// if ObjC wants to call release on an instance we've already called Dispose on.
// Since we detach the handle from the managed instance when Dispose is called,
// there is no way we can get the existing managed instance (which has possibly
// been freed anyway) when ObjC calls release (which ends up in NSObject.NativeRelease).
[Obsolete ("Do not use, this method is only used internally")]
public NSAsyncActionDispatcher (IntPtr handle)
: base (handle)
{
}
public NSAsyncActionDispatcher (NSAction action)
{
this.action = action;
gch = GCHandle.Alloc (this);
}
[Export ("apply")]
[Preserve (Conditional = true)]
public void Apply ()
{
try {
action ();
} finally {
action = null; // this is a one-shot dispatcher
gch.Free ();
//
// Although I would like to call Dispose here, to
// reduce the load on the GC, we have some useful diagnostic
// code in our runtime that is useful to track down
// problems, so we are removing the Dispose and letting
// the GC and our pipeline do their job.
//
}
}
}
}
|
apache-2.0
|
C#
|
aad01a8715f4d0f11ca3076906bb1322b8ce8418
|
Replace input with accelerometer
|
Clicker/unity-space-shooter
|
Assets/Scripts/PlayerController.cs
|
Assets/Scripts/PlayerController.cs
|
using UnityEngine;
[System.Serializable]
public class Boundary
{
public float XMin, XMax, ZMin, ZMax;
}
public class PlayerController : MonoBehaviour
{
public float Speed;
public float Tilt;
public Boundary Boundary;
public GameObject Shot;
public Transform ShotSpawn;
public float FireRate;
private float _nextFire;
private Quaternion _calibrationQuaternion;
private Rigidbody _rigidbody;
private AudioSource _audioSource;
private void Start()
{
_rigidbody = GetComponent<Rigidbody>();
_audioSource = GetComponent<AudioSource>();
CalibrateAccelerometer();
}
private void Update()
{
if (Input.GetButton("Fire1") && Time.time > _nextFire)
{
_nextFire = Time.time + FireRate;
Instantiate(Shot, ShotSpawn.position, ShotSpawn.rotation);
_audioSource.Play();
}
}
private void CalibrateAccelerometer()
{
Vector3 accelerationSnapshot = Input.acceleration;
Quaternion rotateQuaternion = Quaternion.FromToRotation(new Vector3(0f, 0f, -1f), accelerationSnapshot);
_calibrationQuaternion = Quaternion.Inverse(rotateQuaternion);
}
private Vector3 FixAcceleration(Vector3 acceleration)
{
Vector3 fixedAcceleration = _calibrationQuaternion * acceleration;
return fixedAcceleration;
}
private void FixedUpdate()
{
//float moveHorizontal = Input.GetAxis("Horizontal");
//float moveVertical = Input.GetAxis("Vertical");
//Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
//_rigidbody.velocity = movement * Speed;
Vector3 accelerationRaw = Input.acceleration;
Vector3 acceleration = FixAcceleration(accelerationRaw);
Vector3 movement = new Vector3(acceleration.x, 0.0f, acceleration.y);
_rigidbody.velocity = movement * Speed;
_rigidbody.position = new Vector3
(
Mathf.Clamp(_rigidbody.position.x, Boundary.XMin, Boundary.XMax),
0.0f,
Mathf.Clamp(_rigidbody.position.z, Boundary.ZMin, Boundary.ZMax)
);
_rigidbody.rotation = Quaternion.Euler(0.0f, 0.0f, _rigidbody.velocity.x * -Tilt);
}
}
|
using UnityEngine;
[System.Serializable]
public class Boundary
{
public float XMin, XMax, ZMin, ZMax;
}
public class PlayerController : MonoBehaviour
{
public float Speed;
public float Tilt;
public Boundary Boundary;
public GameObject Shot;
public Transform ShotSpawn;
public float FireRate;
private float nextFire;
private Rigidbody _rigidbody;
private AudioSource _audioSource;
private void Start()
{
_rigidbody = GetComponent<Rigidbody>();
_audioSource = GetComponent<AudioSource>();
}
void Update()
{
if (Input.GetButton("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + FireRate;
Instantiate(Shot, ShotSpawn.position, ShotSpawn.rotation);
_audioSource.Play();
}
}
private void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
_rigidbody.velocity = movement * Speed;
_rigidbody.position = new Vector3
(
Mathf.Clamp(_rigidbody.position.x, Boundary.XMin, Boundary.XMax),
0.0f,
Mathf.Clamp(_rigidbody.position.z, Boundary.ZMin, Boundary.ZMax)
);
_rigidbody.rotation = Quaternion.Euler(0.0f, 0.0f, _rigidbody.velocity.x * -Tilt);
}
}
|
mit
|
C#
|
cc0b9dd6278b340f46b58f9d5395cddd556d36f8
|
Tweak raw sql data update
|
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
|
Battery-Commander.Web/Migrations/20190126183747_CanLogin.cs
|
Battery-Commander.Web/Migrations/20190126183747_CanLogin.cs
|
using Microsoft.EntityFrameworkCore.Migrations;
using System;
using System.Collections.Generic;
namespace BatteryCommander.Web.Migrations
{
public partial class CanLogin : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "CanLogin",
table: "Soldiers",
nullable: false,
defaultValue: false);
migrationBuilder.Sql("UPDATE Soldiers SET CanLogin = 1 WHERE CivilianEmail IS NOT NULL");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "CanLogin",
table: "Soldiers");
}
}
}
|
using Microsoft.EntityFrameworkCore.Migrations;
using System;
using System.Collections.Generic;
namespace BatteryCommander.Web.Migrations
{
public partial class CanLogin : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "CanLogin",
table: "Soldiers",
nullable: false,
defaultValue: false);
migrationBuilder.Sql("UPDATE dbo.Soldiers SET CanLogin = 1 WHERE CivilianEmail IS NOT NULL");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "CanLogin",
table: "Soldiers");
}
}
}
|
mit
|
C#
|
0064d64fa27c20893be07e2d3f26cdaba8a6dda6
|
Set assembly version to 5.0.0.0
|
marcoaoteixeira/NEventStore,D3-LucaPiombino/NEventStore,gael-ltd/NEventStore,jamiegaines/NEventStore,chris-evans/NEventStore,AGiorgetti/NEventStore,NEventStore/NEventStore,deltatre-webplu/NEventStore,paritoshmmmec/NEventStore,adamfur/NEventStore,nerdamigo/NEventStore
|
src/VersionAssemblyInfo.cs
|
src/VersionAssemblyInfo.cs
|
using System.Reflection;
[assembly: AssemblyVersion("5.0.0.0")]
[assembly: AssemblyFileVersion("5.0.0.0")]
//// [assembly: AssemblyInformationalVersion("3.1.0.0 Release")]
|
using System.Reflection;
[assembly: AssemblyVersion("3.1.0.0")]
[assembly: AssemblyFileVersion("3.1.0.0")]
//// [assembly: AssemblyInformationalVersion("3.1.0.0 Release")]
|
mit
|
C#
|
bd5d9df346f9e9432fb1da8e9b8228013e48dd17
|
Change count word to medium level.
|
AxeDotNet/AxePractice.CSharpViaTest
|
src/CSharpViaTest.Collections/30_MapReducePractices/CountNumberOfWordsInMultipleTextFiles.cs
|
src/CSharpViaTest.Collections/30_MapReducePractices/CountNumberOfWordsInMultipleTextFiles.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CSharpViaTest.Collections.Annotations;
using CSharpViaTest.Collections.Helpers;
using Xunit;
namespace CSharpViaTest.Collections._30_MapReducePractices
{
[Medium]
public class CountNumberOfWordsInMultipleTextFiles
{
#region Please modifies the code to pass the test
// You can add additional functions for readability and performance considerations.
static int CountNumberOfWords(IEnumerable<Stream> streams)
{
throw new NotImplementedException();
}
#endregion
[Fact]
public void should_count_number_of_words()
{
const int fileCount = 5;
const int wordsInEachFile = 10;
Stream[] streams = Enumerable
.Repeat(0, fileCount)
.Select(_ => TextStreamFactory.Create(wordsInEachFile))
.ToArray();
int count = CountNumberOfWords(streams);
Assert.Equal(fileCount * wordsInEachFile, count);
foreach (Stream stream in streams) { stream.Dispose(); }
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CSharpViaTest.Collections.Annotations;
using CSharpViaTest.Collections.Helpers;
using Xunit;
namespace CSharpViaTest.Collections._30_MapReducePractices
{
[SuperEasy]
public class CountNumberOfWordsInMultipleTextFiles
{
#region Please modifies the code to pass the test
// You can add additional functions for readability and performance considerations.
static int CountNumberOfWords(IEnumerable<Stream> streams)
{
throw new NotImplementedException();
}
#endregion
[Fact]
public void should_count_number_of_words()
{
const int fileCount = 5;
const int wordsInEachFile = 10;
Stream[] streams = Enumerable
.Repeat(0, fileCount)
.Select(_ => TextStreamFactory.Create(wordsInEachFile))
.ToArray();
int count = CountNumberOfWords(streams);
Assert.Equal(fileCount * wordsInEachFile, count);
foreach (Stream stream in streams) { stream.Dispose(); }
}
}
}
|
mit
|
C#
|
f95004911c104964e14328885bd819bf622f1c4d
|
Cover previous fail bug.
|
robert-wallis/ECSLight
|
Tests/ComponentManagerTests.cs
|
Tests/ComponentManagerTests.cs
|
// Copyright (C) 2017 Robert A. Wallis, All Rights Reserved.
using ECSLight;
using NUnit.Framework;
using Tests.Stubs;
namespace Tests
{
[TestFixture]
public class ComponentManagerTests
{
readonly IEntityManager _stubEntityManager = new StubEntityManager();
[Test]
public void CoverEntityComponentsUnInitialized()
{
var componentManager = new ComponentManager(new StubSetManager());
var entity = new Entity(_stubEntityManager, componentManager) {
new AComponent("a")
};
Assert.IsNotNull(componentManager.ComponentFrom<AComponent>(entity));
// removing component that doesn't exist, doesn't crash
entity.Remove<BComponent>();
}
[Test]
public void CoverEntityNotInEntities()
{
var componentManager = new ComponentManager(new StubSetManager());
var otherManager = new ComponentManager(new StubSetManager());
var entity = new Entity(_stubEntityManager, otherManager);
Assert.IsFalse(componentManager.ContainsComponent(entity, typeof(AComponent)));
Assert.IsNull(componentManager.ComponentFrom<AComponent>(entity));
componentManager.RemoveComponent<AComponent>(entity);
}
[Test]
public void CoverIEnumerable()
{
var componentManager = new ComponentManager(new StubSetManager());
using (var enumerator = componentManager.GetEnumerator(new StubEntity())) {
Assert.IsFalse(enumerator.MoveNext());
}
// check again for dispose crash
using (var enumerator = componentManager.GetEnumerator(new StubEntity())) {
Assert.IsFalse(enumerator.MoveNext());
}
}
}
}
|
// Copyright (C) 2017 Robert A. Wallis, All Rights Reserved.
using ECSLight;
using NUnit.Framework;
using Tests.Stubs;
namespace Tests
{
[TestFixture]
public class ComponentManagerTests
{
readonly IEntityManager _stubEntityManager = new StubEntityManager();
[Test]
public void CoverEntityComponentsUnInitialized()
{
var componentManager = new ComponentManager(new StubSetManager());
var entity = new Entity(_stubEntityManager, componentManager) {
new AComponent("a")
};
Assert.IsNotNull(componentManager.ComponentFrom<AComponent>(entity));
}
[Test]
public void CoverEntityNotInEntities()
{
var componentManager = new ComponentManager(new StubSetManager());
var otherManager = new ComponentManager(new StubSetManager());
var entity = new Entity(_stubEntityManager, otherManager);
Assert.IsFalse(componentManager.ContainsComponent(entity, typeof(AComponent)));
Assert.IsNull(componentManager.ComponentFrom<AComponent>(entity));
componentManager.RemoveComponent<AComponent>(entity);
}
[Test]
public void CoverIEnumerable()
{
var componentManager = new ComponentManager(new StubSetManager());
using (var enumerator = componentManager.GetEnumerator(new StubEntity())) {
Assert.IsFalse(enumerator.MoveNext());
}
// check again for dispose crash
using (var enumerator = componentManager.GetEnumerator(new StubEntity())) {
Assert.IsFalse(enumerator.MoveNext());
}
}
}
}
|
mit
|
C#
|
7aae46d8cf7244859025bc03b5efce7c576d9194
|
Fix the routes
|
marinoscar/article-parser,marinoscar/article-parser,marinoscar/article-parser
|
Code/api/App_Start/WebApiConfig.cs
|
Code/api/App_Start/WebApiConfig.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Routing;
namespace api
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.SuppressHostPrincipal();
// Web API configuration and services
// Web API routes
//config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("DefaultApiWithId", "api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
config.Routes.MapHttpRoute("DefaultApiWithAction", "api/{controller}/{action}");
config.Routes.MapHttpRoute("DefaultApiGet", "api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
config.Routes.MapHttpRoute("DefaultApiPost", "api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });
config.Routes.MapHttpRoute("DefaultApiPut", "api/{controller}", new { action = "Put" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Put) });
config.Routes.MapHttpRoute("DefaultApiDelete", "api/{controller}", new { action = "Delete" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Delete) });
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace api
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.SuppressHostPrincipal();
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
|
mit
|
C#
|
4c22d00058e51b425655b83841590bc4a111d979
|
Update NoteGenerator.cs
|
evenam/CSC4263-ART4240,evenam/CSC4263-ART4240
|
game/Assets/scripts/NoteGenerator.cs
|
game/Assets/scripts/NoteGenerator.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/**
* Consumes beats and notifies pads to animate themselves
*/
public class NoteGenerator : MonoBehaviour
{
// References to the pad gameobjects' scripts
public Pad[] pads;
// The time of the "GET READY" animation, should there be one.
public float prepTime = 3;
// The total time from the beginning of the pad animation to the onset in the song
public float animationTime = 3;
// TODO: make this work with difficulty selection.
public bool isEasy = true;
int index = 0;
SongData song;
List<NoteData> notesToUse;
// Use this for initialization
void Start()
{
// Load the song
print(Application.dataPath);
song = new SongData(Application.dataPath+"/Music/example_song/example_song.dat");
if (isEasy)
notesToUse = song.easyNoteData;
else
notesToUse = song.advNoteData;
// TODO: Give the user some indication a song is about to start
// Does unity have a better way to "sleep"?
Invoke("afterPreSong", prepTime);
}
void afterPreSong() {
// Be sure to take into account the delay needed for animations
Invoke("beginAudio", animationTime);
// TODO: are all inital offsets at 0?
Invoke("deployBeat", notesToUse[0].offsetMS);
}
// TODO: use stems instead of full track
void beginAudio() {
Camera.main.GetComponent<AudioSource>().Play();
}
// TODO: handle the obviously-omitted end of song case
void deployBeat() {
NoteData note = notesToUse[index];
pads[note.midiPadIndex].onBeat(note);
index++;
// if this note is a chord
while (notesToUse[index].offsetMS == note.offsetMS)
{
pads[notesToUse[index].midiPadIndex].onBeat(notesToUse[index]);
index++;
}
// Deploy the next note, remember index was already incremented
// Invoke is in seconds, not milliseconds
Invoke("deployBeat", (float)(notesToUse[index].offsetMS - note.offsetMS) / 1000F);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/**
* Consumes beats and notifies pads to animate themselves
*/
public class NoteGenerator : MonoBehaviour
{
// References to the pad gameobjects' scripts
public Pad[] pads;
// The time of the "GET READY" animation, should there be one.
public float prepTime = 3;
// The total time from the beginning of the pad animation to the onset in the song
public float animationTime = 3;
// TODO: make this work with difficulty selection.
public bool isEasy = true;
int index = 0;
SongData song;
List<NoteData> notesToUse;
// Use this for initialization
void Start()
{
// Load the song
print(Application.dataPath);
song = new SongData(Application.dataPath+"/Music/example_song/example_song.dat");
if (isEasy)
notesToUse = song.easyNoteData;
else
notesToUse = song.advNoteData;
// TODO: Give the user some indication a song is about to start
// Does unity have a better way to "sleep"?
Invoke("afterPreSong", prepTime);
}
void afterPreSong() {
// Be sure to take into account the delay needed for animations
Invoke("beginAudio", animationTime);
// TODO: are all inital offsets at 0?
Invoke("deployBeat", notesToUse[0].offsetMS);
}
// TODO: use stems instead of full track
void beginAudio() {
Camera.main.GetComponent<AudioSource>().Play();
}
void deployBeat() {
NoteData note = notesToUse[index];
pads[note.midiPadIndex].onBeat(note);
index++;
// if this note is a chord
while (notesToUse[index].offsetMS == note.offsetMS)
{
pads[notesToUse[index].midiPadIndex].onBeat(notesToUse[index]);
index++;
}
// Deploy the next note, remember index was already incremented
// Invoke is in seconds, not milliseconds
Invoke("deployBeat", (float)(notesToUse[index].offsetMS - note.offsetMS) / 1000F);
}
}
|
mit
|
C#
|
4aa94f206bd86687c02c729b17fc1c016bce6038
|
refactor cache expiration
|
taka-oyama/UniHttp
|
Assets/UniHttp/Support/Cache/CacheMetadata.cs
|
Assets/UniHttp/Support/Cache/CacheMetadata.cs
|
using UnityEngine;
using System;
using System.Text;
namespace UniHttp
{
internal sealed class CacheMetadata
{
internal const int version = 1;
internal string domain;
internal string path;
internal string contentType;
internal string eTag;
internal DateTime? expireAt;
internal DateTime? lastModified;
internal bool IsFresh
{
get { return expireAt > DateTime.Now; }
}
internal bool IsStale
{
get { return !IsFresh; }
}
internal CacheMetadata()
{
}
internal CacheMetadata(HttpResponse response)
{
Uri uri = response.Request.Uri;
this.domain = uri.Authority;
this.path = uri.AbsolutePath;
if(response.Headers.Exist(HeaderField.ContentType)) {
this.contentType = response.Headers[HeaderField.ContentType][0];
}
if(response.Headers.Exist(HeaderField.ETag)) {
this.eTag = response.Headers[HeaderField.ETag][0];
}
if(response.Headers.Exist(HeaderField.Expires)) {
this.expireAt = DateTime.Parse(response.Headers[HeaderField.Expires][0]);
}
if(response.Headers.Exist(HeaderField.CacheControl) && response.Headers[HeaderField.CacheControl][0].Contains("max-age")) {
foreach(string directive in response.Headers[HeaderField.CacheControl][0].Split(',')) {
if(directive.Contains("max-age")) {
this.expireAt = DateTime.Now.AddSeconds(int.Parse(directive.Split('=')[1]));
}
}
}
if(response.Headers.Exist(HeaderField.LastModified)) {
this.lastModified = DateTime.Parse(response.Headers[HeaderField.LastModified][0]);
}
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("[Cache] ");
sb.AppendFormat("{0}{1}\n", domain, path);
if(eTag != null) {
sb.AppendFormat("ETag={0} ", eTag);
}
if(expireAt.HasValue) {
sb.AppendFormat("ExpiresAt={0} ", expireAt);
}
if(lastModified.HasValue) {
sb.AppendFormat("Last-Modified={0} ", lastModified);
}
return sb.ToString();
}
}
}
|
using UnityEngine;
using System;
using System.Text;
namespace UniHttp
{
internal sealed class CacheMetadata
{
internal const int version = 1;
internal string domain;
internal string path;
internal string contentType;
internal string eTag;
internal DateTime? expireAt;
internal DateTime? lastModified;
internal bool IsFresh
{
get { return expireAt > DateTime.Now; }
}
internal bool IsStale
{
get { return !IsFresh; }
}
internal CacheMetadata()
{
}
internal CacheMetadata(HttpResponse response)
{
Uri uri = response.Request.Uri;
this.domain = uri.Authority;
this.path = uri.AbsolutePath;
if(response.Headers.Exist(HeaderField.ContentType)) {
this.contentType = response.Headers[HeaderField.ContentType][0];
}
if(response.Headers.Exist(HeaderField.ETag)) {
this.eTag = response.Headers[HeaderField.ETag][0];
}
if(response.Headers.Exist(HeaderField.Expires)) {
this.expireAt = DateTime.Parse(response.Headers[HeaderField.Expires][0]);
}
if(response.Headers.Exist(HeaderField.LastModified)) {
this.lastModified = DateTime.Parse(response.Headers[HeaderField.LastModified][0]);
}
if(response.Headers.Exist(HeaderField.CacheControl) && response.Headers[HeaderField.CacheControl][0].Contains("max-age")) {
foreach(string directive in response.Headers[HeaderField.CacheControl][0].Split(',')) {
if(directive.Contains("max-age")) {
int maxAge = int.Parse(directive.Split('=')[1]);
this.expireAt = DateTime.Now + TimeSpan.FromSeconds(maxAge);
}
}
}
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("[Cache] ");
sb.AppendFormat("{0}{1}\n", domain, path);
if(eTag != null) {
sb.AppendFormat("ETag={0} ", eTag);
}
if(expireAt.HasValue) {
sb.AppendFormat("ExpiresAt={0} ", expireAt);
}
if(lastModified.HasValue) {
sb.AppendFormat("Last-Modified={0} ", lastModified);
}
return sb.ToString();
}
}
}
|
mit
|
C#
|
20d49fb69e917ca4426c3bd31d980ea4cf58f65b
|
fix a name error
|
ladace/BoundBox
|
Assets/CollisionTest.cs
|
Assets/CollisionTest.cs
|
using UnityEngine;
using System.Collections;
public class CollisionTest : MonoBehaviour {
private string touching = "";
void Update () {
transform.position += new Vector3(Input.GetAxis("Horizontal") * Time.deltaTime * 4, Input.GetAxis("Vertical") * Time.deltaTime * 4);
touching = "";
}
void OnCollide (CollisionInfo info) {
touching += info.normal.ToString();
}
void OnGUI () {
GUI.Box(new Rect(0, 0, Screen.width, 40), touching);
}
}
|
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
private string touching = "";
void Update () {
transform.position += new Vector3(Input.GetAxis("Horizontal") * Time.deltaTime * 4, Input.GetAxis("Vertical") * Time.deltaTime * 4);
touching = "";
}
void OnCollide (CollisionInfo info) {
touching += info.normal.ToString();
}
void OnGUI () {
GUI.Box(new Rect(0, 0, Screen.width, 40), touching);
}
}
|
mit
|
C#
|
e04226ac88201f95e3064a57927e93b9468b31dd
|
Add way to get HTTP error code
|
IvionSauce/MeidoBot
|
IvionWebSoft/WebResources/WebResource.cs
|
IvionWebSoft/WebResources/WebResource.cs
|
using System;
using System.Net;
namespace IvionWebSoft
{
public abstract class WebResource
{
public Uri Location { get; private set; }
public bool Success { get; private set; }
public Exception Exception { get; private set; }
public WebResource(Uri uri)
{
if (uri == null)
throw new ArgumentNullException("uri");
Location = uri;
Success = true;
Exception = null;
}
public WebResource(Exception ex) : this(null, ex) {}
public WebResource(Uri uri, Exception ex)
{
if (ex == null)
throw new ArgumentNullException("ex");
Location = uri;
Success = false;
Exception = ex;
}
public WebResource(WebResource resource)
{
if (resource == null)
throw new ArgumentNullException("resource");
Location = resource.Location;
Success = resource.Success;
Exception = resource.Exception;
}
public bool TryGetHttpError(out HttpStatusCode error)
{
var webEx = Exception as WebException;
if (webEx != null && webEx.Status == WebExceptionStatus.ProtocolError)
{
var resp = webEx.Response as HttpWebResponse;
if (resp != null)
{
error = resp.StatusCode;
return true;
}
}
error = default(HttpStatusCode);
return false;
}
public bool HttpErrorIs(HttpStatusCode error)
{
HttpStatusCode status;
if (TryGetHttpError(out status))
return status == error;
return false;
}
}
}
|
using System;
namespace IvionWebSoft
{
public abstract class WebResource
{
public Uri Location { get; private set; }
public bool Success { get; private set; }
public Exception Exception { get; private set; }
public WebResource(Uri uri)
{
if (uri == null)
throw new ArgumentNullException("uri");
Location = uri;
Success = true;
Exception = null;
}
public WebResource(Exception ex) : this(null, ex) {}
public WebResource(Uri uri, Exception ex)
{
if (ex == null)
throw new ArgumentNullException("ex");
Location = uri;
Success = false;
Exception = ex;
}
public WebResource(WebResource resource)
{
if (resource == null)
throw new ArgumentNullException("resource");
Location = resource.Location;
Success = resource.Success;
Exception = resource.Exception;
}
}
}
|
bsd-2-clause
|
C#
|
54b9a0fd3a5cee84b30f6a5ef0cc23996ad28e3f
|
debug brackets
|
DMagic1/Science-Contracts
|
ContractScienceUtils.cs
|
ContractScienceUtils.cs
|
#region license
/*The MIT License (MIT)
Science Contract Utilities
Copyright (c) 2014 DMagic
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Contract_Science
{
static class ContractScienceUtils
{
internal static System.Random rand;
internal static Dictionary<string, contractScienceContainer> availableScience = new Dictionary<string, contractScienceContainer>();
internal static float science, reward, forward, penalty;
internal static List<string> storyList = new List<string>();
internal static void Logging(string s, params object[] stringObjects)
{
s = string.Format(s, stringObjects);
string finalLog = string.Format("[CS] {0}", s);
Debug.Log(finalLog);
}
#region Debug Logging
internal static void DebugLog(string s, params object[] stringObjects)
{
#if DEBUG
s = string.Format(s, stringObjects);
string finalLog = string.Format("[CS] {0}", s);
Debug.Log(finalLog);
#endif
}
#endregion
}
}
|
#region license
/*The MIT License (MIT)
Science Contract Utilities
Copyright (c) 2014 DMagic
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Contract_Science
{
static class ContractScienceUtils
{
internal static System.Random rand;
internal static Dictionary<string, contractScienceContainer> availableScience = new Dictionary<string, contractScienceContainer>();
internal static float science, reward, forward, penalty;
internal static List<string> storyList = new List<string>();
internal static void Logging(string s, params object[] stringObjects)
{
s = string.Format(s, stringObjects);
string finalLog = string.Format("[CS] {0}", s);
Debug.Log(finalLog);
}
#region Debug Logging
#if DEBUG
internal static void DebugLog(string s, params object[] stringObjects)
{
s = string.Format(s, stringObjects);
string finalLog = string.Format("[CS] {0}", s);
Debug.Log(finalLog);
}
#endif
#endregion
}
}
|
mit
|
C#
|
6cb8db23a9174a8d1285ec0457c51c4090879a71
|
Correct AccountNotFoud to AccountNotFound in some doc
|
ismaelbelghiti/Tigwi,ismaelbelghiti/Tigwi
|
storage/Storage/StorageLibrary/interfaces/IAccountStorage.cs
|
storage/Storage/StorageLibrary/interfaces/IAccountStorage.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StorageLibrary
{
public interface IAccountStorage
{
/// <summary>
/// Return the id of an account given its name
/// Can throw : AccountNotFound
/// </summary>
Guid GetId(string name);
/// <summary>
/// Return the infos related to the given account
/// Can throw : AccountNotFound
/// </summary>
IAccountInfo GetInfo(Guid accountId);
/// <summary>
/// Update informations about the given account
/// Can throw : AccountNotFound, AccountAlreadyExists
/// </summary>
void SetInfo(Guid accountId, string name, string description);
/// <summary>
/// Get the users who can post with the given account
/// Can throw : AccountNotFound
/// </summary>
HashSet<Guid> GetUsers(Guid accountId);
/// <summary>
/// Get the admin of the given account
/// Can throw : AccountNotFound
/// </summary>
Guid GetAdminId(Guid accountId);
/// <summary>
/// Set the admin of the given account
/// Can throw : AccountNotFound, UserNotFound
/// </summary>
void SetAdminId(Guid accountId, Guid userId);
/// <summary>
/// Give the given user the right to post with the given account
/// Can throw : AccountNotFound, UserNotFound
/// </summary>
void Add(Guid accountId, Guid userId);
/// <summary>
/// Remove the right to the given user to post with the given account
/// Can throw : UserIsAdmin
/// </summary>
void Remove(Guid accountId, Guid userId);
/// <summary>
/// Create an account and return its ID
/// Can throw : UserNotFound, AccountAlreadyExists
/// </summary>
Guid Create(Guid adminId, string name, string description);
/// <summary>
/// Delete the given account
/// </summary>
void Delete(Guid accountId);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StorageLibrary
{
public interface IAccountStorage
{
/// <summary>
/// Return the id of an account given its name
/// Can throw : AccountNotFoud
/// </summary>
Guid GetId(string name);
/// <summary>
/// Return the infos related to the given account
/// Can throw : AccountNotFound
/// </summary>
IAccountInfo GetInfo(Guid accountId);
/// <summary>
/// Update informations about the given account
/// Can throw : AccountNotFoud, AccountAlreadyExists
/// </summary>
void SetInfo(Guid accountId, string name, string description);
/// <summary>
/// Get the users who can post with the given account
/// Can throw : AccountNotFound
/// </summary>
HashSet<Guid> GetUsers(Guid accountId);
/// <summary>
/// Get the admin of the given account
/// Can throw : AccountNotFound
/// </summary>
Guid GetAdminId(Guid accountId);
/// <summary>
/// Set the admin of the given account
/// Can throw : AccountNotFound, UserNotFound
/// </summary>
void SetAdminId(Guid accountId, Guid userId);
/// <summary>
/// Give the given user the right to post with the given account
/// Can throw : AccountNotFound, UserNotFound
/// </summary>
void Add(Guid accountId, Guid userId);
/// <summary>
/// Remove the right to the given user to post with the given account
/// Can throw : UserIsAdmin
/// </summary>
void Remove(Guid accountId, Guid userId);
/// <summary>
/// Create an account and return its ID
/// Can throw : UserNotFound, AccountAlreadyExists
/// </summary>
Guid Create(Guid adminId, string name, string description);
/// <summary>
/// Delete the given account
/// </summary>
void Delete(Guid accountId);
}
}
|
bsd-3-clause
|
C#
|
2da8cd06d0e667aeb85a64c87bbef4c8c222ba91
|
fix Silverlight and VB projects
|
telerik/JustMockLite
|
Telerik.JustMock/Core/Context/MockingContextResolverBase.cs
|
Telerik.JustMock/Core/Context/MockingContextResolverBase.cs
|
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Telerik.JustMock.Core.Castle.Core.Internal;
namespace Telerik.JustMock.Core.Context
{
internal abstract class MockingContextResolverBase : IMockingContextResolver
{
protected readonly string assertFailedExceptionTypeName;
public abstract MocksRepository ResolveRepository(UnresolvedContextBehavior unresolvedContextBehavior);
public abstract bool RetireRepository();
public MockingContextResolverBase(string assertFailedExceptionTypeName)
{
this.assertFailedExceptionTypeName = assertFailedExceptionTypeName;
}
public Action<string, Exception> GetFailMethod()
{
var factoryExpr = CreateExceptionFactory();
var factory = factoryExpr.Compile();
return (message, innerException) =>
{
var exception = factory(message, innerException);
throw exception;
};
}
protected virtual Expression<Func<string, Exception, Exception>> CreateExceptionFactory()
{
var assertionException = FindType(this.assertFailedExceptionTypeName);
return this.CreateExceptionFactory(assertionException);
}
protected Expression<Func<string, Exception, Exception>> CreateExceptionFactory(Type assertionException)
{
var exceptionCtor = assertionException.GetConstructor(new[] { typeof(string), typeof(Exception) });
var messageParam = Expression.Parameter(typeof(string), "message");
var innerExceptionParam = Expression.Parameter(typeof(Exception), "innerException");
var newException = Expression.New(exceptionCtor, messageParam, innerExceptionParam);
return (Expression<Func<string, Exception, Exception>>)Expression.Lambda(typeof(Func<string, Exception, Exception>), newException, messageParam, innerExceptionParam);
}
protected static Type FindType(string assemblyAndTypeName, bool throwOnNotFound = true)
{
var parts = assemblyAndTypeName.Split(',').Select(s => s.Trim()).ToArray();
var assembly = AppDomain.CurrentDomain.GetAssemblies()
.FirstOrDefault(a => String.Equals(a.GetAssemblyName(), parts[1], StringComparison.OrdinalIgnoreCase));
var foundType = assembly != null ? assembly.GetType(parts[0]) : null;
if (foundType == null && throwOnNotFound)
throw new InvalidOperationException(String.Format("Test framework type '{0}' not found", assemblyAndTypeName));
return foundType;
}
}
}
|
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Telerik.JustMock.Core.Castle.Core.Internal;
namespace Telerik.JustMock.Core.Context
{
internal abstract class MockingContextResolverBase : IMockingContextResolver
{
protected readonly string assertFailedExceptionTypeName;
public abstract MocksRepository ResolveRepository(UnresolvedContextBehavior unresolvedContextBehavior);
public abstract bool RetireRepository();
public MockingContextResolverBase(string assertFailedExceptionTypeName)
{
this.assertFailedExceptionTypeName = assertFailedExceptionTypeName;
}
public Action<string, Exception> GetFailMethod()
{
var factoryExpr = CreateExceptionFactory();
var factory = factoryExpr.Compile();
return (message, innerException) =>
{
var exception = factory(message, innerException);
throw exception;
};
}
protected virtual Expression<Func<string, Exception, Exception>> CreateExceptionFactory()
{
var assertionException = FindType(this.assertFailedExceptionTypeName);
return this.CreateExceptionFactory(assertionException);
}
protected Expression<Func<string, Exception, Exception>> CreateExceptionFactory(Type assertionException)
{
var exceptionCtor = assertionException.GetConstructor(new[] { typeof(string), typeof(Exception) });
var messageParam = Expression.Parameter(typeof(string), "message");
var innerExceptionParam = Expression.Parameter(typeof(Exception), "innerException");
var newException = Expression.New(exceptionCtor, messageParam, innerExceptionParam);
return (Expression<Func<string, Exception, Exception>>)Expression.Lambda(typeof(Func<string, Exception, Exception>), newException, messageParam, innerExceptionParam);
}
protected static Type FindType(string assemblyAndTypeName, bool throwOnNotFound = true)
{
var parts = assemblyAndTypeName.Split(',').Select(s => s.Trim()).ToArray();
var assembly = AppDomain.CurrentDomain.GetAssemblies()
.FirstOrDefault(a => String.Equals(a.GetName().Name, parts[1], StringComparison.OrdinalIgnoreCase));
var foundType = assembly != null ? assembly.GetType(parts[0]) : null;
if (foundType == null && throwOnNotFound)
throw new InvalidOperationException(String.Format("Test framework type '{0}' not found", assemblyAndTypeName));
return foundType;
}
}
}
|
apache-2.0
|
C#
|
a4e64542d01b368d9018e5d0a49eb6fb332bd685
|
use floats
|
JasonCrease/SeeBoard
|
Engine/OLSRegression.cs
|
Engine/OLSRegression.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Engine
{
internal class OLSRegression
{
internal float R2 { get; private set; }
internal float A { get; private set; }
internal float B { get; private set; }
internal OLSRegression()
{
}
public void Perform(FullLine[] data)
{
float n = data.Length;
float Sx = data.Sum(x => x.m);
float Sy = data.Sum(x => x.c);
float Sxx = data.Sum(x => x.m * x.m);
float Syy = data.Sum(x => x.c * x.c);
float Sxy = data.Sum(x => x.m * x.c);
B = ((n * Sxy) - (Sx * Sy)) /
((n * Sxx) - (Sx * Sx));
A = (Sy / n) - (B * Sx / n);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Engine
{
internal class OLSRegression
{
internal double R2 { get; private set; }
internal double A { get; private set; }
internal double B { get; private set; }
internal OLSRegression()
{
}
public void Perform(FullLine[] data)
{
double n = data.Length;
double Sx = data.Sum(x => x.m);
double Sy = data.Sum(x => x.c);
double Sxx = data.Sum(x => x.m * x.m);
double Syy = data.Sum(x => x.c * x.c);
double Sxy = data.Sum(x => x.m * x.c);
B = ((n * Sxy) - (Sx * Sy)) /
((n * Sxx) - (Sx * Sx));
A = (Sy / n) - (B * Sx / n);
}
}
}
|
mit
|
C#
|
a274dd38182d8a7a04120d7b17c10064516205f3
|
correct type for time actual in name similarity api
|
brainded/FullContactDotNet
|
FullContactDotNet/Entities/DistanceMetrics.cs
|
FullContactDotNet/Entities/DistanceMetrics.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FullContactDotNet.Entities
{
public class DistanceMetrics
{
/// <summary>
/// Gets or sets the similarity.
/// </summary>
/// <value>
/// The similarity.
/// </value>
public double Similarity { get; set; }
/// <summary>
/// Gets or sets the time estimated.
/// </summary>
/// <value>
/// The time estimated.
/// </value>
public double TimeEstimated { get; set; }
/// <summary>
/// Gets or sets the time actual.
/// </summary>
/// <value>
/// The time actual.
/// </value>
public double TimeActual { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FullContactDotNet.Entities
{
public class DistanceMetrics
{
/// <summary>
/// Gets or sets the similarity.
/// </summary>
/// <value>
/// The similarity.
/// </value>
public double Similarity { get; set; }
/// <summary>
/// Gets or sets the time estimated.
/// </summary>
/// <value>
/// The time estimated.
/// </value>
public double TimeEstimated { get; set; }
/// <summary>
/// Gets or sets the time actual.
/// </summary>
/// <value>
/// The time actual.
/// </value>
public int TimeActual { get; set; }
}
}
|
mit
|
C#
|
707696677a596d3292cb282e5822b4a31d59c9b0
|
Set version to 3.3.0
|
blairconrad/FakeItEasy,thomaslevesque/FakeItEasy,adamralph/FakeItEasy,FakeItEasy/FakeItEasy,thomaslevesque/FakeItEasy,adamralph/FakeItEasy,FakeItEasy/FakeItEasy,blairconrad/FakeItEasy
|
src/CommonAssemblyInfo.cs
|
src/CommonAssemblyInfo.cs
|
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.3.0")]
[assembly: AssemblyFileVersion("3.3.0")]
[assembly: AssemblyInformationalVersion("3.3.0")]
[assembly: AssemblyCompany("Patrik Hägne")]
[assembly: AssemblyCopyright("Copyright (c) FakeItEasy contributors. (fakeiteasyfx@gmail.com)")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: ComVisible(false)]
|
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.2.0")]
[assembly: AssemblyFileVersion("3.2.0")]
[assembly: AssemblyInformationalVersion("3.2.0")]
[assembly: AssemblyCompany("Patrik Hägne")]
[assembly: AssemblyCopyright("Copyright (c) FakeItEasy contributors. (fakeiteasyfx@gmail.com)")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: ComVisible(false)]
|
mit
|
C#
|
0fea0e610dbc0550faef1441adb604ac23c92a90
|
Allow attribute inheritance
|
CIR2000/BusinessObjects
|
DomainAttributes.cs
|
DomainAttributes.cs
|
using System;
using System.Runtime.CompilerServices;
namespace BusinessObjects
{
public class DomainObjectAttribute : Attribute { }
/// <summary>
/// Use this attribute to flag DataObject properties which are meant to be represent actual Business Object values
/// (i.e. LastName, but not IsValid). Also, in order for the Read/Write XML methods to work properly, remember
/// that these properties should be defined in the same order with which they are expected to appear in the XML file.
/// </summary>
[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
public sealed class OrderedDataProperty : DomainObjectAttribute
{
private readonly int _order;
public OrderedDataProperty([CallerLineNumber]int order = 0) {
_order = order;
}
public int Order { get { return _order; } }
}
}
|
using System;
using System.Runtime.CompilerServices;
namespace BusinessObjects
{
public class DomainObjectAttribute : Attribute { }
/// <summary>
/// Use this attribute to flag DataObject properties which are meant to be represent actual Business Object values
/// (i.e. LastName, but not IsValid). Also, in order for the Read/Write XML methods to work properly, remember
/// that these properties should be defined in the same order with which they are expected to appear in the XML file.
/// </summary>
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public sealed class OrderedDataProperty : DomainObjectAttribute
{
private readonly int _order;
public OrderedDataProperty([CallerLineNumber]int order = 0) {
_order = order;
}
public int Order { get { return _order; } }
}
}
|
bsd-3-clause
|
C#
|
ba4094ac01e601412df38a69bb9714c815831c30
|
Update LoadProfilesOnStartup.cs
|
killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity
|
Assets/MRTK/Examples/Common/Scripts/LoadProfilesOnStartup.cs
|
Assets/MRTK/Examples/Common/Scripts/LoadProfilesOnStartup.cs
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Examples.Demos.EyeTracking
{
/// <summary>
/// Automatically loads a given Mixed Reality Toolkit configuration profile when loading up the scene.
/// </summary>
[AddComponentMenu("Scripts/MRTK/Examples/LoadProfilesOnStartup")]
public class LoadProfilesOnStartup : MonoBehaviour
{
[Tooltip("Mixed Reality Toolkit profile to load when starting up this scene.")]
[SerializeField]
private MixedRealityToolkitConfigurationProfile configProfile = null;
private void Update()
{
if ((configProfile != null) && (MixedRealityToolkit.Instance != null))
{
MixedRealityToolkit.Instance.ActiveProfile = configProfile;
Debug.Log($"Loading new MRTK configuration profile: {configProfile.name}");
configProfile = null;
}
}
}
}
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Examples.Demos.EyeTracking
{
/// <summary>
/// Automatically loads a given Mixed Reality Toolkit configuration profile when loading up the scene.
/// </summary>
[AddComponentMenu("Scripts/MRTK/Examples/LoadProfilesOnStartup")]
public class LoadProfilesOnStartup : MonoBehaviour
{
[Tooltip("Mixed Reality Toolkit profile to load when starting up this scene.")]
[SerializeField]
private MixedRealityToolkitConfigurationProfile configProfile = null;
private void LateUpdate()
{
if ((configProfile != null) && (MixedRealityToolkit.Instance != null))
{
MixedRealityToolkit.Instance.ActiveProfile = configProfile;
Debug.Log($"Loading new MRTK configuration profile: {configProfile.name}");
configProfile = null;
}
}
}
}
|
mit
|
C#
|
0f219ae7c111ef65165fc9b5bc01a1a834ad0d77
|
fix not expired precondition logic
|
Chris-Johnston/CSSBot
|
CSSBot/Services/Reminders/Commands/NotExpiredPrecondition.cs
|
CSSBot/Services/Reminders/Commands/NotExpiredPrecondition.cs
|
using Discord.Commands;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace CSSBot
{
public class NotExpiredPreconditionAttribute : ParameterPreconditionAttribute
{
private DateTime now;
public NotExpiredPreconditionAttribute()
{
now = DateTime.Now;
}
public NotExpiredPreconditionAttribute(DateTime date)
{
now = date;
}
public override async Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, ParameterInfo parameter, object value, IServiceProvider services)
{
if (value is DateTime time)
{
return now.CompareTo(time) <= 0 ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("The provided time was after the current time.");
}
return PreconditionResult.FromError("The type of value was not a DateTime.");
}
}
}
|
using Discord.Commands;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace CSSBot
{
public class NotExpiredPreconditionAttribute : ParameterPreconditionAttribute
{
private DateTime now;
public NotExpiredPreconditionAttribute()
{
now = DateTime.Now;
}
public NotExpiredPreconditionAttribute(DateTime date)
{
now = date;
}
public override async Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, ParameterInfo parameter, object value, IServiceProvider services)
{
if (value is DateTime time)
{
return now.CompareTo(time) >= 0 ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("The provided time was after the current time.");
}
return PreconditionResult.FromError("The type of value was not a DateTime.");
}
}
}
|
mit
|
C#
|
569f10785d1cfe6e48611ddf5ad5cc7d7bf06d73
|
Update sensor description from Klaus
|
BuildingSMART/IfcDoc,pipauwel/IfcDoc,BuildingSMART/IfcDoc,pipauwel/IfcDoc,BuildingSMART/IfcDoc,pipauwel/IfcDoc
|
IfcKit/schemas/IfcBuildingControlsDomain/IfcSensorTypeEnum.cs
|
IfcKit/schemas/IfcBuildingControlsDomain/IfcSensorTypeEnum.cs
|
// This file may be edited manually or auto-generated using IfcKit at www.buildingsmart-tech.org.
// IFC content is copyright (C) 1996-2018 BuildingSMART International Ltd.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Xml.Serialization;
namespace BuildingSmart.IFC.IfcBuildingControlsDomain
{
public enum IfcSensorTypeEnum
{
[Description("A device that senses or detects carbon monoxide.")]
COSENSOR = 1,
[Description("A device that senses or detects carbon dioxide.")]
CO2SENSOR = 2,
[Description("A device that senses or detects electrical conductance.")]
CONDUCTANCESENSOR = 3,
[Description("A device that senses or detects contact, such as for detecting if a door is close" +
"d.")]
CONTACTSENSOR = 4,
[Description("A device that senses or detects fire")]
FIRESENSOR = 5,
[Description("A device that senses or detects flow in a fluid.")]
FLOWSENSOR = 6,
[Description("A device that senses or detects frost on a window.")]
FROSTSENSOR = 7,
[Description("A device that senses or detects gas concentration (other than CO2)")]
GASSENSOR = 8,
[Description("A device that senses or detects heat.")]
HEATSENSOR = 9,
[Description("A device that senses or detects humidity.")]
HUMIDITYSENSOR = 10,
[Description("A device that reads a tag, such as for gaining access to a door or elevator")]
IDENTIFIERSENSOR = 11,
[Description("A device that senses or detects ion concentration, such as for water hardness.")]
IONCONCENTRATIONSENSOR = 12,
[Description("A device that senses or detects fill level, such as for a tank.")]
LEVELSENSOR = 13,
[Description("A device that senses or detects light.")]
LIGHTSENSOR = 14,
[Description("A device that senses or detects moisture.")]
MOISTURESENSOR = 15,
[Description("A device that senses or detects movement.")]
MOVEMENTSENSOR = 16,
[Description("A device that senses or detects acidity.")]
PHSENSOR = 17,
[Description("A device that senses or detects pressure.")]
PRESSURESENSOR = 18,
[Description("A device that senses or detects radiation.")]
RADIATIONSENSOR = 19,
[Description("A device that senses or detects atomic decay.")]
RADIOACTIVITYSENSOR = 20,
[Description("A device that senses or detects smoke.")]
SMOKESENSOR = 21,
[Description("A device that senses or detects sound.")]
SOUNDSENSOR = 22,
[Description("A device that senses or detects temperature.")]
TEMPERATURESENSOR = 23,
[Description("A device that senses or detects airflow speed and direction.")]
WINDSENSOR = 24,
[Description("User-defined type.")]
USERDEFINED = -1,
[Description("Undefined type.")]
NOTDEFINED = 0,
}
}
|
// This file may be edited manually or auto-generated using IfcKit at www.buildingsmart-tech.org.
// IFC content is copyright (C) 1996-2018 BuildingSMART International Ltd.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Xml.Serialization;
namespace BuildingSmart.IFC.IfcBuildingControlsDomain
{
public enum IfcSensorTypeEnum
{
[Description("A device that senses or detects carbon monoxide.")]
COSENSOR = 1,
[Description("A device that senses or detects carbon dioxide.")]
CO2SENSOR = 2,
[Description("A device that senses or detects electrical conductance.")]
CONDUCTANCESENSOR = 3,
[Description("A device that senses or detects contact, such as for detecting if a door is close" +
"d.")]
CONTACTSENSOR = 4,
[Description("A device that senses or detects fire")]
FIRESENSOR = 5,
[Description("A device that senses or detects flow in a fluid.")]
FLOWSENSOR = 6,
[Description("A device that senses or detects frost on a window.")]
FROSTSENSOR = 7,
[Description("A device that senses or detects gas concentration (other than CO2)")]
GASSENSOR = 8,
[Description("A device that senses or detects heat.")]
HEATSENSOR = 9,
[Description("A device that senses or detects humidity.")]
HUMIDITYSENSOR = 10,
[Description("A device that reads a tag, such as for gaining access to a door or elevator")]
IDENTIFIERSENSOR = 11,
[Description("A device that senses or detects ion concentration, such as for water hardness.")]
IONCONCENTRATIONSENSOR = 12,
[Description("A device that senses or detects fill level, such as for a tank.")]
LEVELSENSOR = 13,
[Description("A device that senses or detects light.")]
LIGHTSENSOR = 14,
[Description("A device that senses or detects moisture.")]
MOISTURESENSOR = 15,
[Description("A device that senses or detects movement.")]
MOVEMENTSENSOR = 16,
[Description("A device that senses or detects acidity.")]
PHSENSOR = 17,
[Description("A device that senses or detects pressure.")]
PRESSURESENSOR = 18,
[Description("A device that senses or detects pressure.")]
RADIATIONSENSOR = 19,
[Description("A device that senses or detects atomic decay.")]
RADIOACTIVITYSENSOR = 20,
[Description("A device that senses or detects smoke.")]
SMOKESENSOR = 21,
[Description("A device that senses or detects sound.")]
SOUNDSENSOR = 22,
[Description("A device that senses or detects temperature.")]
TEMPERATURESENSOR = 23,
[Description("A device that senses or detects airflow speed and direction.")]
WINDSENSOR = 24,
[Description("User-defined type.")]
USERDEFINED = -1,
[Description("Undefined type.")]
NOTDEFINED = 0,
}
}
|
agpl-3.0
|
C#
|
2b6647f42dc7a276df2e7c14b82a9bf9d7555cc3
|
Add using directive
|
whampson/bft-spec,whampson/cascara
|
Cascara/Src/CascaraObject.cs
|
Cascara/Src/CascaraObject.cs
|
#region License
/* Copyright (c) 2017 Wes Hampson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
using WHampson.Cascara.Interpreter;
namespace WHampson.Cascara
{
internal class CascaraObjectFactory
{
public static CascaraObject Create(Statement expr)
{
return new CascaraObject();
}
}
public class CascaraObject
{
// TODO: object factory based on expression
internal CascaraObject()
{
}
}
}
|
#region License
/* Copyright (c) 2017 Wes Hampson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
namespace WHampson.Cascara
{
internal class CascaraObjectFactory
{
public static CascaraObject Create(Statement expr)
{
return new CascaraObject();
}
}
public class CascaraObject
{
// TODO: object factory based on expression
internal CascaraObject()
{
}
}
}
|
mit
|
C#
|
d46034b0d43561f62cd2441f41383846cb58b10c
|
load json file path according to command line args if specified.
|
funfair-tech/CoinBot
|
src/CoinBot/Program.cs
|
src/CoinBot/Program.cs
|
using CoinBot.CoinSources;
using CoinBot.CoinSources.CoinMarketCap;
using CoinBot.Discord;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using System;
using System.Threading.Tasks;
namespace CoinBotCore
{
class Program
{
static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
}
static async Task MainAsync(string[] args)
{
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();
// set up an ILogger
ILoggerFactory loggerFactory = new LoggerFactory().AddSerilog();
Microsoft.Extensions.Logging.ILogger logger = loggerFactory.CreateLogger("CoinBot");
// set up the CoinMarketCap source
ICoinSource coinSource = new CoinMarketCap(logger);
coinSource.Start();
// Create our DI container
ServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(coinSource);
serviceCollection.AddSingleton(logger);
IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
// create the discord bot and start it
string jsonFile = args.Length > 0 ? args[0] : "token.json";
DiscordBot bot = new DiscordBot(DiscordBotToken.Load(jsonFile), serviceProvider, logger);
await bot.Start();
Console.ReadLine();
// stop the discord bot
await bot.Stop();
// stop the source
coinSource.Stop();
}
}
}
|
using CoinBot.CoinSources;
using CoinBot.CoinSources.CoinMarketCap;
using CoinBot.Discord;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using System;
using System.Threading.Tasks;
namespace CoinBotCore
{
class Program
{
static void Main(string[] args)
{
MainAsync().GetAwaiter().GetResult();
}
static async Task MainAsync()
{
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();
// set up an ILogger
ILoggerFactory loggerFactory = new LoggerFactory().AddSerilog();
Microsoft.Extensions.Logging.ILogger logger = loggerFactory.CreateLogger("CoinBot");
// set up the CoinMarketCap source
ICoinSource coinSource = new CoinMarketCap(logger);
coinSource.Start();
// Create our DI container
ServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(coinSource);
serviceCollection.AddSingleton(logger);
IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
// create the discord bot and start it
DiscordBot bot = new DiscordBot(DiscordBotToken.Load("token.json"), serviceProvider, logger);
await bot.Start();
Console.ReadLine();
// stop the discord bot
await bot.Stop();
// stop the source
coinSource.Stop();
}
}
}
|
mit
|
C#
|
e800f65c0af5a303be21536d0ca37ae2c351bdfa
|
add lowerCaseUrls
|
Team-Ressurrection/Asp.NetMVCApp,Team-Ressurrection/Asp.NetMVCApp,Team-Ressurrection/Asp.NetMVCApp
|
SalaryCalculator/SalaryCalculatorWeb/App_Start/RouteConfig.cs
|
SalaryCalculator/SalaryCalculatorWeb/App_Start/RouteConfig.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace SalaryCalculatorWeb
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.LowercaseUrls = true;
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace SalaryCalculatorWeb
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
|
mit
|
C#
|
750f7254cf3e283c82992c128f809be082958783
|
Update SimpleBinaryBondDeserializer.cs
|
tiksn/TIKSN-Framework
|
TIKSN.Core/Serialization/Bond/SimpleBinaryBondDeserializer.cs
|
TIKSN.Core/Serialization/Bond/SimpleBinaryBondDeserializer.cs
|
using Bond.IO.Safe;
using Bond.Protocols;
namespace TIKSN.Serialization.Bond
{
public class SimpleBinaryBondDeserializer : DeserializerBase<byte[]>
{
protected override T DeserializeInternal<T>(byte[] serial)
{
var input = new InputBuffer(serial);
var reader = new SimpleBinaryReader<InputBuffer>(input);
return global::Bond.Deserialize<T>.From(reader);
}
}
}
|
using Bond.IO.Safe;
using Bond.Protocols;
using TIKSN.Analytics.Telemetry;
namespace TIKSN.Serialization.Bond
{
public class SimpleBinaryBondDeserializer : DeserializerBase<byte[]>
{
public SimpleBinaryBondDeserializer(IExceptionTelemeter exceptionTelemeter) : base(exceptionTelemeter)
{
}
protected override T DeserializeInternal<T>(byte[] serial)
{
var input = new InputBuffer(serial);
var reader = new SimpleBinaryReader<InputBuffer>(input);
return global::Bond.Deserialize<T>.From(reader);
}
}
}
|
mit
|
C#
|
a56c24766126d53e3a7fa6df9ca26f7b134b2d60
|
Update MessagePackSerializer.cs
|
tiksn/TIKSN-Framework
|
TIKSN.Core/Serialization/MessagePack/MessagePackSerializer.cs
|
TIKSN.Core/Serialization/MessagePack/MessagePackSerializer.cs
|
using MsgPack.Serialization;
using System.IO;
namespace TIKSN.Serialization.MessagePack
{
public class MessagePackSerializer : SerializerBase<byte[]>
{
private readonly SerializationContext _serializationContext;
public MessagePackSerializer(SerializationContext serializationContext)
{
_serializationContext = serializationContext;
}
protected override byte[] SerializeInternal(object obj)
{
var serializer = _serializationContext.GetSerializer(obj.GetType());
using (var stream = new MemoryStream())
{
serializer.Pack(stream, obj);
return stream.ToArray();
}
}
}
}
|
using MsgPack.Serialization;
using System.IO;
using TIKSN.Analytics.Telemetry;
namespace TIKSN.Serialization.MessagePack
{
public class MessagePackSerializer : SerializerBase<byte[]>
{
private readonly SerializationContext _serializationContext;
public MessagePackSerializer(IExceptionTelemeter exceptionTelemeter, SerializationContext serializationContext) : base(exceptionTelemeter)
{
_serializationContext = serializationContext;
}
protected override byte[] SerializeInternal(object obj)
{
var serializer = _serializationContext.GetSerializer(obj.GetType());
using (var stream = new MemoryStream())
{
serializer.Pack(stream, obj);
return stream.ToArray();
}
}
}
}
|
mit
|
C#
|
83a59a131180e428e965997776500a4cec74b587
|
Fix - Corretta notifica Add Chiamata In Corso
|
vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf
|
src/backend/SO115App.SignalR/Sender/GestioneChiamateInCorso/NotificationAddChiamataInCorso.cs
|
src/backend/SO115App.SignalR/Sender/GestioneChiamateInCorso/NotificationAddChiamataInCorso.cs
|
//-----------------------------------------------------------------------
// <copyright file="NotificationAddChiamataInCorso.cs" company="CNVVF">
// Copyright (C) 2017 - CNVVF
//
// This file is part of SOVVF.
// SOVVF is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// SOVVF is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
// </copyright>
//-----------------------------------------------------------------------
using DomainModel.CQRS.Commands.ChiamataInCorsoMarker;
using Microsoft.AspNetCore.SignalR;
using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneChiamateInCorso;
using SO115App.Models.Servizi.Infrastruttura.SistemiEsterni.Competenze;
using SO115App.SignalR.Utility;
using System;
using System.Threading.Tasks;
namespace SO115App.SignalR.Sender.GestioneChiamateInCorso
{
public class NotificationAddChiamataInCorso : INotificationAddChiamataInCorso
{
private readonly IHubContext<NotificationHub> _notificationHubContext;
private readonly GetGerarchiaToSend _getGerarchiaToSend;
private readonly IGetCompetenzeByCoordinateIntervento _getCompetenze;
public NotificationAddChiamataInCorso(IHubContext<NotificationHub> NotificationHubContext,
GetGerarchiaToSend getGerarchiaToSend,
IGetCompetenzeByCoordinateIntervento getCompetenze)
{
_getGerarchiaToSend = getGerarchiaToSend;
_getCompetenze = getCompetenze;
_notificationHubContext = NotificationHubContext;
}
public async Task SendNotification(ChiamataInCorsoMarkerCommand chiamata)
{
var Competenza = _getCompetenze.GetCompetenzeByCoordinateIntervento(chiamata.AddChiamataInCorso.Localita.Coordinate);
string[] CodUOCompetenzaAppo = {
Competenza.CodProvincia + "." + Competenza.CodDistaccamento,
Competenza.CodProvincia + "." + Competenza.CodDistaccamento2,
Competenza.CodProvincia + "." + Competenza.CodDistaccamento3,
Competenza.CodProvincia + ".1000"
};
var SediDaNotificare = _getGerarchiaToSend.Get(CodUOCompetenzaAppo[0]);
foreach (var sede in SediDaNotificare)
await _notificationHubContext.Clients.Group(sede).SendAsync("NotifyChiamataInCorsoMarkerAdd", chiamata);
}
}
}
|
//-----------------------------------------------------------------------
// <copyright file="NotificationAddChiamataInCorso.cs" company="CNVVF">
// Copyright (C) 2017 - CNVVF
//
// This file is part of SOVVF.
// SOVVF is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// SOVVF is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
// </copyright>
//-----------------------------------------------------------------------
using DomainModel.CQRS.Commands.ChiamataInCorsoMarker;
using Microsoft.AspNetCore.SignalR;
using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneChiamateInCorso;
using SO115App.SignalR.Utility;
using System;
using System.Threading.Tasks;
namespace SO115App.SignalR.Sender.GestioneChiamateInCorso
{
public class NotificationAddChiamataInCorso : INotificationAddChiamataInCorso
{
private readonly IHubContext<NotificationHub> _notificationHubContext;
private readonly GetGerarchiaToSend _getGerarchiaToSend;
public NotificationAddChiamataInCorso(IHubContext<NotificationHub> NotificationHubContext,
GetGerarchiaToSend getGerarchiaToSend)
{
_getGerarchiaToSend = getGerarchiaToSend;
_notificationHubContext = NotificationHubContext;
}
public async Task SendNotification(ChiamataInCorsoMarkerCommand chiamata)
{
var SediDaNotificare = _getGerarchiaToSend.Get(chiamata.AddChiamataInCorso.CodiceSedeOperatore);
foreach (var sede in SediDaNotificare)
await _notificationHubContext.Clients.Group(sede).SendAsync("NotifyChiamataInCorsoMarkerAdd", chiamata);
}
}
}
|
agpl-3.0
|
C#
|
68e1982a374ce1a7a9ef02d4bdb8b1f1c44c6b68
|
Rename ScriptExecutor to PythonScriptExecutor
|
RockyTV/Duality.IronPython
|
CorePlugin/ScriptExecutor.cs
|
CorePlugin/ScriptExecutor.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using Duality;
using RockyTV.Duality.Plugins.IronPython.Resources;
using IronPython.Hosting;
using IronPython.Runtime;
using IronPython.Compiler;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using Duality.Editor;
namespace RockyTV.Duality.Plugins.IronPython
{
[EditorHintCategory(Properties.ResNames.CategoryScripts)]
[EditorHintImage(Properties.ResNames.IconScriptGo)]
public class PythonScriptExecutor : Component, ICmpInitializable, ICmpUpdatable
{
public ContentRef<PythonScript> Script { get; set; }
[DontSerialize]
private PythonExecutionEngine _engine;
protected PythonExecutionEngine Engine
{
get { return _engine; }
}
protected virtual float Delta
{
get { return Time.MsPFMult * Time.TimeMult; }
}
public void OnInit(InitContext context)
{
if (Script.IsExplicitNull || !Script.IsAvailable) return;
if (context == InitContext.Loaded)
{
_engine = new PythonExecutionEngine(Script.Res.Content);
_engine.SetVariable("gameObject", GameObj);
}
if (_engine.HasMethod("start"))
_engine.CallMethod("start", context);
}
public void OnUpdate()
{
if (_engine != null)
if (_engine.HasMethod("update"))
_engine.CallMethod("update", Delta);
}
public void OnShutdown(ShutdownContext context)
{
if (context == ShutdownContext.Deactivate)
{
GameObj.DisposeLater();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Duality;
using RockyTV.Duality.Plugins.IronPython.Resources;
using IronPython.Hosting;
using IronPython.Runtime;
using IronPython.Compiler;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using Duality.Editor;
namespace RockyTV.Duality.Plugins.IronPython
{
[EditorHintCategory(Properties.ResNames.CategoryScripts)]
[EditorHintImage(Properties.ResNames.IconScriptGo)]
public class ScriptExecutor : Component, ICmpInitializable, ICmpUpdatable
{
public ContentRef<PythonScript> Script { get; set; }
[DontSerialize]
private PythonExecutionEngine _engine;
protected PythonExecutionEngine Engine
{
get { return _engine; }
}
protected virtual float Delta
{
get { return Time.MsPFMult * Time.TimeMult; }
}
public void OnInit(InitContext context)
{
if (Script.IsExplicitNull || !Script.IsAvailable) return;
if (context == InitContext.Loaded)
{
_engine = new PythonExecutionEngine(Script.Res.Content);
_engine.SetVariable("gameObject", GameObj);
}
if (_engine.HasMethod("start"))
_engine.CallMethod("start", context);
}
public void OnUpdate()
{
if (_engine != null)
if (_engine.HasMethod("update"))
_engine.CallMethod("update", Delta);
}
public void OnShutdown(ShutdownContext context)
{
if (context == ShutdownContext.Deactivate)
{
GameObj.DisposeLater();
}
}
}
}
|
mit
|
C#
|
89520e5e04c5c959fd8c25feb6196d919fc518ab
|
Update src/Avalonia.Controls/Notifications/IManagedNotificationManager.cs
|
grokys/Perspex,grokys/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,Perspex/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Perspex,jkoritzinsky/Avalonia,akrisiun/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex
|
src/Avalonia.Controls/Notifications/IManagedNotificationManager.cs
|
src/Avalonia.Controls/Notifications/IManagedNotificationManager.cs
|
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
namespace Avalonia.Controls.Notifications
{
/// <summary>
/// Represents a notification manager that can show arbitrary content.
/// Managed notification managers can show any content.
/// </summary>
/// <remarks>
/// Because notification managers of this type are implemented purely in managed code, they
/// can display arbitrary content, as opposed to notification managers which display notifications
/// using the host operating system's notification mechanism.
/// </remarks>
public interface IManagedNotificationManager : INotificationManager
{
/// <summary>
/// Shows a notification.
/// </summary>
/// <param name="content">The content to be displayed.</param>
void Show(object content);
}
}
|
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
namespace Avalonia.Controls.Notifications
{
/// <summary>
/// Represents a notification manager that can show arbitrary content.
/// Managed notification managers can show any content.
/// </summary>
public interface IManagedNotificationManager : INotificationManager
{
/// <summary>
/// Shows a notification.
/// </summary>
/// <param name="content">The content to be displayed.</param>
void Show(object content);
}
}
|
mit
|
C#
|
bb816ee7ee570ba7b51cb17be694fff28c256897
|
Set NullValueHandling to Ignore
|
pardahlman/akeneo-csharp
|
src/Akeneo/Serialization/AttributeBaseConverter.cs
|
src/Akeneo/Serialization/AttributeBaseConverter.cs
|
using System;
using Akeneo.Model.Attributes;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Akeneo.Serialization
{
public class AttributeBaseConverter : JsonConverter
{
private static readonly Type Attribute = typeof(AttributeBase);
private const string AttributeTypeProp = "type";
private static readonly JsonSerializer SnakeCaseSerialzer =
new JsonSerializer
{
ContractResolver = AkeneoSerializerSettings.AkeneoContractResolver,
NullValueHandling = NullValueHandling.Ignore
};
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value, typeof(GenericAttribute));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var obj = JObject.Load(reader);
var attributeType = obj.Property(AttributeTypeProp)?.Value.ToString();
switch (attributeType)
{
case AttributeType.Identifier:
return obj.ToObject<IdentifierAttribute>(SnakeCaseSerialzer);
case AttributeType.Boolean:
return obj.ToObject<BooleanAttribute>(SnakeCaseSerialzer);
case AttributeType.Date:
return obj.ToObject<DateAttribute>(SnakeCaseSerialzer);
case AttributeType.Metric:
return obj.ToObject<MetricAttribute>(SnakeCaseSerialzer);
case AttributeType.Number:
return obj.ToObject<NumberAttribute>(SnakeCaseSerialzer);
case AttributeType.Price:
return obj.ToObject<PriceAttribute>(SnakeCaseSerialzer);
case AttributeType.SimpleSelect:
return obj.ToObject<SimpleSelectAttribute>(SnakeCaseSerialzer);
case AttributeType.Text:
return obj.ToObject<TextAttribute>(SnakeCaseSerialzer);
case AttributeType.TextArea:
return obj.ToObject<TextAreaAttribute>(SnakeCaseSerialzer);
case AttributeType.MultiSelect:
return obj.ToObject<MultiSelectAttribute>(SnakeCaseSerialzer);
case AttributeType.File:
return obj.ToObject<FileAttribute>(SnakeCaseSerialzer);
case AttributeType.Image:
return obj.ToObject<ImageAttribute>(SnakeCaseSerialzer);
default:
return obj.ToObject<GenericAttribute>(SnakeCaseSerialzer);
}
}
public override bool CanConvert(Type objectType)
{
return Attribute == objectType;
}
}
}
|
using System;
using Akeneo.Model.Attributes;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Akeneo.Serialization
{
public class AttributeBaseConverter : JsonConverter
{
private static readonly Type Attribute = typeof(AttributeBase);
private const string AttributeTypeProp = "type";
private static readonly JsonSerializer SnakeCaseSerialzer =
new JsonSerializer {ContractResolver = AkeneoSerializerSettings.AkeneoContractResolver};
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value, typeof(GenericAttribute));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var obj = JObject.Load(reader);
var attributeType = obj.Property(AttributeTypeProp)?.Value.ToString();
switch (attributeType)
{
case AttributeType.Identifier:
return obj.ToObject<IdentifierAttribute>(SnakeCaseSerialzer);
case AttributeType.Boolean:
return obj.ToObject<BooleanAttribute>(SnakeCaseSerialzer);
case AttributeType.Date:
return obj.ToObject<DateAttribute>(SnakeCaseSerialzer);
case AttributeType.Metric:
return obj.ToObject<MetricAttribute>(SnakeCaseSerialzer);
case AttributeType.Number:
return obj.ToObject<NumberAttribute>(SnakeCaseSerialzer);
case AttributeType.Price:
return obj.ToObject<PriceAttribute>(SnakeCaseSerialzer);
case AttributeType.SimpleSelect:
return obj.ToObject<SimpleSelectAttribute>(SnakeCaseSerialzer);
case AttributeType.Text:
return obj.ToObject<TextAttribute>(SnakeCaseSerialzer);
case AttributeType.TextArea:
return obj.ToObject<TextAreaAttribute>(SnakeCaseSerialzer);
case AttributeType.MultiSelect:
return obj.ToObject<MultiSelectAttribute>(SnakeCaseSerialzer);
case AttributeType.File:
return obj.ToObject<FileAttribute>(SnakeCaseSerialzer);
case AttributeType.Image:
return obj.ToObject<ImageAttribute>(SnakeCaseSerialzer);
default:
return obj.ToObject<GenericAttribute>(SnakeCaseSerialzer);
}
}
public override bool CanConvert(Type objectType)
{
return Attribute == objectType;
}
}
}
|
mit
|
C#
|
db4180cff752fd02ae9e3dbe1b96ed1f857eae01
|
Reduce reflection over Moq internals & fix regressions
|
dwhelan/Moq-Sequences
|
src/Moq.Sequences/Step.cs
|
src/Moq.Sequences/Step.cs
|
using System.Reflection;
using System.Text;
namespace Moq.Sequences
{
public class Step
{
private readonly Times expectedCount;
private readonly string action;
private int actualCount;
internal bool Started { get { return actualCount > 0; } }
internal bool Complete { get; private set; }
private static readonly MethodInfo getExceptionMessage = typeof(Times).GetMethod("GetExceptionMessage", BindingFlags.Instance | BindingFlags.NonPublic);
internal Step(Times expectedCount, string action = "")
{
this.expectedCount = expectedCount;
this.action = action;
}
internal void CountCall()
{
if (Complete)
throw new SequenceException(this + " is not invokable because it has already completed.");
var (_, maxCount) = expectedCount;
if (++actualCount > maxCount)
throw new SequenceException(GetFailureMessage("Exceeded maximum number of invocations."));
}
internal virtual void EnsureComplete(string context)
{
if (!Verified())
throw new SequenceException(GetFailureMessage(context + " but invocations for " + this + " were not completed."));
Complete = true;
}
private bool Verified()
{
var (minCount, maxCount) = expectedCount;
return minCount <= actualCount && actualCount <= maxCount;
}
protected virtual string GetFailureMessage(string failMessage)
{
var message = new StringBuilder();
message.AppendLine(failMessage);
message.Append((string)getExceptionMessage.Invoke(expectedCount, new object[] { actualCount }));
message.AppendLine(action);
return message.ToString();
}
internal virtual void Reset()
{
actualCount = 0;
Complete = false;
}
public override string ToString()
{
return action;
}
}
}
|
using System.Reflection;
namespace Moq.Sequences
{
public class Step
{
private readonly Times expectedCount;
private readonly string action;
private readonly int maxCount;
private int actualCount;
internal bool Started { get { return actualCount > 0; } }
internal bool Complete { get; private set; }
private static readonly FieldInfo to = typeof(Times).GetField("to", BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly MethodInfo verify = typeof(Times).GetMethod("Verify", BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly MethodInfo getExceptionMessage = typeof(Times).GetMethod("GetExceptionMessage", BindingFlags.Instance | BindingFlags.NonPublic);
internal Step(Times expectedCount, string action = "")
{
this.expectedCount = expectedCount;
this.action = action;
maxCount = (int)to.GetValue(expectedCount);
}
internal void CountCall()
{
if (Complete)
throw new SequenceException(this + " is not invokable because it has already completed.");
if (++actualCount > maxCount)
throw new SequenceException(GetFailureMessage("Exceeded maximum number of invocations."));
}
internal virtual void EnsureComplete(string context)
{
if (!Verified())
throw new SequenceException(GetFailureMessage(context + " but invocations for " + this + " were not completed."));
Complete = true;
}
private bool Verified()
{
return (bool) verify.Invoke(expectedCount, new[] { (object)actualCount });
}
protected virtual string GetFailureMessage(string failMessage)
{
return (string) getExceptionMessage.Invoke(expectedCount, new object[] { failMessage, ToString(), actualCount });
}
internal virtual void Reset()
{
actualCount = 0;
Complete = false;
}
public override string ToString()
{
return action;
}
}
}
|
mit
|
C#
|
66457fd1b561ca0f8e6c8528468fdbffb6fa096a
|
Use linq to simplify enumeration
|
davidebbo-test/SettingsAPISampleSiteExtension,davidebbo-test/SettingsAPISampleSiteExtension
|
SettingsAPISample/Models/ARMListEntry.cs
|
SettingsAPISample/Models/ARMListEntry.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
namespace SettingsAPISample.Models
{
public class ARMListEntry<T> where T : INamedObject
{
public static ARMListEntry<T> Create(IEnumerable<T> objects, HttpRequestMessage request)
{
return new ARMListEntry<T>
{
Value = objects.Select(entry => ARMEntry<T>.Create(entry, request, isChild: true))
};
}
public IEnumerable<ARMEntry<T>> Value { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
namespace SettingsAPISample.Models
{
public class ARMListEntry<T> where T : INamedObject
{
public static ARMListEntry<T> Create(IEnumerable<T> objects, HttpRequestMessage request)
{
return new ARMListEntry<T>
{
Value = CreateList(objects, request)
};
}
private static IEnumerable<ARMEntry<T>> CreateList(IEnumerable<T> objects, HttpRequestMessage request)
{
foreach (var entry in objects)
{
yield return ARMEntry<T>.Create(entry, request, isChild: true);
}
}
public IEnumerable<ARMEntry<T>> Value { get; set; }
}
}
|
apache-2.0
|
C#
|
ce00009edce1a26f1f15c9f437642d0d00d5dced
|
remove using
|
tynor88/Topshelf.SimpleInjector
|
Source/Topshelf.SimpleInjector.CI/Properties/AssemblyInfo.cs
|
Source/Topshelf.SimpleInjector.CI/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("Topshelf.SimpleInjector.CI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Topshelf.SimpleInjector.CI")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c496bff2-294c-4253-89fd-bfc7d8a05201")]
// 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("Topshelf.SimpleInjector.CI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Topshelf.SimpleInjector.CI")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c496bff2-294c-4253-89fd-bfc7d8a05201")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
mit
|
C#
|
37bf79e8a412d88b4796627b4447d78458bd56af
|
Remove unused automapper setup for the time being
|
NeoAdonis/osu,smoogipooo/osu,peppy/osu-new,peppy/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu
|
osu.Game/Database/RealmExtensions.cs
|
osu.Game/Database/RealmExtensions.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 AutoMapper;
using osu.Game.Input.Bindings;
using Realms;
namespace osu.Game.Database
{
public static class RealmExtensions
{
private static readonly IMapper mapper = new MapperConfiguration(c =>
{
c.ShouldMapField = fi => false;
c.ShouldMapProperty = pi => pi.SetMethod != null && pi.SetMethod.IsPublic;
c.CreateMap<RealmKeyBinding, RealmKeyBinding>();
}).CreateMapper();
/// <summary>
/// Create a detached copy of the each item in the collection.
/// </summary>
/// <param name="items">A list of managed <see cref="RealmObject"/>s to detach.</param>
/// <typeparam name="T">The type of object.</typeparam>
/// <returns>A list containing non-managed copies of provided items.</returns>
public static List<T> Detach<T>(this IEnumerable<T> items) where T : RealmObject
{
var list = new List<T>();
foreach (var obj in items)
list.Add(obj.Detach());
return list;
}
/// <summary>
/// Create a detached copy of the item.
/// </summary>
/// <param name="item">The managed <see cref="RealmObject"/> to detach.</param>
/// <typeparam name="T">The type of object.</typeparam>
/// <returns>A non-managed copy of provided item. Will return the provided item if already detached.</returns>
public static T Detach<T>(this T item) where T : RealmObject
{
if (!item.IsManaged)
return item;
return mapper.Map<T>(item);
}
}
}
|
// 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 AutoMapper;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Input.Bindings;
using osu.Game.IO;
using osu.Game.Rulesets;
using osu.Game.Scoring;
using osu.Game.Skinning;
using Realms;
namespace osu.Game.Database
{
public static class RealmExtensions
{
private static readonly IMapper mapper = new MapperConfiguration(c =>
{
c.ShouldMapField = fi => false;
c.ShouldMapProperty = pi => pi.SetMethod != null && pi.SetMethod.IsPublic;
c.CreateMap<BeatmapDifficulty, BeatmapDifficulty>();
c.CreateMap<BeatmapInfo, BeatmapInfo>();
c.CreateMap<BeatmapMetadata, BeatmapMetadata>();
c.CreateMap<BeatmapSetFileInfo, BeatmapSetFileInfo>();
c.CreateMap<BeatmapSetInfo, BeatmapSetInfo>()
.ForMember(s => s.Beatmaps, d => d.MapFrom(s => s.Beatmaps))
.ForMember(s => s.Files, d => d.MapFrom(s => s.Files))
.MaxDepth(2);
c.CreateMap<RealmKeyBinding, RealmKeyBinding>();
c.CreateMap<DatabasedSetting, DatabasedSetting>();
c.CreateMap<FileInfo, FileInfo>();
c.CreateMap<ScoreFileInfo, ScoreFileInfo>();
c.CreateMap<SkinInfo, SkinInfo>();
c.CreateMap<RulesetInfo, RulesetInfo>();
}).CreateMapper();
/// <summary>
/// Create a detached copy of the each item in the collection.
/// </summary>
/// <param name="items">A list of managed <see cref="RealmObject"/>s to detach.</param>
/// <typeparam name="T">The type of object.</typeparam>
/// <returns>A list containing non-managed copies of provided items.</returns>
public static List<T> Detach<T>(this IEnumerable<T> items) where T : RealmObject
{
var list = new List<T>();
foreach (var obj in items)
list.Add(obj.Detach());
return list;
}
/// <summary>
/// Create a detached copy of the item.
/// </summary>
/// <param name="item">The managed <see cref="RealmObject"/> to detach.</param>
/// <typeparam name="T">The type of object.</typeparam>
/// <returns>A non-managed copy of provided item. Will return the provided item if already detached.</returns>
public static T Detach<T>(this T item) where T : RealmObject
{
if (!item.IsManaged)
return item;
return mapper.Map<T>(item);
}
}
}
|
mit
|
C#
|
839b76fdf64dd8bfe419e809ea664f1e7361cc87
|
Refactor jQuery validate inclusion
|
peterblazejewicz/aspnet-5-bootstrap-4,peterblazejewicz/aspnet-5-bootstrap-4
|
WebApplication/Views/Shared/_ValidationScriptsPartial.cshtml
|
WebApplication/Views/Shared/_ValidationScriptsPartial.cshtml
|
<environment names="Development">
<script src="~/lib/jquery-validation/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</environment>
<environment names="Staging,Production">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"
asp-fallback-src="~/lib/jquery-validation/jquery.validate.js"
asp-fallback-test="window.jQuery && window.jQuery.validator">
</script>
<script src="//cdn.rawgit.com/aspnet/jquery-validation-unobtrusive/master/jquery.validate.unobtrusive.min.js"
asp-fallback-src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"
asp-fallback-test="window.jQuery && window.jQuery.validator && window.jQuery.validator.unobtrusive">
</script>
</environment>
|
<environment names="Development">
<script src="~/lib/jquery-validation/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</environment>
<environment names="Staging,Production">
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"
asp-fallback-src="~/lib/jquery-validation/jquery.validate.js"
asp-fallback-test="window.jquery && window.jquery.validator">
</script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.min.js"
asp-fallback-src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"
asp-fallback-test="window.jquery && window.jquery.validator && window.jquery.validator.unobtrusive">
</script>
</environment>
|
mit
|
C#
|
edffe9bbf8e8b162e599a929180a18c9ad6e7896
|
Disable System.Collections.Tests.ComparersGenericTests.EqualityComparer_SerializationRoundtrip test for uap as well (#21021)
|
Jiayili1/corefx,ptoonen/corefx,fgreinacher/corefx,the-dwyer/corefx,ericstj/corefx,tijoytom/corefx,zhenlan/corefx,seanshpark/corefx,nbarbettini/corefx,ravimeda/corefx,wtgodbe/corefx,yizhang82/corefx,ptoonen/corefx,tijoytom/corefx,JosephTremoulet/corefx,nbarbettini/corefx,nchikanov/corefx,ravimeda/corefx,DnlHarvey/corefx,mazong1123/corefx,krytarowski/corefx,krk/corefx,jlin177/corefx,alexperovich/corefx,fgreinacher/corefx,axelheer/corefx,Ermiar/corefx,dotnet-bot/corefx,BrennanConroy/corefx,axelheer/corefx,gkhanna79/corefx,Jiayili1/corefx,parjong/corefx,nchikanov/corefx,cydhaselton/corefx,JosephTremoulet/corefx,mmitche/corefx,alexperovich/corefx,cydhaselton/corefx,DnlHarvey/corefx,ViktorHofer/corefx,nchikanov/corefx,rubo/corefx,richlander/corefx,mazong1123/corefx,zhenlan/corefx,jlin177/corefx,DnlHarvey/corefx,yizhang82/corefx,krk/corefx,wtgodbe/corefx,alexperovich/corefx,jlin177/corefx,stone-li/corefx,Ermiar/corefx,the-dwyer/corefx,twsouthwick/corefx,BrennanConroy/corefx,dotnet-bot/corefx,Ermiar/corefx,ericstj/corefx,wtgodbe/corefx,krytarowski/corefx,JosephTremoulet/corefx,ravimeda/corefx,Ermiar/corefx,rubo/corefx,shimingsg/corefx,wtgodbe/corefx,BrennanConroy/corefx,nbarbettini/corefx,Jiayili1/corefx,ravimeda/corefx,zhenlan/corefx,jlin177/corefx,gkhanna79/corefx,jlin177/corefx,krk/corefx,billwert/corefx,JosephTremoulet/corefx,ViktorHofer/corefx,cydhaselton/corefx,tijoytom/corefx,DnlHarvey/corefx,twsouthwick/corefx,parjong/corefx,nbarbettini/corefx,zhenlan/corefx,dotnet-bot/corefx,the-dwyer/corefx,yizhang82/corefx,richlander/corefx,nchikanov/corefx,shimingsg/corefx,ravimeda/corefx,MaggieTsang/corefx,krk/corefx,zhenlan/corefx,krk/corefx,Jiayili1/corefx,dotnet-bot/corefx,mmitche/corefx,wtgodbe/corefx,zhenlan/corefx,ravimeda/corefx,Jiayili1/corefx,fgreinacher/corefx,parjong/corefx,mazong1123/corefx,ericstj/corefx,richlander/corefx,MaggieTsang/corefx,shimingsg/corefx,mmitche/corefx,twsouthwick/corefx,twsouthwick/corefx,ericstj/corefx,wtgodbe/corefx,seanshpark/corefx,the-dwyer/corefx,ptoonen/corefx,ptoonen/corefx,shimingsg/corefx,shimingsg/corefx,richlander/corefx,billwert/corefx,MaggieTsang/corefx,cydhaselton/corefx,ViktorHofer/corefx,rubo/corefx,shimingsg/corefx,cydhaselton/corefx,dotnet-bot/corefx,tijoytom/corefx,stone-li/corefx,ravimeda/corefx,seanshpark/corefx,parjong/corefx,twsouthwick/corefx,stone-li/corefx,stone-li/corefx,MaggieTsang/corefx,ptoonen/corefx,ViktorHofer/corefx,alexperovich/corefx,seanshpark/corefx,billwert/corefx,krytarowski/corefx,krytarowski/corefx,MaggieTsang/corefx,yizhang82/corefx,jlin177/corefx,billwert/corefx,DnlHarvey/corefx,rubo/corefx,nbarbettini/corefx,MaggieTsang/corefx,seanshpark/corefx,twsouthwick/corefx,gkhanna79/corefx,gkhanna79/corefx,billwert/corefx,Ermiar/corefx,ViktorHofer/corefx,seanshpark/corefx,the-dwyer/corefx,Ermiar/corefx,stone-li/corefx,tijoytom/corefx,nchikanov/corefx,alexperovich/corefx,yizhang82/corefx,dotnet-bot/corefx,mazong1123/corefx,ericstj/corefx,wtgodbe/corefx,mmitche/corefx,ericstj/corefx,gkhanna79/corefx,alexperovich/corefx,mazong1123/corefx,nchikanov/corefx,Jiayili1/corefx,mmitche/corefx,krk/corefx,gkhanna79/corefx,nbarbettini/corefx,rubo/corefx,fgreinacher/corefx,JosephTremoulet/corefx,ptoonen/corefx,parjong/corefx,Jiayili1/corefx,DnlHarvey/corefx,axelheer/corefx,ericstj/corefx,cydhaselton/corefx,mmitche/corefx,twsouthwick/corefx,richlander/corefx,mazong1123/corefx,billwert/corefx,tijoytom/corefx,nbarbettini/corefx,the-dwyer/corefx,MaggieTsang/corefx,Ermiar/corefx,richlander/corefx,yizhang82/corefx,dotnet-bot/corefx,DnlHarvey/corefx,stone-li/corefx,parjong/corefx,axelheer/corefx,stone-li/corefx,ViktorHofer/corefx,jlin177/corefx,parjong/corefx,JosephTremoulet/corefx,shimingsg/corefx,zhenlan/corefx,mazong1123/corefx,the-dwyer/corefx,alexperovich/corefx,axelheer/corefx,axelheer/corefx,krytarowski/corefx,yizhang82/corefx,ViktorHofer/corefx,nchikanov/corefx,ptoonen/corefx,krytarowski/corefx,cydhaselton/corefx,richlander/corefx,gkhanna79/corefx,JosephTremoulet/corefx,mmitche/corefx,krytarowski/corefx,krk/corefx,seanshpark/corefx,tijoytom/corefx,billwert/corefx
|
src/System.Collections/tests/Generic/Comparers/EqualityComparer.Generic.Serialization.Tests.cs
|
src/System.Collections/tests/Generic/Comparers/EqualityComparer.Generic.Serialization.Tests.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Generic.Tests
{
public abstract partial class ComparersGenericTests<T>
{
[Fact]
[ActiveIssue(20888, TargetFrameworkMonikers.Uap)]
public void EqualityComparer_SerializationRoundtrip()
{
var bf = new BinaryFormatter();
var s = new MemoryStream();
EqualityComparer<T> orig = EqualityComparer<T>.Default;
bf.Serialize(s, orig);
s.Position = 0;
object result = bf.Deserialize(s);
// On .NET Framework, some EnumEqualityComparers deserialize as ObjectEqualityComparer.
// On .NET Core, they deserialize as the right type.
Assert.IsAssignableFrom<EqualityComparer<T>>(result);
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Generic.Tests
{
public abstract partial class ComparersGenericTests<T>
{
[Fact]
[ActiveIssue(20888, TargetFrameworkMonikers.UapAot)]
public void EqualityComparer_SerializationRoundtrip()
{
var bf = new BinaryFormatter();
var s = new MemoryStream();
EqualityComparer<T> orig = EqualityComparer<T>.Default;
bf.Serialize(s, orig);
s.Position = 0;
object result = bf.Deserialize(s);
// On .NET Framework, some EnumEqualityComparers deserialize as ObjectEqualityComparer.
// On .NET Core, they deserialize as the right type.
Assert.IsAssignableFrom<EqualityComparer<T>>(result);
}
}
}
|
mit
|
C#
|
8dc976ac6f8e7ed109eb3828daa9d7f766b22900
|
Fix handling of detaching media items and the serialization thereof
|
kamsar/Unicorn,kamsar/Unicorn
|
src/Unicorn/Data/DataProvider/FieldChangeParser.cs
|
src/Unicorn/Data/DataProvider/FieldChangeParser.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using Rainbow.Model;
using Sitecore.Configuration;
using Sitecore.Data.Items;
using Sitecore.Data.Managers;
using Sitecore.Diagnostics;
namespace Unicorn.Data.DataProvider
{
/// <summary>
/// Evaluates a Sitecore FieldChanges and applies it to a set of Unicorn IItemFieldValues.
/// Changes from the FieldChanges override any existing values in the Unicorn values. Values without changes
/// are preserved.
/// </summary>
/// <remarks>
/// This is necessary because when installing packages and update packages Sitecore can provide only PARTIAL item data
/// to the data provider (e.g. changes.Item is INCOMPLETE). Parsing and applying the changes to the existing item, if any,
/// enables us to augment the item with the changes from Sitecore without tossing out any incomplete data the save may include.
/// </remarks>
public class FieldChangeParser
{
public IEnumerable<IItemFieldValue> ParseFieldChanges(IEnumerable<FieldChange> applicableFieldChanges, IEnumerable<IItemFieldValue> baseFieldValues, string databaseName)
{
var fields = baseFieldValues?.ToDictionary(value => value.FieldId) ?? new Dictionary<Guid, IItemFieldValue>();
foreach (var change in applicableFieldChanges)
{
if (change.RemoveField)
{
fields.Remove(change.FieldID.Guid);
continue;
}
IItemFieldValue targetField;
ProxyFieldValue newChangeValue;
if(fields.TryGetValue(change.FieldID.Guid, out targetField)) newChangeValue = new ProxyFieldValue(targetField);
else newChangeValue = new ProxyFieldValue(change.FieldID.Guid, change.Value);
newChangeValue.FieldType = change.Definition.Type;
newChangeValue.NameHint = change.Definition.Name;
if (!change.IsBlob)
{
newChangeValue.Value = change.Value;
}
else
{
Guid blobId;
if (Guid.TryParse(change.Value, out blobId))
{
newChangeValue.BlobId = blobId;
newChangeValue.Value = GetBlobValue(blobId, databaseName);
}
else
{
newChangeValue.BlobId = null;
newChangeValue.Value = null;
}
}
fields[change.FieldID.Guid] = newChangeValue;
}
return fields.Values;
}
protected string GetBlobValue(Guid blobId, string database)
{
var db = Factory.GetDatabase(database);
Assert.IsNotNull(db, "Database {0} does not exist!", database);
using (var stream = ItemManager.GetBlobStream(blobId, db))
{
// during package installs the blob might not yet be in the database.
// so if it does not yet exist we'll act like the value is blank.
// this works out because the blob is actually written in a later data push from the package installer
// so the blob actually does end up in the item
if (stream == null) return string.Empty;
var buf = new byte[stream.Length];
stream.Read(buf, 0, (int)stream.Length);
return Convert.ToBase64String(buf);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Rainbow.Model;
using Sitecore.Configuration;
using Sitecore.Data.Items;
using Sitecore.Data.Managers;
using Sitecore.Diagnostics;
namespace Unicorn.Data.DataProvider
{
/// <summary>
/// Evaluates a Sitecore FieldChanges and applies it to a set of Unicorn IItemFieldValues.
/// Changes from the FieldChanges override any existing values in the Unicorn values. Values without changes
/// are preserved.
/// </summary>
/// <remarks>
/// This is necessary because when installing packages and update packages Sitecore can provide only PARTIAL item data
/// to the data provider (e.g. changes.Item is INCOMPLETE). Parsing and applying the changes to the existing item, if any,
/// enables us to augment the item with the changes from Sitecore without tossing out any incomplete data the save may include.
/// </remarks>
public class FieldChangeParser
{
public IEnumerable<IItemFieldValue> ParseFieldChanges(IEnumerable<FieldChange> applicableFieldChanges, IEnumerable<IItemFieldValue> baseFieldValues, string databaseName)
{
var fields = baseFieldValues?.ToDictionary(value => value.FieldId) ?? new Dictionary<Guid, IItemFieldValue>();
foreach (var change in applicableFieldChanges)
{
if (change.RemoveField)
{
fields.Remove(change.FieldID.Guid);
continue;
}
IItemFieldValue targetField;
ProxyFieldValue newChangeValue;
if(fields.TryGetValue(change.FieldID.Guid, out targetField)) newChangeValue = new ProxyFieldValue(targetField);
else newChangeValue = new ProxyFieldValue(change.FieldID.Guid, change.Value);
newChangeValue.FieldType = change.Definition.Type;
newChangeValue.NameHint = change.Definition.Name;
if (!change.IsBlob)
{
newChangeValue.Value = change.Value;
}
else
{
newChangeValue.BlobId = Guid.Parse(change.Value);
newChangeValue.Value = GetBlobValue(newChangeValue.BlobId.Value, databaseName);
}
fields[change.FieldID.Guid] = newChangeValue;
}
return fields.Values;
}
protected string GetBlobValue(Guid blobId, string database)
{
var db = Factory.GetDatabase(database);
Assert.IsNotNull(db, "Database {0} does not exist!", database);
using (var stream = ItemManager.GetBlobStream(blobId, db))
{
// during package installs the blob might not yet be in the database.
// so if it does not yet exist we'll act like the value is blank.
// this works out because the blob is actually written in a later data push from the package installer
// so the blob actually does end up in the item
if (stream == null) return string.Empty;
var buf = new byte[stream.Length];
stream.Read(buf, 0, (int)stream.Length);
return Convert.ToBase64String(buf);
}
}
}
}
|
mit
|
C#
|
b137c3b2caa021c656e9af88b2c6d13dac26501d
|
Adjust ticks size
|
peppy/osu,UselessToucan/osu,smoogipooo/osu,DrabWeb/osu,EVAST9919/osu,ZLima12/osu,2yangk23/osu,peppy/osu-new,ppy/osu,peppy/osu,smoogipoo/osu,naoey/osu,smoogipoo/osu,UselessToucan/osu,johnneijzen/osu,ppy/osu,DrabWeb/osu,EVAST9919/osu,ppy/osu,2yangk23/osu,ZLima12/osu,peppy/osu,Nabile-Rahmani/osu,naoey/osu,naoey/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,Frontear/osuKyzer,DrabWeb/osu,johnneijzen/osu
|
osu.Game.Rulesets.Catch/Objects/Drawable/DrawableDroplet.cs
|
osu.Game.Rulesets.Catch/Objects/Drawable/DrawableDroplet.cs
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Catch.Objects.Drawable.Pieces;
using OpenTK;
namespace osu.Game.Rulesets.Catch.Objects.Drawable
{
public class DrawableDroplet : DrawableCatchHitObject<Droplet>
{
public DrawableDroplet(Droplet h)
: base(h)
{
Origin = Anchor.Centre;
Size = new Vector2((float)CatchHitObject.OBJECT_RADIUS) / 4;
AccentColour = h.ComboColour;
Masking = false;
}
[BackgroundDependencyLoader]
private void load()
{
Child = new Pulp
{
AccentColour = AccentColour,
Size = Size
};
}
}
}
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Catch.Objects.Drawable.Pieces;
using OpenTK;
namespace osu.Game.Rulesets.Catch.Objects.Drawable
{
public class DrawableDroplet : DrawableCatchHitObject<Droplet>
{
public DrawableDroplet(Droplet h)
: base(h)
{
Origin = Anchor.Centre;
Size = new Vector2((float)CatchHitObject.OBJECT_RADIUS);
AccentColour = h.ComboColour;
Masking = false;
}
[BackgroundDependencyLoader]
private void load()
{
Child = new Pulp
{
AccentColour = AccentColour,
Scale = new Vector2(0.8f),
};
}
}
}
|
mit
|
C#
|
38d24849345adb576f61f96e549a8ebf21f270c3
|
Use parameterless constructor for DiplomContext
|
denismaster/dcs,denismaster/dcs,denismaster/dcs,denismaster/dcs
|
src/Diploms.DataLayer/DiplomContext.cs
|
src/Diploms.DataLayer/DiplomContext.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Diploms.Core;
namespace Diploms.DataLayer
{
public class DiplomContext : DbContext
{
public DbSet<Department> Departments { get; set; }
public DiplomContext() : base()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//TODO: Use appsettings.json or environment variable, not the string here.
optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=diploms;UserId=postgres;Password=12345678;Pooling=true");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Diploms.Core;
namespace Diploms.DataLayer
{
public class DiplomContext : DbContext
{
public DbSet<Department> Departments { get; set; }
public DiplomContext(DbContextOptions<DiplomContext> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//TODO: Use appsettings.json or environment variable, not the string here.
optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=diploms;UserId=postgres;Password=12345678;Pooling=true");
}
}
}
|
mit
|
C#
|
6def353324ebb411d0fb1c44a5659cf82b372994
|
Add AccessTokenConfiguration#DeleteAccessToken
|
appharbor/appharbor-cli
|
src/AppHarbor/AccessTokenConfiguration.cs
|
src/AppHarbor/AccessTokenConfiguration.cs
|
using System;
namespace AppHarbor
{
public class AccessTokenConfiguration
{
private const string TokenEnvironmentVariable = "AppHarborToken";
private const EnvironmentVariableTarget TokenEnvironmentVariableTarget = EnvironmentVariableTarget.User;
public virtual void DeleteAccessToken()
{
Environment.SetEnvironmentVariable(TokenEnvironmentVariable, null, TokenEnvironmentVariableTarget);
}
public virtual string GetAccessToken()
{
return Environment.GetEnvironmentVariable(TokenEnvironmentVariable, TokenEnvironmentVariableTarget);
}
public virtual void SetAccessToken(string username, string password)
{
throw new NotImplementedException();
//Environment.SetEnvironmentVariable(TokenEnvironmentVariable, "foo", TokenEnvironmentVariableTarget);
}
}
}
|
using System;
namespace AppHarbor
{
public class AccessTokenConfiguration
{
private const string TokenEnvironmentVariable = "AppHarborToken";
private const EnvironmentVariableTarget TokenEnvironmentVariableTarget = EnvironmentVariableTarget.User;
public virtual string GetAccessToken()
{
return Environment.GetEnvironmentVariable(TokenEnvironmentVariable, TokenEnvironmentVariableTarget);
}
public virtual void SetAccessToken(string username, string password)
{
throw new NotImplementedException();
//Environment.SetEnvironmentVariable(TokenEnvironmentVariable, "foo", TokenEnvironmentVariableTarget);
}
}
}
|
mit
|
C#
|
35c8fe90d36f7a72f0100ec6188e10187259b3aa
|
Remove unused check
|
JakeGinnivan/ApiApprover
|
src/PublicApiGenerator/AttributeFilter.cs
|
src/PublicApiGenerator/AttributeFilter.cs
|
using Mono.Cecil;
using System.Collections.Generic;
using System.Linq;
namespace PublicApiGenerator
{
internal sealed partial class AttributeFilter
{
private readonly HashSet<string> _excludedAttributes;
public AttributeFilter(IEnumerable<string> excludedAttributes)
{
_excludedAttributes = excludedAttributes is null
? SkippedAttributeNames
: new HashSet<string>(SkippedAttributeNames.Concat(excludedAttributes));
}
public bool ShouldIncludeAttribute(CustomAttribute attribute)
{
var attributeTypeDefinition = attribute.AttributeType.Resolve();
return attributeTypeDefinition != null && !_excludedAttributes.Contains(attribute.AttributeType.FullName) && attributeTypeDefinition.IsPublic;
}
}
}
|
using Mono.Cecil;
using System.Collections.Generic;
using System.Linq;
namespace PublicApiGenerator
{
internal sealed partial class AttributeFilter
{
private readonly HashSet<string> _excludedAttributes;
public AttributeFilter(IEnumerable<string> excludedAttributes)
{
_excludedAttributes = excludedAttributes is null
? SkippedAttributeNames
: new HashSet<string>(SkippedAttributeNames.Concat(excludedAttributes));
}
public bool ShouldIncludeAttribute(CustomAttribute attribute)
{
var attributeTypeDefinition = attribute.AttributeType.Resolve();
return attributeTypeDefinition != null && !_excludedAttributes.Contains(attribute.AttributeType.FullName) && (attributeTypeDefinition.IsPublic || attributeTypeDefinition.FullName == "System.Runtime.CompilerServices.NullableAttribute");
}
}
}
|
mit
|
C#
|
be132c95d8b0b09b7d044e00a8aea579c6e06f96
|
Align with Nuget Package Version 1.0.7
|
dhont/Custom-ErrorSignal-Elmah
|
CustomErrorSignal/Properties/AssemblyInfo.cs
|
CustomErrorSignal/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("ElmahExtensions")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CustomErrorSignal")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5ffd977a-b2cf-4f08-a7f9-c5fc0fd3e5c1")]
// 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.7.0")]
[assembly: AssemblyFileVersion("1.0.7.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("ElmahExtensions")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CustomErrorSignal")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5ffd977a-b2cf-4f08-a7f9-c5fc0fd3e5c1")]
// 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.6.0")]
[assembly: AssemblyFileVersion("1.0.6.0")]
|
apache-2.0
|
C#
|
ad9592555567187d87e0631304ebd5fd0ab75185
|
Enable QEP for Nullable.
|
chtoucas/Narvalo.NET,chtoucas/Narvalo.NET
|
src/Narvalo.Fx/Applicative/Nullable.cs
|
src/Narvalo.Fx/Applicative/Nullable.cs
|
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.
namespace Narvalo.Applicative
{
using System;
/// <summary>
/// Provides a set of static and extension methods for <see cref="Nullable{T}"/>.
/// </summary>
public static class Nullable
{
#region Query Expression Pattern
public static TResult? Select<TSource, TResult>(this TSource? @this, Func<TSource, TResult> selector)
where TSource : struct
where TResult : struct
{
Require.NotNull(selector, nameof(selector));
return @this.HasValue ? (TResult?)selector(@this.Value) : null;
}
public static TSource? Where<TSource>(
this TSource? @this,
Func<TSource, bool> predicate)
where TSource : struct
{
Require.NotNull(predicate, nameof(predicate));
return @this.HasValue && predicate(@this.Value) ? @this : null;
}
public static TResult? SelectMany<TSource, TMiddle, TResult>(
this TSource? @this,
Func<TSource, TMiddle?> valueSelector,
Func<TSource, TMiddle, TResult> resultSelector)
where TSource : struct
where TMiddle : struct
where TResult : struct
{
Require.NotNull(valueSelector, nameof(valueSelector));
Require.NotNull(resultSelector, nameof(resultSelector));
if (!@this.HasValue) { return null; }
var middle = valueSelector(@this.Value);
if (!middle.HasValue) { return null; }
return resultSelector(@this.Value, middle.Value);
}
#endregion
}
}
|
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.
namespace Narvalo.Applicative
{
using System;
/// <summary>
/// Provides a set of static and extension methods for <see cref="Nullable{T}"/>.
/// </summary>
public static class Nullable
{
public static TResult? Select<TSource, TResult>(this TSource? @this, Func<TSource, TResult> selector)
where TSource : struct
where TResult : struct
{
Require.NotNull(selector, nameof(selector));
return @this.HasValue ? (TResult?)selector(@this.Value) : null;
}
}
}
|
bsd-2-clause
|
C#
|
2c69edca5321f19d36077966e30f5e89ed5104f1
|
Test to ensure Funq doesn't autowire BCL and string types
|
nataren/NServiceKit,NServiceKit/NServiceKit,nataren/NServiceKit,NServiceKit/NServiceKit,MindTouch/NServiceKit,ZocDoc/ServiceStack,nataren/NServiceKit,timba/NServiceKit,MindTouch/NServiceKit,MindTouch/NServiceKit,ZocDoc/ServiceStack,timba/NServiceKit,nataren/NServiceKit,MindTouch/NServiceKit,NServiceKit/NServiceKit,timba/NServiceKit,NServiceKit/NServiceKit,ZocDoc/ServiceStack,timba/NServiceKit,ZocDoc/ServiceStack
|
tests/ServiceStack.ServiceHost.Tests/IoCTests.cs
|
tests/ServiceStack.ServiceHost.Tests/IoCTests.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using ServiceStack.ServiceHost.Tests.Support;
using Funq;
namespace ServiceStack.ServiceHost.Tests
{
[TestFixture]
public class IoCTests
{
[Test]
public void Can_AutoWire_types_dynamically_with_expressions()
{
var serviceType = typeof(AutoWireService);
var container = new Container();
container.Register<IFoo>(c => new Foo());
container.Register<IBar>(c => new Bar());
container.Register<int>(c => 100);
container.RegisterAutoWiredType(serviceType);
var service = container.Resolve<AutoWireService>();
Assert.That(service.Foo, Is.Not.Null);
Assert.That(service.Bar, Is.Not.Null);
Assert.That(service.Count, Is.EqualTo(0));
}
public class Test
{
public IFoo Foo { get; set; }
public IBar Bar { get; set; }
public IFoo Foo2 { get; set; }
public IEnumerable<string> Names { get; set; }
public int Age { get; set; }
public Test()
{
this.Foo2 = new Foo2();
this.Names = new List<string>() { "Steffen", "Demis" };
}
}
[Test]
public void Can_AutoWire_Existing_Instance()
{
var test = new Test();
var container = new Container();
container.Register<IFoo>(c => new Foo());
container.Register<IBar>(c => new Bar());
container.Register<int>(c => 10);
container.AutoWire(test);
Assert.That(test.Foo, Is.Not.Null);
Assert.That(test.Bar, Is.Not.Null);
Assert.That(test.Foo2 as Foo, Is.Null);
Assert.That(test.Names, Is.Not.Null);
Assert.That(test.Age, Is.EqualTo(0));
}
public class DependencyWithBuiltInTypes
{
public DependencyWithBuiltInTypes()
{
this.String = "A String";
this.Age = 27;
}
public IFoo Foo { get; set; }
public IBar Bar { get; set; }
public string String { get; set; }
public int Age { get; set; }
}
[Test]
public void Does_not_AutoWire_BuiltIn_BCL_and_ValueTypes()
{
var container = new Container();
container.Register<IFoo>(c => new Foo());
container.Register<IBar>(c => new Bar());
//Should not be autowired
container.Register<string>(c => "Replaced String");
container.Register<int>(c => 99);
container.RegisterAutoWired<DependencyWithBuiltInTypes>();
var test = container.Resolve<DependencyWithBuiltInTypes>();
Assert.That(test.Foo, Is.Not.Null);
Assert.That(test.Bar, Is.Not.Null);
Assert.That(test.String, Is.EqualTo("A String"));
Assert.That(test.Age, Is.EqualTo(27));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using ServiceStack.ServiceHost.Tests.Support;
using Funq;
namespace ServiceStack.ServiceHost.Tests
{
[TestFixture]
public class IoCTests
{
[Test]
public void Can_AutoWire_types_dynamically_with_expressions()
{
var serviceType = typeof(AutoWireService);
var container = new Container();
container.Register<IFoo>(c => new Foo());
container.Register<IBar>(c => new Bar());
container.Register<int>(c => 100);
container.RegisterAutoWiredType(serviceType);
var service = container.Resolve<AutoWireService>();
Assert.That(service.Foo, Is.Not.Null);
Assert.That(service.Bar, Is.Not.Null);
Assert.That(service.Count, Is.EqualTo(0));
}
public class Test
{
public IFoo Foo { get; set; }
public IBar Bar { get; set; }
public IFoo Foo2 { get; set; }
public IEnumerable<string> Names { get; set; }
public int Age { get; set; }
public Test()
{
this.Foo2 = new Foo2();
this.Names = new List<string>() { "Steffen", "Demis" };
}
}
[Test]
public void Can_AutoWire_Existing_Instance()
{
var test = new Test();
var container = new Container();
container.Register<IFoo>(c => new Foo());
container.Register<IBar>(c => new Bar());
container.Register<int>(c => 10);
container.AutoWire(test);
Assert.That(test.Foo, Is.Not.Null);
Assert.That(test.Bar, Is.Not.Null);
Assert.That(test.Foo2 as Foo, Is.Null);
Assert.That(test.Names, Is.Not.Null);
Assert.That(test.Age, Is.EqualTo(0));
}
}
}
|
bsd-3-clause
|
C#
|
2b28664283405cfb935025b7ec8247bef8317bbd
|
Update version
|
agileharbor/shipStationAccess
|
src/Global/GlobalAssemblyInfo.cs
|
src/Global/GlobalAssemblyInfo.cs
|
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ShipStationAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ShipStation webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// 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.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "1.3.72.0" ) ]
|
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ShipStationAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ShipStation webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// 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.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "1.3.71.0" ) ]
|
bsd-3-clause
|
C#
|
db0af2d7e85e051d0e4392b75a1a9eb899a11d15
|
update assembly version
|
agileharbor/shipStationAccess
|
src/Global/GlobalAssemblyInfo.cs
|
src/Global/GlobalAssemblyInfo.cs
|
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ShipStationAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ShipStation webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// 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.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "1.3.60.0" ) ]
|
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ShipStationAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ShipStation webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// 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.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "1.3.59.0" ) ]
|
bsd-3-clause
|
C#
|
71a88b7d182df3b241723413e649833fca29d8fd
|
Update XssFilterMiddlewareTests.cs
|
ziyasal/helmet.net
|
Helmet.Net.Tests/XssFilterMiddlewareTests.cs
|
Helmet.Net.Tests/XssFilterMiddlewareTests.cs
|
using NUnit.Framework;
namespace Helmet.Net.Tests
{
public class XssFilterMiddlewareTests : TestBase
{
[Test]
public async Task HelloTest()
{
Assert.IsTrue(true);
}
}
}
|
namespace Helmet.Net.Tests
{
public class XssFilterMiddlewareTests : TestBase
{
[Test]
public async Task HelloTest()
{
Assert.IsTrue(true);
}
}
}
|
mit
|
C#
|
a28056f8483244d8457f7a37539f938506153421
|
add enrichers to logs
|
dicko2/BlueGreenDeployTestWebApp,dicko2/BlueGreenDeployTestWebApp
|
Hostsol.Demo.BlueGreenTestWeb/Global.asax.cs
|
Hostsol.Demo.BlueGreenTestWeb/Global.asax.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Http;
using System.Web.Routing;
using Serilog;
using System.Configuration;
using System.Reflection;
using System.Web.Hosting;
using System.Web.Compilation;
namespace Hostsol.Demo.BlueGreenTestWeb
{
public class MvcApplication : System.Web.HttpApplication
{
private readonly Assembly _assembly = HostingEnvironment.IsHosted
? BuildManager.GetGlobalAsaxType().BaseType.Assembly
: Assembly.GetEntryAssembly()
?? Assembly.GetExecutingAssembly();
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Log.Logger = new LoggerConfiguration()
.Enrich.WithProperty("MachineName",Environment.MachineName)
.Enrich.WithProperty("AppName", _assembly.GetName().Name)
.Enrich.WithProperty("AppVersion", _assembly.GetName().Version)
.WriteTo.ColoredConsole()
.WriteTo.Seq(ConfigurationManager.AppSettings["SeqServerUrl"])
.CreateLogger();
//emulate long warmup process
System.Threading.Thread.Sleep(10000);
StartUpComplete = true;
}
public static bool StartUpComplete = false;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Http;
using System.Web.Routing;
using Serilog;
using System.Configuration;
namespace Hostsol.Demo.BlueGreenTestWeb
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Log.Logger = new LoggerConfiguration()
.WriteTo.ColoredConsole()
.WriteTo.Seq(ConfigurationManager.AppSettings["SeqServerUrl"])
.CreateLogger();
//emulate long warmup process
System.Threading.Thread.Sleep(10000);
StartUpComplete = true;
}
public static bool StartUpComplete = false;
}
}
|
mit
|
C#
|
124c2d8847798436a07f6e12acfe555ca4cedb49
|
fix build issue, renamed field should not have happened during previous merge
|
abelsilva/swaggerwcf
|
src/SwaggerWcf/Attributes/SwaggerWcfAttribute.cs
|
src/SwaggerWcf/Attributes/SwaggerWcfAttribute.cs
|
using System;
namespace SwaggerWcf.Attributes
{
/// <summary>
/// Attribute to enable a class or interface to be scanned by SwaggerWcf
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)]
public class SwaggerWcfAttribute : Attribute
{
/// <summary>
/// The base path on which the API is served, which is relative to the host. If it is not included,
/// the API is served directly under the host. The value MUST start with a leading slash (/). The
/// basePath does not support path templating.
/// </summary>
public string ServicePath { get; set; }
/// <summary>
/// Export this service on Swagger file
/// </summary>
public SwaggerWcfAttribute()
{
}
/// <summary>
/// Export this service on Swagger file with base path of <paramref name="servicePath"/>
/// </summary>
/// <param name="servicePath">Service path</param>
public SwaggerWcfAttribute(string servicePath)
{
ServicePath = servicePath.StartsWith("/") ? servicePath : $"/{servicePath}";
}
}
}
|
using System;
namespace SwaggerWcf.Attributes
{
/// <summary>
/// Attribute to enable a class or interface to be scanned by SwaggerWcf
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)]
public class SwaggerWcfAttribute : Attribute
{
/// <summary>
/// The base path on which the API is served, which is relative to the host. If it is not included,
/// the API is served directly under the host. The value MUST start with a leading slash (/). The
/// basePath does not support path templating.
/// </summary>
public string BasePath { get; set; }
/// <summary>
/// Export this service on Swagger file
/// </summary>
public SwaggerWcfAttribute()
{
}
/// <summary>
/// Export this service on Swagger file with base path of <paramref name="servicePath"/>
/// </summary>
/// <param name="servicePath">Service path</param>
public SwaggerWcfAttribute(string servicePath)
{
BasePath = servicePath.StartsWith("/") ? servicePath : $"/{servicePath}";
}
}
}
|
apache-2.0
|
C#
|
afebd88d455b5fc26c6e7058d304f702d7388e38
|
Update ImageProcessorLogger - to use the new Error logger method that contains only an ex - and under the hood it will pass on an empty string to the message
|
bjarnef/Umbraco-CMS,abjerner/Umbraco-CMS,leekelleher/Umbraco-CMS,KevinJump/Umbraco-CMS,lars-erik/Umbraco-CMS,arknu/Umbraco-CMS,WebCentrum/Umbraco-CMS,bjarnef/Umbraco-CMS,robertjf/Umbraco-CMS,rasmuseeg/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,leekelleher/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,lars-erik/Umbraco-CMS,hfloyd/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,hfloyd/Umbraco-CMS,hfloyd/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,bjarnef/Umbraco-CMS,lars-erik/Umbraco-CMS,tompipe/Umbraco-CMS,lars-erik/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,tcmorris/Umbraco-CMS,arknu/Umbraco-CMS,tcmorris/Umbraco-CMS,abryukhov/Umbraco-CMS,NikRimington/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,WebCentrum/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,leekelleher/Umbraco-CMS,rasmuseeg/Umbraco-CMS,hfloyd/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,mattbrailsford/Umbraco-CMS,tompipe/Umbraco-CMS,tompipe/Umbraco-CMS,NikRimington/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,rasmuseeg/Umbraco-CMS,tcmorris/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,madsoulswe/Umbraco-CMS,tcmorris/Umbraco-CMS,leekelleher/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,bjarnef/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,madsoulswe/Umbraco-CMS,lars-erik/Umbraco-CMS,madsoulswe/Umbraco-CMS,WebCentrum/Umbraco-CMS,tcmorris/Umbraco-CMS,NikRimington/Umbraco-CMS,tcmorris/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,hfloyd/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,leekelleher/Umbraco-CMS,marcemarc/Umbraco-CMS
|
src/Umbraco.Core/Logging/ImageProcessorLogger.cs
|
src/Umbraco.Core/Logging/ImageProcessorLogger.cs
|
using System;
using System.Runtime.CompilerServices;
using ImageProcessor.Common.Exceptions;
using Umbraco.Core.Composing;
namespace Umbraco.Core.Logging
{
/// <summary>
/// A logger for explicitly logging ImageProcessor exceptions.
/// <remarks>
/// Creating this logger is enough for ImageProcessor to find and replace its in-built debug logger
/// without any additional configuration required. This class currently has to be public in order
/// to do so.
/// </remarks>
/// </summary>
public sealed class ImageProcessorLogger : ImageProcessor.Common.Exceptions.ILogger
{
/// <summary>
/// Logs the specified message as an error.
/// </summary>
/// <typeparam name="T">The type calling the logger.</typeparam>
/// <param name="text">The message to log.</param>
/// <param name="callerName">The property or method name calling the log.</param>
/// <param name="lineNumber">The line number where the method is called.</param>
public void Log<T>(string text, [CallerMemberName] string callerName = null, [CallerLineNumber] int lineNumber = 0)
{
// Using LogHelper since the ImageProcessor logger expects a parameterless constructor.
var message = $"{callerName} {lineNumber} : {text}";
Current.Logger.Error<T>(new ImageProcessingException(message));
}
/// <summary>
/// Logs the specified message as an error.
/// </summary>
/// <param name="type">The type calling the logger.</param>
/// <param name="text">The message to log.</param>
/// <param name="callerName">The property or method name calling the log.</param>
/// <param name="lineNumber">The line number where the method is called.</param>
public void Log(Type type, string text, [CallerMemberName] string callerName = null, [CallerLineNumber] int lineNumber = 0)
{
// Using LogHelper since the ImageProcessor logger expects a parameterless constructor.
var message = $"{callerName} {lineNumber} : {text}";
Current.Logger.Error(type, new ImageProcessingException(message));
}
}
}
|
using System;
using System.Runtime.CompilerServices;
using ImageProcessor.Common.Exceptions;
using Umbraco.Core.Composing;
namespace Umbraco.Core.Logging
{
/// <summary>
/// A logger for explicitly logging ImageProcessor exceptions.
/// <remarks>
/// Creating this logger is enough for ImageProcessor to find and replace its in-built debug logger
/// without any additional configuration required. This class currently has to be public in order
/// to do so.
/// </remarks>
/// </summary>
public sealed class ImageProcessorLogger : ImageProcessor.Common.Exceptions.ILogger
{
/// <summary>
/// Logs the specified message as an error.
/// </summary>
/// <typeparam name="T">The type calling the logger.</typeparam>
/// <param name="text">The message to log.</param>
/// <param name="callerName">The property or method name calling the log.</param>
/// <param name="lineNumber">The line number where the method is called.</param>
public void Log<T>(string text, [CallerMemberName] string callerName = null, [CallerLineNumber] int lineNumber = 0)
{
// Using LogHelper since the ImageProcessor logger expects a parameterless constructor.
var message = $"{callerName} {lineNumber} : {text}";
Current.Logger.Error<T>(new ImageProcessingException(message), string.Empty);
}
/// <summary>
/// Logs the specified message as an error.
/// </summary>
/// <param name="type">The type calling the logger.</param>
/// <param name="text">The message to log.</param>
/// <param name="callerName">The property or method name calling the log.</param>
/// <param name="lineNumber">The line number where the method is called.</param>
public void Log(Type type, string text, [CallerMemberName] string callerName = null, [CallerLineNumber] int lineNumber = 0)
{
// Using LogHelper since the ImageProcessor logger expects a parameterless constructor.
var message = $"{callerName} {lineNumber} : {text}";
Current.Logger.Error(type, new ImageProcessingException(message), string.Empty);
}
}
}
|
mit
|
C#
|
ca772b60b183e33d0c42896f5340088c5f3206b8
|
Use regular test steps rather than one-time set up and scheduling
|
peppy/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu-new,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,peppy/osu,smoogipooo/osu,ppy/osu
|
osu.Game.Tests/Visual/Ranking/TestSceneStarRatingDisplay.cs
|
osu.Game.Tests/Visual/Ranking/TestSceneStarRatingDisplay.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 NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Screens.Ranking.Expanded;
namespace osu.Game.Tests.Visual.Ranking
{
public class TestSceneStarRatingDisplay : OsuTestScene
{
[Test]
public void TestDisplay()
{
StarRatingDisplay changingStarRating = null;
AddStep("load displays", () => Child = new FillFlowContainer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
new StarRatingDisplay(new StarDifficulty(1.23, 0)),
new StarRatingDisplay(new StarDifficulty(2.34, 0)),
new StarRatingDisplay(new StarDifficulty(3.45, 0)),
new StarRatingDisplay(new StarDifficulty(4.56, 0)),
new StarRatingDisplay(new StarDifficulty(5.67, 0)),
new StarRatingDisplay(new StarDifficulty(6.78, 0)),
new StarRatingDisplay(new StarDifficulty(10.11, 0)),
changingStarRating = new StarRatingDisplay(),
}
});
AddRepeatStep("change bottom rating", () =>
{
changingStarRating.Current.Value = new StarDifficulty(RNG.NextDouble(0, 10), RNG.Next());
}, 10);
}
}
}
|
// 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.Framework.Graphics.Containers;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Screens.Ranking.Expanded;
namespace osu.Game.Tests.Visual.Ranking
{
public class TestSceneStarRatingDisplay : OsuTestScene
{
[SetUp]
public void SetUp() => Schedule(() =>
{
StarRatingDisplay changingStarRating;
Child = new FillFlowContainer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
new StarRatingDisplay(new StarDifficulty(1.23, 0)),
new StarRatingDisplay(new StarDifficulty(2.34, 0)),
new StarRatingDisplay(new StarDifficulty(3.45, 0)),
new StarRatingDisplay(new StarDifficulty(4.56, 0)),
new StarRatingDisplay(new StarDifficulty(5.67, 0)),
new StarRatingDisplay(new StarDifficulty(6.78, 0)),
new StarRatingDisplay(new StarDifficulty(10.11, 0)),
changingStarRating = new StarRatingDisplay(),
}
};
Scheduler.AddDelayed(() =>
{
changingStarRating.Current.Value = new StarDifficulty(RNG.NextDouble(0, 10), RNG.Next());
}, 500, true);
});
}
}
|
mit
|
C#
|
20d9351500dee0d0bcdf5b97715a44ce732d5dac
|
Remove unused code
|
lpatalas/NhLogAnalyzer
|
NhLogAnalyzer/Infrastructure/StatementRow.cs
|
NhLogAnalyzer/Infrastructure/StatementRow.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NhLogAnalyzer.Infrastructure
{
public class StatementRow : IEquatable<StatementRow>
{
public int Id { get; set; }
public string SqlText { get; set; }
public string StackTrace { get; set; }
public DateTime Timestamp { get; set; }
public StatementRow()
{
}
public StatementRow(int id, string sqlText, string stackTrace, DateTime timestamp)
{
this.Id = id;
this.SqlText = sqlText;
this.StackTrace = stackTrace;
this.Timestamp = timestamp;
}
public override bool Equals(object obj)
{
var other = obj as StatementRow;
return this.Equals(other);
}
public bool Equals(StatementRow other)
{
return other != null
&& this.Id == other.Id
&& string.Equals(this.SqlText, other.SqlText, StringComparison.Ordinal)
&& string.Equals(this.StackTrace, other.StackTrace, StringComparison.Ordinal)
&& this.Timestamp == other.Timestamp;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NhLogAnalyzer.Infrastructure
{
public class StatementRow : IEquatable<StatementRow>
{
public int Id { get; set; }
public string SqlText { get; set; }
public string StackTrace { get; set; }
public DateTime Timestamp { get; set; }
public StatementRow()
{
}
public StatementRow(int id, string sqlText, string stackTrace, DateTime timestamp)
{
this.Id = id;
this.SqlText = sqlText;
this.StackTrace = stackTrace;
this.Timestamp = timestamp;
}
public override bool Equals(object obj)
{
var other = obj as StatementRow;
return this.Equals(other);
}
public bool Equals(StatementRow other)
{
return other != null
&& this.Id == other.Id
&& string.Equals(this.SqlText, other.SqlText, StringComparison.Ordinal)
&& string.Equals(this.StackTrace, other.StackTrace, StringComparison.Ordinal)
&& this.Timestamp == other.Timestamp;
}
private static bool DateTimeEqualsWithSecondPrecision(DateTime first, DateTime second)
{
return RoundToSeconds(first) == RoundToSeconds(second);
}
private static DateTime RoundToSeconds(DateTime dateTime)
{
return new DateTime(dateTime.Ticks / 10000000);
}
}
}
|
mit
|
C#
|
aa29734cef22eaf459f84b0e942f22f77f53b709
|
Fix `KendoAutoCompleteTests`
|
atata-framework/atata-kendoui,atata-framework/atata-kendoui
|
test/Atata.KendoUI.Tests/KendoAutoCompleteTests.cs
|
test/Atata.KendoUI.Tests/KendoAutoCompleteTests.cs
|
using NUnit.Framework;
namespace Atata.KendoUI.Tests
{
public class KendoAutoCompleteTests : UITestFixture
{
private static AutoCompletePage GoToTestPage()
{
return Go.To<AutoCompletePage>();
}
[PlainTestCaseSource(KendoLibrary.JQuery, KendoLibrary.Vue, KendoLibrary.Angular)]
public void KendoAutoComplete(KendoLibrary library)
{
var control = GoToSnippetPage(library)
.Get<KendoAutoComplete<SnippetPage>>();
TestControl(control);
}
[Test]
public void ReactKendoAutoComplete()
{
var control = GoToSnippetPage(KendoLibrary.React)
.Get<ReactKendoAutoComplete<SnippetPage>>();
TestControl(control);
}
[Test]
public void KendoAutoComplete_Disabled()
{
var control = GoToTestPage().Disabled;
control.Should.BeDisabled();
control.Should.Not.BeReadOnly();
control.Should.Equal("Spain");
}
[Test]
public void KendoAutoComplete_ReadOnly()
{
var control = GoToTestPage().ReadOnly;
control.Should.BeEnabled();
control.Should.BeReadOnly();
control.Should.Equal("Norway");
}
private static void TestControl<TPage>(KendoAutoComplete<string, TPage> control)
where TPage : PageObject<TPage>
{
control.Should.BeEnabled();
control.Should.Not.BeReadOnly();
control.Set("France");
control.Should.Equal("France");
control.Set("Germany, Austria");
control.Should.Equal("Germany, Austria");
control.Clear();
control.Should.BeEmpty();
}
}
}
|
using NUnit.Framework;
namespace Atata.KendoUI.Tests
{
public class KendoAutoCompleteTests : UITestFixture
{
private static AutoCompletePage GoToTestPage()
{
return Go.To<AutoCompletePage>();
}
[PlainTestCaseSource(KendoLibrary.JQuery, KendoLibrary.Vue, KendoLibrary.Angular)]
public void KendoAutoComplete(KendoLibrary library)
{
var control = GoToSnippetPage(library)
.Get<KendoAutoComplete<SnippetPage>>();
TestControl(control);
}
[Test]
public void ReactKendoAutoComplete()
{
var control = GoToSnippetPage(KendoLibrary.React)
.Get<ReactKendoAutoComplete<SnippetPage>>();
TestControl(control);
}
[Test]
public void KendoAutoComplete_Disabled()
{
var control = GoToTestPage().Disabled;
control.Should.BeDisabled();
control.Should.Not.BeReadOnly();
control.Should.Equal("Spain");
}
[Test]
public void KendoAutoComplete_ReadOnly()
{
var control = GoToTestPage().ReadOnly;
control.Should.BeEnabled();
control.Should.BeReadOnly();
control.Should.Equal("Norway");
}
private static void TestControl<TPage>(KendoAutoComplete<string, TPage> control)
where TPage : PageObject<TPage>
{
control.Should.BeEnabled();
control.Should.Not.BeReadOnly();
control.Set("France");
control.Should.Equal("France");
control.Set("Germany, Austria");
control.Should.Equal("Germany, Austria");
control.Clear();
control.Should.BeNull();
}
}
}
|
apache-2.0
|
C#
|
eb869ed023a76e0420505d02366e8acce9ae1ffb
|
add indexData tests
|
bertt/quantized-mesh-tile-cs,bertt/quantized-mesh-tile-cs
|
tests/quantized-mesh-tile-cs.tests/QuantizedMeshTileParserTests.cs
|
tests/quantized-mesh-tile-cs.tests/QuantizedMeshTileParserTests.cs
|
using NUnit.Framework;
using System.Reflection;
namespace Quantized.Mesh.Tile.Tests
{
public class QuantizedMeshTileParserTests
{
[Test]
public void TestFirstTileParsing()
{
// arrange
const string firstTerrainFile = "Quantized.Mesh.Tile.Tests.data.9_533_383.terrain";
// act
var pbfStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(firstTerrainFile);
var qmt = QuantizedMeshTileParser.Parse(pbfStream);
// assert
Assert.IsTrue(qmt != null);
// check headers
Assert.IsTrue(qmt.Header.CenterX == 4492197.38443436);
Assert.IsTrue(qmt.Header.CenterY == 596134.0874495716);
Assert.IsTrue(qmt.Header.CenterZ == 4473851.280340988);
Assert.IsTrue(qmt.Header.MinimumHeight == 206.3408660888672);
Assert.IsTrue(qmt.Header.MaximumHeight == 787.9429931640625);
Assert.IsTrue(qmt.Header.BoundingSphereCenterX == 4492197.38443436);
Assert.IsTrue(qmt.Header.BoundingSphereCenterY == 596134.0874495716);
Assert.IsTrue(qmt.Header.BoundingSphereCenterZ == 4473851.280340988);
Assert.IsTrue(qmt.Header.BoundingSphereRadius== 24100.511082898243);
Assert.IsTrue(qmt.Header.HorizonOcclusionPointX== 0.5);
Assert.IsTrue(qmt.Header.HorizonOcclusionPointY == 0.5);
Assert.IsTrue(qmt.Header.HorizonOcclusionPointZ == 0.5);
// check vertexdata
Assert.IsTrue(qmt.VertexData.vertexCount==103);
Assert.IsTrue(qmt.VertexData.u[0] == 21075);
Assert.IsTrue(qmt.VertexData.v[0] == 26684);
Assert.IsTrue(qmt.VertexData.height[0] == 543);
// check IndexData
Assert.IsTrue(qmt.IndexData16.indices.Length == 381);
Assert.IsTrue(qmt.IndexData16.indices[0]== 0);
Assert.IsTrue(qmt.IndexData16.indices[qmt.IndexData16.indices.Length-1] == 100);
Assert.IsTrue(qmt.IndexData16.indices.Length/3 == qmt.IndexData16.triangleCount);
}
}
}
|
using NUnit.Framework;
using System.Reflection;
namespace Quantized.Mesh.Tile.Tests
{
public class QuantizedMeshTileParserTests
{
[Test]
public void TestFirstTileParsing()
{
// arrange
const string firstTerrainFile = "Quantized.Mesh.Tile.Tests.data.9_533_383.terrain";
// act
var pbfStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(firstTerrainFile);
var qmt = QuantizedMeshTileParser.Parse(pbfStream);
// assert
Assert.IsTrue(qmt != null);
// check headers
Assert.IsTrue(qmt.Header.CenterX == 4492197.38443436);
Assert.IsTrue(qmt.Header.CenterY == 596134.0874495716);
Assert.IsTrue(qmt.Header.CenterZ == 4473851.280340988);
Assert.IsTrue(qmt.Header.MinimumHeight == 206.3408660888672);
Assert.IsTrue(qmt.Header.MaximumHeight == 787.9429931640625);
Assert.IsTrue(qmt.Header.BoundingSphereCenterX == 4492197.38443436);
Assert.IsTrue(qmt.Header.BoundingSphereCenterY == 596134.0874495716);
Assert.IsTrue(qmt.Header.BoundingSphereCenterZ == 4473851.280340988);
Assert.IsTrue(qmt.Header.BoundingSphereRadius== 24100.511082898243);
Assert.IsTrue(qmt.Header.HorizonOcclusionPointX== 0.5);
Assert.IsTrue(qmt.Header.HorizonOcclusionPointY == 0.5);
Assert.IsTrue(qmt.Header.HorizonOcclusionPointZ == 0.5);
// check vertexdata
Assert.IsTrue(qmt.VertexData.vertexCount==103);
Assert.IsTrue(qmt.VertexData.u[0] == 21075);
Assert.IsTrue(qmt.VertexData.v[0] == 26684);
Assert.IsTrue(qmt.VertexData.height[0] == 543);
// todo: check IndexData, EdgeIndices, extensions
}
}
}
|
mit
|
C#
|
fc6284b311ce91dc55e10dc53dce673a05f75de7
|
Bump version to 3.6.1
|
SharpeRAD/RazorEngine,csantero/RazorEngine,bcuff/RazorEngine,HongJunRen/RazorEngine,bcuff/RazorEngine,csantero/RazorEngine,Antaris/RazorEngine,MetSystem/RazorEngine,MetSystem/RazorEngine,SharpeRAD/RazorEngine,HongJunRen/RazorEngine,Antaris/RazorEngine,aviatrix/RazorEngine,aviatrix/RazorEngine
|
src/SharedAssemblyInfo.cs
|
src/SharedAssemblyInfo.cs
|
// <auto-generated/>
using System.Reflection;
[assembly: AssemblyCompanyAttribute("RazorEngine")]
[assembly: AssemblyProductAttribute("RazorEngine")]
[assembly: AssemblyCopyrightAttribute("Copyright � RazorEngine Project 2011-2014")]
[assembly: AssemblyVersionAttribute("3.6.1")]
[assembly: AssemblyFileVersionAttribute("3.6.1")]
[assembly: AssemblyInformationalVersionAttribute("3.6.1")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "3.6.1";
}
}
|
// <auto-generated/>
using System.Reflection;
[assembly: AssemblyCompanyAttribute("RazorEngine")]
[assembly: AssemblyProductAttribute("RazorEngine")]
[assembly: AssemblyCopyrightAttribute("Copyright � RazorEngine Project 2011-2014")]
[assembly: AssemblyVersionAttribute("3.6.0")]
[assembly: AssemblyFileVersionAttribute("3.6.0")]
[assembly: AssemblyInformationalVersionAttribute("3.6.0")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "3.6.0";
}
}
|
apache-2.0
|
C#
|
7ff67566ec6d337c68e865b95d08d2f3a2d55eb9
|
Fix argument order in Linux.Native.Library.Load documentation
|
DrabWeb/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,Tom94/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,ZLima12/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ppy/osu-framework
|
osu.Framework/Platform/Linux/Native/Library.cs
|
osu.Framework/Platform/Linux/Native/Library.cs
|
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace osu.Framework.Platform.Linux.Native
{
public static class Library
{
[DllImport("libdl.so", EntryPoint = "dlopen")]
private static extern IntPtr dlopen(string library, LoadFlags flags);
/// <summary>
/// Loads a library with flags to use with dlopen. Uses <see cref="LoadFlags"/> for the flags
///
/// Uses NATIVE_DLL_SEARCH_DIRECTORIES and then ld.so for library paths
/// </summary>
/// <param name="library">Full name of the library</param>
/// <param name="flags">See 'man dlopen' for more information.</param>
public static void Load(string library, LoadFlags flags)
{
var paths = (string)AppContext.GetData("NATIVE_DLL_SEARCH_DIRECTORIES");
foreach (var path in paths.Split(':'))
{
if (dlopen(Path.Combine(path, library), flags) != IntPtr.Zero)
break;
}
}
[Flags]
public enum LoadFlags
{
RTLD_LAZY = 0x00001,
RTLD_NOW = 0x00002,
RTLD_BINDING_MASK = 0x00003,
RTLD_NOLOAD = 0x00004,
RTLD_DEEPBIND = 0x00008,
RTLD_GLOBAL = 0x00100,
RTLD_LOCAL = 0x00000,
RTLD_NODELETE = 0x01000
}
}
}
|
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace osu.Framework.Platform.Linux.Native
{
public static class Library
{
[DllImport("libdl.so", EntryPoint = "dlopen")]
private static extern IntPtr dlopen(string library, LoadFlags flags);
/// <summary>
/// Loads a library with flags to use with dlopen. Uses <see cref="LoadFlags"/> for the flags
///
/// Uses NATIVE_DLL_SEARCH_DIRECTORIES and then ld.so for library paths
/// </summary>
/// <param name="flags">See 'man dlopen' for more information.</param>
/// <param name="library">Full name of the library</param>
public static void Load(string library, LoadFlags flags)
{
var paths = (string)AppContext.GetData("NATIVE_DLL_SEARCH_DIRECTORIES");
foreach (var path in paths.Split(':'))
{
if (dlopen(Path.Combine(path, library), flags) != IntPtr.Zero)
break;
}
}
[Flags]
public enum LoadFlags
{
RTLD_LAZY = 0x00001,
RTLD_NOW = 0x00002,
RTLD_BINDING_MASK = 0x00003,
RTLD_NOLOAD = 0x00004,
RTLD_DEEPBIND = 0x00008,
RTLD_GLOBAL = 0x00100,
RTLD_LOCAL = 0x00000,
RTLD_NODELETE = 0x01000
}
}
}
|
mit
|
C#
|
49bec2c021da6c3ac97f6ecac0422d4d7d8512a4
|
Correct names for http verbs
|
brecons/brecons-tag-helper
|
BSolutions.Brecons/BSolutions.Brecons.Core/Enumerations/HttpVerb.cs
|
BSolutions.Brecons/BSolutions.Brecons.Core/Enumerations/HttpVerb.cs
|
//-----------------------------------------------------------------------
// <copyright file="HttpVerb.cs" company="Bremus Solutions">
// Copyright (c) Bremus Solutions. All rights reserved.
// </copyright>
// <author>Timm Bremus</author>
// <license>
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// </license>
//-----------------------------------------------------------------------
namespace BSolutions.Brecons.Core.Enumerations
{
using BSolutions.Brecons.Core.Attributes.Enumerations;
public enum HttpVerb
{
[EnumInfo("GET")]
Get,
[EnumInfo("POST")]
Post,
[EnumInfo("PUT")]
Put,
[EnumInfo("DELETE")]
Delete
}
}
|
//-----------------------------------------------------------------------
// <copyright file="HttpVerb.cs" company="Bremus Solutions">
// Copyright (c) Bremus Solutions. All rights reserved.
// </copyright>
// <author>Timm Bremus</author>
// <license>
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// </license>
//-----------------------------------------------------------------------
namespace BSolutions.Brecons.Core.Enumerations
{
using BSolutions.Brecons.Core.Attributes.Enumerations;
public enum HttpVerb
{
[EnumInfo("get")]
Get,
[EnumInfo("Post")]
Post,
[EnumInfo("Put")]
Put,
[EnumInfo("Delete")]
Delete
}
}
|
apache-2.0
|
C#
|
7109ac6b3d6115ef9abc1b4ef7a87a462a52c686
|
Fix typo
|
amay077/Xamarin.Forms.GoogleMaps,JKennedy24/Xamarin.Forms.GoogleMaps,JKennedy24/Xamarin.Forms.GoogleMaps,quesera2/Xamarin.Forms.GoogleMaps
|
Xamarin.Forms.GoogleMaps/Xamarin.Forms.GoogleMaps.Android/Extensions/LatLngExtensions.cs
|
Xamarin.Forms.GoogleMaps/Xamarin.Forms.GoogleMaps.Android/Extensions/LatLngExtensions.cs
|
using System;
using Android.Gms.Maps.Model;
namespace Xamarin.Forms.GoogleMaps.Android.Extensions
{
internal static class LatLngExtensions
{
public static Position ToPosition(this LatLng self)
{
return new Position(self.Latitude, self.Longitude);
}
}
}
|
using System;
using Android.Gms.Maps.Model;
namespace Xamarin.Forms.GoogleMaps.Android.Extensions
{
internal static class LatLngExtensions
{
public static Position ToPosition(this LatLng self)
{
return new Position(self.Longitude, self.Longitude);
}
}
}
|
mit
|
C#
|
798b6c0c38c8dcc2808c8d00532c73e13222a1dd
|
Update FillDrawNode.cs
|
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
|
src/Core2D/Modules/Renderer/SkiaSharp/Nodes/FillDrawNode.cs
|
src/Core2D/Modules/Renderer/SkiaSharp/Nodes/FillDrawNode.cs
|
#nullable enable
using Core2D.Model.Renderer.Nodes;
using Core2D.ViewModels.Style;
using SkiaSharp;
namespace Core2D.Modules.Renderer.SkiaSharp.Nodes;
internal class FillDrawNode : DrawNode, IFillDrawNode
{
public SKRect Rect { get; set; }
public BaseColorViewModel? Color { get; set; }
public double X { get; set; }
public double Y { get; set; }
public double Width { get; set; }
public double Height { get; set; }
public FillDrawNode(double x, double y, double width, double height, BaseColorViewModel color)
{
X = x;
Y = y;
Width = width;
Height = height;
Color = color;
UpdateGeometry();
}
public sealed override void UpdateGeometry()
{
ScaleThickness = false;
ScaleSize = false;
Rect = SKRect.Create((float)X, (float)Y, (float)Width, (float)Height);
Center = new SKPoint(Rect.MidX, Rect.MidY);
}
public override void UpdateStyle()
{
if (Color is { })
{
Fill = SkiaSharpDrawUtil.ToSKPaintBrush(Color);
}
}
public override void Draw(object? dc, double zoom)
{
OnDraw(dc, zoom);
}
public override void OnDraw(object? dc, double zoom)
{
if (dc is not SKCanvas canvas)
{
return;
}
if (!Rect.IsEmpty)
{
canvas.DrawRect(Rect, Fill);
}
}
}
|
#nullable enable
using Core2D.Model.Renderer.Nodes;
using Core2D.ViewModels.Style;
using SkiaSharp;
namespace Core2D.Modules.Renderer.SkiaSharp.Nodes;
internal class FillDrawNode : DrawNode, IFillDrawNode
{
public SKRect Rect { get; set; }
public BaseColorViewModel Color { get; set; }
public double X { get; set; }
public double Y { get; set; }
public double Width { get; set; }
public double Height { get; set; }
public FillDrawNode(double x, double y, double width, double height, BaseColorViewModel color)
{
X = x;
Y = y;
Width = width;
Height = height;
Color = color;
UpdateGeometry();
}
public sealed override void UpdateGeometry()
{
ScaleThickness = false;
ScaleSize = false;
Rect = SKRect.Create((float)X, (float)Y, (float)Width, (float)Height);
Center = new SKPoint(Rect.MidX, Rect.MidY);
}
public override void UpdateStyle()
{
Fill = SkiaSharpDrawUtil.ToSKPaintBrush(Color);
}
public override void Draw(object? dc, double zoom)
{
OnDraw(dc, zoom);
}
public override void OnDraw(object? dc, double zoom)
{
if (dc is not SKCanvas canvas)
{
return;
}
if (!Rect.IsEmpty)
{
canvas.DrawRect(Rect, Fill);
}
}
}
|
mit
|
C#
|
9234e3f7a2d68266111a0c2447c695da07e24b90
|
Mark the "Auto" variable scope as not expensive
|
PowerShell/PowerShellEditorServices
|
src/PowerShellEditorServices.Protocol/DebugAdapter/Scope.cs
|
src/PowerShellEditorServices.Protocol/DebugAdapter/Scope.cs
|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
namespace Microsoft.PowerShell.EditorServices.Protocol.DebugAdapter
{
public class Scope
{
/// <summary>
/// Gets or sets the name of the scope (as such 'Arguments', 'Locals')
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the variables of this scope can be retrieved by passing the
/// value of variablesReference to the VariablesRequest.
/// </summary>
public int VariablesReference { get; set; }
/// <summary>
/// Gets or sets a boolean value indicating if number of variables in
/// this scope is large or expensive to retrieve.
/// </summary>
public bool Expensive { get; set; }
public static Scope Create(VariableScope scope)
{
return new Scope {
Name = scope.Name,
VariablesReference = scope.Id,
// Temporary fix for #95 to get debug hover tips to work well at least for the local scope.
Expensive = ((scope.Name != VariableContainerDetails.LocalScopeName) &&
(scope.Name != VariableContainerDetails.AutoVariablesName))
};
}
}
}
|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
namespace Microsoft.PowerShell.EditorServices.Protocol.DebugAdapter
{
public class Scope
{
/// <summary>
/// Gets or sets the name of the scope (as such 'Arguments', 'Locals')
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the variables of this scope can be retrieved by passing the
/// value of variablesReference to the VariablesRequest.
/// </summary>
public int VariablesReference { get; set; }
/// <summary>
/// Gets or sets a boolean value indicating if number of variables in
/// this scope is large or expensive to retrieve.
/// </summary>
public bool Expensive { get; set; }
public static Scope Create(VariableScope scope)
{
return new Scope {
Name = scope.Name,
VariablesReference = scope.Id,
// Temporary fix for #95 to get debug hover tips to work well at least for the local scope.
Expensive = (scope.Name != VariableContainerDetails.LocalScopeName)
};
}
}
}
|
mit
|
C#
|
62e59c8826035b0e53cc0ff825e8efd2345c2cac
|
Add property to identity a Channel Notice
|
Fredi/NetIRC
|
src/NetIRC/Messages/NoticeMessage.cs
|
src/NetIRC/Messages/NoticeMessage.cs
|
using System.Collections.Generic;
namespace NetIRC.Messages
{
public class NoticeMessage : IRCMessage, IServerMessage, IClientMessage
{
public string From { get; }
public string Target { get; }
public string Message { get; }
public NoticeMessage(ParsedIRCMessage parsedMessage)
{
From = parsedMessage.Prefix.From;
Target = parsedMessage.Parameters[0];
Message = parsedMessage.Trailing;
}
public NoticeMessage(string target, string text)
{
Target = target;
Message = text;
}
public bool IsChannelMessage => Target[0] == '#';
public IEnumerable<string> Tokens => new[] { "NOTICE", Target, Message };
}
}
|
using System.Collections.Generic;
namespace NetIRC.Messages
{
public class NoticeMessage : IRCMessage, IServerMessage, IClientMessage
{
public string From { get; }
public string Target { get; }
public string Message { get; }
public NoticeMessage(ParsedIRCMessage parsedMessage)
{
From = parsedMessage.Prefix.From;
Target = parsedMessage.Parameters[0];
Message = parsedMessage.Trailing;
}
public NoticeMessage(string target, string text)
{
Target = target;
Message = text;
}
public IEnumerable<string> Tokens => new[] { "NOTICE", Target, Message };
}
}
|
mit
|
C#
|
f6523b7fe9177650ea4c1972d0040fadb858d8cb
|
Add ICreateGitHubRelease component
|
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
|
source/Nuke.Components/ICreateGitHubRelease.cs
|
source/Nuke.Components/ICreateGitHubRelease.cs
|
// Copyright 2022 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Nuke.Common;
using Nuke.Common.ChangeLog;
using Nuke.Common.CI.GitHubActions;
using Nuke.Common.IO;
using Nuke.Common.Tools.GitHub;
using Nuke.Common.Utilities;
using Octokit;
namespace Nuke.Components
{
[PublicAPI]
[ParameterPrefix(GitHubRelease)]
public interface ICreateGitHubRelease : IHazGitRepository, IHazChangelog
{
public const string GitHubRelease = nameof(GitHubRelease);
[Parameter] [Secret] string Token => TryGetValue(() => Token) ?? GitHubActions.Instance.Token;
string Version { get; }
IEnumerable<AbsolutePath> AssetFiles { get; }
Target CreateGitHubRelease => _ => _
.Requires(() => Token)
.Executes(async () =>
{
GitHubTasks.GitHubClient.Credentials = new Credentials(Token);
var release = await GitHubTasks.GitHubClient.Repository.Release.Create(
GitRepository.GetGitHubOwner(),
GitRepository.GetGitHubName(),
new NewRelease(Version)
{
Name = $"v{Version}",
Body = ChangelogTasks.ExtractChangelogSectionNotes(NuGetReleaseNotes).JoinNewLine()
});
var uploadTasks = AssetFiles.Select(async x =>
{
await using var assetFile = File.OpenRead(x);
var asset = new ReleaseAssetUpload
{
FileName = x.Name,
ContentType = "application/octet-stream",
RawData = assetFile
};
await GitHubTasks.GitHubClient.Repository.Release.UploadAsset(release, asset);
}).ToArray();
Task.WaitAll(uploadTasks);
});
}
}
|
// Copyright 2021 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
// using System.Linq;
//
// using Nuke.Common;
// using Nuke.Common.Tools.GitHub;
// using Nuke.GitHub;
//
// using static Nuke.Common.ValueInjection.ValueInjectionUtility;
// using static Nuke.GitHub.GitHubTasks;
//
// public interface ICreateGitHubRelease : INukeBuild
// {
// [Parameter]
// string GitHubToken => TryGetValue(() => GitHubToken);
//
// Target CreateGitHubRelease => _ => _
// .Requires(() => GitHubToken)
// .Executes(async () =>
// {
// await PublishRelease(_ => _
// .SetToken(GitHubToken)
// .WhenNotNull((this as IHazGitRepository)?.GitRepository, (_, repository) => _
// .SetRepositoryOwner(repository.GetGitHubOwner())
// .SetRepositoryName(repository.GetGitHubName())
// .WhenNotNull(repository.Tags.FirstOrDefault(), (_, tag) => _
// .SetName($"v{tag}")
// .SetTag(tag)))
// .WhenNotNull(this as IHazChangelog, (_, o) => _
// .SetReleaseNotes(o.ReleaseNotes))
// .SetArtifactPaths(new string[0]));
// });
// }
|
mit
|
C#
|
dec4ecb21269acc76acbbe69b901112964cee779
|
Add animation path curves to the debug component
|
bartlomiejwolk/AnimationPathAnimator
|
AnimationPathCurvesDebug.cs
|
AnimationPathCurvesDebug.cs
|
using UnityEngine;
using System.Collections;
using ATP.AnimationPathTools;
[ExecuteInEditMode]
public class AnimationPathCurvesDebug : MonoBehaviour {
private AnimationPathAnimator animator;
private AnimationPath animationPath;
[Header("Animation Path")]
public AnimationCurve pathCurveX;
public AnimationCurve pathCurveY;
public AnimationCurve pathCurveZ;
[Header("Rotation curves")]
public AnimationCurve rotationCurveX;
public AnimationCurve rotationCurveY;
public AnimationCurve rotationCurveZ;
[Header("Ease curve")]
public AnimationCurve easeCurve;
// Use this for initialization
void Awake() {
}
void OnEnable() {
animator = GetComponent<AnimationPathAnimator>();
animationPath = GetComponent<AnimationPath>();
rotationCurveX = animator.RotationCurves[0];
rotationCurveY = animator.RotationCurves[1];
rotationCurveZ = animator.RotationCurves[2];
pathCurveX = animationPath.AnimationCurves[0];
pathCurveY = animationPath.AnimationCurves[1];
pathCurveZ = animationPath.AnimationCurves[2];
easeCurve = animator.EaseCurve;
}
void Start() {
}
// Update is called once per frame
void Update() {
}
}
|
using UnityEngine;
using System.Collections;
using ATP.AnimationPathTools;
[ExecuteInEditMode]
public class AnimationPathCurvesDebug : MonoBehaviour {
private AnimationPathAnimator animator;
[Header("Rotation curves")]
public AnimationCurve curveX;
public AnimationCurve curveY;
public AnimationCurve curveZ;
[Header("Ease curve")]
public AnimationCurve easeCurve;
// Use this for initialization
void Awake() {
}
void OnEnable() {
animator = GetComponent<AnimationPathAnimator>();
curveX = animator.RotationCurves[0];
curveY = animator.RotationCurves[1];
curveZ = animator.RotationCurves[2];
easeCurve = animator.EaseCurve;
}
void Start() {
}
// Update is called once per frame
void Update() {
}
}
|
mit
|
C#
|
7eb1e363a7e2751531abcfb253fd1579430e947c
|
Test for TeamCity.
|
XemioNetwork/GameLibrary
|
Testing/Xemio.Testing.EventSystem/Program.cs
|
Testing/Xemio.Testing.EventSystem/Program.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Xemio.GameLibrary;
using Xemio.GameLibrary.Common;
using Xemio.GameLibrary.Common.Extensions;
using Xemio.GameLibrary.Components;
using Xemio.GameLibrary.Events;
using Xemio.GameLibrary.Events.Logging;
using Xemio.GameLibrary.Network.Packages;
using Xemio.GameLibrary.Network.Timing;
using Xemio.GameLibrary.Plugins.Implementations;
namespace Xemio.Testing.EventSystem
{
public class Program
{
private static IDisposable disposable;
static void Main(string[] args)
{
var config = XGL.Configure()
.WithDefaultComponents()
.BuildConfiguration();
XGL.Run(config);
EventManager eventManager = XGL.Components.Get<EventManager>();
disposable = eventManager.Subscribe<ExceptionEvent>(Program.OnException);
throw new InvalidOperationException("Some exception text.");
}
private static void OnException(ExceptionEvent obj)
{
disposable.Dispose();
Console.WriteLine(obj.Message);
}
public static void OnNext(TestEvent value)
{
Console.WriteLine(value.Message);
}
public static void OnRed(RedEvent value)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(value.Message);
Console.ForegroundColor = ConsoleColor.White;
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Xemio.GameLibrary;
using Xemio.GameLibrary.Common;
using Xemio.GameLibrary.Common.Extensions;
using Xemio.GameLibrary.Components;
using Xemio.GameLibrary.Events;
using Xemio.GameLibrary.Events.Logging;
using Xemio.GameLibrary.Network.Packages;
using Xemio.GameLibrary.Network.Timing;
using Xemio.GameLibrary.Plugins.Implementations;
namespace Xemio.Testing.EventSystem
{
public class Program
{
private static IDisposable disposable;
static void Main(string[] args)
{
var config = XGL.Configure()
.WithDefaultComponents()
.BuildConfiguration();
XGL.Run(config, );
EventManager eventManager = XGL.Components.Get<EventManager>();
disposable = eventManager.Subscribe<ExceptionEvent>(Program.OnException);
throw new InvalidOperationException("Some exception text.");
}
private static void OnException(ExceptionEvent obj)
{
disposable.Dispose();
Console.WriteLine(obj.Message);
}
public static void OnNext(TestEvent value)
{
Console.WriteLine(value.Message);
}
public static void OnRed(RedEvent value)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(value.Message);
Console.ForegroundColor = ConsoleColor.White;
}
}
}
|
mit
|
C#
|
f35809a849bcdf721a20b76fc40227cbecaea519
|
disable paste command is extended tb is made readonly.
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Gui/Controls/ExtendedTextBox.cs
|
WalletWasabi.Gui/Controls/ExtendedTextBox.cs
|
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Styling;
using ReactiveUI;
using System;
using System.Reactive.Linq;
namespace WalletWasabi.Gui.Controls
{
public class ExtendedTextBox : TextBox, IStyleable
{
public ExtendedTextBox()
{
CopyCommand = ReactiveCommand.Create(() =>
{
CopyAsync();
});
PasteCommand = ReactiveCommand.Create(() =>
{
PasteAsync();
}, this.GetObservable(IsReadOnlyProperty).Select(x => !x));
}
Type IStyleable.StyleKey => typeof(TextBox);
private ReactiveCommand CopyCommand { get; }
private ReactiveCommand PasteCommand { get; }
private async void PasteAsync()
{
var text = await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard))).GetTextAsync();
if (text == null)
{
return;
}
OnTextInput(new TextInputEventArgs { Text = text });
}
private string GetSelection()
{
var text = Text;
if (string.IsNullOrEmpty(text))
return "";
var selectionStart = SelectionStart;
var selectionEnd = SelectionEnd;
var start = Math.Min(selectionStart, selectionEnd);
var end = Math.Max(selectionStart, selectionEnd);
if (start == end || (Text?.Length ?? 0) < end)
{
return "";
}
return text.Substring(start, end - start);
}
private async void CopyAsync()
{
var selection = GetSelection();
if (string.IsNullOrWhiteSpace(selection))
{
selection = Text;
}
if (!string.IsNullOrWhiteSpace(selection))
{
await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard)))
.SetTextAsync(selection);
}
}
protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
{
base.OnTemplateApplied(e);
ContextMenu = new ContextMenu
{
DataContext = this,
};
ContextMenu.Items = new Avalonia.Controls.Controls
{
new MenuItem { Header = "Copy", Command = CopyCommand },
new MenuItem { Header = "Paste", Command = PasteCommand}
};
}
}
}
|
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Styling;
using ReactiveUI;
using System;
namespace WalletWasabi.Gui.Controls
{
public class ExtendedTextBox : TextBox, IStyleable
{
public ExtendedTextBox()
{
CopyCommand = ReactiveCommand.Create(() =>
{
CopyAsync();
});
PasteCommand = ReactiveCommand.Create(() =>
{
PasteAsync();
});
}
Type IStyleable.StyleKey => typeof(TextBox);
private ReactiveCommand CopyCommand { get; }
private ReactiveCommand PasteCommand { get; }
private async void PasteAsync()
{
var text = await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard))).GetTextAsync();
if (text == null)
{
return;
}
OnTextInput(new TextInputEventArgs { Text = text });
}
private string GetSelection()
{
var text = Text;
if (string.IsNullOrEmpty(text))
return "";
var selectionStart = SelectionStart;
var selectionEnd = SelectionEnd;
var start = Math.Min(selectionStart, selectionEnd);
var end = Math.Max(selectionStart, selectionEnd);
if (start == end || (Text?.Length ?? 0) < end)
{
return "";
}
return text.Substring(start, end - start);
}
private async void CopyAsync()
{
var selection = GetSelection();
if (string.IsNullOrWhiteSpace(selection))
{
selection = Text;
}
if (!string.IsNullOrWhiteSpace(selection))
{
await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard)))
.SetTextAsync(selection);
}
}
protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
{
base.OnTemplateApplied(e);
ContextMenu = new ContextMenu
{
DataContext = this,
};
if (IsReadOnly)
{
ContextMenu.Items = new Avalonia.Controls.Controls
{
new MenuItem { Header = "Copy", Command = CopyCommand }
};
}
else
{
ContextMenu.Items = new Avalonia.Controls.Controls
{
new MenuItem { Header = "Copy", Command = CopyCommand },
new MenuItem { Header = "Paste", Command = PasteCommand}
};
}
}
}
}
|
mit
|
C#
|
dc7304dfca48a235acc5411e542b6889f68b4cec
|
Update header
|
Tannheuser/DeutschAktivCore,Tannheuser/DeutschAktivCore
|
DeutschAktiv.Web/Startup.cs
|
DeutschAktiv.Web/Startup.cs
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace DeutschAktiv.Web
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
}
}
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace DeutschAktiv.Web
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
// app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); });
app.UseMvcWithDefaultRoute();
}
}
}
|
mit
|
C#
|
9db24d3df4e0b8645229154916c8bd70e86fad36
|
fix for android by adding thread sleep (20)
|
yasokada/unity-150829-udpEcho,yasokada/unity-150917-udpEmu
|
Assets/UdpEchoServer.cs
|
Assets/UdpEchoServer.cs
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // for Text
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class UdpEchoServer : MonoBehaviour {
Thread rcvThr;
UdpClient client;
public int port = 6000;
public string lastRcvd;
public Text myipText; // to show my IP address
public Text portText; // to show UDP port
public Text recvdText;
private bool stopThr = false;
string getMyIPAddress()
{
string hostname = Dns.GetHostName ();
IPAddress[] adrList = Dns.GetHostAddresses (hostname);
foreach (IPAddress adr in adrList) {
string ipadr = adr.ToString();
if (ipadr.Contains("192.")) {
return adr.ToString();
}
if (ipadr.Contains("172.") && ipadr.Contains(".20.")) {
return adr.ToString();
}
}
return "IPadr: not found";
}
void Start () {
myipText.text = getMyIPAddress ();
portText.text = port.ToString ();
init ();
}
void Update() {
recvdText.text = lastRcvd;
}
void OnGUI() {
if (GUI.Button (new Rect (10, 250, 100, 40), "Quit")) {
Application.Quit ();
}
}
void init() {
Debug.Log ("init");
rcvThr = new Thread( new ThreadStart(FuncRcvData));
rcvThr.Start ();
}
void OnApplicationQuit() {
stopThr = true;
rcvThr.Abort ();
}
private void FuncRcvData()
{
client = new UdpClient (port);
client.Client.ReceiveTimeout = 300; // msec
client.Client.Blocking = false;
while (stopThr == false) {
try {
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = client.Receive(ref anyIP);
string text = Encoding.ASCII.GetString(data);
lastRcvd = text;
if (lastRcvd.Length > 0) {
client.Send(data, data.Length, anyIP); // echo
}
}
catch (Exception err)
{
// print(err.ToString());
}
// without this sleep, on adnroid, the app will not start (freeze at Unity splash)
Thread.Sleep(20); // 200
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // for Text
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class UdpEchoServer : MonoBehaviour {
Thread rcvThr;
UdpClient client;
public int port = 6000;
public string lastRcvd;
public Text myipText; // to show my IP address
public Text portText; // to show UDP port
public Text recvdText;
private bool stopThr = false;
string getMyIPAddress()
{
string hostname = Dns.GetHostName ();
IPAddress[] adrList = Dns.GetHostAddresses (hostname);
foreach (IPAddress adr in adrList) {
string ipadr = adr.ToString();
if (ipadr.Contains("192.")) {
return adr.ToString();
}
if (ipadr.Contains("172.") && ipadr.Contains(".20.")) {
return adr.ToString();
}
}
return "IPadr: not found";
}
void Start () {
init ();
// myipText.text = getMyIPAddress ();
portText.text = port.ToString ();
}
void Update() {
recvdText.text = lastRcvd;
}
void OnGUI() {
if (GUI.Button (new Rect (10, 250, 100, 40), "Quit")) {
Application.Quit ();
}
}
void init() {
Debug.Log ("init");
rcvThr = new Thread( new ThreadStart(FuncRcvData));
rcvThr.Start ();
}
void OnApplicationQuit() {
stopThr = true;
rcvThr.Abort ();
}
private void FuncRcvData()
{
client = new UdpClient (port);
client.Client.ReceiveTimeout = 300; // msec
client.Client.Blocking = false;
while (stopThr == false) {
try {
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = client.Receive(ref anyIP);
string text = Encoding.ASCII.GetString(data);
lastRcvd = text;
if (lastRcvd.Length > 0) {
client.Send(data, data.Length, anyIP); // echo
}
}
catch (Exception err)
{
// print(err.ToString());
}
}
}
}
|
mit
|
C#
|
8bf8a0d8d5d7eb6886a1072c85a880bffa9306e2
|
Make the monitor tool build again
|
tmds/Tmds.DBus
|
AssemblyInfo.cs
|
AssemblyInfo.cs
|
// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System.Reflection;
using System.Runtime.CompilerServices;
//[assembly: AssemblyVersion("0.0.0.*")]
[assembly: AssemblyTitle ("NDesk.DBus")]
[assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")]
[assembly: AssemblyCopyright ("Copyright (C) Alp Toker")]
[assembly: AssemblyCompany ("NDesk")]
[assembly: InternalsVisibleTo ("dbus-monitor, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
[assembly: InternalsVisibleTo ("NDesk.DBus.GLib, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
|
// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System.Reflection;
using System.Runtime.CompilerServices;
//[assembly: AssemblyVersion("0.0.0.*")]
[assembly: AssemblyTitle ("NDesk.DBus")]
[assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")]
[assembly: AssemblyCopyright ("Copyright (C) Alp Toker")]
[assembly: AssemblyCompany ("NDesk")]
[assembly: InternalsVisibleTo ("NDesk.DBus.GLib, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
//[assembly: InternalsVisibleTo ("dbus-monitor")]
//[assembly: InternalsVisibleTo ("dbus-daemon")]
|
mit
|
C#
|
b72a9f2d55dff9d8b29a7a93d828249c27ecf5f1
|
Change Proxy constructor to protected
|
lou1306/CIV,lou1306/CIV
|
CIV.Interfaces/Proxy.cs
|
CIV.Interfaces/Proxy.cs
|
using System.Reflection;
namespace CIV.Interfaces
{
public abstract class Proxy<T, CTX>
{
protected IFactory<T, CTX> factory;
protected CTX context;
T _real;
protected T Real
{
get
{
if (_real == null)
_real = factory.Create(context);
return _real;
}
}
protected Proxy(IFactory<T, CTX> factory, CTX context)
{
this.factory = factory;
this.context = context;
}
}
}
|
using System.Reflection;
namespace CIV.Interfaces
{
public abstract class Proxy<T, CTX>
{
protected IFactory<T, CTX> factory;
protected CTX context;
T _real;
protected T Real
{
get
{
if (_real == null)
_real = factory.Create(context);
return _real;
}
}
public Proxy(IFactory<T, CTX> factory, CTX context)
{
this.factory = factory;
this.context = context;
}
}
}
|
mit
|
C#
|
fbf955e866c4127061a8415827bd30a03a6b9892
|
Simplify CloseWindowCommand
|
y-iihoshi/ThScoreFileConverter,y-iihoshi/ThScoreFileConverter
|
ThScoreFileConverter/Commands/CloseWindowCommand.cs
|
ThScoreFileConverter/Commands/CloseWindowCommand.cs
|
//-----------------------------------------------------------------------
// <copyright file="CloseWindowCommand.cs" company="None">
// Copyright (c) IIHOSHI Yoshinori.
// Licensed under the BSD-2-Clause license. See LICENSE.txt file in the project root for full license information.
// </copyright>
//-----------------------------------------------------------------------
namespace ThScoreFileConverter.Commands
{
using System;
using System.Windows;
using System.Windows.Input;
/// <summary>
/// Represents the command to close the specified window.
/// </summary>
public class CloseWindowCommand : ICommand
{
/// <summary>
/// Prevents a default instance of the <see cref="CloseWindowCommand"/> class from being created.
/// </summary>
private CloseWindowCommand()
{
}
/// <summary>
/// Occurs when changes occur that affect whether or not the command should execute.
/// </summary>
#pragma warning disable CS0067
public event EventHandler CanExecuteChanged;
#pragma warning restore CS0067
/// <summary>
/// Gets the instance.
/// </summary>
public static ICommand Instance { get; } = new CloseWindowCommand();
/// <summary>
/// Determines whether the command can execute in its current state.
/// </summary>
/// <param name="parameter">A <see cref="Window"/> instance which will be closed.</param>
/// <returns><c>true</c> if this command can be executed; otherwise, <c>false</c>.</returns>
public bool CanExecute(object parameter) => parameter is Window;
/// <summary>
/// Called when the command is invoked.
/// </summary>
/// <param name="parameter">A <see cref="Window"/> instance which is closed.</param>
public void Execute(object parameter)
{
if (this.CanExecute(parameter))
(parameter as Window).Close();
}
}
}
|
//-----------------------------------------------------------------------
// <copyright file="CloseWindowCommand.cs" company="None">
// Copyright (c) IIHOSHI Yoshinori.
// Licensed under the BSD-2-Clause license. See LICENSE.txt file in the project root for full license information.
// </copyright>
//-----------------------------------------------------------------------
namespace ThScoreFileConverter.Commands
{
using System;
using System.Windows;
using System.Windows.Input;
/// <summary>
/// Represents the command to close the specified window.
/// </summary>
public class CloseWindowCommand : ICommand
{
/// <summary>
/// Only one instance of this class.
/// </summary>
private static readonly ICommand InstanceImpl = new CloseWindowCommand();
/// <summary>
/// Prevents a default instance of the <see cref="CloseWindowCommand"/> class from being created.
/// </summary>
private CloseWindowCommand()
{
}
/// <summary>
/// Occurs when changes occur that affect whether or not the command should execute.
/// </summary>
public event EventHandler CanExecuteChanged
{
add { }
remove { }
}
/// <summary>
/// Gets the instance.
/// </summary>
public static ICommand Instance
{
get { return InstanceImpl; }
}
/// <summary>
/// Determines whether the command can execute in its current state.
/// </summary>
/// <param name="parameter">A <see cref="Window"/> instance which will be closed.</param>
/// <returns><c>true</c> if this command can be executed; otherwise, <c>false</c>.</returns>
public bool CanExecute(object parameter)
{
return parameter is Window;
}
/// <summary>
/// Called when the command is invoked.
/// </summary>
/// <param name="parameter">A <see cref="Window"/> instance which is closed.</param>
public void Execute(object parameter)
{
if (this.CanExecute(parameter))
(parameter as Window).Close();
}
}
}
|
bsd-2-clause
|
C#
|
9dd32297def6ed5224933f5acf9f40c1ce4695dd
|
add obsolete Item1 and Item2 properties to ConnectionStringInfo for backward compability
|
volkanceylan/Serenity,TukekeSoft/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,rolembergfilho/Serenity,rolembergfilho/Serenity,linpiero/Serenity,linpiero/Serenity,dfaruque/Serenity,WasimAhmad/Serenity,WasimAhmad/Serenity,TukekeSoft/Serenity,linpiero/Serenity,dfaruque/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,WasimAhmad/Serenity,TukekeSoft/Serenity,volkanceylan/Serenity,TukekeSoft/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,dfaruque/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity,dfaruque/Serenity,linpiero/Serenity,linpiero/Serenity,dfaruque/Serenity
|
Serenity.Data/Connections/ConnectionStringInfo.cs
|
Serenity.Data/Connections/ConnectionStringInfo.cs
|
using System;
using System.Data.Common;
namespace Serenity.Data
{
public class ConnectionStringInfo
{
public ConnectionStringInfo(string connectionString, string providerName, DbProviderFactory providerFactory)
{
this.ConnectionString = connectionString;
this.ProviderName = providerName;
this.ProviderFactory = providerFactory;
}
public string ConnectionString { get; private set; }
public string ProviderName { get; private set; }
public DbProviderFactory ProviderFactory { get; private set; }
[Obsolete("Use ConnectionString")]
public string Item1 { get { return ConnectionString; } }
[Obsolete("Use ProviderName")]
public string Item2 { get { return ProviderName; } }
}
}
|
using System.Data.Common;
namespace Serenity.Data
{
public class ConnectionStringInfo
{
public ConnectionStringInfo(string connectionString, string providerName, DbProviderFactory providerFactory)
{
this.ConnectionString = connectionString;
this.ProviderName = providerName;
this.ProviderFactory = providerFactory;
}
public string ConnectionString { get; private set; }
public string ProviderName { get; private set; }
public DbProviderFactory ProviderFactory { get; private set; }
}
}
|
mit
|
C#
|
b26fdff21d255a02fc0e658bd2ece504ac497b30
|
Remove unused code
|
kiyoaki/bitflyer-api-dotnet-client
|
src/BitFlyer.Apis/Extensions/EnumExtensions.cs
|
src/BitFlyer.Apis/Extensions/EnumExtensions.cs
|
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Runtime.Serialization;
namespace BitFlyer.Apis
{
public static class EnumExtensions
{
private static readonly ConcurrentDictionary<Enum, string> EnumMemberCache = new ConcurrentDictionary<Enum, string>();
public static string GetEnumMemberValue(this Enum value)
{
string returnValue;
if (EnumMemberCache.TryGetValue(value, out returnValue))
{
return returnValue;
}
var attributes = value.GetType()
.GetField(value.ToString())
.GetCustomAttributes(typeof(EnumMemberAttribute), false) as EnumMemberAttribute[];
returnValue = attributes?.FirstOrDefault()?.Value;
if (returnValue != null)
{
EnumMemberCache.TryAdd(value, returnValue);
}
return returnValue;
}
}
}
|
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Runtime.Serialization;
#if NET_CORE || PORTABLE
using System.Reflection;
#endif
namespace BitFlyer.Apis
{
public static class EnumExtensions
{
private static readonly ConcurrentDictionary<Enum, string> EnumMemberCache = new ConcurrentDictionary<Enum, string>();
public static string GetEnumMemberValue(this Enum value)
{
string returnValue;
if (EnumMemberCache.TryGetValue(value, out returnValue))
{
return returnValue;
}
#if NET_CORE
var attributes = value.GetType().GetTypeInfo().GetField(value.ToString()).GetCustomAttributes<EnumMemberAttribute>(false);
#elif PORTABLE
var attributes = value.GetType().GetTypeInfo().GetDeclaredField(value.ToString()).GetCustomAttributes(typeof(EnumMemberAttribute), false) as EnumMemberAttribute[];
#else
var attributes = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(EnumMemberAttribute), false) as EnumMemberAttribute[];
#endif
returnValue = attributes?.FirstOrDefault()?.Value;
if (returnValue != null)
{
EnumMemberCache.TryAdd(value, returnValue);
}
return returnValue;
}
}
}
|
mit
|
C#
|
67c3a7c4a41bb5d729f6102eaee0a803502a303e
|
Fix message deserialization
|
DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer
|
Common/Message/Data/PlayerStatus/PlayerStatusReplyMsgData.cs
|
Common/Message/Data/PlayerStatus/PlayerStatusReplyMsgData.cs
|
using Lidgren.Network;
using LunaCommon.Message.Base;
using LunaCommon.Message.Types;
namespace LunaCommon.Message.Data.PlayerStatus
{
public class PlayerStatusReplyMsgData: PlayerStatusBaseMsgData
{
/// <inheritdoc />
internal PlayerStatusReplyMsgData() { }
public override PlayerStatusMessageType PlayerStatusMessageType => PlayerStatusMessageType.Reply;
public int PlayerStatusCount;
public PlayerStatusInfo[] PlayerStatus = new PlayerStatusInfo[0];
public override string ClassName { get; } = nameof(PlayerStatusReplyMsgData);
internal override void InternalSerialize(NetOutgoingMessage lidgrenMsg, bool dataCompressed)
{
base.InternalSerialize(lidgrenMsg, dataCompressed);
lidgrenMsg.Write(PlayerStatusCount);
for (var i = 0; i < PlayerStatusCount; i++)
{
PlayerStatus[i].Serialize(lidgrenMsg, dataCompressed);
}
}
internal override void InternalDeserialize(NetIncomingMessage lidgrenMsg, bool dataCompressed)
{
base.InternalDeserialize(lidgrenMsg, dataCompressed);
PlayerStatusCount = lidgrenMsg.ReadInt32();
PlayerStatus = ArrayPool<PlayerStatusInfo>.Claim(PlayerStatusCount);
for (var i = 0; i < PlayerStatusCount; i++)
{
if (PlayerStatus[i] == null)
PlayerStatus[i] = new PlayerStatusInfo();
PlayerStatus[i].Deserialize(lidgrenMsg, dataCompressed);
}
}
public override void Recycle()
{
base.Recycle();
ArrayPool<PlayerStatusInfo>.Release(ref PlayerStatus);
}
internal override int InternalGetMessageSize(bool dataCompressed)
{
var arraySize = 0;
for (var i = 0; i < PlayerStatusCount; i++)
{
arraySize += PlayerStatus[i].GetByteCount(dataCompressed);
}
return base.InternalGetMessageSize(dataCompressed) + sizeof(int) + arraySize;
}
}
}
|
using Lidgren.Network;
using LunaCommon.Message.Base;
using LunaCommon.Message.Types;
namespace LunaCommon.Message.Data.PlayerStatus
{
public class PlayerStatusReplyMsgData: PlayerStatusBaseMsgData
{
/// <inheritdoc />
internal PlayerStatusReplyMsgData() { }
public override PlayerStatusMessageType PlayerStatusMessageType => PlayerStatusMessageType.Reply;
public int PlayerStatusCount;
public PlayerStatusInfo[] PlayerStatus = new PlayerStatusInfo[0];
public override string ClassName { get; } = nameof(PlayerStatusReplyMsgData);
internal override void InternalSerialize(NetOutgoingMessage lidgrenMsg, bool dataCompressed)
{
base.InternalSerialize(lidgrenMsg, dataCompressed);
lidgrenMsg.Write(PlayerStatusCount);
for (var i = 0; i < PlayerStatusCount; i++)
{
PlayerStatus[i].Serialize(lidgrenMsg, dataCompressed);
}
}
internal override void InternalDeserialize(NetIncomingMessage lidgrenMsg, bool dataCompressed)
{
base.InternalDeserialize(lidgrenMsg, dataCompressed);
PlayerStatusCount = lidgrenMsg.ReadInt32();
PlayerStatus = ArrayPool<PlayerStatusInfo>.Claim(PlayerStatusCount);
for (var i = 0; i < PlayerStatusCount; i++)
{
PlayerStatus[i].Deserialize(lidgrenMsg, dataCompressed);
}
}
public override void Recycle()
{
base.Recycle();
ArrayPool<PlayerStatusInfo>.Release(ref PlayerStatus);
}
internal override int InternalGetMessageSize(bool dataCompressed)
{
var arraySize = 0;
for (var i = 0; i < PlayerStatusCount; i++)
{
arraySize += PlayerStatus[i].GetByteCount(dataCompressed);
}
return base.InternalGetMessageSize(dataCompressed) + sizeof(int) + arraySize;
}
}
}
|
mit
|
C#
|
8d903e448a3e70c939cabc51bb2b61c04f546d49
|
update composite curve to properly handle StatusNumber
|
IxMilia/Iges,IxMilia/Iges
|
src/IxMilia.Iges/Entities/IgesCompositeCurve.cs
|
src/IxMilia.Iges/Entities/IgesCompositeCurve.cs
|
// Copyright (c) IxMilia. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
namespace IxMilia.Iges.Entities
{
public partial class IgesCompositeCurve : IgesEntity
{
public override IgesEntityType EntityType { get { return IgesEntityType.CompositeCurve; } }
// custom properties
public List<IgesEntity> Entities
{
get
{
return SubEntities;
}
}
public IgesCompositeCurve()
: base()
{
}
protected override void ReadParameters(List<string> parameters)
{
var entityCount = Integer(parameters, 0);
for (int i = 0; i < entityCount; i++)
{
this.SubEntityIndices.Add(Integer(parameters, i + 1));
}
}
protected override void WriteParameters(List<object> parameters)
{
parameters.Add(this.Entities.Count);
parameters.AddRange(this.SubEntityIndices.Cast<object>());
}
}
}
|
// Copyright (c) IxMilia. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
namespace IxMilia.Iges.Entities
{
public partial class IgesCompositeCurve : IgesEntity
{
public override IgesEntityType EntityType { get { return IgesEntityType.CompositeCurve; } }
// properties
private int EntityCount { get; set; }
// custom properties
public List<IgesEntity> Entities
{
get
{
return SubEntities;
}
}
public IgesCompositeCurve()
: base()
{
this.EntityCount = 0;
}
protected override void ReadParameters(List<string> parameters)
{
this.EntityCount = Integer(parameters, 0);
for (int i = 0; i < EntityCount; i++)
{
this.SubEntityIndices.Add(Integer(parameters, i + 1));
}
}
protected override void WriteParameters(List<object> parameters)
{
parameters.Add(this.Entities.Count);
parameters.AddRange(this.SubEntityIndices.Cast<object>());
}
}
}
|
apache-2.0
|
C#
|
9d546972806c019d47663127ea534a91044c1f62
|
fix compile issue
|
AMVSoftware/NSaga
|
NSaga/StubSagaRepository.cs
|
NSaga/StubSagaRepository.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSaga
{
public class StubSagaRepository : ISagaRepository
{
public ISaga<TSagaData> InitiateSaga<TSagaData>()
{
throw new NotImplementedException();
}
public ISaga<TSagaData> Find<TSagaData>(Guid correlationId)
{
throw new NotImplementedException();
}
public dynamic Find(Guid correlationId)
{
throw new NotImplementedException();
}
public dynamic InitiateSaga(Type sagaType)
{
throw new NotImplementedException();
}
public void Save<TSagaData>(ISaga<TSagaData> saga)
{
throw new NotImplementedException();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSaga
{
public class StubSagaRepository : ISagaRepository
{
public ISaga<TSagaData> InitiateSaga<TSagaData>()
{
throw new NotImplementedException();
}
public ISaga<TSagaData> Find<TSagaData>(Guid correlationId)
{
throw new NotImplementedException();
}
public void Save<TSagaData>(ISaga<TSagaData> saga)
{
throw new NotImplementedException();
}
}
}
|
mit
|
C#
|
c80eaa44692cda1b2fc5fd0fc2759dec3cdca5a3
|
optimize MinChangeCount
|
dgg/nmoneys,dgg/nmoneys
|
src/NMoneys/Change/Operations.MinChangeCount.cs
|
src/NMoneys/Change/Operations.MinChangeCount.cs
|
using System;
using System.Linq;
using NMoneys.Extensions;
namespace NMoneys.Change
{
[CLSCompliant(false)]
public static class MinChangeCountOperation
{
public static ushort MinChangeCount(this Money money, params Denomination[] denominations)
{
Positive.Amounts.AssertArgument(nameof(money), money.Amount);
long n = money.MinorIntegralAmount;
int m = denominations.Length;
Currency currencyOperation = money.GetCurrency();
IntegralDenomination[] integralDenominations = denominations
.Select(d => new IntegralDenomination(d, currencyOperation))
.ToArray();
// table[i] will be storing the minimum number of denominations
// required for i value. So table[n] will have result
ushort[] table = new ushort[n + 1];
// Base case (If given value n is 0)
table[0] = 0;
// Compute minimum denominations required for all
// values from 1 to n
for (long i = 1; i <= n; i++)
{
// Initialize all table values as Infinite
table[i] = ushort.MaxValue;
// Go through all denominations smaller than i
for (int j = 0; j < m; j++)
{
if (integralDenominations[j].IntegralAmount <= i)
{
uint subResult = table[i - integralDenominations[j].IntegralAmount];
if (subResult != ushort.MaxValue && subResult + 1u < table[i])
{
table[i] = (ushort) (subResult + 1);
}
}
}
}
return table[n] == ushort.MaxValue ? default(ushort) : table[n];
}
public static ushort MinChangeCount(this Money money, params decimal[] denominationValues)
{
return money.MinChangeCount(denominationValues.Select(v => new Denomination(v)).ToArray());
}
}
}
|
using System;
using System.Linq;
namespace NMoneys.Change
{
[CLSCompliant(false)]
public static class MinChangeCountOperation
{
public static ushort MinChangeCount(this Money money, params Denomination[] denominations)
{
Positive.Amounts.AssertArgument(nameof(money), money.Amount);
long n = money.MinorIntegralAmount;
int m = denominations.Length;
long[] integralDenominations = denominations
.Select(d => new Money(d.Value, money.CurrencyCode))
.Select(mm => mm.MinorIntegralAmount)
.ToArray();
// table[i] will be storing the minimum number of denominations
// required for i value. So table[n] will have result
ushort[] table = new ushort[n + 1];
// Base case (If given value n is 0)
table[0] = 0;
// Compute minimum denominations required for all
// values from 1 to n
for (long i = 1; i <= n; i++)
{
// Initialize all table values as Infinite
table[i] = ushort.MaxValue;
// Go through all denominations smaller than i
for (int j = 0; j < m; j++)
{
if (integralDenominations[j] <= i)
{
uint subResult = table[i - integralDenominations[j]];
if (subResult != ushort.MaxValue && subResult + 1u < table[i])
{
table[i] = (ushort) (subResult + 1);
}
}
}
}
return table[n] == ushort.MaxValue ? default(ushort) : table[n];
}
public static ushort MinChangeCount(this Money money, params decimal[] denominationValues)
{
return money.MinChangeCount(denominationValues.Select(v => new Denomination(v)).ToArray());
}
}
}
|
bsd-3-clause
|
C#
|
3c35f64c1d520d11d829f36227371070ab89ce8b
|
Remove cruft
|
wbsimms/PracticeTime,wbsimms/PracticeTime,wbsimms/PracticeTime,wbsimms/PracticeTime
|
src/Web/PracticeTime.Web/Helpers/UserHelper.cs
|
src/Web/PracticeTime.Web/Helpers/UserHelper.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using PracticeTime.Web.DataAccess;
using PracticeTime.Web.DataAccess.Models;
namespace PracticeTime.Web.Helpers
{
public interface IUserHelper
{
string GetUserId(string name);
}
public class UserHelper : IUserHelper
{
static Random random = new Random();
private static string _passwordArray = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
public string GetUserId(string name)
{
return new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new PracticeTimeContext())).
FindByNameAsync(name).Result.Id;
}
public static PracticeTimeRoles GetRoleFromId(string id)
{
switch (id)
{
case "Student":
return PracticeTimeRoles.Student;
case "Instructor":
return PracticeTimeRoles.Instructor;
default:
throw new ApplicationException("Unable to determine role");
}
}
public static string RandomString(int length)
{
StringBuilder password = new StringBuilder();
for (int i = 0; i < length; i++)
{
int index = (int)Math.Ceiling(random.NextDouble() * _passwordArray.Length-1);
password.Append(_passwordArray[index]);
}
return password.ToString(); }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using PracticeTime.Web.DataAccess;
using PracticeTime.Web.DataAccess.Models;
namespace PracticeTime.Web.Helpers
{
public interface IUserHelper
{
string GetUserId(string name);
}
public class UserHelper : IUserHelper
{
static Random random = new Random();
private static string _passwordArray = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
public void GetAllUsers()
{
}
public string GetUserId(string name)
{
return new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new PracticeTimeContext())).
FindByNameAsync(name).Result.Id;
}
public static PracticeTimeRoles GetRoleFromId(string id)
{
switch (id)
{
case "Student":
return PracticeTimeRoles.Student;
case "Instructor":
return PracticeTimeRoles.Instructor;
default:
throw new ApplicationException("Unable to determine role");
}
}
public static string RandomString(int length)
{
StringBuilder password = new StringBuilder();
for (int i = 0; i < length; i++)
{
int index = (int)Math.Ceiling(random.NextDouble() * _passwordArray.Length-1);
password.Append(_passwordArray[index]);
}
return password.ToString(); }
}
}
|
apache-2.0
|
C#
|
30649eb2b815aa15ea498a7798efaa792baf56c5
|
Update ParenthesizedExpressionTemplateProvider.cs
|
controlflow/resharper-postfix
|
TemplateProviders/ParenthesizedExpressionTemplateProvider.cs
|
TemplateProviders/ParenthesizedExpressionTemplateProvider.cs
|
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using JetBrains.ReSharper.ControlFlow.PostfixCompletion.LookupItems;
using JetBrains.ReSharper.Feature.Services.Lookup;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.Psi.CSharp.Tree;
namespace JetBrains.ReSharper.ControlFlow.PostfixCompletion.TemplateProviders
{
// todo: foo as Bar.par - available in auto
// todo: (Bar) foo.par - available in auto?
[PostfixTemplateProvider(
templateName: "par",
description: "Parenthesizes current expression",
example: "(expr)")]
public class ParenthesizedExpressionTemplateProvider : IPostfixTemplateProvider
{
public void CreateItems(PostfixTemplateAcceptanceContext context, ICollection<ILookupItem> consumer)
{
if (context.ForceMode)
{
PrefixExpressionContext bestExpression = null;
foreach (var expression in context.Expressions.Reverse())
{
if (CommonUtils.IsNiceExpression(expression.Expression))
{
bestExpression = expression;
break;
}
}
consumer.Add(new LookupItem(bestExpression ?? context.OuterExpression));
}
}
private sealed class LookupItem : ExpressionPostfixLookupItem<ICSharpExpression>
{
public LookupItem([NotNull] PrefixExpressionContext context)
: base("par", context) { }
protected override ICSharpExpression CreateExpression(
CSharpElementFactory factory, ICSharpExpression expression)
{
return factory.CreateExpression("($0)", expression);
}
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using JetBrains.ReSharper.ControlFlow.PostfixCompletion.LookupItems;
using JetBrains.ReSharper.Feature.Services.Lookup;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.Psi.CSharp.Tree;
namespace JetBrains.ReSharper.ControlFlow.PostfixCompletion.TemplateProviders
{
[PostfixTemplateProvider(
templateName: "par",
description: "Parenthesizes current expression",
example: "(expr)")]
public class ParenthesizedExpressionTemplateProvider : IPostfixTemplateProvider
{
public void CreateItems(PostfixTemplateAcceptanceContext context, ICollection<ILookupItem> consumer)
{
if (context.ForceMode)
{
PrefixExpressionContext bestExpression = null;
foreach (var expression in context.Expressions.Reverse())
{
if (CommonUtils.IsNiceExpression(expression.Expression))
{
bestExpression = expression;
break;
}
}
consumer.Add(new LookupItem(bestExpression ?? context.OuterExpression));
}
}
private sealed class LookupItem : ExpressionPostfixLookupItem<ICSharpExpression>
{
public LookupItem([NotNull] PrefixExpressionContext context)
: base("par", context) { }
protected override ICSharpExpression CreateExpression(
CSharpElementFactory factory, ICSharpExpression expression)
{
return factory.CreateExpression("($0)", expression);
}
}
}
}
|
mit
|
C#
|
666da4a8c8fe8f88f184137e7cb069e207a42ab7
|
print if traceleve less or equal
|
n8allan/Dataphor,DBCG/Dataphor,n8allan/Dataphor,n8allan/Dataphor,DBCG/Dataphor,DBCG/Dataphor,DBCG/Dataphor,DBCG/Dataphor,n8allan/Dataphor,n8allan/Dataphor,DBCG/Dataphor,n8allan/Dataphor
|
Dataphor/Logging/Logger.cs
|
Dataphor/Logging/Logger.cs
|
using System.Diagnostics;
namespace Alphora.Dataphor.Logging
{
internal class Logger : ILogger
{
private static TraceSwitch FTraceSwitch;
public Logger(string ADisplayName):this(ADisplayName,"TraceSwitch for "+ADisplayName)
{
}
public Logger(string ADisplayName, string ADescription)
{
FTraceSwitch=new TraceSwitch(ADisplayName,ADescription);
}
public void WriteLine(TraceLevel ATraceLevel, string AFormat)
{
bool LWillWriteLine = FTraceSwitch.Level <= ATraceLevel;
Debug.WriteLineIf(LWillWriteLine, AFormat, FTraceSwitch.DisplayName);
}
public void WriteLine(TraceLevel ATraceLevel, string AFormat, params object[] AArgs)
{
bool LWillWriteLine = FTraceSwitch.Level <= ATraceLevel;
Debug.WriteLineIf(LWillWriteLine, string.Format(AFormat, AArgs), FTraceSwitch.DisplayName);
}
}
}
|
using System.Diagnostics;
namespace Alphora.Dataphor.Logging
{
internal class Logger : ILogger
{
private static TraceSwitch FTraceSwitch;
public Logger(string ADisplayName):this(ADisplayName,"TraceSwitch for "+ADisplayName)
{
}
public Logger(string ADisplayName, string ADescription)
{
FTraceSwitch=new TraceSwitch(ADisplayName,ADescription);
}
public void WriteLine(TraceLevel ATraceLevel, string AFormat)
{
Debug.WriteLineIf(FTraceSwitch.Level == ATraceLevel,AFormat,FTraceSwitch.DisplayName);
}
public void WriteLine(TraceLevel ATraceLevel, string AFormat, params object[] AArgs)
{
Debug.WriteLineIf(FTraceSwitch.Level == ATraceLevel, string.Format(AFormat, AArgs), FTraceSwitch.DisplayName);
}
}
}
|
bsd-3-clause
|
C#
|
08a876df866fed64428d22cbccbba989c8b13421
|
Move Settings tab just after OfflinePayment settings
|
OShop/OShop.PayPal,OShop/OShop.PayPal
|
Navigation/AdminMenu.cs
|
Navigation/AdminMenu.cs
|
using Orchard.Localization;
using Orchard.UI.Navigation;
using OShop.Permissions;
namespace OShop.PayPal.Navigation {
public class AdminMenu : INavigationProvider {
public Localizer T { get; set; }
public AdminMenu() {
T = NullLocalizer.Instance;
}
public string MenuName { get { return "admin"; } }
public void GetNavigation(NavigationBuilder builder) {
builder
.AddImageSet("oshop")
.Add(menu => menu
.Caption(T("OShop"))
.Add(subMenu => subMenu
.Caption(T("Settings"))
.Add(tab => tab
.Caption(T("PayPal"))
.Position("7.1")
.Action("Settings", "Admin", new { area = "OShop.PayPal" })
.Permission(OShopPermissions.ManageShopSettings)
.LocalNav()
)
)
);
}
}
}
|
using Orchard.Localization;
using Orchard.UI.Navigation;
using OShop.Permissions;
namespace OShop.PayPal.Navigation {
public class AdminMenu : INavigationProvider {
public Localizer T { get; set; }
public AdminMenu() {
T = NullLocalizer.Instance;
}
public string MenuName { get { return "admin"; } }
public void GetNavigation(NavigationBuilder builder) {
builder
.AddImageSet("oshop")
.Add(menu => menu
.Caption(T("OShop"))
.Add(subMenu => subMenu
.Caption(T("Settings"))
.Add(tab => tab
.Caption(T("PayPal"))
.Position("7")
.Action("Settings", "Admin", new { area = "OShop.PayPal" })
.Permission(OShopPermissions.ManageShopSettings)
.LocalNav()
)
)
);
}
}
}
|
mit
|
C#
|
6bd591b544faa92cacf27cef63f13c1f160f7633
|
add 2 properties to UserVotesViewModel - NumberOfVotes and Voters
|
KristianMariyanov/VotingSystem,KristianMariyanov/VotingSystem,KristianMariyanov/VotingSystem
|
VotingSystem.Web/Areas/User/ViewModels/UserVotesViewModel.cs
|
VotingSystem.Web/Areas/User/ViewModels/UserVotesViewModel.cs
|
namespace VotingSystem.Web.Areas.User.ViewModels
{
using System;
using System.Web.Mvc;
using VotingSystem.Models;
using VotingSystem.Web.Infrastructure.Mapping;
public class UserVotesViewModel : IMapFrom<Vote>, IHaveCustomMappings
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
[HiddenInput(DisplayValue = false)]
public string Author { get; set; }
public int NumberOfVotes { get; set; }
public bool IsPublic { get; set; }
public int Voters { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
[HiddenInput(DisplayValue = false)]
public string UserId { get; set; }
public void CreateMappings(AutoMapper.IConfiguration configuration)
{
configuration.CreateMap<Vote, UserVotesViewModel>()
.ForMember(m => m.Author, opt => opt.MapFrom(a => a.User.UserName));
}
}
}
|
namespace VotingSystem.Web.Areas.User.ViewModels
{
using System;
using System.Web.Mvc;
using VotingSystem.Models;
using VotingSystem.Web.Infrastructure.Mapping;
public class UserVotesViewModel : IMapFrom<Vote>, IHaveCustomMappings
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
[HiddenInput(DisplayValue = false)]
public string Author { get; set; }
public bool IsPublic { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
[HiddenInput(DisplayValue = false)]
public string UserId { get; set; }
public void CreateMappings(AutoMapper.IConfiguration configuration)
{
configuration.CreateMap<Vote, UserVotesViewModel>()
.ForMember(m => m.Author, opt => opt.MapFrom(a => a.User.UserName));
}
}
}
|
mit
|
C#
|
5b4aeb81c0838aabaa3ccb364b6c953f89bc363d
|
Update Vector2.cs
|
elacy/PopulationSimulator
|
PopSim.Logic/Vector2.cs
|
PopSim.Logic/Vector2.cs
|
using System;
namespace PopSim.Logic
{
public class Vector2
{
public Vector2(double x, double y)
{
X = x;
Y = y;
IsZero = Math.Abs(x) < double.Epsilon && Math.Abs(y) < double.Epsilon;
}
public Vector2(double theta)
{
X = Math.Cos(theta);
Y = Math.Sin(theta);
}
public bool IsZero { get; private set; }
public double X { get; private set; }
public double Y { get; private set; }
public Vector2 Add(Vector2 vector2)
{
return new Vector2(X + vector2.X,Y + vector2.Y);
}
public double GetDistance(Vector2 vector2)
{
return Math.Sqrt(Squared(vector2.X - X) + Squared(vector2.Y - Y));
}
private static double Squared(double value)
{
return Math.Pow(value, 2);
}
public double AngleBetween(Vector2 vector2)
{
return Math.Atan2(vector2.Y - Y, vector2.X - X);
}
public Vector2 GetDirection(Vector2 destination)
{
var angle = AngleBetween(destination);
RetVector = new Vector2(Math.Cos(angle),Math.Sin(angle));
RetVector = RetVector.UnitVector();
return RetVector;
}
public Vector2 ScalarMultiply(double multiplier)
{
return new Vector2(X*multiplier,Y*multiplier);
}
public double VectorMagnitude()
{
return Math.Sqrt(X*X + Y*Y);
}
public Vector2 UnitVector()
{
return new Vector2( X / VectorMagnitude(), Y / VectorMagnitude())
}
}
}
|
using System;
namespace PopSim.Logic
{
public class Vector2
{
public Vector2(double x, double y)
{
X = x;
Y = y;
IsZero = Math.Abs(x) < double.Epsilon && Math.Abs(y) < double.Epsilon;
}
public bool IsZero { get; private set; }
public double X { get; private set; }
public double Y { get; private set; }
public Vector2 Add(Vector2 vector2)
{
return new Vector2(X + vector2.X,Y + vector2.Y);
}
public double GetDistance(Vector2 vector2)
{
return Math.Sqrt(Squared(vector2.X - X) + Squared(vector2.Y - Y));
}
private static double Squared(double value)
{
return Math.Pow(value, 2);
}
public double AngleBetween(Vector2 vector2)
{
return Math.Atan2(vector2.Y - Y, vector2.X - X);
}
public Vector2 GetDirection(Vector2 destination)
{
var angle = AngleBetween(destination);
RetVector = new Vector2(Math.Cos(angle),Math.Sin(angle));
RetVector = RetVector.UnitVector();
return RetVector;
}
public Vector2 ScalarMultiply(double multiplier)
{
return new Vector2(X*multiplier,Y*multiplier);
}
public double VectorMagnitude()
{
return Math.Sqrt(X*X + Y*Y);
}
public Vector2 UnitVector()
{
return new Vector2( X / VectorMagnitude(), Y / VectorMagnitude())
}
}
}
|
mit
|
C#
|
95cc80610a838c38bdc5e9a9596ec53712b9ebba
|
Add missing DesignInstance
|
aluxnimm/outlookcaldavsynchronizer
|
CalDavSynchronizer/Ui/Options/ViewModels/TimeRangeViewModel.cs
|
CalDavSynchronizer/Ui/Options/ViewModels/TimeRangeViewModel.cs
|
// This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/)
// Copyright (c) 2015 Gerhard Zehetbauer
// Copyright (c) 2015 Alexander Nimmervoll
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Text;
using CalDavSynchronizer.Ui.Options.Models;
namespace CalDavSynchronizer.Ui.Options.ViewModels
{
public class TimeRangeViewModel : ModelBase, IOptionsSection
{
private readonly OptionsModel _model;
public TimeRangeViewModel(OptionsModel model, IViewOptions viewOptions)
{
if (model == null) throw new ArgumentNullException(nameof(model));
if (viewOptions == null) throw new ArgumentNullException(nameof(viewOptions));
_model = model;
ViewOptions = viewOptions;
RegisterPropertyChangePropagation(_model, nameof(_model.UseSynchronizationTimeRange), nameof(UseSynchronizationTimeRange));
RegisterPropertyChangePropagation(_model, nameof(_model.DaysToSynchronizeInThePast), nameof(DaysToSynchronizeInThePast));
RegisterPropertyChangePropagation(_model, nameof(_model.DaysToSynchronizeInTheFuture), nameof(DaysToSynchronizeInTheFuture));
}
public bool UseSynchronizationTimeRange
{
get { return _model.UseSynchronizationTimeRange; }
set { _model.UseSynchronizationTimeRange = value; }
}
public int DaysToSynchronizeInThePast
{
get { return _model.DaysToSynchronizeInThePast; }
set { _model.DaysToSynchronizeInThePast = value; }
}
public int DaysToSynchronizeInTheFuture
{
get { return _model.DaysToSynchronizeInTheFuture; }
set { _model.DaysToSynchronizeInTheFuture = value; }
}
public IViewOptions ViewOptions { get; }
public static TimeRangeViewModel DesignInstance { get; } = new TimeRangeViewModel(OptionsModel.DesignInstance, OptionsCollectionViewModel.DesignViewOptions)
{
UseSynchronizationTimeRange = true,
DaysToSynchronizeInTheFuture = 11,
DaysToSynchronizeInThePast = 22
};
}
}
|
// This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/)
// Copyright (c) 2015 Gerhard Zehetbauer
// Copyright (c) 2015 Alexander Nimmervoll
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Text;
using CalDavSynchronizer.Ui.Options.Models;
namespace CalDavSynchronizer.Ui.Options.ViewModels
{
public class TimeRangeViewModel : ModelBase, IOptionsSection
{
private readonly OptionsModel _model;
public TimeRangeViewModel(OptionsModel model, IViewOptions viewOptions)
{
if (model == null) throw new ArgumentNullException(nameof(model));
if (viewOptions == null) throw new ArgumentNullException(nameof(viewOptions));
_model = model;
ViewOptions = viewOptions;
RegisterPropertyChangePropagation(_model, nameof(_model.UseSynchronizationTimeRange), nameof(UseSynchronizationTimeRange));
RegisterPropertyChangePropagation(_model, nameof(_model.DaysToSynchronizeInThePast), nameof(DaysToSynchronizeInThePast));
RegisterPropertyChangePropagation(_model, nameof(_model.DaysToSynchronizeInTheFuture), nameof(DaysToSynchronizeInTheFuture));
}
public bool UseSynchronizationTimeRange
{
get { return _model.UseSynchronizationTimeRange; }
set { _model.UseSynchronizationTimeRange = value; }
}
public int DaysToSynchronizeInThePast
{
get { return _model.DaysToSynchronizeInThePast; }
set { _model.DaysToSynchronizeInThePast = value; }
}
public int DaysToSynchronizeInTheFuture
{
get { return _model.DaysToSynchronizeInTheFuture; }
set { _model.DaysToSynchronizeInTheFuture = value; }
}
public IViewOptions ViewOptions { get; }
//public static TimeRangeViewModel DesignInstance { get; } = new TimeRangeViewModel
// {
// UseSynchronizationTimeRange = true,
// DaysToSynchronizeInTheFuture = 11,
// DaysToSynchronizeInThePast = 22
// };
}
}
|
agpl-3.0
|
C#
|
af04f9904a1be45992c876fa7ffdd8db5c37f681
|
Check if image is supported before uploading in the validation tag
|
stewartmatheson/CollAction,stewartmatheson/CollAction,stewartmatheson/CollAction,CollActionteam/CollAction,CollActionteam/CollAction,CollActionteam/CollAction,stewartmatheson/CollAction,CollActionteam/CollAction,CollActionteam/CollAction
|
CollAction/ValidationAttributes/MaxImageDimensionsAttribute.cs
|
CollAction/ValidationAttributes/MaxImageDimensionsAttribute.cs
|
using ImageSharp;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
namespace CollAction.ValidationAttributes
{
public class MaxImageDimensionsAttribute : ValidationAttribute
{
private readonly int _maxWidth;
private readonly int _maxHeight;
public MaxImageDimensionsAttribute(int width, int height)
{
_maxWidth = width;
_maxHeight = height;
}
public override bool IsValid(object value)
{
if (value == null) return true;
using (Stream imageStream = (value as IFormFile).OpenReadStream())
{
using (MemoryStream ms = new MemoryStream())
{
imageStream.CopyTo(ms);
try
{
using (Image image = Image.Load(ms.ToArray()))
{
return image.Width <= _maxWidth && image.Height <= _maxHeight;
}
}
catch (NotSupportedException)
{
return false;
}
}
}
}
public override string FormatErrorMessage(string name)
{
return string.Format("Only images with dimensions of or smaller than {0}x{1}px are accepted.", _maxWidth, _maxHeight);
}
}
}
|
using ImageSharp;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
namespace CollAction.ValidationAttributes
{
public class MaxImageDimensionsAttribute : ValidationAttribute
{
private readonly int _maxWidth;
private readonly int _maxHeight;
public MaxImageDimensionsAttribute(int width, int height)
{
_maxWidth = width;
_maxHeight = height;
}
public override bool IsValid(object value)
{
if (value == null) return true;
using (Stream imageStream = (value as IFormFile).OpenReadStream())
{
using (MemoryStream ms = new MemoryStream())
{
imageStream.CopyTo(ms);
using (Image image = Image.Load(ms.ToArray()))
{
return image.Width <= _maxWidth && image.Height <= _maxHeight;
}
}
}
}
public override string FormatErrorMessage(string name)
{
return string.Format("Only images with dimensions of or smaller than {0}x{1}px are accepted.", _maxWidth, _maxHeight);
}
}
}
|
agpl-3.0
|
C#
|
b9e364220ec74dcaf46159cc9a550b9070c9da98
|
Add more hosts to tokenserver
|
ukahoot/ukahoot,ukahoot/ukahoot,ukahoot/ukahoot,ukahoot/ukahoot,ukahoot/ukahoot.github.io,ukahoot/ukahoot.github.io,ukahoot/ukahoot.github.io
|
TokenServer/src/Main.cs
|
TokenServer/src/Main.cs
|
using System;
using System.Threading;
using System.Threading.Tasks;
namespace UKahoot {
class MainClass {
public static string[] Hosts = {
"tokenserver.ukahoot.it",
"http://tokenserver.ukahoot.it",
"https://tokenserver.ukahoot.it",
"http://www.tokenserver.ukahoot.it",
"https://www.tokenserver.ukahoot.it"
};
public static int Port = 5556;
public static TokenServer ts;
public static void Main(string[] args) {
ts = new TokenServer(Hosts, Port);
ts.Init();
Console.WriteLine("Token server started.");
Console.WriteLine("Port: " + Port);
Console.WriteLine("Hosts: " + Hosts.Length);
Console.WriteLine("Press any key to terminate the server.");
Console.ReadKey();
return;
}
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
namespace UKahoot {
class MainClass {
public static string[] Hosts = {
"tokenserver.ukahoot.it"
};
public static int Port = 5556;
public static TokenServer ts;
public static void Main(string[] args) {
ts = new TokenServer(Hosts, Port);
ts.Init();
Console.WriteLine("Token server started.");
Console.WriteLine("Port: " + Port);
Console.WriteLine("Hosts: " + Hosts.Length);
Console.WriteLine("Press any key to terminate the server.");
Console.ReadKey();
return;
}
}
}
|
mit
|
C#
|
14beed680f7965f048ceaf59bddcd28db04b5983
|
Change assertions in ProcessExtensions to have IProcess as return value.
|
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
|
source/Nuke.Core/Tooling/ProcessExtensions.cs
|
source/Nuke.Core/Tooling/ProcessExtensions.cs
|
// Copyright Matthias Koch 2018.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Core.Utilities;
namespace Nuke.Core.Tooling
{
[PublicAPI]
[DebuggerStepThrough]
[DebuggerNonUserCode]
public static class ProcessExtensions
{
[AssertionMethod]
public static IProcess AssertWaitForExit(
[AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull]
this IProcess process)
{
ControlFlow.Assert(process != null && process.WaitForExit(), "process != null && process.WaitForExit()");
return process;
}
[AssertionMethod]
public static IProcess AssertZeroExitCode(
[AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull]
this IProcess process)
{
process.AssertWaitForExit();
ControlFlow.Assert(process.ExitCode == 0,
new[]
{
$"Process '{Path.GetFileName(process.FileName)}' exited with code {process.ExitCode}. Please verify the invocation.",
$"> {process.FileName.DoubleQuoteIfNeeded()} {process.Arguments}"
}.JoinNewLine());
return process;
}
public static IEnumerable<Output> EnsureOnlyStd(this IEnumerable<Output> output)
{
var outputList = output.ToList();
foreach (var o in outputList)
{
ControlFlow.Assert(o.Type == OutputType.Std, "o.Type == OutputType.Std");
}
return outputList;
}
}
}
|
// Copyright Matthias Koch 2018.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Core.Utilities;
namespace Nuke.Core.Tooling
{
[PublicAPI]
[DebuggerStepThrough]
[DebuggerNonUserCode]
public static class ProcessExtensions
{
[AssertionMethod]
public static void AssertWaitForExit(
[AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull]
this IProcess process)
{
ControlFlow.Assert(process != null && process.WaitForExit(), "process != null && process.WaitForExit()");
}
[AssertionMethod]
public static void AssertZeroExitCode(
[AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull]
this IProcess process)
{
process.AssertWaitForExit();
ControlFlow.Assert(process.ExitCode == 0,
new[]
{
$"Process '{Path.GetFileName(process.FileName)}' exited with code {process.ExitCode}. Please verify the invocation.",
$"> {process.FileName.DoubleQuoteIfNeeded()} {process.Arguments}"
}.JoinNewLine());
}
public static IEnumerable<Output> EnsureOnlyStd(this IEnumerable<Output> output)
{
var outputList = output.ToList();
foreach (var o in outputList)
{
ControlFlow.Assert(o.Type == OutputType.Std, "o.Type == OutputType.Std");
}
return outputList;
}
}
}
|
mit
|
C#
|
719c0d30261c52dc6cc49253bf6ece2a50ec26e0
|
bump version
|
raml-org/raml-dotnet-parser-2,raml-org/raml-dotnet-parser-2
|
source/Raml.Parser/Properties/AssemblyInfo.cs
|
source/Raml.Parser/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("RAML.Parser")]
[assembly: AssemblyDescription("A RAML Parser implementation in .NET for all CLR languages. RESTful API Modeling Language (RAML) is a simple and succinct way of describing practically-RESTful APIs. It encourages reuse, enables discovery and pattern-sharing, and aims for merit-based emergence of best practices.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mulesoft Inc")]
[assembly: AssemblyProduct("Raml.Parser")]
[assembly: AssemblyCopyright("Copyright © 2015 MuleSoft")]
[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("d5f8e5f6-634a-4487-be70-591c4d8546f2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.9.6")]
|
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("RAML.Parser")]
[assembly: AssemblyDescription("A RAML Parser implementation in .NET for all CLR languages. RESTful API Modeling Language (RAML) is a simple and succinct way of describing practically-RESTful APIs. It encourages reuse, enables discovery and pattern-sharing, and aims for merit-based emergence of best practices.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mulesoft Inc")]
[assembly: AssemblyProduct("Raml.Parser")]
[assembly: AssemblyCopyright("Copyright © 2015 MuleSoft")]
[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("d5f8e5f6-634a-4487-be70-591c4d8546f2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.9.5")]
|
apache-2.0
|
C#
|
d55f8f3f7af437279f41615b7547461b1be58ba8
|
Remove unused parameter
|
Fody/PropertyChanged
|
PropertyChanged.Fody.Analyzer/ExtensionMethods.cs
|
PropertyChanged.Fody.Analyzer/ExtensionMethods.cs
|
global using static ExtensionMethods;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
[assembly: InternalsVisibleTo("PropertyChanged.Fody.Ananlyzer.Tests")]
static class ExtensionMethods
{
public static readonly SymbolDisplayFormat FullNameDisplayFormat = new(SymbolDisplayGlobalNamespaceStyle.Omitted, SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers);
public static readonly SymbolDisplayFormat NameDisplayFormat = new(SymbolDisplayGlobalNamespaceStyle.Omitted, SymbolDisplayTypeQualificationStyle.NameOnly, SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers);
public static IncrementalValuesProvider<TSource> ExceptNullItems<TSource>(this IncrementalValuesProvider<TSource?> source)
{
// ! We guarantee all items are not null:
return source.Where(static item => item is not null)!;
}
public static IEnumerable<BaseTypeSyntax> GetInterfaceTypeCandidates(this BaseListSyntax? baseListSyntax)
{
return baseListSyntax == null ? Enumerable.Empty<BaseTypeSyntax>() : baseListSyntax.Types.Where(type => type.ToString().EndsWith("INotifyPropertyChanged"));
}
public static string? NullIfEmpty(this string? value)
{
return string.IsNullOrEmpty(value) ? null : value;
}
public static IEnumerable<string> EnumerateContainingTypeNames(this INamedTypeSymbol? type)
{
while ((type = type?.ContainingType) != null)
{
yield return type.ToDisplayString(NameDisplayFormat);
}
}
public static bool HasImplementationAttribute(this ClassDeclarationSyntax classDeclaration)
{
return classDeclaration.AttributeLists.SelectMany(list => list.Attributes).Any(attr => attr.Name.ToString().Contains("AddINotifyPropertyChangedInterface"));
}
public static bool HasNoPropertyChangedEvent(this ClassDeclarationSyntax classDeclaration)
{
return classDeclaration.Members.OfType<EventFieldDeclarationSyntax>().SelectMany(member => member.Declaration.Variables).All(variable => variable.Identifier.Text != "PropertyChanged");
}
public static bool AreAllContainingTypesPartialClasses(this ClassDeclarationSyntax classDeclaration)
{
while (classDeclaration?.Parent is { } parent)
{
if (parent.IsKind(SyntaxKind.NamespaceDeclaration) || parent.IsKind(SyntaxKind.CompilationUnit))
return true;
if (parent is not ClassDeclarationSyntax parentClass || !parentClass.Modifiers.Any(SyntaxKind.PartialKeyword))
return false;
classDeclaration = parentClass;
}
return false;
}
[Conditional("DEBUG")]
public static void DebugBeep()
{
Task.Run(Console.Beep);
}
}
|
global using static ExtensionMethods;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
[assembly: InternalsVisibleTo("PropertyChanged.Fody.Ananlyzer.Tests")]
static class ExtensionMethods
{
public static readonly SymbolDisplayFormat FullNameDisplayFormat = new(SymbolDisplayGlobalNamespaceStyle.Omitted, SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers);
public static readonly SymbolDisplayFormat NameDisplayFormat = new(SymbolDisplayGlobalNamespaceStyle.Omitted, SymbolDisplayTypeQualificationStyle.NameOnly, SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers);
public static IncrementalValuesProvider<TSource> ExceptNullItems<TSource>(this IncrementalValuesProvider<TSource?> source)
{
// ! We guarantee all items are not null:
return source.Where(static item => item is not null)!;
}
public static IEnumerable<BaseTypeSyntax> GetInterfaceTypeCandidates(this BaseListSyntax? baseListSyntax, string name = "INotifyPropertyChanged")
{
return baseListSyntax == null ? Enumerable.Empty<BaseTypeSyntax>() : baseListSyntax.Types.Where(type => type.ToString().EndsWith(name));
}
public static string? NullIfEmpty(this string? value)
{
return string.IsNullOrEmpty(value) ? null : value;
}
public static IEnumerable<string> EnumerateContainingTypeNames(this INamedTypeSymbol? type)
{
while ((type = type?.ContainingType) != null)
{
yield return type.ToDisplayString(NameDisplayFormat);
}
}
public static bool HasImplementationAttribute(this ClassDeclarationSyntax classDeclaration)
{
return classDeclaration.AttributeLists.SelectMany(list => list.Attributes).Any(attr => attr.Name.ToString().Contains("AddINotifyPropertyChangedInterface"));
}
public static bool HasNoPropertyChangedEvent(this ClassDeclarationSyntax classDeclaration)
{
return classDeclaration.Members.OfType<EventFieldDeclarationSyntax>().SelectMany(member => member.Declaration.Variables).All(variable => variable.Identifier.Text != "PropertyChanged");
}
public static bool AreAllContainingTypesPartialClasses(this ClassDeclarationSyntax classDeclaration)
{
while (classDeclaration?.Parent is { } parent)
{
if (parent.IsKind(SyntaxKind.NamespaceDeclaration) || parent.IsKind(SyntaxKind.CompilationUnit))
return true;
if (parent is not ClassDeclarationSyntax parentClass || !parentClass.Modifiers.Any(SyntaxKind.PartialKeyword))
return false;
classDeclaration = parentClass;
}
return false;
}
[Conditional("DEBUG")]
public static void DebugBeep()
{
Task.Run(Console.Beep);
}
}
|
mit
|
C#
|
1a28abd6acb7eb9f7b500e4de47832604e71ce06
|
Fix Travis CI
|
lecaillon/Evolve
|
test/Evolve.Core.Test.Driver/DatabaseFixture.cs
|
test/Evolve.Core.Test.Driver/DatabaseFixture.cs
|
using System;
using System.Threading;
using Evolve.Test.Utilities;
using Xunit;
namespace Evolve.Core.Test
{
public class DatabaseFixture : IDisposable
{
public DatabaseFixture()
{
MsSql = new MsSqlDockerContainer();
MsSql.Start();
MySql = new MySqlDockerContainer();
MySql.Start();
Pg = new PostgreSqlDockerContainer();
Pg.Start();
Thread.Sleep(60000);
}
public MySqlDockerContainer MySql { get; }
public MsSqlDockerContainer MsSql { get; }
public PostgreSqlDockerContainer Pg { get; }
public void Dispose()
{
MySql.Dispose();
MsSql.Dispose();
Pg.Dispose();
}
}
[CollectionDefinition("Database collection")]
public class DatabaseCollection : ICollectionFixture<DatabaseFixture>
{
}
}
|
using System;
using System.Threading;
using Evolve.Test.Utilities;
using Xunit;
namespace Evolve.Core.Test
{
public class DatabaseFixture : IDisposable
{
public DatabaseFixture()
{
#if DEBUG
MySql = new MySqlDockerContainer();
MySql.Start();
MsSql = new MsSqlDockerContainer();
MsSql.Start();
Pg = new PostgreSqlDockerContainer();
Pg.Start();
Thread.Sleep(10000);
#endif
}
public MySqlDockerContainer MySql { get; }
public MsSqlDockerContainer MsSql { get; }
public PostgreSqlDockerContainer Pg { get; }
public void Dispose()
{
#if DEBUG
MySql.Dispose();
MsSql.Dispose();
Pg.Dispose();
#endif
}
}
[CollectionDefinition("Database collection")]
public class DatabaseCollection : ICollectionFixture<DatabaseFixture>
{
}
}
|
mit
|
C#
|
67ae232b46a6eda5ba30babc593989fc45cd8ed6
|
remove extraneous newline.
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Gui/Program.cs
|
WalletWasabi.Gui/Program.cs
|
using Avalonia;
using AvalonStudio.Shell;
using AvalonStudio.Shell.Extensibility.Platforms;
using NBitcoin;
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using WalletWasabi.Gui.ViewModels;
using WalletWasabi.Logging;
namespace WalletWasabi.Gui
{
internal class Program
{
#pragma warning disable IDE1006 // Naming Styles
private static async Task Main(string[] args)
#pragma warning restore IDE1006 // Naming Styles
{
StatusBarViewModel statusBar = null;
try
{
BuildAvaloniaApp().BeforeStarting(async builder =>
{
try
{
MainWindowViewModel.Instance = new MainWindowViewModel();
Logger.InitializeDefaults(Path.Combine(Global.DataDir, "Logs.txt"));
var configFilePath = Path.Combine(Global.DataDir, "Config.json");
var config = new Config(configFilePath);
await config.LoadOrCreateDefaultFileAsync();
Logger.LogInfo<Config>("Config is successfully initialized.");
Global.InitializeConfig(config);
if (!File.Exists(Global.IndexFilePath)) // Load the index file from working folder if we have it.
{
var cachedIndexFilePath = Path.Combine("Assets", Path.GetFileName(Global.IndexFilePath));
if (File.Exists(cachedIndexFilePath))
{
File.Copy(cachedIndexFilePath, Global.IndexFilePath, overwrite: false);
}
}
Global.InitializeNoWallet();
statusBar = new StatusBarViewModel(Global.Nodes.ConnectedNodes, Global.MemPoolService, Global.IndexDownloader, Global.UpdateChecker);
MainWindowViewModel.Instance.StatusBar = statusBar;
if (Global.IndexDownloader.Network != Network.Main)
{
MainWindowViewModel.Instance.Title += $" - {Global.IndexDownloader.Network}";
}
}
catch (Exception ex)
{
Logger.LogCritical<Program>(ex);
}
}).StartShellApp<AppBuilder, MainWindow>("Wasabi Wallet", null, () => MainWindowViewModel.Instance);
}
catch (Exception ex)
{
Logger.LogCritical<Program>(ex);
}
finally
{
statusBar?.Dispose();
await Global.DisposeAsync();
}
}
private static AppBuilder BuildAvaloniaApp()
{
return AppBuilder.Configure<App>().UsePlatformDetect().UseReactiveUI();
}
}
}
|
using Avalonia;
using AvalonStudio.Shell;
using AvalonStudio.Shell.Extensibility.Platforms;
using NBitcoin;
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using WalletWasabi.Gui.ViewModels;
using WalletWasabi.Logging;
namespace WalletWasabi.Gui
{
internal class Program
{
#pragma warning disable IDE1006 // Naming Styles
private static async Task Main(string[] args)
#pragma warning restore IDE1006 // Naming Styles
{
StatusBarViewModel statusBar = null;
try
{
BuildAvaloniaApp().BeforeStarting(async builder =>
{
try
{
MainWindowViewModel.Instance = new MainWindowViewModel();
Logger.InitializeDefaults(Path.Combine(Global.DataDir, "Logs.txt"));
var configFilePath = Path.Combine(Global.DataDir, "Config.json");
var config = new Config(configFilePath);
await config.LoadOrCreateDefaultFileAsync();
Logger.LogInfo<Config>("Config is successfully initialized.");
Global.InitializeConfig(config);
if (!File.Exists(Global.IndexFilePath)) // Load the index file from working folder if we have it.
{
var cachedIndexFilePath = Path.Combine("Assets", Path.GetFileName(Global.IndexFilePath));
if (File.Exists(cachedIndexFilePath))
{
File.Copy(cachedIndexFilePath, Global.IndexFilePath, overwrite: false);
}
}
Global.InitializeNoWallet();
statusBar = new StatusBarViewModel(Global.Nodes.ConnectedNodes, Global.MemPoolService, Global.IndexDownloader, Global.UpdateChecker);
MainWindowViewModel.Instance.StatusBar = statusBar;
if (Global.IndexDownloader.Network != Network.Main)
{
MainWindowViewModel.Instance.Title += $" - {Global.IndexDownloader.Network}";
}
}
catch (Exception ex)
{
Logger.LogCritical<Program>(ex);
}
}).StartShellApp<AppBuilder, MainWindow>("Wasabi Wallet", null, () => MainWindowViewModel.Instance);
}
catch (Exception ex)
{
Logger.LogCritical<Program>(ex);
}
finally
{
statusBar?.Dispose();
await Global.DisposeAsync();
}
}
private static AppBuilder BuildAvaloniaApp()
{
return AppBuilder.Configure<App>().UsePlatformDetect().UseReactiveUI();
}
}
}
|
mit
|
C#
|
4e460b3bf73cfdc723cfff5dae78900e2911c73a
|
Disable fog and clouds in all game modes
|
earalov/Skylines-FogOptions
|
FogOptions/LoadingExtension.cs
|
FogOptions/LoadingExtension.cs
|
using ICities;
namespace FogOptions
{
public class LoadingExtension : LoadingExtensionBase
{
public override void OnLevelLoaded(LoadMode mode)
{
base.OnLevelLoaded(mode);
FogController.Initialize();
}
public override void OnLevelUnloading()
{
base.OnLevelUnloading();
FogController.Dispose();
}
}
}
|
using ICities;
namespace FogOptions
{
public class LoadingExtension : LoadingExtensionBase
{
public override void OnLevelLoaded(LoadMode mode)
{
base.OnLevelLoaded(mode);
if (mode == LoadMode.LoadMap || mode == LoadMode.NewMap)
{
return;
}
FogController.Initialize();
}
public override void OnLevelUnloading()
{
base.OnLevelUnloading();
FogController.Dispose();
}
}
}
|
mit
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.