content stringlengths 23 1.05M |
|---|
namespace LionFire.FlexObjects
{
public class FlexObject : IFlex
{
public object Value { get; set; }
public FlexObject() { }
public FlexObject(object value)
{
Value = value;
}
public override string ToString() => Value == null ? "(null)" : Value.ToString();
}
}
|
using JetBrains.ReSharper.Daemon.CSharp.Stages;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Tree;
using ReSharper.Exceptional.Models;
using ReSharper.Exceptional.Settings;
namespace ReSharper.Exceptional.Contexts
{
internal class NullProcessContext : IProcessContext
{
public IAnalyzeUnit Model { get { return null; } }
public void StartProcess(IAnalyzeUnit analyzeUnit)
{
}
public void RunAnalyzers()
{
}
public void EnterTryBlock(ITryStatement tryStatement)
{
}
public void LeaveTryBlock()
{
}
public void EnterCatchClause(ICatchClause catchClauseNode)
{
}
public void LeaveCatchClause()
{
}
public void Process(IThrowStatement throwStatement)
{
}
public void Process(ICatchVariableDeclaration catchVariableDeclaration)
{
}
public void Process(IReferenceExpression invocationExpression)
{
}
public void Process(IObjectCreationExpression objectCreationExpression)
{
}
#if R8
public void Process(IDocCommentBlockNode docCommentBlockNode)
#endif
#if R9 || R10
public void Process(IDocCommentBlock docCommentBlockNode)
#endif
{
}
#if R2017_1
public void Process(IThrowExpression throwExpression)
{
}
#endif
public void EnterAccessor(IAccessorDeclaration accessorDeclarationNode)
{
}
public void LeaveAccessor()
{
}
}
} |
namespace System.Windows.Forms
{
public enum DataGridViewTriState
{
NotSet,
True,
False
}
}
|
using BcFileTool.CGUI.Controllers;
using BcFileTool.CGUI.Dialogs.ExtensionsEdit;
using BcFileTool.CGUI.Dialogs.Progress;
using BcFileTool.CGUI.Models;
using BcFileTool.CGUI.Services;
using BcFileTool.CGUI.Views;
using BcFileTool.Library.Interfaces.Services;
using BcFileTool.Library.Services;
using Microsoft.Extensions.DependencyInjection;
using System;
namespace BcFileTool.CGUI.Bootstrap
{
public class Bootstrapper
{
public const string SettingsFile = "bft.settings.yaml";
IServiceProvider _serviceProvider;
ISerializationService _serializationService;
IFileService _fileService;
public Bootstrapper SetUpDependencyInjection()
{
_serializationService = new YamlService();
_fileService = new FileService();
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
_serviceProvider = serviceCollection.BuildServiceProvider();
return this;
}
public MainController CreateMainController() =>
_serviceProvider.GetRequiredService<MainController>();
private void ConfigureServices(ServiceCollection serviceCollection)
{
ConfigureCommonServices(serviceCollection);
ConfigureModels(serviceCollection);
ConfigureViews(serviceCollection);
ConfigureControllers(serviceCollection);
}
private void ConfigureControllers(ServiceCollection serviceCollection)
{
serviceCollection.AddSingleton<SourcesController>();
serviceCollection.AddSingleton<ExtensionsController>();
serviceCollection.AddSingleton<OptionsController>();
serviceCollection.AddSingleton<MainController>();
}
private void ConfigureViews(ServiceCollection serviceCollection)
{
serviceCollection.AddSingleton<SourcesView>();
serviceCollection.AddSingleton<MainView>();
serviceCollection.AddSingleton<ExtensionsView>();
serviceCollection.AddSingleton<OptionsView>();
}
private void ConfigureModels(ServiceCollection serviceCollection)
{
var mainModel = LoadModel();
serviceCollection.AddSingleton<SourcesModel>(_ => mainModel.Sources);
serviceCollection.AddSingleton<ExtensionsModel>(_ => mainModel.Extensions);
serviceCollection.AddSingleton<OptionsModel>(_ => mainModel.Options);
serviceCollection.AddSingleton<MainModel>(_ => mainModel);
}
private void ConfigureCommonServices(ServiceCollection serviceCollection)
{
serviceCollection.AddSingleton<DisplayService>();
serviceCollection.AddSingleton<ExtensionsEditDialog>();
serviceCollection.AddSingleton<ProgressDialog>();
serviceCollection.AddSingleton<ISerializationService>(_ => _serializationService);
serviceCollection.AddSingleton<IFileService>(_ => _fileService);
}
private MainModel LoadModel()
{
if(!_fileService.FileExists(SettingsFile))
{
return new MainModel();
}
return _serializationService.Deserialize<MainModel>(SettingsFile);
}
}
}
|
using NuGet;
using Splat;
using Squirrel;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace TemplePlusConfig
{
class Program
{
private const string UpdateFeed = "https://templeplus.org/update-feeds/stable";
[STAThread]
public static void Main(string[] args)
{
bool firstStart = false;
// Note, in most of these scenarios, the app exits after this method
// completes!
HandleEvents(
onInitialInstall: () => CreateShortcuts(),
onAppUpdate: () => CreateShortcuts(),
onAppUninstall: () => RemoveShortcuts(),
onFirstRun: () =>{
firstStart = true;
var notifWnd = new InstalledNotifWnd();
notifWnd.ShowDialog();
});
App.LaunchAfterSave = firstStart;
App.Main();
}
private static void CreateShortcuts()
{
using (var mgr = new UpdateManager(UpdateFeed))
{
var update = Environment.CommandLine.Contains("squirrel-install") == false;
mgr.CreateShortcutsForExecutable("TemplePlusConfig.exe",
ShortcutLocation.StartMenu,
update,
null,
null);
// Get path to TemplePlus.exe and create shortcut for it
mgr.CreateShortcutsForExecutable("TemplePlus.exe",
ShortcutLocation.StartMenu,
update,
null,
null);
}
}
private static void RemoveShortcuts()
{
using (var mgr = new UpdateManager(UpdateFeed))
{
mgr.RemoveShortcutsForExecutable("TemplePlusConfig.exe", ShortcutLocation.StartMenu);
mgr.RemoveShortcutsForExecutable("TemplePlus.exe", ShortcutLocation.StartMenu);
}
}
/// <summary>
/// Call this method as early as possible in app startup. This method
/// will dispatch to your methods to set up your app. Depending on the
/// parameter, your app will exit after this method is called, which
/// is required by Squirrel. UpdateManager has methods to help you to
/// do this, such as CreateShortcutForThisExe.
/// </summary>
/// <param name="onInitialInstall">Called when your app is initially
/// installed. Set up app shortcuts here as well as file associations.
/// </param>
/// <param name="onAppUpdate">Called when your app is updated to a new
/// version.</param>
/// <param name="onAppObsoleted">Called when your app is no longer the
/// latest version (i.e. they have installed a new version and your app
/// is now the old version)</param>
/// <param name="onAppUninstall">Called when your app is uninstalled
/// via Programs and Features. Remove all of the things that you created
/// in onInitialInstall.</param>
/// <param name="onFirstRun">Called the first time an app is run after
/// being installed. Your application will **not** exit after this is
/// dispatched, you should use this as a hint (i.e. show a 'Welcome'
/// screen, etc etc.</param>
/// <param name="arguments">Use in a unit-test runner to mock the
/// arguments. In your app, leave this as null.</param>
public static void HandleEvents(
Action onInitialInstall = null,
Action onAppUpdate = null,
Action onAppObsoleted = null,
Action onAppUninstall = null,
Action onFirstRun = null,
string[] arguments = null)
{
Action defaultBlock = (() => { });
var args = arguments ?? Environment.GetCommandLineArgs().Skip(1).ToArray();
if (args.Length == 0) return;
var lookup = new[] {
new { Key = "--squirrel-install", Value = onInitialInstall ?? defaultBlock },
new { Key = "--squirrel-updated", Value = onAppUpdate ?? defaultBlock },
new { Key = "--squirrel-obsolete", Value = onAppObsoleted ?? defaultBlock },
new { Key = "--squirrel-uninstall", Value = onAppUninstall ?? defaultBlock },
}.ToDictionary(k => k.Key, v => v.Value);
if (args[0] == "--squirrel-firstrun")
{
(onFirstRun ?? (() => { }))();
return;
}
if (args.Length != 2) return;
if (!lookup.ContainsKey(args[0])) return;
try
{
lookup[args[0]]();
Environment.Exit(0);
}
catch (Exception ex)
{
LogHost.Default.ErrorException("Failed to handle Squirrel events", ex);
Environment.Exit(-1);
}
}
}
}
|
using IdeaStatiCa.BimImporter.Common;
using NUnit.Framework;
namespace IdeaStatiCa.BimImporter.Tests.Common
{
[TestFixture]
public class DoubleApproximateEqualityComparerTest
{
[Test]
public void GetHashCode_IfNumbersAreWithinPrecisionRange_HashCodesShouldNotEqual()
{
// Setup: with precision 0.1
DoubleApproximateEqualityComparer comparer = new DoubleApproximateEqualityComparer(0.1);
// Assert: 0.1 and 0.2 are within of 0.1 precision range, hashcodes shouldn't equal
Assert.That(comparer.GetHashCode(0.1), Is.Not.EqualTo(comparer.GetHashCode(0.2)));
}
[Test]
public void GetHashCode_IfNumbersAreOutsidePrecisionRange_HashCodesShouldEqual()
{
// Setup: with precision 0.1
DoubleApproximateEqualityComparer comparer = new DoubleApproximateEqualityComparer(0.1);
// Assert: 0.1 and 0.11 are outside of 0.1 precision range, hashcodes equal
Assert.That(comparer.GetHashCode(0.1), Is.EqualTo(comparer.GetHashCode(0.11)));
}
[Test]
public void GetHashCode_AfterChangingPrecision_IfNumbersAreWithinPrecisionRange_HashCodesShouldNotEqual()
{
// Setup: with precision 0.1
DoubleApproximateEqualityComparer comparer = new DoubleApproximateEqualityComparer(0.1);
// change precision to 0.01
comparer.Precision = 0.01;
// Assert: 0.1 and 0.11 are outside of 0.1 precision range, hashcodes equal
Assert.That(comparer.GetHashCode(0.1), Is.Not.EqualTo(comparer.GetHashCode(0.11)));
}
[Test]
public void Equals_IfNumbersAreWithinPrecisionRange_ShouldReturnFalse()
{
// Setup: with precision 0.1
DoubleApproximateEqualityComparer comparer = new DoubleApproximateEqualityComparer(0.1);
// Assert: 0.1 and 0.2 are within of 0.1 precision range, Equals should return false
Assert.That(comparer.Equals(0.1, 0.2), Is.False);
}
[Test]
public void Equals_IfNumbersAreOutsidePrecisionRange_ShouldReturnTrue()
{
// Setup: with precision 0.1
DoubleApproximateEqualityComparer comparer = new DoubleApproximateEqualityComparer(0.1);
// Assert: 0.1 and 0.15 are outside of 0.1 precision range, Equals should return true
Assert.That(comparer.Equals(0.1, 0.15), Is.True);
}
[Test]
public void Equals_AfterChangingPrecision_IfNumbersAreWithinPrecisionRange_ShouldReturnFalse()
{
// Setup: with precision 0.1
DoubleApproximateEqualityComparer comparer = new DoubleApproximateEqualityComparer(0.1);
comparer.Precision = 0.01;
Assert.That(comparer.Equals(0.1, 0.15), Is.False);
}
}
} |
using Microsoft.AspNetCore.Mvc;
namespace akabutbetter.Controllers
{
[Route("owner")]
[ApiController]
public class OwnerController : ControllerBase
{
}
} |
using ImageResizer.Plugins.UniqueUrlFolderPresets.Configuration;
using ImageResizer.Plugins.UniqueUrlFolderPresets.Helpers;
using NSubstitute;
using Shouldly;
using Xunit;
namespace ImageResizer.Plugins.UniqueUrlFolderPresets.Tests
{
public class ResizeHelperTests
{
[Theory]
[InlineData(null, "this", null)]
[InlineData("", "this", "")]
[InlineData(" ", "this", " ")]
[InlineData("xxx/yyy/zzz.png", null, "xxx/yyy/zzz.png")]
[InlineData("/xxx/yyy/zzz.png", null, "/xxx/yyy/zzz.png")]
[InlineData("xxx/yyy/zzz.png", "this", "/optimized/this/xxx/yyy/zzz.png")]
[InlineData("/xxx/yyy/zzz.png", "this", "/optimized/this/xxx/yyy/zzz.png")]
[InlineData("/optimized/this/xxx/yyy/zzz.png", "this", "/optimized/this/xxx/yyy/zzz.png")]
[InlineData("/optimized/that/xxx/yyy/zzz.png", "this", "/optimized/this/xxx/yyy/zzz.png")]
public void PrependResizingInstruction(string url, string preset, string expected)
{
var configuration = Substitute.For<IUniqueUrlFolderPresetsConfiguration>();
configuration.BaseSegment.Returns("optimized");
var sut = new ResizeHelper(configuration, new PresetParser(configuration));
var actual = sut.PrependResizingInstruction(url, preset);
actual.ShouldBe(expected);
}
}
} |
using Sparrow.Json.Parsing;
namespace Raven.Server.NotificationCenter.Notifications.Details
{
public class MessageDetails : INotificationDetails
{
public string Message { get; set; }
public DynamicJsonValue ToJson()
{
return new DynamicJsonValue(GetType())
{
[nameof(Message)] = Message
};
}
}
} |
using System;
namespace Gicco.Module.News.ViewModels
{
public class NewsItemThumbnail
{
public long Id { get; set; }
public string ShortContent { get; set; }
public string ImageUrl { get; set; }
public DateTimeOffset PublishedOn { get; set; }
public string Slug { get; set; }
}
}
|
using System.Collections.Generic;
namespace InfrastructureCli.Models;
public record AwsCloudFormationTemplateOptions
(
string? StackName,
bool? UseChangeSet,
string[]? Capabilities,
Dictionary<string, string>? Tags
);
|
using DAL.Models;
using System.Linq;
namespace BLL.QueryObjects.FilterDTOs
{
/// <summary>
/// Filter DTO used to filter user data in queries
/// </summary>
public class UserFilterDTO : QueryFilterDTO<User>
{
/// <summary>
/// Consturcts filter DTO that filters users based on given name
/// </summary>
/// <param name="name"> string name to filter on </param>
public UserFilterDTO(string name)
{
Filter.Add(queryable => queryable.Where(user => user.Name == name));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CefSharp
{
public interface IURLRequest : IDisposable
{
/// <summary>
/// True if the response was served from the cache.
/// </summary>
bool ResponseWasCached();
/// <summary>
/// The response, or null if no response information is available
/// </summary>
IResponse GetResponse();
/// <summary>
/// The request status.
/// </summary>
UrlRequestStatus GetRequestStatus();
}
}
|
using System;
using System.Collections.Generic;
namespace EnvironmentalMonitoringReciever
{
abstract class Program
{
private static readonly List<string> InputValues = new List<string>();
static void Main()
{
string s;
while ((s = Console.ReadLine()) != null)
{
InputValues.Add(s);
}
ReadConsoleOutput rd = new ReadConsoleOutput();
rd.ParseInputList();
}
private class ReadConsoleOutput
{
private int _val;
private void ReadTemperature(string input)
{
TemperatureValueChecker value = new TemperatureValueChecker();
TrimInputToGetValue(input);
value.Temperature(_val);
}
private void TrimInputToGetValue(string input)
{
string tmp = input.Split(':')[1].TrimStart();
try
{
_val = Convert.ToInt32(tmp);
}
catch (Exception)
{
Console.WriteLine("Value Not Present");
}
}
private void ReadHumidity(string input)
{
HumidityValueChecker value = new HumidityValueChecker();
TrimInputToGetValue(input);
value.Humidity(_val);
}
public void ParseInputList()
{
foreach (var input in InputValues)
{
if (input.StartsWith("Temperature"))
{
ReadConsoleOutput rd = new ReadConsoleOutput();
rd.ReadTemperature(input);
}
if (input.StartsWith("Humidity"))
{
ReadConsoleOutput rd = new ReadConsoleOutput();
rd.ReadHumidity(input);
}
}
}
}
}
}
|
using System;
using System.Diagnostics.CodeAnalysis;
namespace JetBrains.Annotations
{
[SuppressMessage("Microsoft.Naming",
"CA1726:UsePreferredTerms",
MessageId = "Flags",
Justification = "It is JetBrains code")]
[Flags]
public enum ImplicitUseKindFlags
{
Default = Access | Assign | InstantiatedWithFixedConstructorSignature,
/// <summary>
/// Only entity marked with attribute considered used
/// </summary>
Access = 1,
/// <summary>
/// Indicates implicit assignment to a member
/// </summary>
Assign = 2,
/// <summary>
/// Indicates implicit instantiation of a type with fixed constructor signature.
/// That means any unused constructor parameters won't be reported as such.
/// </summary>
InstantiatedWithFixedConstructorSignature = 4,
/// <summary>
/// Indicates implicit instantiation of a type
/// </summary>
InstantiatedNoFixedConstructorSignature = 8,
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSnowshoes
{
class ResolutionDisplayStyleManagement
{
private String resolutionReturn()
{
int screenX = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width;
int screenY = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height;
if (screenX == 1366 && screenY == 768)
{
return "1366x768";
}
else if (screenX == 1280 && screenY == 720)
{
return "1280x720";
}
else if (screenX == 3200 && screenY == 1800)
{
return "3200x1800";
}
else
{
return "unknown";
}
// This part of code was written for The Bridge build, yet does not need to be used as of yet (10/15/2014).
}
}
}
|
using Game;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using MonoGame.Extended.NuclexGui;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Game
{
class GameState : State
{
/// <summary>
/// The game being played
/// </summary>
protected Game G;
/// <summary>
/// Create a game interface from a given game
/// </summary>
/// <param name="Game">Game object that is being played</param>
public GameState(Game Game)
{
this.G = Game;
gui.Screen = new GuiScreen();
}
/// <summary>
/// State as of the previous Update
/// </summary>
private KeyboardState LastState;
/// <summary>
/// Run logic for this state - including input
/// </summary>
/// <param name="GameTime">Snapshot of timing</param>
public override void Update(GameTime GameTime)
{
// Get the current state, get the last state, and any new buttons are acted upon
var currentState = Keyboard.GetState();
foreach (var i in currentState.GetPressedKeys())
{
if (LastState.IsKeyUp(i))
{
KeyPressed(i);
}
}
LastState = currentState;
// Do turn, if player next move is set
//if (G.Player.NextMove != Player.Instruction.NOT_SET)
//{
// G.DoTurn();
//}
//if (G.GameOver)
//{
// StateStack.Add(new AtlasWarriors.LoseState(G));
//}
}
/// <summary>
/// Act upon a pressed key
/// </summary>
/// <param name="Key"></param>
private void KeyPressed(Keys Key)
{
switch (Key)
{
case Keys.H:
case Keys.Left:
case Keys.NumPad4:
//G.Player.NextMove = Player.Instruction.MOVE_W;
break;
case Keys.K:
case Keys.Up:
case Keys.NumPad8:
//G.Player.NextMove = Player.Instruction.MOVE_N;
break;
case Keys.L:
case Keys.Right:
case Keys.NumPad6:
//G.Player.NextMove = Player.Instruction.MOVE_E;
break;
case Keys.J:
case Keys.Down:
case Keys.NumPad2:
//G.Player.NextMove = Player.Instruction.MOVE_S;
break;
case Keys.Y:
case Keys.NumPad7:
//G.Player.NextMove = Player.Instruction.MOVE_NW;
break;
case Keys.U:
case Keys.NumPad9:
//G.Player.NextMove = Player.Instruction.MOVE_NE;
break;
case Keys.B:
case Keys.NumPad1:
//G.Player.NextMove = Player.Instruction.MOVE_SW;
break;
case Keys.N:
case Keys.NumPad3:
//G.Player.NextMove = Player.Instruction.MOVE_SE;
break;
}
}
/// <summary>
/// Draw this state
/// </summary>
/// <param name="GameTime">Snapshot of timing</param>
public override void Draw(GameTime GameTime)
{
AppSpriteBatch.Begin();
// Draw things here
AppSpriteBatch.End();
}
}
}
|
// This source code was generated by ClangCaster
namespace NWindowsKits
{
// C:/Program Files (x86)/Windows Kits/10/Include/10.0.18362.0/um/d3d11.h:7278
public enum D3D11_FEATURE
{
_THREADING = 0x0,
_DOUBLES = 0x1,
_FORMAT_SUPPORT = 0x2,
_FORMAT_SUPPORT2 = 0x3,
_D3D10_X_HARDWARE_OPTIONS = 0x4,
_D3D11_OPTIONS = 0x5,
_ARCHITECTURE_INFO = 0x6,
_D3D9_OPTIONS = 0x7,
_SHADER_MIN_PRECISION_SUPPORT = 0x8,
_D3D9_SHADOW_SUPPORT = 0x9,
_D3D11_OPTIONS1 = 0xa,
_D3D9_SIMPLE_INSTANCING_SUPPORT = 0xb,
_MARKER_SUPPORT = 0xc,
_D3D9_OPTIONS1 = 0xd,
_D3D11_OPTIONS2 = 0xe,
_D3D11_OPTIONS3 = 0xf,
_GPU_VIRTUAL_ADDRESS_SUPPORT = 0x10,
_D3D11_OPTIONS4 = 0x11,
_SHADER_CACHE = 0x12,
_D3D11_OPTIONS5 = 0x13,
}
}
|
// <copyright>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
namespace System.Runtime.Serialization
{
using System.Globalization;
/// <summary>
/// This class is used to customize the way DateTime is
/// serialized or deserialized by <see cref="Json.DataContractJsonSerializer"/>
/// </summary>
public class DateTimeFormat
{
private string formatString;
private IFormatProvider formatProvider;
private DateTimeStyles dateTimeStyles;
/// <summary>
/// Initailizes a new <see cref="DateTimeFormat"/> with the specified
/// formatString and DateTimeFormatInfo.CurrentInfo as the
/// formatProvider.
/// </summary>
/// <param name="formatString">Specifies the formatString to be used.</param>
public DateTimeFormat(string formatString) : this(formatString, DateTimeFormatInfo.CurrentInfo)
{
}
/// <summary>
/// Initailizes a new <see cref="DateTimeFormat"/> with the specified
/// formatString and formatProvider.
/// </summary>
/// <param name="formatString">Specifies the formatString to be used.</param>
/// <param name="formatProvider">Specifies the formatProvider to be used.</param>
public DateTimeFormat(string formatString, IFormatProvider formatProvider)
{
if (formatString == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("formatString");
}
if (formatProvider == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("formatProvider");
}
this.formatString = formatString;
this.formatProvider = formatProvider;
this.dateTimeStyles = DateTimeStyles.RoundtripKind;
}
/// <summary>
/// Gets the FormatString set on this instance.
/// </summary>
public string FormatString
{
get
{
return this.formatString;
}
}
/// <summary>
/// Gets the FormatProvider set on this instance.
/// </summary>
public IFormatProvider FormatProvider
{
get
{
return this.formatProvider;
}
}
/// <summary>
/// Gets or sets the <see cref="DateTimeStyles"/> on this instance.
/// </summary>
public DateTimeStyles DateTimeStyles
{
get
{
return this.dateTimeStyles;
}
set
{
this.dateTimeStyles = value;
}
}
}
}
|
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Roblox.Web.WebAPI.Pages
{
public class Docs : PageModel
{
public static string pageTitle { get; set; }
public static string pageDescription { get; set; }
public static string[] versions { get; set; }
public void OnGet()
{
}
}
} |
// This source code is dual-licensed under the Apache License, version
// 2.0, and the Mozilla Public License, version 1.1.
//
// The APL v2.0:
//
//---------------------------------------------------------------------------
// Copyright (C) 2007-2010 LShift Ltd., Cohesive Financial
// Technologies LLC., and Rabbit Technologies Ltd.
//
// 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.
//---------------------------------------------------------------------------
//
// The MPL v1.1:
//
//---------------------------------------------------------------------------
// The contents of this file are subject to the Mozilla Public License
// Version 1.1 (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.rabbitmq.com/mpl.html
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
// License for the specific language governing rights and limitations
// under the License.
//
// The Original Code is The RabbitMQ .NET Client.
//
// The Initial Developers of the Original Code are LShift Ltd,
// Cohesive Financial Technologies LLC, and Rabbit Technologies Ltd.
//
// Portions created before 22-Nov-2008 00:00:00 GMT by LShift Ltd,
// Cohesive Financial Technologies LLC, or Rabbit Technologies Ltd
// are Copyright (C) 2007-2008 LShift Ltd, Cohesive Financial
// Technologies LLC, and Rabbit Technologies Ltd.
//
// Portions created by LShift Ltd are Copyright (C) 2007-2010 LShift
// Ltd. Portions created by Cohesive Financial Technologies LLC are
// Copyright (C) 2007-2010 Cohesive Financial Technologies
// LLC. Portions created by Rabbit Technologies Ltd are Copyright
// (C) 2007-2010 Rabbit Technologies Ltd.
//
// All Rights Reserved.
//
// Contributor(s): ______________________________________.
//
//---------------------------------------------------------------------------
using System;
using System.Collections;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using RabbitMQ.Client.Impl;
namespace RabbitMQ.Client
{
///<summary>Represents a configurable SSL option, used
///in setting up an SSL connection.</summary>
public class SslOption
{
private bool m_enabled;
///<summary>Flag specifying if Ssl should indeed be
///used</summary>
public bool Enabled
{
get { return m_enabled; }
set { m_enabled = value; }
}
private SslProtocols m_version = SslProtocols.Ssl3;
///<summary>Retrieve or set the Ssl protocol version
///</summary>
public SslProtocols Version
{
get { return m_version; }
set { m_version = value; }
}
private string m_certPath;
///<summary>Retrieve or set the path to client certificate.
///</summary>
public string CertPath
{
get { return m_certPath; }
set { m_certPath = value; }
}
private string m_certPass;
///<summary>Retrieve or set the path to client certificate.
///</summary>
public string CertPassphrase
{
get { return m_certPass; }
set { m_certPass = value; }
}
///<summary>Convenience read-only property to retrieve an X509CertificateCollection
///containing the client certificate</summary>
public X509CertificateCollection Certs
{
get {
if(m_certPath == "") {
return null;
} else {
X509CertificateCollection c = new X509CertificateCollection();
c.Add(new X509Certificate2(m_certPath, m_certPass));
return c;
}
}
}
private string m_serverName;
///<summary>Retrieve or set server's Canonical Name. This MUST match the CN
///on the Certificate else the SSL connection will fail</summary>
public string ServerName
{
get { return m_serverName; }
set { m_serverName = value; }
}
private SslPolicyErrors m_acceptablePolicyErrors = SslPolicyErrors.None;
///<summary>Retrieve or set the set of ssl policy errors that
///are deemed acceptable</summary>
public SslPolicyErrors AcceptablePolicyErrors
{
get { return m_acceptablePolicyErrors; }
set { m_acceptablePolicyErrors = value; }
}
///<summary>Construct an SslOption specifying both the server cannonical name
///and the client's certificate path.
///</summary>
public SslOption(string serverName, string certPath, bool enabled)
{
m_serverName= serverName;
m_certPath = certPath;
m_enabled = enabled;
}
///<summary>Construct an SslOption with just the server cannonical name.
///The Certificate path is set to an empty string
///</summary>
public SslOption(string serverName): this(serverName, "", false)
{
}
///<summary>Construct an SslOption with no parameters set</summary>
public SslOption(): this("", "", false)
{
}
}
}
|
using Newtonsoft.Json;
namespace PasteMystNet
{
public class PasteMystPastyForm
{
[JsonProperty("_id", NullValueHandling = NullValueHandling.Ignore)] internal string? Id { get; init; }
[JsonProperty("title")] public string Title { get; set; } = string.Empty;
[JsonProperty("language")] public string Language { get; set; } = "Autodetect";
[JsonProperty("code")] public string Code { get; set; }
}
} |
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.CognitiveSearch.Search;
using Microsoft.CognitiveSearch.Skills.Cryptonyms;
using Microsoft.CognitiveSearch.Skills.Hocr;
using Microsoft.CognitiveSearch.Skills.Image;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.CognitiveSearch.WebApiSkills
{
public static class JfkWebApiSkills
{
private static string GetAppSetting(string key)
{
return Environment.GetEnvironmentVariable(key, EnvironmentVariableTarget.Process);
}
}
} |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
namespace Microsoft.Build.UnitTests
{
public class MockFaultInjectionHelper<FailurePointEnum>
where FailurePointEnum : IComparable
{
private FailurePointEnum _failureToInject;
private Exception _exceptionToThrow;
public MockFaultInjectionHelper()
{
}
public void InjectFailure(FailurePointEnum failureToInject, Exception exceptionToThrow)
{
_failureToInject = failureToInject;
_exceptionToThrow = exceptionToThrow;
}
public void FailurePointThrow(FailurePointEnum failurePointId)
{
if (_failureToInject.CompareTo(failurePointId) == 0)
{
throw _exceptionToThrow;
}
}
}
}
|
using System.Runtime.Serialization;
namespace MusicDb.Api.Dto.ArtistDto
{
[DataContract]
public class InputArtistData : BasicArtistData
{
}
}
|
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script> |
namespace Samples.HelloBlazorHybrid.Abstractions;
public interface ICounterService
{
[ComputeMethod]
Task<int> Get(CancellationToken cancellationToken = default);
Task Increment(CancellationToken cancellationToken = default);
}
|
using System;
using System.Linq;
using System.Runtime.InteropServices;
using HardyBits.Wrappers.Leptonica.Enums;
using HardyBits.Wrappers.Leptonica.Imports;
namespace HardyBits.Wrappers.Leptonica
{
public class Pix : IPix
{
private static readonly int[] AllowedDepths = { 1, 2, 4, 8, 16, 32 };
internal Pix(int imageWidth, int imageHeight, int imageDepth)
{
if (!AllowedDepths.Contains(imageDepth))
throw new ArgumentException("Depth must be 1, 2, 4, 8, 16, or 32 bits.", nameof(imageDepth));
if (imageWidth <= 0)
throw new ArgumentException("Width must be greater than zero", nameof(imageWidth));
if (imageHeight <= 0)
throw new ArgumentException("Height must be greater than zero", nameof(imageHeight));
var handle = Leptonica5Pix.pixCreate(imageWidth, imageHeight, imageDepth);
if (handle == IntPtr.Zero)
throw new InvalidOperationException("Failed to create leptonica pix.");
Handle = new HandleRef(this, handle);
Width = imageWidth;
Height = imageHeight;
Depth = imageDepth;
}
internal Pix(string imageFilePath)
{
if (imageFilePath == null)
throw new ArgumentNullException(nameof(imageFilePath));
if (!IsFileFormatSupported(imageFilePath, out _))
throw new ArgumentException("File format not supported or not recognized.", nameof(imageFilePath));
var handle = Leptonica5Pix.pixRead(imageFilePath);
if (handle == IntPtr.Zero)
throw new InvalidOperationException("Failed to read file.");
Handle = new HandleRef(this, handle);
Width = Leptonica5Pix.pixGetWidth(Handle);
Height = Leptonica5Pix.pixGetHeight(Handle);
Depth = Leptonica5Pix.pixGetDepth(Handle);
}
internal Pix(IntPtr handle)
{
if (handle == IntPtr.Zero)
throw new ArgumentNullException(nameof(handle), "Image pointer is null.");
Handle = new HandleRef(this, handle);
Width = Leptonica5Pix.pixGetWidth(Handle);
Height = Leptonica5Pix.pixGetHeight(Handle);
Depth = Leptonica5Pix.pixGetDepth(Handle);
}
public int Width { get; }
public int Height { get; }
public int Depth { get; }
public static bool IsFileFormatSupported(string filePath, out ImageFileFormat format)
{
if (filePath == null)
throw new ArgumentNullException(nameof(filePath));
return Leptonica5Pix.findFileFormat(filePath, out format) == 0;
}
public static unsafe bool IsFileFormatSupported(ReadOnlyMemory<byte> file, out ImageFileFormat format)
{
using var handle = file.Pin();
return Leptonica5Pix.findFileFormatBuffer(handle.Pointer, out format) == 0;
}
public int XRes
{
get => Leptonica5Pix.pixGetXRes(Handle);
private set => Leptonica5Pix.pixSetXRes(Handle, value);
}
public int YRes
{
get => Leptonica5Pix.pixGetYRes(Handle);
private set => Leptonica5Pix.pixSetYRes(Handle, value);
}
public HandleRef Handle { get; private set; }
public IPix Clone()
{
var clonePointer = Leptonica5Pix.pixClone(Handle);
if (clonePointer == IntPtr.Zero)
throw new InvalidOperationException("Failed to clone pix.");
return new Pix(clonePointer);
}
private void ReleaseUnmanagedResources()
{
var tmpHandle = Handle.Handle;
Leptonica5Pix.pixDestroy(ref tmpHandle);
Handle = new HandleRef(this, IntPtr.Zero);
}
public void Dispose()
{
ReleaseUnmanagedResources();
GC.SuppressFinalize(this);
}
~Pix()
{
ReleaseUnmanagedResources();
}
}
} |
// Copyright 2014 Pēteris Ņikiforovs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Latvian.Tokenization.Readers
{
public class PositionCounter
{
public PositionCounter()
{
}
public PositionCounter(PositionCounter other)
{
Position = other.Position;
Line = other.Line;
LinePosition = other.LinePosition;
}
public int Position { get; private set; }
public int Line { get; private set; }
public int LinePosition { get; private set; }
public void Add(char c)
{
Position++;
LinePosition++;
if (c == '\n')
{
Line++;
LinePosition = 0;
}
}
public void Add(string s)
{
foreach (char c in s)
{
Add(c);
}
}
}
abstract class CharReader : IDisposable
{
PositionCounter counter = new PositionCounter();
PositionCounter before = new PositionCounter();
public PositionCounter PositionCounter { get { return new PositionCounter(counter); } }
public int Position { get { return counter.Position; } }
public int Line { get { return counter.Line; } }
public int LinePosition { get { return counter.LinePosition; } }
public abstract bool IsEnd { get; }
public abstract char this[int position] { get; }
public abstract char Peek();
public abstract string Substring(int start, int end);
public virtual char Read()
{
char c = Peek();
counter.Add(c);
return c;
}
public virtual void MoveBack(int position)
{
counter = new PositionCounter(before);
while (counter.Position < position)
{
counter.Add(this[counter.Position]);
}
}
public virtual void Release()
{
before = new PositionCounter(counter);
}
public virtual void Reset()
{
counter = new PositionCounter();
before = new PositionCounter();
}
public virtual void Dispose()
{
counter = null;
before = null;
}
}
class StringCharReader : CharReader
{
string s;
public StringCharReader(string s)
{
this.s = s;
}
public override bool IsEnd
{
get { return Position >= s.Length; }
}
public override char this[int position]
{
get { return s[position]; }
}
public override char Peek()
{
return s[Position];
}
public override string Substring(int start, int end)
{
return s.Substring(start, end - start);
}
public override void Dispose()
{
s = null;
base.Dispose();
}
}
abstract class BufferingCharReader : CharReader
{
const int MinReleaseBufferSize = 16 * 1024;
int sourcePosition = 0;
bool sourceEnd = false;
int sourceReleasePosition = 0;
StringBuilder buffer = new StringBuilder();
int bufferPosition = 0;
int bufferStartsAtThisSourcePosition = 0;
protected abstract char? ReadNextFromSource();
public override bool IsEnd
{
get
{
if (sourceEnd)
return true;
if (buffer.Length > 0 && bufferPosition < buffer.Length)
return false;
char? next = ReadNextFromSource();
if (next != null)
{
buffer.Append(next.Value);
sourcePosition++;
return false;
}
sourceEnd = true;
return true;
}
}
public override char Peek()
{
if ((buffer.Length > 0 && bufferPosition < buffer.Length) || !IsEnd)
{
return buffer[bufferPosition];
}
throw new EndOfStreamException();
}
public override char Read()
{
char c = base.Read();
bufferPosition++;
return c;
}
public override char this[int position]
{
get { return buffer[position - bufferStartsAtThisSourcePosition]; }
}
public override string Substring(int start, int end)
{
int bufferStart = start - bufferStartsAtThisSourcePosition;
int bufferEnd = end - bufferStartsAtThisSourcePosition;
return buffer.ToString(bufferStart, bufferEnd - bufferStart);
}
public override void MoveBack(int position)
{
bufferPosition = position - bufferStartsAtThisSourcePosition;
base.MoveBack(position);
}
public override void Release()
{
sourceReleasePosition = Position;
if (bufferPosition >= MinReleaseBufferSize)
{
buffer.Remove(0, bufferPosition);
bufferStartsAtThisSourcePosition += bufferPosition;
bufferPosition = 0;
}
base.Release();
}
public override void Reset()
{
sourcePosition = 0;
sourceEnd = false;
sourceReleasePosition = 0;
buffer = new StringBuilder();
bufferPosition = 0;
bufferStartsAtThisSourcePosition = 0;
base.Reset();
}
public override void Dispose()
{
buffer = null;
base.Dispose();
}
}
class EnumeratorCharReader : BufferingCharReader
{
IEnumerator<char> source;
public EnumeratorCharReader(IEnumerable<char> source)
{
this.source = source.GetEnumerator();
}
protected override char? ReadNextFromSource()
{
if (source.MoveNext())
{
return source.Current;
}
return null;
}
public override void Reset()
{
source.Reset();
base.Reset();
}
public override void Dispose()
{
source.Dispose();
source = null;
base.Dispose();
}
}
class TextReaderCharReader : BufferingCharReader
{
TextReader textReader;
public TextReaderCharReader(TextReader textReader)
{
this.textReader = textReader;
}
protected override char? ReadNextFromSource()
{
int c = textReader.Read();
if (c != -1)
return (char)c;
return null;
}
public override void Reset()
{
throw new NotSupportedException();
}
public override void Dispose()
{
textReader.Dispose();
textReader = null;
base.Dispose();
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq.Expressions;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Query.Expressions;
using Microsoft.EntityFrameworkCore.Query.ExpressionTranslators;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Query.ExpressionVisitors
{
public class SqlTranslatingExpressionVisitorFactory : ISqlTranslatingExpressionVisitorFactory
{
private readonly IRelationalAnnotationProvider _relationalAnnotationProvider;
private readonly IExpressionFragmentTranslator _compositeExpressionFragmentTranslator;
private readonly IMethodCallTranslator _methodCallTranslator;
private readonly IMemberTranslator _memberTranslator;
public SqlTranslatingExpressionVisitorFactory(
[NotNull] IRelationalAnnotationProvider relationalAnnotationProvider,
[NotNull] IExpressionFragmentTranslator compositeExpressionFragmentTranslator,
[NotNull] IMethodCallTranslator methodCallTranslator,
[NotNull] IMemberTranslator memberTranslator)
{
Check.NotNull(relationalAnnotationProvider, nameof(relationalAnnotationProvider));
Check.NotNull(compositeExpressionFragmentTranslator, nameof(compositeExpressionFragmentTranslator));
Check.NotNull(methodCallTranslator, nameof(methodCallTranslator));
Check.NotNull(memberTranslator, nameof(memberTranslator));
_relationalAnnotationProvider = relationalAnnotationProvider;
_compositeExpressionFragmentTranslator = compositeExpressionFragmentTranslator;
_methodCallTranslator = methodCallTranslator;
_memberTranslator = memberTranslator;
}
public virtual SqlTranslatingExpressionVisitor Create(
RelationalQueryModelVisitor queryModelVisitor,
SelectExpression targetSelectExpression = null,
Expression topLevelPredicate = null,
bool bindParentQueries = false,
bool inProjection = false)
=> new SqlTranslatingExpressionVisitor(
_relationalAnnotationProvider,
_compositeExpressionFragmentTranslator,
_methodCallTranslator,
_memberTranslator,
Check.NotNull(queryModelVisitor, nameof(queryModelVisitor)),
targetSelectExpression,
topLevelPredicate,
bindParentQueries,
inProjection);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using WampSharp.V2.Rpc;
using TaskExtensions = WampSharp.Core.Utilities.TaskExtensions;
namespace WampSharp.CodeGeneration
{
internal class SimpleProxyMethodWriter : IProxyMethodWriter
{
private string mMethodTemplate =
@"
public {$returnType} {$methodName}({$parametersDeclaration})
{
{$return}{$methodHandler}({$parameterList});
}";
private string GetDelegateType(MethodInfo method)
{
string prefix = GetDelegateNamePrefix(method);
Type returnType = TaskExtensions.UnwrapReturnType(method.ReturnType);
string returnTypeAlias = FormatTypeExtensions.FormatType(returnType);
string result = $"{prefix}Delegate<{returnTypeAlias}>";
return result;
}
private static string GetDelegateNamePrefix(MethodInfo method)
{
string result;
if (method.GetCustomAttribute<WampProgressiveResultProcedureAttribute>() != null)
{
result = "InvokeProgressiveAsync";
}
else if (typeof(Task).IsAssignableFrom(method.ReturnType))
{
result = "InvokeAsync";
}
else
{
result = "InvokeSync";
}
return result;
}
public string WriteMethod(int methodIndex, MethodInfo method)
{
string methodHandler = "mMethodHandler" + methodIndex;
IDictionary<string, string> dictionary =
new Dictionary<string, string>();
IEnumerable<ParameterInfo> methodCallParameters = method.GetParameters();
IEnumerable<string> specialParameters = Enumerable.Empty<string>();
if (typeof(Task).IsAssignableFrom(method.ReturnType))
{
specialParameters = new[] { FormatTypeExtensions.FormatType(typeof(CancellationToken)) + ".None" };
}
if (typeof(Task).IsAssignableFrom(method.ReturnType) &&
methodCallParameters.LastOrDefault()?.ParameterType == typeof(CancellationToken))
{
specialParameters = new[] {methodCallParameters.LastOrDefault().Name};
methodCallParameters = methodCallParameters.Take(methodCallParameters.Count() - 1);
}
if (method.GetCustomAttribute<WampProgressiveResultProcedureAttribute>() != null)
{
specialParameters = new[] { methodCallParameters.LastOrDefault().Name }.Concat(specialParameters);
methodCallParameters = methodCallParameters.Take(methodCallParameters.Count() - 1);
}
dictionary["methodName"] = method.Name;
dictionary["parameterList"] =
string.Join(", ",
new[] {"this"}.Concat(specialParameters).Concat(methodCallParameters
.Select(x => x.Name)));
dictionary["returnType"] = FormatTypeExtensions.GetFormattedReturnType(method);
if (method.ReturnType != typeof(void))
{
dictionary["return"] = "return ";
}
else
{
dictionary["return"] = string.Empty;
}
dictionary["methodHandler"] = methodHandler;
dictionary["parametersDeclaration"] =
string.Join(", ",
method.GetParameters().Select
(x => FormatTypeExtensions.FormatType(x.ParameterType) + " " + x.Name));
return CodeGenerationHelper.ProcessTemplate(mMethodTemplate, dictionary);
}
private string mFieldTemplate =
@"private static readonly {$delegateType} mMethodHandler{$methodIndex} = Get{$delegatePrefix}<{$genericType}>(
GetMethodInfo(({$interfaceType} instance) => instance.{$methodName}({$defaults}))
);";
public string WriteField(int methodIndex, MethodInfo method)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
Type type = method.DeclaringType;
dictionary["methodIndex"] = methodIndex.ToString();
dictionary["delegateType"] = GetDelegateType(method);
dictionary["delegatePrefix"] = GetDelegateNamePrefix(method);
dictionary["interfaceType"] = FormatTypeExtensions.FormatType(type);
Type genericType = TaskExtensions.UnwrapReturnType(method.ReturnType);
dictionary["genericType"] = FormatTypeExtensions.FormatType(genericType);
dictionary["methodName"] = method.Name;
dictionary["defaults"] =
string.Join(", ",
method.GetParameters()
.Select(x => $"default({FormatTypeExtensions.FormatType(x.ParameterType)})"));
return CodeGenerationHelper.ProcessTemplate(mFieldTemplate, dictionary);
}
}
} |
// <copyright file="KeyGestureListener.cs" company="Velocity Systems">
// Copyright (c) 2020 Velocity Systems
// </copyright>
using System;
using System.Windows.Input;
using Xamarin.Forms;
namespace Velocity.Gestures.Forms
{
/// <summary>
/// A key interaction listener.
/// </summary>
public class KeyGestureListener : GestureListener
{
/// <summary>
/// The key(s) pressed event handler.
/// </summary>
public event EventHandler<KeyEventArgs> Pressed;
/// <summary>
/// The key down event handler.
/// </summary>
public event EventHandler<Key> KeyDown;
/// <summary>
/// The key up event handler.
/// </summary>
public event EventHandler<Key> KeyUp;
/// <summary>
/// Invoke the key(s) pressed event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="keys">The key(s) pressed.</param>
internal void InvokePressed(View sender, Key[] keys)
{
Pressed?.Invoke(sender, new KeyEventArgs(keys));
if (Command is ICommand cmd && cmd.CanExecute(CommandParameter))
{
cmd.Execute(CommandParameter);
}
}
/// <summary>
/// Invoke the key down event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="key">The key.</param>
internal void InvokeKeyDown(View sender, Key key) => KeyDown?.Invoke(sender, key);
/// <summary>
/// Invoke the key up event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="key">The key.</param>
internal void InvokeKeyUp(View sender, Key key) => KeyUp?.Invoke(sender, key);
}
} |
namespace RotaDasTapas.Constants
{
public static class ErrorConstants
{
public const string InternalError = "Something went wrong";
public const string UnauthorizedError = "Unauthorized: you can't access this request";
public const string InvalidDatetime = "Datetime provided is not valid";
public const string InvalidCountry = "Country invalid or not supported";
public const string InvalidLengthJourney = "Should have at least 3 Tapas to calculate the journey";
public const string InvalidListFormat = "Invalid format";
}
} |
using Harmony;
using Planetbase;
using PlanetbaseMultiplayer.Client;
using PlanetbaseMultiplayer.SharedLibs;
using PlanetbaseMultiplayer.SharedLibs.DataPackages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace PlanetbaseMultiplayer.Patcher.Patches
{
[HarmonyPatch(typeof(Module), "updateMining", new[] { typeof(float) })]
class Hook_UpdateMining
{
static bool Prefix(Module __instance, float timeStep)
{
if (!Globals.IsInMultiplayerMode) return true;
if (!Globals.LocalPlayer.IsSimulationOwner) return false;
return true;
}
}
}
|
using System.Collections.Generic;
using System.Web.Routing;
namespace CavemanTools.Mvc.Routing
{
/// <summary>
/// How to generate routes from actions
/// </summary>
public interface IRouteConvention
{
bool Match(ActionCall actionCall);
IEnumerable<Route> Build(ActionCall actionInfo);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WeddingBidders.Server.Models;
namespace WeddingBidders.Server.Dtos
{
public class CustomerDto
{
public CustomerDto()
{
}
public CustomerDto(Customer customer)
{
this.Id = customer.Id;
this.Firstname = customer.Firstname;
this.Lastname = customer.Lastname;
this.Email = customer.Email;
}
public int? Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public ProfileType ProfileType { get { return ProfileType.Customer; } }
}
} |
using Machine.Specifications;
using PlainElastic.Net.Mappings;
using PlainElastic.Net.Utils;
namespace PlainElastic.Net.Tests.Builders.Mappings
{
[Subject(typeof(NumberMap<>))]
class When_Number_mapping_for_string_type_built
{
Because of = () => result = new NumberMap<FieldsTestClass>()
.Field(doc => doc.StringProperty)
.Fields(f => f.String("multi_field"))
.ToString();
It should_start_from_specified_field_name = () => result.ShouldStartWith("'StringProperty': {".AltQuote());
It should_contain_double_type_declaration_part = () => result.ShouldContain("'type': 'double'".AltQuote());
It should_generate_correct_JSON_result = () => result.ShouldEqual(("'StringProperty': { 'type': 'double','fields': { 'multi_field': { 'type': 'string' } } }").AltQuote());
It should_contain_fields_part = () => result.ShouldContain("'fields': { 'multi_field': { 'type': 'string' } }".AltQuote());
private static string result;
}
}
|
using System;
using System.Collections.Generic;
using FreeSql.DataAnnotations;
using Newtonsoft.Json;
namespace LibCommon.Structs.DBModels
{
[Serializable]
/// <summary>
/// 超过限制时怎么处理
/// StopDvr=停止录制
/// DeleteFile=删除文件
/// </summary>
public enum OverStepPlan
{
StopDvr,
DeleteFile,
}
/// <summary>
/// 录制计划,是数据库StreamDvrPlan表的字段映射
/// </summary>
[Table(Name = "RecordPlan")]
[Index("idx_rp_name", "Name", true)]
[Serializable]
/// <summary>
/// 录制计划
/// </summary>
public class RecordPlan
{
/// <summary>
/// 数据库主键
/// </summary>
[Column(IsPrimary = true, IsIdentity = true)]
[JsonIgnore]
public int? Id { get; set; }
/// <summary>
/// 录制计划名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 是否启用该录制计划(true为启用)
/// </summary>
public bool Enable { get; set; }
/// <summary>
/// 录制计划的描述
/// </summary>
public string Describe { get; set; } = null!;
/// <summary>
/// 录制占用空间限制(Byte),最大录制到某个值后做相应处理
/// </summary>
public long? LimitSpace { get; set; }
/// <summary>
/// 录制占用天数限制,最大录制到某个值后做相应处理
/// </summary>
public int? LimitDays { get; set; }
/// <summary>
/// 具体的录制计划列表
/// </summary>
[Column(MapType = typeof(string))]
public OverStepPlan? OverStepPlan { get; set; }
[Navigate(nameof(RecordPlanRange.RecordPlanId))]
public List<RecordPlanRange> TimeRangeList { get; set; } = null!;
}
} |
using Aoc2019.Commands;
using Xunit;
namespace Aoc2019.Tests
{
public abstract class ModuleFuelCalculatorTests : CommandTestBase
{
public static string ModuleWeightKey = "mwk";
protected ModuleFuelCalculatorTests()
{
Cmd = new ModuleFuelCalculator(ModuleWeightKey);
}
public class Execute : ModuleFuelCalculatorTests
{
[Fact]
public void Should_add_entries_for_module_fuel_weight_into_data_dictionary()
{
Data.Add(ModuleWeightKey, new[] { 0 });
Cmd.Execute(Data);
Assert.Contains(ModuleFuelCalculator.DataKey, Data.Keys);
Assert.Contains(ModuleFuelCalculator.DataSumKey, Data.Keys);
}
[Theory]
[InlineData(12, 2)]
[InlineData(14,2)]
[InlineData(1969,654)]
[InlineData(100756,33583)]
public void Should_calculate_module_fuel_according_to_example(int input, int output)
{
Data.Add(ModuleWeightKey, new[]{input});
Cmd.Execute(Data);
Assert.Equal(output, ModuleFuelData[0]);
}
public int[] ModuleFuelData => (int[])Data[ModuleFuelCalculator.DataKey];
[Fact]
public void Should_sum_module_fuel_and_add_into_data_dictionary()
{
Data.Add(ModuleWeightKey, new[] { 12,12 });
Cmd.Execute(Data);
Assert.Equal(2+2, ModuleFuelSum);
}
public int ModuleFuelSum => (int)Data[ModuleFuelCalculator.DataSumKey];
}
}
}
|
/// <summary>
/// Interface for a Basic Grid Generator.
/// </summary>
public interface IGenerator
{
void Generate();
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using JetBrains.Annotations;
namespace Skyra.Core.Utils
{
public static class StringExtensions
{
private static readonly Regex EscapeRegex = new Regex(@"[-/\\^$*+?.()|[\]{}]");
[Pure]
[NotNull]
public static string Replace([NotNull] this string value, [NotNull] Regex pattern,
Func<Group[], string> callback)
{
var source = value;
var length = source.Length;
var lastIndex = 0;
var builder = new StringBuilder();
foreach (var match in value.Matches(pattern))
{
var index = match.Index;
builder.Append(source.Substring(lastIndex, index - lastIndex));
lastIndex = index + match.Length;
builder.Append(callback(match.Groups.Values.ToArray()));
}
if (lastIndex < length) builder.Append(source.Substring(lastIndex, length - lastIndex));
return builder.ToString();
}
[Pure]
[NotNull]
public static IEnumerable<Match> Matches([NotNull] this string value, [NotNull] Regex pattern)
{
return pattern.Matches(value, 0);
}
[Pure]
[NotNull]
public static string EscapeRegexPatterns([NotNull] this string value)
{
return value.Replace(EscapeRegex, groups => $"\\{groups[0]}");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NHibernate;
using NHibernate.Linq;
using Users.Domain.Common;
namespace Users.Infrastructure
{
public class UserRepository : IUserRepository
{
private readonly ISession _session;
public UserRepository(ISession session)
{
_session = session ?? throw new ArgumentNullException(nameof(session));
}
public Task<User> GetByIdAsync(Guid id, CancellationToken cancellation = default)
=> _session.GetAsync<User>(id, cancellation);
public Task<bool> EmailExistAsync(string email, CancellationToken cancellation = default)
=> _session.Query<User>()
.AnyAsync(x => x.Email == email, cancellation);
public Task RemoveAsync(Address address, CancellationToken cancellation = default)
=> _session.DeleteAsync(address, cancellation);
public Task RemoveAsync(Phone phone, CancellationToken cancellation = default)
=> _session.DeleteAsync(phone, cancellation);
public async Task SaveAsync(User user, CancellationToken cancellation = default)
{
await _session.SaveOrUpdateAsync(user, cancellation)
.ConfigureAwait(false);
await _session.FlushAsync(cancellation)
.ConfigureAwait(false);
}
public IEnumerable<User> GetAll(int skip, int take)
=> _session.Query<User>().Skip(skip).Take(take);
}
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="EntityComponentBehaviour.cs" company="Slash Games">
// Copyright (c) Slash Games. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Slash.Unity.Common.ECS
{
using Slash.ECS.Components;
using UnityEngine;
public class EntityComponentBehaviour<T> : MonoBehaviour
where T : class, IEntityComponent
{
#region Fields
public EntityBehaviour Entity;
#endregion
#region Properties
protected T Component { get; set; }
#endregion
#region Methods
protected void Start()
{
this.Component = this.Entity != null ? this.Entity.GetLogicComponent<T>() : null;
}
#endregion
}
} |
//--------------------------------------
// OpenTransfr
//
// For documentation or
// if you have any issues, visit
// opentrans.fr
//
// Licensed under MIT
//--------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using Wrench;
namespace OpenTransfr{
/// <summary>
/// Represents a location that a particular API is available at.
/// For example, 'txroot.opentrans.fr' is a location that the root API is available from.
/// </summary>
public class Location{
/// <summary>The DNS address.</summary>
public string Address;
/// <summary>The full URL of the location. Doesn't include the version (as the actual functions do).
/// Includes a trailing forward slash.</summary>
public string Url;
/// <summary>The API being used at this location.</summary>
public Api Api;
/// <summary>Don't use this directly; instead, see the Api.GetAt method.</summary>
internal Location(string address,Api api){
Address=address;
Api=api;
// Note we don't include version here as the function/type names include the version.
Url="https://"+Address+"/";
if(api.AvailableObjects==null){
// Load the index and apply it to available objects now:
api.AvailableObjects=GetIndex();
}
}
/// <summary>Gets the index of the API which lists all types/functions available.</summary>
public Dictionary<string,ApiObject> GetIndex(){
// Create the set:
Dictionary<string,ApiObject> set=new Dictionary<string,ApiObject>();
// Now we add the version:
string path=Url+Api.VersionString;
// Go get it:
HttpResponse req;
JSObject json=Http.RequestJson(path,out req);
// Load functions and types - we just put them all into a single buffer:
LoadIndex(json["functions"],set,false);
LoadIndex(json["types"],set,true);
return set;
}
/// <summary>Loads e.g. a set of functions described with JSON into a dictionary.</summary>
private void LoadIndex(JSObject data,Dictionary<string,ApiObject> set,bool isType){
// Get as array:
JSArray dataSet=data as JSArray;
// For each one in the data set..
foreach(KeyValuePair<string,JSObject> kvp in dataSet.Values){
// Transfer to set, creating an API function or API type for it:
JSObject value=kvp.Value;
// Get the path (including the version, but never a forward slash at the beginning):
string path=kvp.Key;
if(isType){
// Value is from the types set. Let's create an ApiType for it:
set[path]=new ApiType(value,Api,path);
}else{
// Value is from the functions set. Let's create an ApiFunction for it:
set[path]=new ApiFunction(value,Api,path);
}
}
}
/// <summary>Runs the given function at this location.</summary>
public JSObject Run(string function,JSObject payload,Signee signer){
// Get the function from the API:
ApiObject func=Api[function];
if(func==null){
// Function not found.
throw new Exception("The function '"+function+"' is not a valid function for this API.");
}
// Try running it:
return func.Run(payload,signer,this);
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DroidExplorer.Plugins.Data;
namespace DroidExplorer.Plugins.UI {
/// <summary>
///
/// </summary>
public partial class BartForm : Form {
ConsoleWriter cwOut = null;
ConsoleWriter cwError = null;
/// <summary>
/// Initializes a new instance of the <see cref="BartForm"/> class.
/// </summary>
public BartForm ( ) {
InitializeComponent ( );
cwOut = new ConsoleWriter ( ref this.console );
cwError = new ConsoleWriter ( ref this.console );
this.console.ReadOnly = true;
BartExecutor.Instance.ConsoleOutput = cwOut;
BartExecutor.Instance.ConsoleError = cwError;
BartExecutor.Instance.Complete += delegate ( object sender, EventArgs e ) {
backups.DataSource = BartExecutor.Instance.List ( );
};
backups.DataSource = BartExecutor.Instance.List ( );
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Form.Closing"/> event.
/// </summary>
/// <param name="e">A <see cref="T:System.ComponentModel.CancelEventArgs"/> that contains the event data.</param>
protected override void OnClosing ( CancelEventArgs e ) {
if ( BartExecutor.Instance.IsRunning ) {
if ( !BartExecutor.Instance.BaseProcess.HasExited ) {
BartExecutor.Instance.BaseProcess.Kill ( );
}
BartExecutor.Instance.BaseProcess = null;
}
base.OnClosing ( e );
}
/// <summary>
/// Handles the Click event of the create control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void create_Click ( object sender, EventArgs e ) {
if ( string.IsNullOrEmpty ( this.name.Text ) ) {
this.errorProvider.SetError ( this.name, "Name is required" );
this.errorProvider.SetIconAlignment ( this.name, ErrorIconAlignment.MiddleRight );
this.errorProvider.SetIconPadding ( this.name, 5 );
return;
}
this.errorProvider.Clear ( );
BartExecutor.Instance.Verbose = verbose.Checked;
BartExecutor.Instance.Compress = compress.Checked;
BartExecutor.Instance.IncludeBoot = includeBoot.Checked;
BartExecutor.Instance.IncludeData = includeData.Checked;
BartExecutor.Instance.IncludeRecovery = includeRecovery.Checked;
BartExecutor.Instance.IncludeSystem = includeSystem.Checked;
BartExecutor.Instance.CompletionTask = reboot.Checked ? CompleteTask.Reboot : shutdown.Checked ? CompleteTask.Shutdown : CompleteTask.None;
BartExecutor.Instance.Backup ( this.name.Text );
tabs.SelectedIndex = 2;
}
/// <summary>
/// Handles the Click event of the restore control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void restore_Click ( object sender, EventArgs e ) {
if ( backups.SelectedItem == null ) {
this.errorProvider.SetError ( this.restore, "You must select a ROM to restore" );
this.errorProvider.SetIconAlignment ( this.restore, ErrorIconAlignment.MiddleLeft );
this.errorProvider.SetIconPadding ( this.restore, 5 );
return;
}
this.errorProvider.Clear ( );
BartExecutor.Instance.Verbose = verbose.Checked;
BartExecutor.Instance.IncludeBoot = includeBoot.Checked;
BartExecutor.Instance.IncludeData = includeData.Checked;
BartExecutor.Instance.IncludeRecovery = includeRecovery.Checked;
BartExecutor.Instance.IncludeSystem = includeSystem.Checked;
BartExecutor.Instance.CompletionTask = reboot.Checked ? CompleteTask.Reboot : shutdown.Checked ? CompleteTask.Shutdown : CompleteTask.None;
BartExecutor.Instance.Restore ( (string)backups.SelectedItem );
tabs.SelectedIndex = 2;
}
/// <summary>
/// Handles the Click event of the gotoCreate control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void gotoCreate_Click ( object sender, EventArgs e ) {
tabs.SelectedIndex = 1;
}
/// <summary>
/// Handles the Click event of the delete control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void delete_Click ( object sender, EventArgs e ) {
if ( backups.SelectedItem == null ) {
this.errorProvider.SetError ( this.delete, "You must select a ROM to delete" );
this.errorProvider.SetIconAlignment ( this.delete, ErrorIconAlignment.MiddleRight );
this.errorProvider.SetIconPadding ( this.delete, 5 );
return;
}
this.errorProvider.Clear ( );
DialogResult dr = MessageBox.Show ( this, string.Format ( "Are you sure you want to remove '{0}'? This can not be undone.", (string)backups.SelectedItem ), "Confirm Delete", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question );
switch ( dr ) {
case DialogResult.Cancel:
case DialogResult.No:
return;
case DialogResult.Yes:
BartExecutor.Instance.Delete ( (string)backups.SelectedItem );
tabs.SelectedIndex = 2;
break;
}
}
/// <summary>
/// Handles the Click event of the close control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void close_Click ( object sender, EventArgs e ) {
this.Close ( );
}
}
}
|
namespace _3.Megapixels
{
using System;
public class Program
{
public static void Main()
{
var width = int.Parse(Console.ReadLine());
var heigth = int.Parse(Console.ReadLine());
var megapixels = (width * heigth)/ 1000000.0;
Console.WriteLine($"{width}x{heigth} => {Math.Round(megapixels, 1)}MP");
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MZUtils;
namespace QEditor
{
public partial class FormSelectableItemList : Form
{
/// <summary>
/// 新しいインスタンスを構築する。
/// </summary>
public FormSelectableItemList()
{
InitializeComponent();
}
/// <summary>
/// 選択可能な項目リストを設定する。
/// </summary>
/// <param name="items">項目リスト</param>
public void SetItemList(List<IItem> items)
{
listBoxItems.Items.Clear();
foreach (IItem item in items)
{
listBoxItems.Items.Add(item);
}
}
/// <summary>
/// アイテムが選択されたときに通知する。
/// </summary>
public event EventHandler ItemSelected;
/// <summary>
/// リストボックスの項目を描画するときに通知を受け取る。
/// </summary>
/// <param name="sender">送信元オブジェクト</param>
/// <param name="e">イベントオブジェクト</param>
private void OnListBoxDrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
ListBox listBox = (ListBox)(sender);
if (e.Index >= 0)
{
IItem item = (IItem)(listBox.Items[e.Index]);
string text = string.Empty;
if (item is DataItem di)
{
text = "Item:" + di.Id + ":" + di.Name;
}
else if (item is DataWeapon dw)
{
text = "Weapon:" + dw.Id + ":" + dw.Name;
}
else if (item is DataArmor da)
{
text = "Weapon:" + da.Id + ":" + da.Name;
}
using (Brush brush = new SolidBrush(e.ForeColor))
{
e.Graphics.DrawString(text, e.Font, brush, e.Bounds);
}
}
e.DrawFocusRectangle();
}
/// <summary>
/// 追加ボタンがクリックされたときに通知を受け取る。
/// </summary>
/// <param name="sender">送信元オブジェクト</param>
/// <param name="e">イベントオブジェクト</param>
private void OnButtonAddClick(object sender, EventArgs e)
{
if (listBoxItems.SelectedIndex >= 0)
{
this.ItemSelected?.Invoke(this, new EventArgs());
}
}
/// <summary>
/// アイテムリストでダブルクリックされたときに通知を受け取る。
/// </summary>
/// <param name="sender">送信元オブジェクト</param>
/// <param name="e">イベントオブジェクト</param>
private void OnItemListDoubleClick(object sender, EventArgs e)
{
if (listBoxItems.SelectedIndex >= 0)
{
this.ItemSelected?.Invoke(this, new EventArgs());
}
}
/// <summary>
/// 選択されている項目
/// </summary>
public IItem SelectedItem {
get {
return (IItem)(listBoxItems.SelectedItem);
}
}
/// <summary>
/// クローズボタンがクリックされたときに通知を受け取る。
/// </summary>
/// <param name="sender">送信元オブジェクト</param>
/// <param name="e">イベントオブジェクト</param>
private void OnButtonCancelClick(object sender, EventArgs e)
{
Close();
}
}
}
|
using JT808.Protocol.Attributes;
using JT808.Protocol.Formatters.MessageBodyFormatters;
using System;
namespace JT808.Protocol.MessageBody
{
/// <summary>
/// 查询指定终端参数
/// 0x8106
/// </summary>
[JT808Formatter(typeof(JT808_0x8106_Formatter))]
public class JT808_0x8106 : JT808Bodies
{
/// <summary>
/// 参数总数
/// 参数总数为 n
/// </summary>
public byte ParameterCount { get; set; }
/// <summary>
/// 参数 ID 列表
/// 参数顺序排列,如“参数 ID1 参数 ID2......参数IDn”。
/// </summary>
public UInt32[] Parameters { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DAF.Core
{
/// <summary>
/// The global session factory. It holds global configuration for all sessions and create global session object.
/// </summary>
public class SessionFactory : ISessionFactory
{
public DataAccessConfiguration Configuration { get; private set; }
public ICachePool CachePool { get; private set; }
public SessionFactory(DataAccessConfiguration configuration)
{
Configuration = configuration;
CachePool = new Caching.CachePool(configuration);
}
public ISession CreateSession()
{
return new Core.Session(this);
}
public ISession CreateSession(ISecurityToken token)
{
return new Core.Session(this, token);
}
}
}
|
namespace DAO
{
public class DAOShiftReportList : List<DAOShiftReport>
{
}
}
|
using Client = GuardianRP.Service.SocketClient.SocketClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using GuardianRP.Service.SocketClient.Event;
namespace GuardianRP.Services.Tcp {
public class TcpSocketService : TcpListener {
private readonly List<Client> _clients = new List<Client>();
public readonly int Port;
public readonly IReadOnlyList<Client> Clients;
public event EventHandler<SocketClientEventArgs> OnClientConnected = delegate { };
public TcpSocketService(int port) : base(IPAddress.Any, port) {
Port = port;
Clients = _clients.AsReadOnly();
}
public new void Start() {
base.Start();
BeginAcceptingClients();
Console.WriteLine($"Started listening for incomming TCP connections on port {Port}.");
}
private void BeginAcceptingClients() {
BeginAcceptSocket(new AsyncCallback(OnClientAccepted), this);
}
private void OnClientAccepted(IAsyncResult result) {
Socket socket = EndAcceptSocket(result);
Client client = new Client(socket);
client.Start();
_clients.Add(client);
client.OnConnectionStateChanged += (sender, args) => {
if(args.Connected)
return;
Console.WriteLine($"Client from {client.Ip} has disconnected.");
client.Stop();
_clients.Remove(client);
};
client.OnMessageReceived += (sender, args) => {
Console.WriteLine($"[{client.Ip}] {args.Message}");
};
Console.WriteLine($"Client from {client.Ip} was accepted.");
OnClientConnected(this, new SocketClientEventArgs(client));
BeginAcceptingClients();
}
public void Broadcast(string message) {
byte[] payload = Encoding.UTF8.GetBytes(message);
foreach(Client client in Clients)
client.Send(payload);
}
}
}
|
namespace Appeon.SnapObjectsDemo.Services
{
public interface IGenericServiceFactory
{
IGenericService<TModel> Get<TModel>();
}
}
|
using DragonMail.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace DragonMail.POPWorkerRole.Commands
{
public abstract class BasePOPCommand : TCPServiceCommand
{
protected List<DSMail> mailBoxMail;
protected BasePOPCommand(NetworkStream clientStream, List<DSMail> mailBoxMail)
: base(clientStream)
{
this.mailBoxMail = mailBoxMail;
}
public override void Execute(string message)
{
throw new NotImplementedException();
}
}
}
|
using System;
using HelperFramework.DataType;
namespace WordfeudHelper.Business
{
class Letter : StaticList<Letter>
{
public String Charackter { get; private set; }
public Int32 Count { get; private set; }
public Int32 Points { get; private set; }
public Letter(String charakter, Int32 points, Int32 count)
{
Charackter = charakter.ToUpper();
Count = count;
Points = points;
}
public Letter(String charakter, Int32 points)
: this(charakter, points, 1) { }
public Letter(String charakter)
: this(charakter, 1, 1) { }
public Letter() { }
public class Dutch : StaticList<Letter>
{
public static Letter A = new Letter("a", 1, 7);
public static Letter B = new Letter("b", 4, 2);
public static Letter C = new Letter("c", 5, 2);
public static Letter D = new Letter("d", 2, 5);
public static Letter E = new Letter("e", 1, 18);
public static Letter F = new Letter("f", 4, 2);
public static Letter G = new Letter("g", 3, 3);
public static Letter H = new Letter("h", 4, 2);
public static Letter I = new Letter("i", 2, 4);
public static Letter J = new Letter("j", 4, 2);
public static Letter K = new Letter("k", 3, 3);
public static Letter L = new Letter("l", 3, 3);
public static Letter M = new Letter("m", 3, 3);
public static Letter N = new Letter("n", 1, 11);
public static Letter O = new Letter("o", 1, 6);
public static Letter P = new Letter("p", 4, 2);
public static Letter Q = new Letter("q", 10, 1);
public static Letter R = new Letter("r", 2, 5);
public static Letter S = new Letter("s", 2, 5);
public static Letter T = new Letter("t", 2, 5);
public static Letter U = new Letter("u", 2, 3);
public static Letter V = new Letter("v", 4, 2);
public static Letter W = new Letter("w", 5, 2);
public static Letter X = new Letter("x", 8, 1);
public static Letter Y = new Letter("y", 8, 1);
public static Letter Z = new Letter("z", 5, 2);
}
}
} |
namespace Template
{
public class CignaPharmacyInsuranceValidator : PharmacyInsuranceValidator
{
public CignaPharmacyInsuranceValidator(PatientProfile patient) : base(patient)
{
}
protected override decimal GetCoveragePrice(Drug drug)
{
return drug.Price / 2;
}
protected override bool IsDrugCovered(Drug drug)
{
return (drug.DrugCode.StartsWith("CI"));
}
protected override void CreatePatientSummaryReport()
{
System.Console.WriteLine($"Patient Summary Report created in CIGNA format");
}
}
} |
using System;
using System.Collections.Generic;
using OneWindow_Unity.Interfaces;
using UnityEngine;
namespace OneWindow_Unity.Unity
{
public class Fake : WindowInterface
{
private string title = "Title";
private string version = "v";
private ContentLocation location = ContentLocation.UpperCenter;
private bool showL;
private bool showR;
private bool showK;
private bool showS;
private Vector2 size = new Vector2(560, 300);
private Vector2 pos = new Vector2(40, -100);
public Fake()
{
location = ContentLocation.UpperCenter;
}
public string Title { get { return title; } }
public string Version { get { return version; } }
public bool ShowLocationIcon
{
get { return showL; }
set { showL = value; }
}
public bool ShowRealTime
{
get { return showR; }
set { showR = value; }
}
public bool ShowKSPTime
{
get { return showK; }
set { showK = value; }
}
public bool ShowStandardMessages
{
get { return showS; }
set { showS = value; }
}
public Vector2 Position
{
get { return pos; }
set { pos = value; }
}
public Vector2 Size
{
get { return size; }
set { size = value; }
}
public void ClampToScreen(RectTransform rect)
{
}
public ContentLocation Location { get { return location; } set { location = value; } }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Const = SeeReal.GlobalConstants;
namespace SeeReal
{
public class SettingStruct
{
/// <summary>
/// 버튼간 간격
/// </summary>
public int Margin { get; set; }
/// <summary>
/// 언어 설정값
/// </summary>
public Const.LanguageType LanguageType { get; set; }
/// <summary>
/// 테마 설정값
/// </summary>
public Const.ThemeType ThemeType { get; set; }
/// <summary>
/// 스타일 설정값
/// </summary>
public Const.StyleType StyleType { get; set; }
/// <summary>
/// Tray Icon 사용 유무
/// </summary>
public bool TrayIconEnable { get; set; }
}
}
|
using System.Management.Automation;
using WebApiConsumer = Microsoft.VisualStudio.Services.ServiceHooks.WebApi.Consumer;
namespace TfsCmdlets.Cmdlets.ServiceHook
{
/// <summary>
/// Gets one or more service hook consumers.
/// </summary>
/// <remarks>
/// Service hook consumers are the services that can consume (receive) notifications triggered by
/// Azure DevOps. Examples of consumers available out-of-box with Azure DevOps are Microsoft Teams,
/// Slack, Trello ou the generic WebHook consumer. Use this cmdlet to list the available consumers and get
/// the ID of the desired one to be able to manage service hook subscriptions.
/// </remarks>
[TfsCmdlet(CmdletScope.Collection, OutputType = typeof(WebApiConsumer))]
partial class GetServiceHookConsumer
{
/// <summary>
/// Specifies the name or ID of the service hook consumer to return. Wildcards are supported.
/// When omitted, all service hook consumers registered in the given project collection/organization
/// are returned.
/// </summary>
[Parameter(Position = 0)]
[SupportsWildcards()]
[Alias("Name", "Id")]
public string Consumer { get; set; } = "*";
}
} |
using System.Collections.Generic;
using TBNMobile.UserInterface.Models;
using Xamarin.Forms;
namespace TBNMobile.UserInterface
{
public partial class MasterPage : ContentPage
{
public string SocialMediaHeader => "Join us on the web!";
public string MainMenuHeader => "The Brewing Network";
public ListView MainMenu => mainMenu;
public ListView SocialMediaMenu => socialMediaMenu;
public MasterPage ()
{
InitializeComponent ();
BindingContext = this;
var masterPageItems = new List<MasterPageItem>
{
new MasterPageItem
{
Title = "Live Stream",
IconSource = "live.png",
TargetType = typeof(LiveStreamPage)
},
new MasterPageItem
{
Title = "Show Archive",
IconSource = "archive.png",
TargetType = typeof(ShowArchivesPage)
},
new MasterPageItem
{
Title = "Settings",
IconSource = "settings.png",
TargetType = typeof(SettingsPage)
}
};
mainMenu.ItemsSource = masterPageItems;
var socialMediaItems = new List<SocialMediaItem>
{
new SocialMediaItem
{
Title = "The Forums",
IconSource = "archive.png",
URL = "http://www.thebrewingnetwork.com/forum/"
},
new SocialMediaItem
{
Title = "Facebook",
IconSource = "archive.png",
URL = "https://www.facebook.com/brewingnetwork/"
},
new SocialMediaItem
{
Title = "Twitter",
IconSource = "archive.png",
URL = "https://twitter.com/brewingnetwork"
},
new SocialMediaItem
{
Title = "Instagram",
IconSource = "archive.png",
URL = "https://www.instagram.com/brewingnetwork/"
}
};
socialMediaMenu.ItemsSource = socialMediaItems;
}
}
}
|
using NUnit.Framework;
using System;
using System.Collections.Generic;
namespace Nez.Persistence.JsonTests
{
[TestFixture]
public class TypeHintAndReferencesTests
{
class Entity
{
[JsonInclude]
public bool enabled { get; set; } = true;
public List<Component> components;
[BeforeEncode]
public void BeforeDecode()
{
System.Console.WriteLine( "Entity.BeforeEncode" );
}
[AfterDecode]
public void AfterDecode()
{
System.Console.WriteLine( "Entity.AfterDecode" );
}
}
class Component
{
public Entity entity;
public int index;
}
class Sprite : Component
{ }
[Test]
public void TypeHintAuto()
{
var entity = new Entity
{
components = new List<Component> { new Component(), new Sprite() }
};
var json = Json.ToJson( entity, new JsonSettings
{
PrettyPrint = true,
TypeNameHandling = TypeNameHandling.Auto
} );
var outEntity = Json.FromJson<Entity>( json );
Assert.IsInstanceOf( typeof( Sprite ), outEntity.components[1] );
outEntity = Json.FromJson<Entity>( json );
Assert.IsInstanceOf( typeof( Sprite ), outEntity.components[1] );
}
[Test]
public void PreserveReferences_Preserves()
{
var entity = new Entity();
entity.components = new List<Component> { new Component(), new Sprite { entity = entity } };
var json = Json.ToJson( entity, new JsonSettings
{
PrettyPrint = true,
TypeNameHandling = TypeNameHandling.Auto,
PreserveReferencesHandling = true
} );
var outEntity = Json.FromJson<Entity>( json );
Assert.AreEqual( outEntity, outEntity.components[1].entity );
}
[Test]
public void ArrayTypeHint_Hints()
{
var entity = new Entity();
entity.components = new List<Component> { new Component(), new Sprite { entity = entity } };
var json = Json.ToJson( entity, new JsonSettings
{
PrettyPrint = true,
TypeNameHandling = TypeNameHandling.Arrays,
PreserveReferencesHandling = true
} );
var outEntity = Json.FromJson<Entity>( json );
Assert.IsInstanceOf( typeof( Sprite ), outEntity.components[1] );
}
[Test]
public void NoTypeHint_DoesntHint()
{
var entity = new Entity();
entity.components = new List<Component> { new Component(), new Sprite { entity = entity } };
var json = Json.ToJson( entity, new JsonSettings
{
PreserveReferencesHandling = true
} );
var outEntity = Json.FromJson<Entity>( json );
Assert.IsNotInstanceOf( typeof( Sprite ), outEntity.components[1] );
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
public class PauseMenu : MonoBehaviour
{
public GameObject pauseMenu;
public GameObject optionsMenu;
public static bool isPaused;
public static bool isOptions;
private Controls playerControlsAction;
private PlayerInput playerInput;
// Start is called before the first frame update
void Start()
{
pauseMenu.SetActive(false);
optionsMenu.SetActive(false);
playerControlsAction = new Controls();
playerInput = GetComponent<PlayerInput>();
}
/**
private void OnEnable()
{
playerControlsAction.Enable();
}
private void OnDisable()
{
playerControlsAction.Disable();
}*/
// Update is called once per frame
void Update()
{
/**
bool pressPause = playerControlsAction.Gameplay.OpenPauseMenu.ReadValue<bool>();
if (pressPause == true)
{
if (isOptions)
{
CloseOptions();
}
else if (isPaused)
{
ResumeGame();
}
else
{
PauseGame();
}
}*/
Debug.Log(playerInput.currentActionMap);
}
private void SwitchActionMapPaused()
{
//playerInput.SwitchCurrentActionMap("Paused");
playerControlsAction.Paused.Enable();
playerControlsAction.Gameplay.Disable();
}
private void SwitchActionMapResume()
{
//playerInput.SwitchCurrentActionMap("Gameplay");
playerControlsAction.Gameplay.Enable();
playerControlsAction.Paused.Disable();
}
public void PauseGame()
{
playerInput.SwitchCurrentActionMap("Paused");
pauseMenu.SetActive(true);
Time.timeScale = 0f;
isPaused = true;
//SwitchActionMapPaused();
}
public void ResumeGame()
{
playerInput.SwitchCurrentActionMap("Gameplay");
pauseMenu.SetActive(false);
Time.timeScale = 1f;
isPaused = false;
//SwitchActionMapResume();
}
// Options menu
public void OpenOptions()
{
optionsMenu.SetActive(true);
isOptions = true;
}
public void CloseOptions()
{
optionsMenu.SetActive(false);
isOptions = false;
}
// Quit to main menu
public void QuitToMenu()
{
Time.timeScale = 1f;
SceneManager.LoadScene("MainMenu");
}
}
|
@{
Layout = "_Layout";
}
<div class="container receipt-container">
<div class="row">
<h2>Order Placed!</h2>
<h4>@Model["order"].GetCheckoutDate()
</div>
<div class="row product-order">
@foreach (var item in @Model["order"].GetItems())
{
<div class ="product">
<img src="@item.GetProductInfo().GetImage()" alt="@item.GetProductInfo().GetName()">
<p>@item.GetColor() @item.GetProductInfo().GetName()</p>
<p>@item.GetSize() </p>
<p>@item.GetProductInfo().GetBrand()</p>
<p>Price: $@item.GetProductInfo().GetPrice().ToString("0.00")</p>
</div>
}
</div>
<div class="row details-receipt">
<div class="col-md-6">
<h4>Shipping Address</h4>
<h5>@Model["address"].GetName()</h5>
<p>@Model["address"].GetStreet()</p>
<p>@Model["address"].GetCity() @Model["address"].GetState() @Model["address"].GetZip()</p>
<p>@Model["address"].GetCountry()</p>
</div>
<div class="col-md-6">
<h4>Bill Details</h4>
<h5>Total Items: @Model["order"].GetItems().Count</h5>
<h5>Total Items Cost: $@Model["order"].GetSubtotal()</h5>
<h5 id="shipping_cost">Shipping Cost: $@((int)@Model["order"].GetSubtotal()/15)</h5>
<h5>Tax:$@((int)@Model["order"].GetSubtotal()/10)</h5>
</div>
</div>
<a href='/@Model["buyer"].GetId()' class="btn btn-default home-button">Back Home</a>
</div>
|
// Copyright (c) MicroElements. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
using MicroElements.Functional;
namespace MicroElements.Metadata.OpenXml.Excel.Reporting
{
public enum ExcelError
{
CellFormatNotFound,
CellFormatsIsNotRegistered
}
public class ExcelException : ExceptionWithError<ExcelError>
{
/// <inheritdoc />
public ExcelException(Error<ExcelError> error)
: base(error)
{
}
/// <inheritdoc />
protected ExcelException()
{
}
/// <inheritdoc />
protected ExcelException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
public static class ExcelErrors
{
public static Error<ExcelError> CellFormatNotFound(string name) => Error.CreateError(
ExcelError.CellFormatNotFound,
"CellFormat not found by name {name}",
name);
public static Error<ExcelError> CellFormatsIsNotRegistered = Error.CreateError(
ExcelError.CellFormatsIsNotRegistered,
"No CellFormat registered in stylesheet");
[DoesNotReturn]
public static void Throw(this in Error<ExcelError> error)
{
throw new ExcelException(error);
}
}
}
|
public enum ePartyFeedback
{
none,
invite,
errorAlreadyInParty,
kicked,
prodemoted,
partyFull
}
|
using System;
namespace Reddit.Inputs.Flair
{
[Serializable]
public class FlairCreateInput : FlairLinkInput
{
/// <summary>
/// a valid subreddit image name
/// </summary>
public string css_class { get; set; }
/// <summary>
/// a string no longer than 64 characters
/// </summary>
public string text { get; set; }
/// <summary>
/// Required by the API.
/// </summary>
public string api_type { get; set; }
/// <summary>
/// Create a new flair.
/// </summary>
/// <param name="text">a string no longer than 64 characters</param>
/// <param name="link">a fullname of a link</param>
/// <param name="name">a user by name</param>
/// <param name="cssClass">a valid subreddit image name</param>
public FlairCreateInput(string text, string link = null, string name = null, string cssClass = "")
{
this.text = text;
this.link = link;
this.name = name;
css_class = cssClass;
api_type = "json";
}
}
}
|
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using CliWrap;
using Microsoft.Extensions.Logging;
namespace Xappium.Tools
{
public class Appium
{
private const string defaultLog = "appium.log";
private Node _node { get; }
private ILogger _logger { get; }
public Appium(Node node, ILogger<Appium> logger)
{
_node = node;
_logger = logger;
}
public string Address { get; set; } = "127.0.0.1";
public int Port { get; set; } = 4723;
public string Version
{
get
{
var toolPath = EnvironmentHelper.GetToolPath("appium");
if (string.IsNullOrEmpty(toolPath))
return null;
var address = string.Empty;
if (!string.IsNullOrEmpty(Address))
address = $"--address {Address}";
var port = $"--port {Port}";
var process = new Process
{
StartInfo = new ProcessStartInfo(toolPath, $"{address} {port} -v")
{
CreateNoWindow = true,
RedirectStandardOutput = true
},
};
try
{
process.Start();
while (!process.StandardOutput.EndOfStream)
{
var line = process.StandardOutput.ReadLine();
if (!string.IsNullOrEmpty(line))
{
_logger.LogInformation($"Appium: {line} installed");
return line;
}
}
}
catch(Win32Exception)
{
_logger.LogWarning("Appium is not currently installed");
}
return null;
}
}
public async Task<bool> Install(CancellationToken cancellationToken)
{
if (!string.IsNullOrEmpty(Version))
return true;
return _node.IsInstalled && await _node.InstallPackage("appium", cancellationToken).ConfigureAwait(false);
}
public Task<IDisposable> Run(string baseWorkingDirectory)
{
if (string.IsNullOrEmpty(Version))
throw new Exception("Appium is not installed.");
var completed = false;
var tcs = new TaskCompletionSource<IDisposable>();
var cancellationSource = new CancellationTokenSource();
var logDirectory = Path.Combine(baseWorkingDirectory, "logs");
if (!Directory.Exists(logDirectory))
Directory.CreateDirectory(logDirectory);
void HandleConsoleLine(string line)
{
if (line.Contains("listener started on ") && line.Contains($":{Port}"))
{
_logger.LogInformation(line);
if(!completed)
tcs.SetResult(new AppiumTask(cancellationSource));
completed = true;
}
else if(line.Contains("make sure there is no other instance of this server running already") ||
line.Contains("listen EADDRINUSE: address already in use"))
{
_logger.LogWarning(line);
if (!completed)
tcs.SetResult(new AppiumTask(cancellationSource));
completed = true;
}
else
{
//Logger.WriteLine(line, LogLevel.Verbose, defaultLog);
}
}
var stdOut = PipeTarget.ToDelegate(HandleConsoleLine);
var stdErr = PipeTarget.Merge(
PipeTarget.ToFile(Path.Combine(logDirectory, "appium-error.log")),
PipeTarget.ToDelegate(HandleConsoleLine));
_logger.LogInformation("Starting Appium...");
var toolPath = EnvironmentHelper.GetToolPath("appium");
var cmd = Cli.Wrap(toolPath)
.WithStandardOutputPipe(stdOut)
.WithStandardErrorPipe(stdErr)
.WithValidation(CommandResultValidation.None)
.ExecuteAsync(cancellationSource.Token);
return tcs.Task;
}
private class AppiumTask : IDisposable
{
private CancellationTokenSource _tokenSource { get; }
public AppiumTask(CancellationTokenSource tokenSource)
{
_tokenSource = tokenSource;
}
public void Dispose()
{
_tokenSource.Cancel();
_tokenSource.Dispose();
}
}
}
}
|
using System;
using Avalonia.Controls;
namespace Material.Styles.Themes {
public class ThemeChangedEventArgs : EventArgs {
public ThemeChangedEventArgs(IResourceDictionary resourceDictionary, ITheme oldTheme, ITheme newTheme) {
ResourceDictionary = resourceDictionary;
OldTheme = oldTheme;
NewTheme = newTheme;
}
public IResourceDictionary ResourceDictionary { get; }
public ITheme NewTheme { get; }
public ITheme OldTheme { get; }
}
} |
using SideLoader.SLPacks;
namespace SideLoader
{
public class SL_RecipeItem : SL_Item
{
public string RecipeUID;
public override void ApplyToItem(Item item)
{
base.ApplyToItem(item);
SLPackManager.AddLateApplyListener(OnLateApply, item);
}
private void OnLateApply(object[] obj)
{
var recipeItem = obj[0] as RecipeItem;
if (!recipeItem)
return;
if (this.RecipeUID != null && References.ALL_RECIPES.ContainsKey(this.RecipeUID))
{
var recipe = References.ALL_RECIPES[this.RecipeUID];
recipeItem.Recipe = recipe;
}
}
public override void SerializeItem(Item item)
{
base.SerializeItem(item);
var recipeItem = item as RecipeItem;
RecipeUID = recipeItem.Recipe.UID;
}
}
}
|
using Newtonsoft.Json;
using SQLite;
using Kinvey;
using System.Runtime.Serialization;
namespace Kinvey.Tests
{
[JsonObject(MemberSerialization.OptIn)]
[DataContract]
public class Address : IPersistable
{
[JsonProperty("_id")]
[DataMember(Name = "_id")]
[Preserve]
[PrimaryKey, Column("_id")]
public string ID { get; set; }
[JsonProperty("_acl")]
[DataMember(Name = "_acl")]
[Preserve]
[Column("_acl")]
public AccessControlList Acl { get; set; }
public AccessControlList ACL
{
get
{
return Acl;
}
set
{
Acl = value;
}
}
[JsonProperty("_kmd")]
[DataMember(Name = "_kmd")]
[Preserve]
[Column("_kmd")]
public KinveyMetaData Kmd { get; set; }
public KinveyMetaData KMD
{
get
{
return Kmd;
}
set
{
Kmd = value;
}
}
[JsonProperty]
[DataMember]
public bool IsApartment { get; set; }
[JsonProperty]
[DataMember]
public string Street { get; set; }
}
}
|
namespace Abc.NCrafts.Quizz.Performance.Questions._011
{
public class Answer1
{
public static void Run()
{
// begin
var result = Factorial(1234);
// end
Logger.Log("Factorial: {0}", result);
}
private static long Factorial(long n)
{
if (n == 0)
return 1;
return n * Factorial(n - 1);
}
}
} |
namespace CarService.Services.Mechanics
{
using CarService.Data;
using CarService.Data.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
public class MechanicsService : IMechanicsService
{
private readonly ApplicationDbContext data;
public MechanicsService(ApplicationDbContext data)
{
this.data = data;
}
public bool BecomeMechanic(string fullName ,string phoneNumber,string userId)
{
var userIdAlreadyMechanic = this.data
.Mechanics
.Any(d => d.UserId == userId);
if (userIdAlreadyMechanic)
{
return false;
}
var mechanicData = new Mechanic
{
FullName = fullName,
PhoneNumber = phoneNumber,
UserId = userId
};
if (mechanicData==null)
{
return false;
}
this.data.Mechanics.Add(mechanicData);
this.data.SaveChanges();
return true;
}
public bool IsMechanic(string userId)
{
var mechanic = this.data
.Mechanics
.Any(m => m.UserId == userId);
return mechanic;
}
}
}
|
using System.Collections.Generic;
using PFW.Model.Armory;
namespace PFW.Service
{
public interface IFactionService : IService<Faction>
{
ICollection<Coalition> AllByFaction(Faction faction);
ICollection<Coalition> AllCoalitions();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataflowActor
{
public class AccountActor : AbstractActor
{
private decimal _balance;
public override void Handle(IMessage message)
{
if (message is QueryBalanceMessage)
{
(message as QueryBalanceMessage).Receiver.Send(new BalanceMessage { Amount = _balance });
}
if (message is DepositMessage)
{
_balance += (message as DepositMessage).Amount;
}
}
}
}
|
using System;
namespace DotnetModelFuzzer.Manipulations.VulnerabilityManips
{
public class JsonInjection : FuzzDbManipulation<string>, IMutationManipulation<string>
{
private const string BasePath = "json";
public JsonInjection() : base(BasePath)
{
}
public JsonInjection(int seed) : base(seed, BasePath)
{
}
public override string Manipulate(string input)
{
if (ViableInputs == null || ViableInputs.Count == 0)
{
return input;
}
var attack = ViableInputs[Random.Next(0, ViableInputs.Count)];
return InsertString(input, attack);
}
}
}
|
namespace atlantis {
public class Population {
public Population(string race, int count) {
Race = race;
Count = count;
}
public string Race { get; }
public int Count { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RMUD
{
public class Container : MudObject
{
[Persist(typeof(ContainerSerializer))]
public Dictionary<RelativeLocations, List<MudObject>> Lists { get; set; }
public RelativeLocations Supported;
public RelativeLocations Default;
public Container(RelativeLocations Locations, RelativeLocations Default)
{
this.Supported = Locations;
this.Default = Default;
this.Lists = new Dictionary<RelativeLocations, List<MudObject>>();
}
public void Remove(MudObject Object)
{
foreach (var list in Lists)
{
if (list.Value.Remove(Object))
Object.Location = null;
}
}
public int RemoveAll(Predicate<MudObject> Func)
{
var r = 0;
foreach (var list in Lists)
r += list.Value.RemoveAll(Func);
return r;
}
public void Add(MudObject Object, RelativeLocations Locations)
{
if (Locations == RelativeLocations.Default) Locations = Default;
if ((Supported & Locations) == Locations)
{
if (!Lists.ContainsKey(Locations)) Lists.Add(Locations, new List<MudObject>());
Lists[Locations].Add(Object);
}
}
public IEnumerable<MudObject> EnumerateObjects()
{
foreach (var list in Lists)
foreach (var item in list.Value)
yield return item;
}
public IEnumerable<Tuple<MudObject, RelativeLocations>> EnumerateObjectsAndRelloc()
{
foreach (var list in Lists)
foreach (var item in list.Value)
yield return Tuple.Create(item, list.Key);
}
public IEnumerable<T> EnumerateObjects<T>() where T : MudObject
{
foreach (var list in Lists)
foreach (var item in list.Value)
if (item is T) yield return item as T;
}
public IEnumerable<MudObject> EnumerateObjects(RelativeLocations Locations)
{
foreach (var list in Lists)
if ((list.Key & Locations) == list.Key)
foreach (var item in list.Value)
yield return item;
}
public IEnumerable<T> EnumerateObjects<T>(RelativeLocations Locations) where T : MudObject
{
foreach (var list in Lists)
if ((list.Key & Locations) == list.Key)
foreach (var item in list.Value)
if (item is T) yield return item as T;
}
public List<MudObject> GetContents(RelativeLocations Locations)
{
return new List<MudObject>(EnumerateObjects(Locations));
}
public bool Contains(MudObject Object, RelativeLocations Locations)
{
if (Locations == RelativeLocations.Default) Locations = Default;
if (Lists.ContainsKey(Locations))
return Lists[Locations].Contains(Object);
return false;
}
public RelativeLocations LocationsSupported { get { return Supported; } }
public RelativeLocations DefaultLocation { get { return Default; } }
public RelativeLocations RelativeLocationOf(MudObject Object)
{
foreach (var list in Lists)
if (list.Value.Contains(Object)) return list.Key;
return RelativeLocations.None;
}
}
}
|
namespace SAMI.Apps.Football
{
internal enum GameParameter
{
Score,
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
namespace Jerrycurl.Relations.Internal
{
internal class IndexedEnumerator<T> : IEnumerator<T>
{
protected IEnumerator<T> innerEnumerator;
public int Index { get; private set; } = -1;
public T Current => this.innerEnumerator.Current;
public IndexedEnumerator(IEnumerable<T> enumerable)
{
this.innerEnumerator = (enumerable ?? Array.Empty<T>()).GetEnumerator();
}
public virtual bool MoveNext()
{
if (this.innerEnumerator.MoveNext())
{
this.Index++;
return true;
}
return false;
}
public void Reset()
{
this.innerEnumerator.Reset();
this.Index = -1;
}
public virtual void Dispose()
{
this.innerEnumerator.Dispose();
}
object IEnumerator.Current => this.Current;
}
}
|
using AutoMapper;
using PhatHanhSach.Model;
using PhatHanhSach.Web.Models;
namespace PhatHanhSach.Web.Mapping
{
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<DaiLy, DaiLyViewModel>();
CreateMap<NhaXuatBan, NhaXuatBanViewModel>();
CreateMap<PhieuNhap, PhieuNhapViewModel>();
CreateMap<PhieuXuat, PhieuXuatViewModel>();
CreateMap<CtPhieuNhap, CtPhieuNhapViewModel>();
CreateMap<CtPhieuXuat, CtPhieuXuatViewModel>();
CreateMap<Sach, SachViewModel>();
CreateMap<TinhTrang, TinhTrangViewModel>();
CreateMap<CtBaoCaoDL, CtBaoCaoDLViewModel>();
CreateMap<BaoCaoDL, BaoCaoDLViewModel>();
CreateMap<ThanhToan, ThanhToanViewModel>();
CreateMap<CtThanhToan, CtThanhToanViewModel>();
CreateMap<TonKho, TonKhoViewModel>();
CreateMap<CongNoDL, CongNoDLViewModel>();
CreateMap<CongNoNXB, CongNoNXBViewModel>();
/*
CreateMap<DoanhThu, DoanhThuViewModel>();
CreateMap<CtDoanhThu, CtDoanhThuViewModel>();
*/
}
}
} |
using System.Drawing;
using System.Windows.Forms;
using GoldBoxExplorer.Lib.Plugins.Hex;
using System;
namespace GoldBoxExplorer.Lib.Plugins.Glb
{
public class FruaGlbFileViewer : IGoldBoxViewer
{
private readonly FruaGlbFile _file;
private readonly PluginParameter _args;
public event EventHandler<ChangeFileEventArgs> ChangeSelectedFile;
public FruaGlbFileViewer(FruaGlbFile file, PluginParameter args)
{
_file = file;
_args = args;
ContainerWidth = args.ContainerWidth;
Zoom = args.Zoom;
}
public Control GetControl()
{
// TODO can't display GLB files yet so just return the hex viewer for now
var provider = new DynamicFileByteProvider(_args.Filename, true);
var control = new HexBox
{
ByteProvider = provider,
Dock = DockStyle.Fill,
GroupSeparatorVisible = false,
ColumnInfoVisible = true,
LineInfoVisible = true,
StringViewVisible = true,
UseFixedBytesPerLine = true,
VScrollBarVisible = true,
};
return control;
}
public float Zoom { get; set; }
public int ContainerWidth { get; set; }
}
} |
using System;
using System.Collections.Generic;
using EverisHire.HireManagement.Domain.Common;
namespace EverisHire.HireManagement.Domain.Entities
{
public class StatusJob: AuditableEntity
{
public Guid StatusJobId { get; set; }
public string Description { get; set; }
public virtual ICollection<Job> Jobs { get; set; }
}
} |
using Flai;
using Flai.CBES;
using Flai.CBES.Systems;
using Flai.DataStructures;
using Microsoft.Xna.Framework;
using Skypiea.Components;
using Skypiea.Misc;
using Skypiea.Prefabs;
namespace Skypiea.Systems.Zombie
{
public class ZombieAttackSystem : ProcessingSystem
{
private Entity _player;
private CPlayerInfo _playerInfo;
protected override int ProcessOrder
{
get { return SystemProcessOrder.Collision + 1; } // after "BulletCollisionSystem", because why not.
}
public ZombieAttackSystem()
: base(Aspect.All<CZombieInfo>())
{
}
protected override void Initialize()
{
_player = this.EntityWorld.FindEntityByName(EntityNames.Player);
_playerInfo = _player.Get<CPlayerInfo>();
}
protected override void Process(UpdateContext updateContext, ReadOnlyBag<Entity> entities)
{
if (!_playerInfo.IsAlive)
{
return;
}
float range = _playerInfo.IsInvulnerable ? 12 : 6;
IZombieSpatialMap zombieSpatialMap = this.EntityWorld.Services.Get<IZombieSpatialMap>();
foreach (Entity zombie in zombieSpatialMap.GetAllIntersecting(_player.Transform, range))
{
CZombieInfo zombieInfo = zombie.Get<CZombieInfo>();
if (!_playerInfo.IsInvulnerable)
{
if (!ZombieAttackSystem.CanAttack(zombieInfo.Type))
{
continue;
}
_playerInfo.KillPlayer();
return;
}
// player is invulnerable
ZombieHelper.Kill(zombie, Vector2.Zero);
}
}
private static bool CanAttack(ZombieType zombieType)
{
return zombieType != ZombieType.GoldenGoblin;
}
}
}
|
using System;
using System.Linq;
using System.Reflection;
using Autofac.Core.Activators.Reflection;
namespace STak.TakHub.Infrastructure
{
public class InjectionConstructorFinder : IConstructorFinder
{
// To support both the default ASP.NET Core DI container and Autofac, we currently use only
// public constructors. (The ASP.NET Core DI container requires constructors to be public.)
public ConstructorInfo[] FindConstructors(Type t) =>
t.GetTypeInfo().DeclaredConstructors.Where(c => c.IsPublic).ToArray();
// If we were to commit to using Autofac we could use this to find only internal constructors,
// and change the access of the relevant injectable classes from public to internal.
//
// public ConstructorInfo[] FindConstructors(Type t) => t.GetTypeInfo().DeclaredConstructors.Where(
// c => !c.IsPrivate && !c.IsPublic).ToArray();
}
}
|
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using ReactiveUI;
using WolvenKit.Common.Services;
using DynamicData;
using Microsoft.WindowsAPICodePack.Dialogs;
using ReactiveUI.Fody.Helpers;
using WolvenManager.App.Services;
namespace WolvenManager.App.ViewModels.Controls
{
public class ModIntegrationViewModel : MainViewModel
{
private readonly ILoggerService _loggerService;
public readonly ISettingsService _settingsService;
public ModIntegrationViewModel(
ILoggerService loggerService,
ISettingsService settingsService
)
{
_loggerService = loggerService;
_settingsService = settingsService;
ModDirBrowseCommand = ReactiveCommand.Create<string>(ModDirBrowseExecute);
RawDirBrowseCommand = ReactiveCommand.Create<string>(RawDirBrowseExecute);
ModDirOpenCommand = ReactiveCommand.Create<string>(ModDirOpenExecute);
RawDirOpenCommand = ReactiveCommand.Create<string>(RawDirOpenExecute);
}
#region properties
public ReactiveCommand<string, Unit> ModDirBrowseCommand { get; }
public ReactiveCommand<string, Unit> RawDirBrowseCommand { get; }
public ReactiveCommand<string, Unit> ModDirOpenCommand { get; }
public ReactiveCommand<string, Unit> RawDirOpenCommand { get; }
#endregion
#region methods
/// <summary>
/// Show the given folder in the windows explorer.
/// </summary>
/// <param name="path">The file/folder to show.</param>
public static void ShowFolderInExplorer(string path)
{
if (Directory.Exists(path))
{
Process.Start("explorer.exe", "\"" + path + "\"");
}
}
private void ModDirOpenExecute(string param) => ShowFolderInExplorer(_settingsService.LocalModFolder);
private void RawDirOpenExecute(string param) => ShowFolderInExplorer(_settingsService.LocalRawFolder);
private void ModDirBrowseExecute(string param)
{
var openFolder = new CommonOpenFileDialog
{
AllowNonFileSystemItems = true,
Multiselect = false,
IsFolderPicker = true,
Title = "Select folders"
};
if (openFolder.ShowDialog() != CommonFileDialogResult.Ok)
{
return;
}
var dir = openFolder.FileNames.FirstOrDefault();
if (string.IsNullOrEmpty(dir))
{
return;
}
_settingsService.LocalModFolder = dir;
}
private void RawDirBrowseExecute(string param)
{
var openFolder = new CommonOpenFileDialog
{
AllowNonFileSystemItems = true,
Multiselect = false,
IsFolderPicker = true,
Title = "Select folders"
};
if (openFolder.ShowDialog() != CommonFileDialogResult.Ok)
{
return;
}
var dir = openFolder.FileNames.FirstOrDefault();
if (string.IsNullOrEmpty(dir))
{
return;
}
_settingsService.LocalRawFolder = dir;
}
#endregion
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Linq;
using Xunit;
namespace Microsoft.Deployment.DotNet.Releases.Tests
{
public class ReleaseComponentTests : TestBase
{
[Theory]
[InlineData("5.0", "5.0.0-preview.7")]
[InlineData("3.1", "3.1.5")]
[InlineData("3.0", "3.0.2")]
[InlineData("2.2", "2.2.8")]
[InlineData("2.1", "2.1.7")]
[InlineData("2.0", "2.0.9")]
[InlineData("1.1", "1.1.10")]
[InlineData("1.0", "1.0.14")]
public void ItDoesNotContainMarketingFiles(string productVersion, string releaseVersion)
{
var release = GetProductRelease(productVersion, releaseVersion);
Assert.All(release.Files, f => Assert.True(!f.Name.Contains("-gs") && !f.Name.Contains("-nj")));
}
}
}
|
// 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.Runtime.CompilerServices;
using Internal.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Threading
{
/// <summary>
/// After much discussion, we decided the Interlocked class doesn't need
/// any HPA's for synchronization or external threading. They hurt C#'s
/// codegen for the yield keyword, and arguably they didn't protect much.
/// Instead, they penalized people (and compilers) for writing threadsafe
/// code.
/// </summary>
public static class Interlocked
{
/// <summary>
/// Implemented: int, long
/// </summary>
public static int Increment(ref int location)
{
return Add(ref location, 1);
}
public static long Increment(ref long location)
{
return Add(ref location, 1);
}
/// <summary>
/// Implemented: int, long
/// </summary>
public static int Decrement(ref int location)
{
return Add(ref location, -1);
}
public static long Decrement(ref long location)
{
return Add(ref location, -1);
}
/// <summary>
/// Implemented: int, long, float, double, Object, IntPtr
/// </summary>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int Exchange(ref int location1, int value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern long Exchange(ref long location1, long value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float Exchange(ref float location1, float value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Exchange(ref double location1, double value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern object Exchange(ref object location1, object value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern IntPtr Exchange(ref IntPtr location1, IntPtr value);
// This whole method reduces to a single call to Exchange(ref object, object) but
// the JIT thinks that it will generate more native code than it actually does.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T Exchange<T>(ref T location1, T value) where T : class
{
return Unsafe.As<T>(Exchange(ref Unsafe.As<T, object>(ref location1), value));
}
/// <summary>
/// Implemented: int, long, float, double, Object, IntPtr
/// </summary>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int CompareExchange(ref int location1, int value, int comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern long CompareExchange(ref long location1, long value, long comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float CompareExchange(ref float location1, float value, float comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double CompareExchange(ref double location1, double value, double comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern object CompareExchange(ref object location1, object value, object comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern IntPtr CompareExchange(ref IntPtr location1, IntPtr value, IntPtr comparand);
// Note that getILIntrinsicImplementationForInterlocked() in vm\jitinterface.cpp replaces
// the body of this method with the the following IL:
// ldarg.0
// ldarg.1
// ldarg.2
// call System.Threading.Interlocked::CompareExchange(ref Object, Object, Object)
// ret
// The workaround is no longer strictly necessary now that we have Unsafe.As but it does
// have the advantage of being less sensitive to JIT's inliner decisions.
public static T CompareExchange<T>(ref T location1, T value, T comparand) where T : class
{
return Unsafe.As<T>(CompareExchange(ref Unsafe.As<T, object>(ref location1), value, comparand));
}
// BCL-internal overload that returns success via a ref bool param, useful for reliable spin locks.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int CompareExchange(ref int location1, int value, int comparand, ref bool succeeded);
/// <summary>
/// Implemented: int, long
/// </summary>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int ExchangeAdd(ref int location1, int value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern long ExchangeAdd(ref long location1, long value);
public static int Add(ref int location1, int value)
{
return ExchangeAdd(ref location1, value) + value;
}
public static long Add(ref long location1, long value)
{
return ExchangeAdd(ref location1, value) + value;
}
public static long Read(ref long location)
{
return Interlocked.CompareExchange(ref location, 0, 0);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void MemoryBarrier();
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void _MemoryBarrierProcessWide();
public static void MemoryBarrierProcessWide()
{
_MemoryBarrierProcessWide();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TheGymWebsite.Models.Repository
{
public class SqlOpenHoursRepository : IOpenHoursRepository
{
private readonly GymDbContext context;
public SqlOpenHoursRepository(GymDbContext context)
{
this.context = context;
}
public void Add(OpenHours openHours)
{
context.OpenHours.Add(openHours);
context.SaveChanges();
}
public void Delete(int id)
{
OpenHours openHours = context.OpenHours.Find(id);
if (openHours != null)
{
context.OpenHours.Remove(openHours);
context.SaveChanges();
}
}
public IEnumerable<OpenHours> GetOpenHours()
{
return context.OpenHours;
}
public OpenHours GetOpenHours(int id)
{
return context.OpenHours.Find(id);
}
public void Update(OpenHours changedOpenHours)
{
var openHours = context.OpenHours.Attach(changedOpenHours);
openHours.State = Microsoft.EntityFrameworkCore.EntityState.Modified;
context.SaveChanges();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Blindspot.Helpers;
namespace Blindspot.Commands
{
public class CloseCommand : HotkeyCommandBase
{
private Form parent;
private IOutputManager _output;
public CloseCommand(Form parentForm)
{
parent = parentForm;
_output = OutputManager.Instance;
}
public override string Key
{
get { return "close_blindspot"; }
}
public override void Execute(object sender, HandledEventArgs e)
{
_output.OutputMessage(StringStore.ExitingProgram);
if (parent.InvokeRequired)
{
parent.Invoke(new Action(() => { parent.Close(); }));
}
else
{
parent.Close();
}
}
}
} |
using System;
using TTMouseclickSimulator.Core;
namespace TTMouseclickSimulator.Project;
/// <summary>
/// A simulator project that can be persisted.
/// </summary>
public class SimulatorProject
{
public SimulatorProject(string title, string description, SimulatorConfiguration configuration)
{
this.Title = title ?? throw new ArgumentNullException(nameof(title));
this.Description = description ?? throw new ArgumentNullException(nameof(description));
this.Configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
}
public string Title
{
get;
}
public string Description
{
get;
}
public SimulatorConfiguration Configuration
{
get;
}
public override string ToString()
{
return this.Title;
}
}
|
using UnityEngine;
[System.Serializable]
public class ClickManager
{
//properties
public float MaxTimeToClick { get { return _maxTimeToClick; } set { _maxTimeToClick = value; } }
public float MinTimeToClick { get { return _minTimeToClick; } set { _minTimeToClick = value; } }
public bool IsDebug { get { return _Isdebug; } set { _Isdebug = value; } }
//property variables
private float _maxTimeToClick = 0.25f;
private float _minTimeToClick = 0.05f;
private bool _Isdebug = false;
//private variables to keep track
private float _minCurrentTime;
private float _maxCurrentTime;
public bool DoubleClick()
{
if (Time.time >= _minCurrentTime && Time.time <= _maxCurrentTime)
{
if (_Isdebug)
Debug.Log("Double Click");
_minCurrentTime = 0;
_maxCurrentTime = 0;
return true;
}
_minCurrentTime = Time.time + MinTimeToClick; _maxCurrentTime = Time.time + MaxTimeToClick;
return false;
}
} |
using System;
namespace ErisPacketCreator.ActionScript.Interpreter.Keywords.Models
{
public class QName
{
private string _rawQName;
/// <summary>
/// Creates a new QName Instance, and splits the string to make it easier to use
/// </summary>
/// <param name="rawString">The raw line from the rabcdasm output</param>
private QName(string rawString)
{
_rawQName = rawString;
PackageNamespace = _rawQName.Split('(')[2].Split(')')[0].Replace("\"", "");
Name = _rawQName.Split(')')[1].Split('"')[1];
}
/// <summary>
/// Creates a new QName Instance from the entire Trait string, and splits the string to make it easier to use
/// </summary>
/// <param name="rawString">The raw line from the rabcdasm output</param>
/// <param name="entireTrait">Is the string the entire trait string?</param>
public QName(string rawString, bool entireTrait = true)
{
//trait method QName(PackageNamespace(""), "writeToOutput") flag OVERRIDE
_rawQName = rawString;
if (entireTrait) {
string split = _rawQName.Split(new[] {"QName"}, StringSplitOptions.None)[1];
PackageNamespace = split.Split('(')[1].Split(')')[0].Replace("\"", "");
Name = split.Split(new[] {", \""}, StringSplitOptions.None)[1].Split('"')[0];
}
}
/// <summary>
/// Returns the PackageNamespace, first string from the QName call
/// </summary>
public string PackageNamespace { get; }
/// <summary>
/// Returns the Name of the Trait, second string fron the QName call
/// </summary>
public string Name { get; }
public static implicit operator QName(string x) => new QName(x);
}
} |
using System;
using System.Collections.Generic;
using ISukces.SolutionDoctor.Logic.Problems;
namespace ISukces.SolutionDoctor.Logic
{
public class MessageColorer
{
public void Color(RichString.FormatContext ctx)
{
if (!ctx.Before) return;
ctx.AutoResetColorsAfter = true;
ConsoleColor? G()
{
if (_projects.Contains(ctx.ParameterIndex))
return ConsoleColor.Cyan;
if (_packages.Contains(ctx.ParameterIndex))
return ConsoleColor.Blue;
if (_versions.Contains(ctx.ParameterIndex))
return ConsoleColor.Yellow;
return null;
}
var color = G();
if (color.HasValue)
ctx.SetTextColor(color.Value);
}
public MessageColorer WithPackageAt(params int[] indexes)
{
return With(_packages, indexes);
}
public MessageColorer WithProjectAt(params int[] indexes)
{
return With(_projects, indexes);
}
public MessageColorer WithVersionAt(params int[] indexes)
{
return With(_versions, indexes);
}
private MessageColorer With(ISet<int> projects, int[] indexes)
{
foreach (var i in indexes)
projects.Add(i);
return this;
}
private readonly HashSet<int> _projects = new HashSet<int>();
private readonly ISet<int> _packages = new HashSet<int>();
private readonly ISet<int> _versions = new HashSet<int>();
}
} |
using System;
using System.Threading.Tasks;
using Nimbus.InfrastructureContracts.Handlers;
using Nimbus.Tests.Unit.TestAssemblies.MessageContracts;
namespace Nimbus.Tests.Unit.TestAssemblies.Handlers
{
public class CommandWhoseAssemblyShouldNotBeIncludedHandler : IHandleCommand<CommandWhoseAssemblyShouldNotBeIncluded>
{
public async Task Handle(CommandWhoseAssemblyShouldNotBeIncluded busCommand)
{
throw new NotImplementedException();
}
}
} |
using Symbiote.Core.Actor;
namespace Messaging.Tests.RequestResponse
{
public class AuctionFactory
: IActorFactory<Auction>
{
public Auction CreateInstance<TKey>( TKey id )
{
return new Auction()
{
Item = id.ToString()
};
}
}
} |
using Assets.Kanau.UnityScene.Containers;
using System;
using UnityEngine;
namespace Assets.Kanau.ThreeScene.Textures {
public class TextureElem : BaseElem
{
public TextureElem(LightmapContainer c) {
SetFilterMode(c.FilterMode);
SetWrapMode(c.WrapMode);
Anisotropy = c.AnisoLevel;
}
public TextureElem(TextureContainer c) {
SetFilterMode(c.FilterMode);
SetWrapMode(c.WrapMode);
Anisotropy = c.AnisoLevel;
}
void SetWrapMode(TextureWrapMode m) {
// wrap mode
switch (m) {
case TextureWrapMode.Clamp:
WrapMode = Three.ClampToEdgeWrapping;
break;
case TextureWrapMode.Repeat:
WrapMode = Three.RepeatWrapping;
break;
default:
Debug.Assert(false, "do not reach");
break;
}
}
void SetFilterMode(FilterMode m) {
switch (m) {
case FilterMode.Point:
MagFilter = Three.NearestFilter;
MinFilter = Three.NearestMipMapNearestFilter;
break;
case FilterMode.Bilinear:
MagFilter = Three.LinearFilter;
MinFilter = Three.LinearMipMapLinearFilter;
break;
case FilterMode.Trilinear:
MagFilter = Three.LinearFilter;
MinFilter = Three.LinearMipMapLinearFilter;
break;
default:
Debug.Assert(false, "do not reach");
break;
}
}
public override void Accept(IVisitor v) { v.Visit(this); }
public override string Type {
get {
throw new NotImplementedException("not need");
}
}
// TODO
public float[] Offset {
get { return new float[] { 0, 0 }; }
}
// TODO
public float[] Repeat {
get { return new float[] { 1, 1 }; }
}
public int MagFilter { get; set; }
public int MinFilter { get; set; }
// 유니티에서는 wrap mode를 s, t축 따로 지정하는게 불가능하다
// 그래서 하나만 받도록해도 문제 없을듯
public int WrapMode { get; set; }
public int[] Wrap {
get {
return new int[] { WrapMode, WrapMode };
}
}
public string ImageUuid {
get {
if (Image == null) {
return "";
}
return Image.Uuid;
}
}
public string ImageName {
get {
if (Image == null) {
return "";
}
return Image.Name;
}
}
public string ImagePath
{
get
{
var name = ImageName;
if(name == "") { return name; }
return string.Format("./{0}/{1}", ExportSettings.Instance.destination.imageDirectory, name);
}
}
public int Anisotropy { get; set; }
public ImageElem Image { get; set; }
}
}
|
/*
* Copyright (c) 2017 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
* distribute, sublicense, create a derivative work, and/or sell copies of the
* Software in any work that is designed, intended, or marketed for pedagogical or
* instructional purposes related to programming, coding, application development,
* or information technology. Permission for such use, copying, modification,
* merger, publication, distribution, sublicensing, creation of derivative works,
* or sale is expressly withheld.
*
* 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 UnityEngine;
using System.Collections;
using System;
using UnityEngine.UI;
public class Player : MonoBehaviour
{
private Text bomb_label;
private Text life_label;
private Text kick_label;
private Text explosion_label;
private Text speed_label;
public GlobalStateManager globalManager;
public float moveSpeed = 5f;
public ParticleSystem Explosion;
public int bombs = 2;
//Amount of bombs the player has left to drop, gets decreased as the player
//drops a bomb, increases as an owned bomb explodes
public bool canKick = false;
public int lifes = 1;
public int explosion_power = 2;
public bool dead = false;
public bool respawning = false;
private fade_script fade;
public void update_label(POWERUPS powerup){
switch(powerup){
case POWERUPS.BOMB:
bomb_label.text = bombs.ToString();
break;
case POWERUPS.KICK:
if(canKick){
kick_label.text = "1";
} else {
kick_label.text = "0";
}
break;
case POWERUPS.LIFE:
life_label.text = lifes.ToString();
break;
case POWERUPS.POWER:
explosion_label.text = explosion_power.ToString();
break;
case POWERUPS.SPEED:
speed_label.text = moveSpeed.ToString();
break;
}
}
IEnumerator respawn_wait()
{
yield return new WaitForSeconds(3);
respawning = false;
}
IEnumerator gameover_wait()
{
yield return new WaitForSeconds(1f);
show_gameover_panel();
}
// Use this for initialization
void Start ()
{
// init fader
foreach(fade_script f in FindObjectsOfType<fade_script>()){
if(f.tag == "fader"){
continue;
} else {
fade = f;
}
}
// init labels
if(GetComponent<Player_Controller>().isActiveAndEnabled){
foreach(Text t in FindObjectsOfType<Text>()){
switch(t.tag){
case "Bomb":
bomb_label = t;
break;
case "life":
life_label = t;
break;
case "power":
explosion_label = t;
break;
case "speed":
speed_label = t;
break;
case "kick":
kick_label = t;
break;
}
}
}
//Cache the attached components for better performance and less typing
}
IEnumerator dmg_animation(){
StartCoroutine(fade.FadeOnly(fade_script.FadeDirection.In));
yield return new WaitForSeconds(1);
StartCoroutine(fade.FadeOnly(fade_script.FadeDirection.Out));
yield return new WaitForSeconds(1);
StartCoroutine(fade.FadeOnly(fade_script.FadeDirection.In));
yield return new WaitForSeconds(1);
StartCoroutine(fade.FadeOnly(fade_script.FadeDirection.Out));
}
private void show_gameover_panel(){
foreach(hide_on_start h in Resources.FindObjectsOfTypeAll<hide_on_start>()){
if(h.tag == "gameover"){
h.toggle();
break;
}
}
Destroy(gameObject);
}
void OnCollisionEnter(Collision collision)
{
if (collision.collider.CompareTag ("Explosion"))
{
if(!respawning){
lifes--;
if(GetComponent<Player_Controller>().isActiveAndEnabled){
update_label(POWERUPS.LIFE);
}
if(lifes <= 0){
dead = true; // 1
if(GetComponent<Player_Controller>().isActiveAndEnabled){
StartCoroutine(gameover_wait());
} else {
Destroy(gameObject);
FindObjectOfType<Global_Game_Controller>().update_labels();
}
// 3
} else {
if(GetComponent<Player_Controller>().isActiveAndEnabled){
StartCoroutine(dmg_animation());
} else {
}
respawning = true;
StartCoroutine(respawn_wait());
}
Instantiate(Explosion,transform.position, Quaternion.identity);
}
}
}
}
|
using Sepes.Infrastructure.Model.Interface;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Sepes.Infrastructure.Model
{
[Table("CloudResources")]
public class CloudResource : UpdateableBaseModel, ISupportSoftDelete
{
public int? StudyId { get; set; }
public int? SandboxId { get; set; }
public int? DatasetId { get; set; }
[MaxLength(256)]
public string ResourceId { get; set; }
[MaxLength(256)]
public string ResourceKey { get; set; }
[MaxLength(256)]
public string ResourceName { get; set; }
[MaxLength(64)]
public string ResourceType { get; set; }
[MaxLength(64)]
public string Purpose { get; set; }
[MaxLength(64)]
public string ResourceGroupName { get; set; }
[MaxLength(64)]
public string LastKnownProvisioningState { get; set; }
[MaxLength(4096)]
public string Tags { get; set; }
[MaxLength(32)]
public string Region { get; set; }
[MaxLength(4096)]
public string ConfigString { get; set; }
public bool SandboxControlled { get; set; }
public bool Deleted { get; set; }
public DateTime? DeletedAt { get; set; }
[MaxLength(64)]
public string DeletedBy { get; set; }
public int? ParentResourceId { get; set; }
public Study Study { get; set; }
public Sandbox Sandbox { get; set; }
public Dataset Dataset { get; set; }
public List<CloudResourceOperation> Operations { get; set; }
public CloudResource ParentResource { get; set; }
public List<CloudResource> ChildResources { get; set; }
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DebugManager.Outputs
{
public class DebugMessage
{
#region Properties
#region Constantes
const int SCALE_SPEED = 4;
#endregion
public string Text { get; set; }
/// <summary>
/// Obtiene y asigna la posición en la que será dibujado el Message.
/// Esto es actualizado cada vez que update es llamado
/// </summary>
public Vector2 Position { get; set; }
/// <summary>
/// Guarda un acceso al DebugBox en la que este Message toma lugar
/// </summary>
internal DebugBox DebugBoxController { get; set; }
/// <summary>
/// Obtiene el espacio en altura que requiere este Message según el texto
/// </summary>
public int TextHeight
{
get { return DebugBoxController.DebugManagerController.Font.LineSpacing; }
//get { return (int)DebugBoxController.DebugManagerController.Font.MeasureString(Text).Y; }
}
/// <summary>
/// Obtiene el espacio en anchura que requiere este Message según el texto.
/// Sirve para centrarlo.
/// </summary>
public int TextWidth
{
get { return (int)DebugBoxController.DebugManagerController.Font.MeasureString(Text).X; }
}
/// <summary>
/// Realiza un efecto de FADE durante un evento del Message.
/// </summary>
private float SelectionFade { get; set; }
/// <summary>
/// Determina la scala del texto según su tamaño dado por la Font
/// </summary>
private Vector2 TextScale { get; set; }
#endregion
#region Events
/// <summary>
/// El evento se activa cuando el DebugMessage es seleccionado.
/// </summary>
public event EventHandler SwitchShowed;
/// <summary>
/// Methodo para activar el Selected Event.
/// </summary>
protected internal virtual void OnSwitchShowedEntry(EventArgs e)
{
if (SwitchShowed != null)
SwitchShowed(this, e);
}
#endregion
#region Constructor
/// <summary>
/// Crea un DebugMessage con el texto especificado
/// </summary>
/// <param name="debugBox">DebugBox donde toma contexto este Message.</param>
/// <param name="text">Texto a escribir en el entry</param>
public DebugMessage(DebugBox debugBox, string text)
{
DebugBoxController = debugBox;
Text = text;
TextScale = new Vector2(0, 1);
}
#endregion
#region Update and Draw
/// <summary>
/// Mantiene actualizada el Message en el Juego
/// </summary>
/// <param name="gameTime">Para obtener el tiempo del juego</param>
/// <param name="text">Texto a mostrar.</param>
/// <param name="isShowed">Para saber si se está mostrando o no.</param>
public virtual void Update(GameTime gameTime, string text, bool isShowed)
{
Text = text;
float showSpeed = (float)gameTime.ElapsedGameTime.TotalSeconds * SCALE_SPEED;
if (isShowed)
TextScale = new Vector2(Math.Min(SelectionFade + showSpeed, 1), 1);
else
TextScale = new Vector2(Math.Max(SelectionFade - showSpeed, 0), 1);
}
/// <summary>
/// Dibuja el Message. Puede realizarce un override de este metodo para mejorar la apariencia
/// </summary>
/// <param name="gameTime">Para obtener el tiempo del juego</param>
/// <param name="isSelected">Booleano para saber si está seleccionada o no</param>
public virtual void Draw(GameTime gameTime, bool isSelected)
{
//Si está seleccionada le da un color amarillo, si no, es blanco
Color color = isSelected ? Color.Yellow : Color.White;
//Modifica el alpha del Message de acuerdo al estado de transición del DebugBox al que pertenece
color *= DebugBoxController.TransitionAlpha;
//Dibuja el texto centrado en la Screen
DebugManager debugManager = DebugBoxController.DebugManagerController;
SpriteBatch spriteBatch = debugManager.SpriteBatch;
SpriteFont font = debugManager.Font;
spriteBatch.DrawString(font, Text, Position, color, 0, Vector2.Zero, TextScale, SpriteEffects.None, 0);
}
#endregion
}
}
|
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using Verse;
using RimWorld;
using HarmonyLib;
using UnityEngine;
namespace SRTS
{
[StaticConstructorOnStartup]
public class FallingBombCE : FallingBomb
{
public FallingBombCE(Thing reference, CompProperties comp, ThingComp CEcomp, Map map, string texPathShadow)
{
if (!SRTSHelper.CEModLoaded)
{
throw new NotImplementedException("Calling wrong constructor. This is only enabled for Combat Extended calls. - Smash Phil");
}
this.def = reference.def;
this.thingIDNumber = reference.thingIDNumber;
this.map = map;
this.factionInt = reference.Faction;
this.graphicInt = reference.DefaultGraphic;
this.hitPointsInt = reference.HitPoints;
this.CEprops = comp;
this.CEcomp = CEcomp;
explosionRadius = (float)AccessTools.Field(SRTSHelper.CompProperties_ExplosiveCE, "explosionRadius").GetValue(comp);
this.texPathShadow = texPathShadow;
}
public override void Tick()
{
if (ticksRemaining < 0)
{
this.ExplodeOnImpact();
}
ticksRemaining--;
}
protected override void ExplodeOnImpact()
{
if (!this.SpawnedOrAnyParentSpawned)
return;
AccessTools.Method(type: SRTSHelper.CompExplosiveCE, "Explode").Invoke(this.CEcomp, new object[] { this as Thing, this.Position.ToVector3(), this.Map, 1f});
this.Destroy();
}
private CompProperties CEprops;
private ThingComp CEcomp;
private float explosionRadius;
}
}
|
/*******************************************************************************
Copyright (c) 2011, Perforce Software, Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL PERFORCE SOFTWARE, INC. BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
/*******************************************************************************
* Name : ClientMetadata.cs
*
* Author(s) : wjb
*
* Description : Class used to abstract client side application data.
*
******************************************************************************/
namespace Perforce.P4
{
/// <summary>
/// Metadata from the client associated with a connection.
/// </summary>
public class ClientMetadata
{
/// <summary>
/// Default constructor
/// </summary>
public ClientMetadata()
{
}
/// <summary>
/// Parameterized constructor
/// </summary>
/// <param name="name">name of client</param>
/// <param name="hostname">hostname of client</param>
/// <param name="address">network address of client</param>
/// <param name="currentdirectory">current directory of user</param>
/// <param name="root">root directory of client/workspace</param>
public ClientMetadata
(
string name,
string hostname,
string address,
string currentdirectory,
string root
)
{
Name = name;
HostName = hostname;
Address = address;
CurrentDirectory = currentdirectory;
Root = root;
}
#region properties
/// <summary>
/// Property to access the Name of the Client
/// </summary>
public string Name { get; set; }
/// <summary>
/// Property to access the HostName of the Client
/// </summary>
public string HostName { get; set; }
/// <summary>
/// Property to access the Network address of the client
/// </summary>
public string Address { get; set; }
/// <summary>
/// Property to access current directory of user
/// </summary>
public string CurrentDirectory { get; set; }
/// <summary>
/// Property to access the root directory of the client/workspace
/// </summary>
public string Root { get; set; }
#endregion
#region fromTaggedOutput
/// <summary>
/// Read the fields from the tagged output of an info command
/// </summary>
/// <param name="objectInfo">Tagged output from the 'info' command</param>
public void FromGetClientMetadataCmdTaggedOutput(TaggedObject objectInfo)
{
if (objectInfo.ContainsKey("clientApplication"))
Name = objectInfo["clientApplication"];
if (objectInfo.ContainsKey("clientHost"))
HostName = objectInfo["clientHost"];
if (objectInfo.ContainsKey("clientAddress"))
Address = objectInfo["clientAddress"];
if (objectInfo.ContainsKey("clientCwd"))
CurrentDirectory = objectInfo["clientCwd"];
if (objectInfo.ContainsKey("clientRoot"))
Root = objectInfo["clientRoot"];
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.