content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using PawnRules.API;
using PawnRules.Interface;
using PawnRules.Patch;
using RimWorld;
using RimWorld.Planet;
using Verse;
namespace PawnRules.Data
{
internal class Registry : WorldObject
{
private const string WorldObjectDefName = "PawnRules_Registry";
private const string CurrentVersion = "v" + Mod.Version;
public static bool IsActive => !_isDeactivating && (_instance != null) && (Current.ProgramState == ProgramState.Playing);
private static Registry _instance;
private static bool _isDeactivating;
public static bool ShowFoodPolicy { get => _instance._showFoodPolicy; set => _instance._showFoodPolicy = value; }
public static bool ShowBondingPolicy { get => _instance._showBondingPolicy; set => _instance._showBondingPolicy = value; }
public static bool ShowAllowCourting { get => _instance._showAllowCourting; set => _instance._showAllowCourting = value; }
public static bool ShowAllowArtisan { get => _instance._showAllowArtisan; set => _instance._showAllowArtisan = value; }
public static bool AllowDrugsRestriction { get => _instance._allowDrugsRestriction; set => _instance._allowDrugsRestriction = value; }
public static bool AllowEmergencyFood { get => _instance._allowEmergencyFood; set => _instance._allowEmergencyFood = value; }
public static bool AllowTrainingFood { get => _instance._allowTrainingFood; set => _instance._allowTrainingFood = value; }
public static Pawn ExemptedTrainer { get => _instance._exemptedTrainer; set => _instance._exemptedTrainer = value; }
private string _loadedVersion;
private readonly Dictionary<Type, Dictionary<IPresetableType, Presetable>> _voidPresets = new Dictionary<Type, Dictionary<IPresetableType, Presetable>>();
private readonly Dictionary<Type, Dictionary<IPresetableType, Dictionary<string, Presetable>>> _presets = new Dictionary<Type, Dictionary<IPresetableType, Dictionary<string, Presetable>>>();
private readonly Dictionary<PawnType, Rules> _defaults = new Dictionary<PawnType, Rules>();
private readonly Dictionary<Pawn, Rules> _rules = new Dictionary<Pawn, Rules>();
private List<Presetable> _savedPresets = new List<Presetable>();
private List<Binding> _savedBindings = new List<Binding>();
private List<Binding> _savedDefaults = new List<Binding>();
private bool _showFoodPolicy = true;
private bool _showBondingPolicy = true;
private bool _showAllowCourting = true;
private bool _showAllowArtisan = true;
private bool _allowDrugsRestriction;
private bool _allowEmergencyFood;
private bool _allowTrainingFood;
private Pawn _exemptedTrainer;
public static void Initialize()
{
var worldObjects = Current.Game.World.worldObjects;
var instance = (Registry) worldObjects.ObjectsAt(0).FirstOrDefault(worldObject => worldObject is Registry);
if (instance != null) { return; }
var def = DefDatabase<WorldObjectDef>.GetNamed(WorldObjectDefName);
def.worldObjectClass = typeof(Registry);
instance = (Registry) WorldObjectMaker.MakeWorldObject(def);
def.worldObjectClass = typeof(WorldObject);
instance.Tile = 0;
worldObjects.Add(instance);
}
public static void Clear() => _instance = null;
public static T GetVoidPreset<T>(IPresetableType type) where T : Presetable => (T) _instance._voidPresets[typeof(T)][type];
public static T GetPreset<T>(IPresetableType type, string name) where T : Presetable
{
if (!_instance._presets.ContainsKey(typeof(T)) || !_instance._presets[typeof(T)].ContainsKey(type) || !_instance._presets[typeof(T)][type].ContainsKey(name)) { return null; }
return (T) _instance._presets[typeof(T)][type][name];
}
public static IEnumerable<T> GetPresets<T>(IPresetableType type) where T : Presetable
{
if (!_instance._presets.ContainsKey(typeof(T)) || !_instance._presets[typeof(T)].ContainsKey(type)) { return new T[] { }; }
return _instance._presets[typeof(T)][type].Values.Cast<T>().OrderBy(preset => preset.Name).ToArray();
}
private static void AddPreset(Presetable preset)
{
if (!_instance._presets.ContainsKey(preset.GetType())) { _instance._presets[preset.GetType()] = new Dictionary<IPresetableType, Dictionary<string, Presetable>>(); }
if (!_instance._presets[preset.GetType()].ContainsKey(preset.Type)) { _instance._presets[preset.GetType()][preset.Type] = new Dictionary<string, Presetable>(); }
_instance._presets[preset.GetType()][preset.Type][preset.Name] = preset;
}
public static T CreatePreset<T>(IPresetableType type, string name) where T : Presetable
{
var preset = (T) Activator.CreateInstance(typeof(T), type, name);
AddPreset(preset);
return preset;
}
public static T RenamePreset<T>(T old, string name) where T : Presetable
{
var preset = _instance._presets[old.GetType()][old.Type][old.Name];
_instance._presets[preset.GetType()][preset.Type].Remove(preset.Name);
preset.Name = name;
_instance._presets[preset.GetType()][preset.Type].Add(preset.Name, preset);
return (T) preset;
}
public static void DeletePreset<T>(T preset) where T : Presetable
{
if ((preset == null) || preset.IsVoid) { throw new Mod.Exception("Tried to delete void preset"); }
if (!_instance._presets.ContainsKey(preset.GetType()) || !_instance._presets[preset.GetType()].ContainsKey(preset.Type)) { return; }
_instance._presets[preset.GetType()][preset.Type].Remove(preset.Name);
if (typeof(T) == typeof(Rules))
{
foreach (var rule in _instance._rules.Where(rule => rule.Value == preset).ToArray()) { _instance._rules[rule.Key] = GetVoidPreset<Rules>(rule.Value.Type).CloneRulesFor(rule.Key); }
foreach (var rule in _instance._defaults.Where(rule => rule.Value == preset).ToArray()) { _instance._defaults[rule.Key] = GetVoidPreset<Rules>(rule.Value.Type); }
}
else if ((typeof(T) == typeof(Restriction)) && _instance._presets.ContainsKey(typeof(Rules)))
{
foreach (var rulesType in _instance._presets[typeof(Rules)].Values.ToArray())
{
foreach (var presetable in rulesType.Values.ToArray())
{
var rule = (Rules) presetable;
var type = (RestrictionType) preset.Type;
if (rule.GetRestriction(type) == preset) { rule.SetRestriction(type, GetVoidPreset<Restriction>(type)); }
}
}
}
}
public static bool PresetNameExists<T>(IPresetableType type, string name) => _instance._presets.ContainsKey(typeof(T)) && _instance._presets[typeof(T)].ContainsKey(type) && _instance._presets[typeof(T)][type].ContainsKey(name);
public static Rules GetDefaultRules(PawnType type) => _instance._defaults[type];
public static void SetDefaultRules(Rules rules) => _instance._defaults[rules.Type] = rules;
public static T GetAddonDefaultValue<T>(OptionTarget target, AddonOption addon, T invalidValue = default)
{
var rules = GetDefaultRules(PawnType.FromTarget(target));
if ((rules == null) || !addon.AllowedInPreset) { return invalidValue; }
return rules.GetAddonValue(addon, invalidValue);
}
public static Rules GetRules(Pawn pawn)
{
if (!pawn.CanHaveRules()) { return null; }
return _instance._rules.ContainsKey(pawn) ? _instance._rules[pawn] : null;
}
public static Rules GetOrNewRules(Pawn pawn)
{
if (!pawn.CanHaveRules()) { return null; }
if (_instance._rules.ContainsKey(pawn)) { return _instance._rules[pawn]; }
var rules = GetVoidPreset<Rules>(pawn.GetTargetType()).CloneRulesFor(pawn);
_instance._rules.Add(pawn, rules);
return rules;
}
public static Rules GetOrDefaultRules(Pawn pawn)
{
if (!pawn.CanHaveRules()) { return null; }
if (_instance._rules.ContainsKey(pawn)) { return _instance._rules[pawn]; }
var defaultRules = GetDefaultRules(pawn.GetTargetType());
var rules = defaultRules.IsVoid ? defaultRules.CloneRulesFor(pawn) : defaultRules;
_instance._rules.Add(pawn, rules);
return rules;
}
public static void ReplaceRules(Pawn pawn, Rules rules) => _instance._rules[pawn] = rules;
public static void ReplaceDefaultRules(PawnType type, Rules rules) => _instance._defaults[type] = rules;
private static void ChangeTypeOrCreateRules(Pawn pawn, PawnType type)
{
if (type == pawn.GetTargetType()) { return; }
var defaultRules = GetDefaultRules(type);
_instance._rules[pawn] = defaultRules.IsVoid ? defaultRules.CloneRulesFor(pawn) : defaultRules;
}
public static Rules CloneRules(Pawn original, Pawn cloner)
{
if (!original.CanHaveRules()) { return null; }
if (!_instance._rules.ContainsKey(original)) { return GetOrDefaultRules(cloner); }
if (_instance._rules.ContainsKey(cloner)) { DeleteRules(cloner); }
var cloned = _instance._rules[original].CloneRulesFor(cloner);
_instance._rules.Add(cloner, cloned);
return cloned;
}
public static void DeleteRules(Pawn pawn)
{
if ((pawn == null) || !_instance._rules.ContainsKey(pawn)) { return; }
_instance._rules.Remove(pawn);
}
public static void FactionUpdate(Thing thing, Faction newFaction, bool? guest = null)
{
if (!IsActive || !(thing is Pawn pawn) || pawn.Dead) { return; }
var oldFaction = guest == null ? pawn.Faction : pawn.HostFaction;
PawnType type;
if (newFaction?.IsPlayer ?? false)
{
if ((guest == null) || (pawn.Faction?.IsPlayer ?? false)) { type = pawn.RaceProps.Animal ? PawnType.Animal : PawnType.Colonist; }
else { type = guest.Value ? PawnType.Guest : PawnType.Prisoner; }
}
else if (oldFaction?.IsPlayer ?? false)
{
DeleteRules(pawn);
return;
}
else { return; }
ChangeTypeOrCreateRules(pawn, type);
}
public static void DeactivateMod()
{
_isDeactivating = true;
ModsConfig.SetActive(Mod.Instance.Content.PackageId, false);
var runningMods = Access.Field_Verse_LoadedModManager_RunningMods_Get();
runningMods.Remove(Mod.Instance.Content);
var addonMods = new StringBuilder();
foreach (var mod in AddonManager.Mods)
{
addonMods.AppendLine(mod.Name);
ModsConfig.SetActive(mod.PackageId, false);
runningMods.Remove(mod);
}
ModsConfig.Save();
if (Find.WorldObjects.Contains(_instance)) { Find.WorldObjects.Remove(_instance); }
const string saveName = "PawnRules_Removed";
GameDataSaveLoader.SaveGame(saveName);
var message = addonMods.Length > 0 ? Lang.Get("Button.RemoveModAndAddonsComplete", saveName.Bold(), addonMods.ToString()) : Lang.Get("Button.RemoveModComplete", saveName.Bold());
Dialog_Alert.Open(message, Dialog_Alert.Buttons.Ok, GenCommandLine.Restart);
}
private void InitVoids()
{
_voidPresets[typeof(Rules)] = new Dictionary<IPresetableType, Presetable>();
foreach (var type in PawnType.List) { _voidPresets[typeof(Rules)][type] = Presetable.CreateVoidPreset<Rules>(type); }
_voidPresets[typeof(Restriction)] = new Dictionary<IPresetableType, Presetable>();
foreach (var type in RestrictionType.List) { _voidPresets[typeof(Restriction)][type] = Presetable.CreateVoidPreset<Restriction>(type); }
}
private void InitDefaults()
{
foreach (var type in PawnType.List.Where(type => !_defaults.ContainsKey(type))) { _defaults.Add(type, (Rules) _voidPresets[typeof(Rules)][type]); }
}
public override void PostAdd()
{
base.PostAdd();
_instance = this;
InitVoids();
InitDefaults();
}
public override void SpawnSetup() { }
public override void PostRemove() { }
public override void Print(LayerSubMesh subMesh) { }
public override void Draw() { }
public override void ExposeData()
{
if (_isDeactivating) { return; }
base.ExposeData();
if (Scribe.mode == LoadSaveMode.LoadingVars)
{
_instance = this;
InitVoids();
}
if (Scribe.mode == LoadSaveMode.Saving) { _loadedVersion = CurrentVersion; }
Scribe_Values.Look(ref _loadedVersion, "version");
if ((Scribe.mode == LoadSaveMode.PostLoadInit) && (_loadedVersion != CurrentVersion)) { Mod.Warning($"Registry loaded was saved by a different mod version ({_loadedVersion ?? "vNULL"} loaded, current is {CurrentVersion})"); }
if (Scribe.mode == LoadSaveMode.Saving)
{
_savedPresets.Clear();
_savedDefaults.Clear();
_savedBindings.Clear();
foreach (var type in _presets.Values.SelectMany(classType => classType.Values)) { _savedPresets.AddRange(type.Values.ToArray()); }
_savedDefaults.AddRange(_defaults.Values.Where(preset => !preset.IsVoid).Select(preset => new Binding(preset.Type, preset)).ToArray());
_savedBindings.AddRange(_rules.Where(rules => rules.Key.CanHaveRules()).Select(rules => new Binding(rules.Key, rules.Value.IsIgnored() ? null : rules.Value)).ToArray());
}
Scribe_Values.Look(ref _showFoodPolicy, "showFoodPolicy", true);
Scribe_Values.Look(ref _showBondingPolicy, "showBondingPolicy", true);
Scribe_Values.Look(ref _showAllowCourting, "showAllowCourting", true);
Scribe_Values.Look(ref _showAllowArtisan, "showAllowArtisan", true);
Scribe_Values.Look(ref _allowDrugsRestriction, "allowDrugsRestriction");
Scribe_Values.Look(ref _allowEmergencyFood, "allowEmergencyFood");
Scribe_Values.Look(ref _allowTrainingFood, "allowTrainingFood");
Scribe_Collections.Look(ref _savedPresets, "presets", LookMode.Deep);
Scribe_Collections.Look(ref _savedBindings, "bindings", LookMode.Deep);
Scribe_Collections.Look(ref _savedDefaults, "defaults", LookMode.Deep);
if (Scribe.mode != LoadSaveMode.PostLoadInit) { return; }
_presets.Clear();
_defaults.Clear();
_rules.Clear();
foreach (var preset in _savedPresets) { AddPreset(preset); }
foreach (var preset in _savedDefaults) { _defaults.Add(preset.Target, preset.Rules); }
InitDefaults();
foreach (var binding in _savedBindings.Where(binding => binding.Pawn.CanHaveRules())) { _rules.Add(binding.Pawn, binding.Rules); }
_savedPresets.Clear();
_savedDefaults.Clear();
_savedBindings.Clear();
Presetable.ResetIds();
}
public static XElement ToXml()
{
var xml = new XElement("PawnRulesPlan", new XAttribute("Version", CurrentVersion));
var presets = new XElement("Presets");
foreach (var type in _instance._presets.Values)
{
foreach (var presetType in type.Values) { presets.Add(from preset in presetType where !preset.Value.IsVoid select preset.Value.ToXml()); }
}
xml.Add(presets);
xml.Add(new XElement("Defaults", from rule in _instance._defaults.Values where !rule.IsVoid select new XElement("Preset", new XAttribute("Type", rule.Type.Id), rule.Name)));
return xml;
}
public static void FromXml(XElement xml)
{
var version = xml.Attribute("Version")?.Value;
if (version != CurrentVersion) { Mod.Warning($"Loaded xml from a different mod version ({version ?? "vNULL"} loaded, current is {CurrentVersion})"); }
var presets = xml.Element("Presets")?.Elements().ToArray();
if (presets == null) { return; }
foreach (var restriction in presets.Where(preset => preset.Name == "Restriction").Select(preset => new Restriction(preset))) { AddPreset(restriction); }
foreach (var rules in presets.Where(preset => preset.Name == "Rules").Select(preset => new Rules(preset))) { AddPreset(rules); }
var defaults = xml.Element("Defaults")?.Elements();
if (defaults == null) { return; }
foreach (var preset in defaults)
{
var type = PawnType.FromId(preset.Attribute("Type")?.Value);
var name = preset.Value;
if ((type == null) || name.NullOrEmpty())
{
Mod.Warning("Skipping invalid default preset");
continue;
}
_instance._defaults[type] = GetPreset<Rules>(type, name);
}
}
}
}
| 45.157895 | 237 | 0.62543 | [
"MIT"
] | Jaxe-Dev/PawnRules | Source/Data/Registry.cs | 18,020 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Web;
using System.Threading;
using PromotItLibrary.Classes;
namespace PromotItLibrary.Models
{
/*TODO*/
/*Disable internal Modes.Local/Modes.NotLocal and Loggings*/
public class HTTPClient
{
private HttpClient _httpClient;
public HTTPClient()
{
using HttpClient httpclient = _httpClient;
_httpClient = new HttpClient();
}
~HTTPClient() => _httpClient.Dispose();
public static string ObjectToJsonString<T>(T data) => JsonConvert.SerializeObject(data);
public static T JsonStringToSingleObject<T>(string mycontent) => JsonConvert.DeserializeObject<T>(mycontent);
public static List<T> JsonStringToObjectList<T>(string mycontent) => JsonConvert.DeserializeObject<List<T>>(mycontent);
public static string HttpUrlDecode(string data) => HttpUtility.UrlDecode(data);
public static Dictionary<string, string> PostMessageSplit(string requestBody)
=> requestBody.Split('&').Select(value => value.Split('=')).ToDictionary(pair => pair[0], pair => pair[1]);
//Post
public async Task<bool?> PostSingleDataInsert<T>(string postUrl, T obj, string type = "")
{
string objString = ObjectToJsonString(obj);
string mycontent = await PostStringRequest(postUrl, objString, type);
try
{
if (mycontent == "ok") return true;
else if (mycontent == "fail") return false;
throw new Exception(mycontent);
}
catch { Loggings.ErrorLog($"PostSingleDataInsert Fail"); throw new Exception("Fail to post a content: \n" + mycontent); }
}
public async Task<T> PostSingleDataRequest<T>(string postUrl, T obj, string type = "")
{
string objString = ObjectToJsonString(obj);
string mycontent = await PostStringRequest(postUrl, objString, type);
try { return JsonStringToSingleObject<T>(mycontent);}
catch { Loggings.ErrorLog($"PostSingleDataRequest Fail"); throw new Exception("Fail to add a content: \n" + mycontent); }
}
//public async static Task<string> PostStringRequest<T>(string postUrl, T obj, string type = "")
//{
// string objString = ObjectToJsonString(obj);
// return await PostStringRequest(postUrl, objString, type);
//}
public async Task<string> PostStringRequest(string postUrl, string objString, string type = "")
{
IEnumerable<KeyValuePair<string, string>> queries = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("type", type),
new KeyValuePair<string, string>("data", objString)
};
return await PostRequest(postUrl, queries);
}
public async Task<string> PostRequest(string postUrl, IEnumerable<KeyValuePair<string, string>> queries) // another check method
{
using HttpContent q = new FormUrlEncodedContent(queries);
using HttpResponseMessage response = await _httpClient.PostAsync(postUrl, q);
using HttpContent content = response.Content;
string mycontent = await content.ReadAsStringAsync(); //Response
return mycontent;
}
//Get
public async Task<List<T>> GetMultipleDataRequest<T>(string getUrl, T obj, string type = "")
{
string objString = ObjectToJsonString(obj);
string mycontent = await GetStringRequest(getUrl, objString, type); //Response
try { return JsonStringToSingleObject<List<T>>(mycontent); }
catch { Loggings.ErrorLog($"GetMultipleDataRequest Fail"); throw new Exception("Fail to get a content: \n" + mycontent); }
}
public async Task<T> GetSingleDataRequest<T>(string getUrl, T obj, string type = "")
{
string objString = ObjectToJsonString(obj);
string mycontent = await GetStringRequest(getUrl, objString, type);
try { return JsonStringToSingleObject<T>(mycontent); }
catch { Loggings.ErrorLog($"GetMultipleDataRequest Fail"); throw new Exception("Fail to get a content: \n" + mycontent); }
}
//public async static Task<string> GetStringRequest<T>(string getUrl, T obj, string type = "")
//{
// string objString = ObjectToJsonString(obj);
// return await GetStringRequest(getUrl, objString, type); //Response
//}
public async Task<string> GetStringRequest(string getUrl, string objString, string type = "")
{
string getRequest = "type=" + type + "&data=" + objString;
getRequest = (getRequest.Contains("?") ? "&" : "?") + getRequest;
return await GetRequest(getUrl, getRequest); //Response
}
public async Task<string> GetRequest(string getUrl, string getRequest)
{
using HttpResponseMessage response = await _httpClient.GetAsync(getUrl + getRequest);
using HttpContent content = response.Content;
string mycontent = await content.ReadAsStringAsync(); //Response
return mycontent;
}
}
}
| 44.966942 | 137 | 0.632421 | [
"MIT"
] | w3arthur/PromoIt-PrivateDevelopment | PromoIt/PromotItLibrary/Models/HTTPClient.cs | 5,443 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using DeltaEngine.Extensions;
using NUnit.Framework;
namespace DeltaEngine.Tests.Extensions
{
public class StringExtensionsTests
{
[Test]
public void ConvertFloatToInvariantString()
{
Assert.AreEqual("2.5", 2.5f.ToInvariantString());
Assert.AreNotEqual("3.5", 1.5f.ToInvariantString());
Assert.AreEqual("01", 1.0f.ToInvariantString("00"));
Assert.AreEqual("1.23", 1.2345f.ToInvariantString("0.00"));
Assert.AreNotEqual("1.2345", 1.2345f.ToInvariantString("0.00"));
Assert.AreEqual("1", StringExtensions.ToInvariantString(1));
}
[Test]
public void Convert()
{
Assert.AreEqual(1.0f, "1.0".Convert<float>());
Assert.AreEqual("abc", "abc".Convert<string>());
Assert.Throws<FormatException>(() => "val".Convert<float>());
Assert.AreEqual(1, "1".Convert<int>());
Assert.AreEqual(24, "24".Convert<int>());
Assert.AreEqual('A', "A".Convert<char>());
Assert.AreEqual(943578.39543, "943578.39543".Convert<double>());
Assert.AreEqual(true, "True".Convert<bool>());
Assert.AreEqual(false, "False".Convert<bool>());
Assert.AreEqual(SomeEnum.Additive, "Additive".Convert<SomeEnum>());
Assert.AreEqual(new DateTime(2002, 12, 24), "2002-12-24".Convert<DateTime>());
}
public enum SomeEnum
{
Normal,
Additive,
}
[Test]
public void ToInvariantString()
{
Assert.AreEqual("null", StringExtensions.ToInvariantString(null));
Assert.AreEqual("1", StringExtensions.ToInvariantString((object)1.0f));
Assert.AreEqual("1.2", StringExtensions.ToInvariantString(1.2));
Assert.AreEqual("1.4", StringExtensions.ToInvariantString(1.4m));
Assert.AreEqual("abc", StringExtensions.ToInvariantString("abc"));
Assert.AreEqual("01/01/2014 00:00:00",
StringExtensions.ToInvariantString(new DateTime(2014, 1, 1)));
}
[Test]
public void MaxStringLength()
{
Assert.AreEqual(null, ((string)null).MaxStringLength(4));
Assert.AreEqual("", "".MaxStringLength(4));
Assert.AreEqual("abcd", "abcd".MaxStringLength(4));
Assert.AreEqual("ab..", "abcde".MaxStringLength(4));
Assert.AreEqual("..", "abcde".MaxStringLength(1));
}
[Test]
public static void SplitAndTrimByChar()
{
string[] components = "abc, 123, def".SplitAndTrim(',');
Assert.AreEqual(components.Length, 3);
Assert.AreEqual(components[0], "abc");
Assert.AreEqual(components[1], "123");
Assert.AreEqual(components[2], "def");
}
[Test]
public static void SplitAndTrimByString()
{
string[] components = "3 plus 5 is 8".SplitAndTrim("plus", "is");
Assert.AreEqual(components.Length, 3);
Assert.AreEqual(components[0], "3");
Assert.AreEqual(components[1], "5");
Assert.AreEqual(components[2], "8");
}
[Test]
public void SplitIntoFloats()
{
var stringFloats = new[]
{ "1.0", "2.0", "0511.580254", Math.PI.ToString(CultureInfo.InvariantCulture) };
var expectedFloats = new[] { 1.0f, 2.0f, 511.580261f, 3.14159274f };
float[] floats = stringFloats.SplitIntoFloats();
CollectionAssert.AreEqual(expectedFloats, floats);
}
[Test]
public void SplitIntoFloatsWithSeparator()
{
const string StringFloats = "1.0, 2.0, 0511.580254";
var expectedFloats = new[] { 1.0f, 2.0f, 511.580261f };
CollectionAssert.AreEqual(expectedFloats, StringFloats.SplitIntoFloats(','));
CollectionAssert.AreEqual(expectedFloats, StringFloats.SplitIntoFloats(", "));
}
[Test]
public void Compare()
{
Assert.IsTrue("AbC1".Compare("aBc1"));
Assert.IsTrue("1.23".Compare("1.23"));
Assert.IsFalse("Hello".Compare("World"));
}
[Test]
public void ContainsCaseInsensitive()
{
Assert.IsTrue("hallo".ContainsCaseInsensitive("ha"));
Assert.IsTrue("1.23".ContainsCaseInsensitive("1.2"));
Assert.IsTrue("Hello".ContainsCaseInsensitive("hel"));
Assert.IsFalse("Banana".ContainsCaseInsensitive("Apple"));
Assert.IsFalse(((String)null).ContainsCaseInsensitive("abc"));
}
[Test]
public void IsFirstCharacterInLowerCase()
{
Assert.IsFalse("Banana".IsFirstCharacterInLowerCase());
Assert.IsTrue("banana".IsFirstCharacterInLowerCase());
Assert.IsTrue("".IsFirstCharacterInLowerCase());
}
[Test]
public void ConvertFirstCharacterToUpperCase()
{
const string UpperCaseWord = "Banana";
Assert.AreEqual(UpperCaseWord, UpperCaseWord.ConvertFirstCharacterToUpperCase());
Assert.AreEqual(UpperCaseWord, "banana".ConvertFirstCharacterToUpperCase());
Assert.AreEqual("", "".ConvertFirstCharacterToUpperCase());
}
[Test]
public void SplitTextIntoWords()
{
var stringWords = "TestForSplittingAStringIntoWords".SplitWords(true);
Assert.AreEqual(' ', stringWords[4]);
Assert.AreEqual("Test for splitting a string into words", stringWords);
}
[Test]
public void FromByteArray()
{
const string TestString = "TestString";
Assert.AreEqual(TestString,
StringExtensions.FromByteArray(StringExtensions.ToByteArray(TestString)));
}
[Test]
public void StartsWith()
{
Assert.True(StringExtensions.StartsWith("Hi there, whattup?", "Hi"));
Assert.False(StringExtensions.StartsWith("Hi there, whattup?", "what"));
Assert.True(StringExtensions.StartsWith("bcdeuf", "bc"));
Assert.False(StringExtensions.StartsWith("bcdeuf", "abc"));
Assert.True("Hi there, whattup?".StartsWith(new[] { "Hi", "there", "what" }));
Assert.False("Hi there, whattup?".StartsWith(new[] { "she", "there", "what" }));
Assert.True(StringExtensions.StartsWith("ATI Radeon 9500+", "ati"));
Assert.False(StringExtensions.StartsWith("A-t-i da gaga", "ati"));
Assert.True(StringExtensions.StartsWith("NVidia Geforce3", "nvidia"));
}
[Test]
public void SplitWordsWithEmptyWord()
{
const string TestString = "";
Assert.AreEqual(TestString, TestString.SplitWords(true));
}
[Test]
public void ConvertNotRecognizedType()
{
Assert.Throws<NotSupportedException>(() => "false,false".Convert<List<bool>>());
}
[Test]
public void ConvertNullStringToDictionaryReturns()
{
const string ArrayOfStrings = null;
var dictionary = ArrayOfStrings.Convert<Dictionary<string, string>>();
Assert.IsInstanceOf<Dictionary<string, string>>(dictionary);
}
[Test]
public void ConvertStringToDictionary()
{
const string ArrayOfStrings = "FirstKey;FirstValue;SecondKey;SecondValue";
var dictionary = ArrayOfStrings.Convert<Dictionary<string, string>>();
Assert.IsTrue(dictionary.ContainsKey("FirstKey"));
Assert.IsTrue(dictionary.ContainsValue("SecondValue"));
}
[Test]
public void ConvertDictionaryToString()
{
var dictionary = new Dictionary<string, string>();
dictionary.Add("FirstKey","FirstValue");
dictionary.Add("SecondKey","SecondValue");
var arrayOfStrings = StringExtensions.ToInvariantString(dictionary);
Assert.AreEqual(41, arrayOfStrings.Length);
Assert.AreEqual(8, arrayOfStrings.IndexOf(';'));
Assert.AreEqual(29, arrayOfStrings.LastIndexOf(';'));
}
[Test]
public void CheckForCleanFileName()
{
Assert.AreEqual("", GetCleanFileName(null));
Assert.AreEqual("", GetCleanFileName(""));
Assert.AreEqual("", GetCleanFileName(" "));
Assert.AreEqual("PureFilename", GetCleanFileName("PureFilename"));
Assert.AreEqual("PureFilename", GetCleanFileName("Pure Filename"));
Assert.AreEqual("FullFilename.ext", GetCleanFileName("FullFilename.ext"));
Assert.AreEqual("File1.ext", GetCleanFileName("File#1.ext"));
Assert.AreEqual("FileAB.ext", GetCleanFileName("FileA|B.ext"));
}
private static string GetCleanFileName(string filename)
{
return StringExtensions.GetFilenameWithoutForbiddenCharactersOrSpaces(filename);
}
}
} | 34.473913 | 85 | 0.685585 | [
"Apache-2.0"
] | DeltaEngine/DeltaEngine | Tests/Extensions/StringExtensionsTests.cs | 7,931 | C# |
using PPDFramework.Texture;
using SharpDX;
using System;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
namespace PPDFramework.Chars
{
class CharCacheInfo : DisposableComponent
{
static int d2dFailedCount;
int count;
int width;
int height;
int t_width;
int t_height;
AvailableSpace availableSpace;
float fontScale;
public float FontSize
{
get;
private set;
}
public float ActualFontSize
{
get;
private set;
}
public string FaceName
{
get;
private set;
}
public Char Character
{
get;
private set;
}
public TextureBase Texture
{
get;
private set;
}
public float Width
{
get
{
return width / fontScale;
}
}
public float Height
{
get
{
return height / fontScale;
}
}
public Vector2 UV
{
get;
private set;
}
public Vector2 UVSize
{
get;
private set;
}
public Vector2 ActualUVSize
{
get;
private set;
}
public Vector2 HalfPixel
{
get;
private set;
}
internal int Count
{
get
{
return count;
}
}
protected override void DisposeResource()
{
base.DisposeResource();
if (PPDSetting.Setting.CharacterTexturePackingDisabled)
{
if (Texture != null)
{
Texture.Dispose();
Texture = null;
}
}
else
{
if (availableSpace != null)
{
availableSpace.Dispose();
}
}
}
internal CharCacheInfo(float fontsize, string facename, char c)
{
FontSize = fontsize;
FaceName = facename;
Character = c;
}
internal void CreateTexture(PPDDevice device, Direct2DImageEncoder encoder, SizeTextureManager sizeTextureManager)
{
fontScale = PPDSetting.Setting.FontScaleDisabled ? 1 : Math.Max(1, device.Scale.X);
ActualFontSize = FontSize * fontScale;
TextureBase texture = null;
switch (PPDSetting.Setting.TextureCharMode)
{
case TextureCharMode.D2D:
if (d2dFailedCount > 10)
{
goto case TextureCharMode.WinAPI;
}
texture = CreateTextureByD2D(device, encoder);
if (texture == null)
{
d2dFailedCount++;
goto case TextureCharMode.WinAPI;
}
else
{
d2dFailedCount = 0;
}
break;
case TextureCharMode.WinAPI:
texture = CreateTextureByWinAPI(device);
break;
}
if (texture != null)
{
if (PPDSetting.Setting.CharacterTexturePackingDisabled)
{
Texture = texture;
UV = Vector2.Zero;
UVSize = Vector2.One;
ActualUVSize = Vector2.One;
HalfPixel = new Vector2(0.5f / t_width, 0.5f / t_height);
}
else
{
var sizeTexture = sizeTextureManager.Write(texture, t_width, t_height, out Vector2 uv, out Vector2 uvSize, out availableSpace);
texture.Dispose();
Texture = sizeTexture.Texture;
UV = uv;
UVSize = uvSize;
ActualUVSize = new Vector2(uvSize.X * width / t_width, uvSize.Y * height / t_height);
HalfPixel = sizeTexture.HalfPixel;
}
}
}
private TextureBase CreateTextureByD2D(PPDDevice device, Direct2DImageEncoder encoder)
{
var retryCount = 0;
while (true)
{
try
{
using (var stream = new MemoryStream())
{
encoder.Save(stream, Direct2DImageFormat.Png, new string(Character, 1), FaceName, ActualFontSize, out int width, out int height);
stream.Seek(0, SeekOrigin.Begin);
var bitmap = new Bitmap(stream);
Utility.PreMultiplyAlpha(bitmap);
var tempStream = new MemoryStream();
bitmap.Save(tempStream, System.Drawing.Imaging.ImageFormat.Png);
tempStream.Seek(0, SeekOrigin.Begin);
var texture = ((PPDFramework.Texture.DX9.TextureFactory)TextureFactoryManager.Factory).FromStream(device, tempStream, width, height, SharpDX.Direct3D9.Pool.SystemMemory, true);
this.width = width;
this.height = height;
this.t_width = Utility.UpperPowerOfTwo(width);
this.t_height = Utility.UpperPowerOfTwo(height);
return texture;
}
}
catch
{
retryCount++;
if (retryCount >= 5)
{
break;
}
}
}
return null;
}
private TextureBase CreateTextureByWinAPI(PPDDevice device)
{
var metrics = new WinAPI.GLYPHMETRICS();
var tmetrics = new WinAPI.TEXTMETRIC();
var matrix = new WinAPI.MAT2();
TextureBase texture = null;
matrix.eM11.value = 1;
matrix.eM12.value = 0;
matrix.eM21.value = 0;
matrix.eM22.value = 1;
using (var font = new System.Drawing.Font(FaceName, ActualFontSize))
using (Graphics g = Graphics.FromHwnd(IntPtr.Zero))
{
var hdc = g.GetHdc();
var prev = WinAPI.SelectObject(hdc, font.ToHfont());
var bufferSize = (int)WinAPI.GetGlyphOutlineW(hdc, Character, (uint)6, out metrics, 0, IntPtr.Zero, ref matrix);
var buffer = Marshal.AllocHGlobal(bufferSize);
try
{
uint ret;
if ((ret = WinAPI.GetGlyphOutlineW(hdc, Character, (uint)6, out metrics, (uint)bufferSize, buffer, ref matrix)) > 0 && WinAPI.GetTextMetrics(hdc, ref tmetrics))
{
int iBmp_w = metrics.gmBlackBoxX + (4 - (metrics.gmBlackBoxX % 4)) % 4;
int iBmp_h = metrics.gmBlackBoxY;
int iOfs_x = metrics.gmptGlyphOrigin.x, iOfs_y = tmetrics.ascent - metrics.gmptGlyphOrigin.y;
width = metrics.gmCellIncX;
height = tmetrics.height;
t_width = Utility.UpperPowerOfTwo(Math.Max(width, iBmp_w + iOfs_x));
t_height = Utility.UpperPowerOfTwo(height);
texture = ((PPDFramework.Texture.DX9.TextureFactory)TextureFactoryManager.Factory).Create(device, t_width, t_height, 1, SharpDX.Direct3D9.Pool.SystemMemory, true);
using (var textureData = texture.GetTextureData())
{
var rec = textureData.DataStream;
try
{
byte[] data = new byte[bufferSize];
Marshal.Copy(buffer, data, 0, bufferSize);
int offset1 = (iOfs_x + iOfs_y * t_width) * 4;
int offset2 = (iOfs_x + t_width - iOfs_x - iBmp_w) * 4;
WinAPI.ZeroMemory(rec.DataPointer, (uint)rec.Length);
var writedata = new byte[] { (byte)255, (byte)255, (byte)255, (byte)255 };
for (int i = 0; i < iBmp_h; i++)
{
for (int j = 0; j < iBmp_w; j++)
{
var alpha = (byte)((255 * data[j + iBmp_w * i]) / 64);
writedata[0] = writedata[1] = writedata[2] = alpha;
writedata[3] = (byte)alpha;
if (j == 0)
{
if (i == 0)
{
rec.Seek(offset1, System.IO.SeekOrigin.Current);
}
else
{
rec.Seek(offset2, System.IO.SeekOrigin.Current);
}
}
rec.Write(writedata, 0, writedata.Length);
}
}
}
catch
{
Console.WriteLine("CharTextureError");
}
}
}
}
finally
{
WinAPI.SelectObject(hdc, prev);
WinAPI.DeleteObject(prev);
g.ReleaseHdc(hdc);
Marshal.FreeHGlobal(buffer);
}
}
return texture;
}
public void Increment()
{
count++;
}
public void Decrement()
{
count--;
}
public Vector2 GetActualUV(Vector2 uv)
{
return UV + ActualUVSize * uv;
}
public SharpDX.RectangleF GetActualUVRectangle(float left, float top, float right, float bottom)
{
var topLeft = GetActualUV(new Vector2(left, top));
var bottomRight = GetActualUV(new Vector2(right, bottom));
var halfPixel = HalfPixel;
return new SharpDX.RectangleF(topLeft.X + halfPixel.X, topLeft.Y + halfPixel.Y,
bottomRight.X - topLeft.X - halfPixel.X,
bottomRight.Y - topLeft.Y - halfPixel.Y);
}
}
}
| 34.801242 | 200 | 0.424951 | [
"Apache-2.0"
] | KHCmaster/PPD | Win/PPDFramework/Chars/CharCacheInfo.cs | 11,208 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FakeItEasy;
using Squidex.Caching;
using Squidex.Domain.Apps.Entities.Apps;
using Squidex.Domain.Apps.Entities.Apps.Indexes;
using Squidex.Domain.Apps.Entities.Rules;
using Squidex.Domain.Apps.Entities.Rules.Indexes;
using Squidex.Domain.Apps.Entities.Schemas;
using Squidex.Domain.Apps.Entities.Schemas.Indexes;
using Squidex.Domain.Apps.Entities.TestHelpers;
using Squidex.Infrastructure;
using Squidex.Infrastructure.Security;
using Xunit;
namespace Squidex.Domain.Apps.Entities
{
public class AppProviderTests
{
private readonly CancellationTokenSource cts = new CancellationTokenSource();
private readonly CancellationToken ct;
private readonly IAppsIndex indexForApps = A.Fake<IAppsIndex>();
private readonly IRulesIndex indexForRules = A.Fake<IRulesIndex>();
private readonly ISchemasIndex indexForSchemas = A.Fake<ISchemasIndex>();
private readonly NamedId<DomainId> appId = NamedId.Of(DomainId.NewGuid(), "my-app");
private readonly NamedId<DomainId> schemaId = NamedId.Of(DomainId.NewGuid(), "my-schema");
private readonly IAppEntity app;
private readonly AppProvider sut;
public AppProviderTests()
{
ct = cts.Token;
app = Mocks.App(appId);
sut = new AppProvider(indexForApps, indexForRules, indexForSchemas, new AsyncLocalCache());
}
[Fact]
public async Task Should_get_app_with_schema_from_index()
{
var schema = Mocks.Schema(app.NamedId(), schemaId);
A.CallTo(() => indexForApps.GetAppAsync(app.Id, false, ct))
.Returns(app);
A.CallTo(() => indexForSchemas.GetSchemaAsync(app.Id, schema.Id, false, ct))
.Returns(schema);
var result = await sut.GetAppWithSchemaAsync(app.Id, schemaId.Id, false, ct);
Assert.Equal(schema, result.Item2);
}
[Fact]
public async Task Should_get_apps_from_index()
{
var permissions = new PermissionSet("*");
A.CallTo(() => indexForApps.GetAppsForUserAsync("user1", permissions, ct))
.Returns(new List<IAppEntity> { app });
var result = await sut.GetUserAppsAsync("user1", permissions, ct);
Assert.Equal(app, result.Single());
}
[Fact]
public async Task Should_get_app_from_index()
{
A.CallTo(() => indexForApps.GetAppAsync(app.Id, false, ct))
.Returns(app);
var result = await sut.GetAppAsync(app.Id, false, ct);
Assert.Equal(app, result);
}
[Fact]
public async Task Should_get_app_by_name_from_index()
{
A.CallTo(() => indexForApps.GetAppAsync(app.Name, false, ct))
.Returns(app);
var result = await sut.GetAppAsync(app.Name, false, ct);
Assert.Equal(app, result);
}
[Fact]
public async Task Should_get_schema_from_index()
{
var schema = Mocks.Schema(app.NamedId(), schemaId);
A.CallTo(() => indexForSchemas.GetSchemaAsync(app.Id, schema.Id, false, ct))
.Returns(schema);
var result = await sut.GetSchemaAsync(app.Id, schema.Id, false, ct);
Assert.Equal(schema, result);
}
[Fact]
public async Task Should_get_schema_by_name_from_index()
{
var schema = Mocks.Schema(app.NamedId(), schemaId);
A.CallTo(() => indexForSchemas.GetSchemaAsync(app.Id, schemaId.Name, false, ct))
.Returns(schema);
var result = await sut.GetSchemaAsync(app.Id, schemaId.Name, false, ct);
Assert.Equal(schema, result);
}
[Fact]
public async Task Should_get_schemas_from_index()
{
var schema = Mocks.Schema(app.NamedId(), schemaId);
A.CallTo(() => indexForSchemas.GetSchemasAsync(app.Id, ct))
.Returns(new List<ISchemaEntity> { schema });
var result = await sut.GetSchemasAsync(app.Id, ct);
Assert.Equal(schema, result.Single());
}
[Fact]
public async Task Should_get_rules_from_index()
{
var rule = new RuleEntity();
A.CallTo(() => indexForRules.GetRulesAsync(app.Id, ct))
.Returns(new List<IRuleEntity> { rule });
var result = await sut.GetRulesAsync(app.Id, ct);
Assert.Equal(rule, result.Single());
}
[Fact]
public async Task Should_get_rule_from_index()
{
var rule = new RuleEntity { Id = DomainId.NewGuid() };
A.CallTo(() => indexForRules.GetRulesAsync(app.Id, ct))
.Returns(new List<IRuleEntity> { rule });
var result = await sut.GetRuleAsync(app.Id, rule.Id, ct);
Assert.Equal(rule, result);
}
}
}
| 33.048485 | 103 | 0.584632 | [
"MIT"
] | Dakraid/squidex | backend/tests/Squidex.Domain.Apps.Entities.Tests/AppProviderTests.cs | 5,455 | C# |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
#if !NETCF
using System.Runtime.Serialization;
#endif
namespace log4net.Core
{
/// <summary>
/// Exception base type for log4net.
/// </summary>
/// <remarks>
/// <para>
/// This type extends <see cref="ApplicationException"/>. It
/// does not add any new functionality but does differentiate the
/// type of exception being thrown.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
#if !NETCF
[Serializable]
#endif
public class LogException : ApplicationException
{
#region Public Instance Constructors
/// <summary>
/// Constructor
/// </summary>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="LogException" /> class.
/// </para>
/// </remarks>
public LogException()
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="message">A message to include with the exception.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="LogException" /> class with
/// the specified message.
/// </para>
/// </remarks>
public LogException(String message) : base(message)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="message">A message to include with the exception.</param>
/// <param name="innerException">A nested exception to include.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="LogException" /> class
/// with the specified message and inner exception.
/// </para>
/// </remarks>
public LogException(String message, Exception innerException) : base(message, innerException)
{
}
#endregion Public Instance Constructors
#region Protected Instance Constructors
#if !NETCF
/// <summary>
/// Serialization constructor
/// </summary>
/// <param name="info">The <see cref="SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="LogException" /> class
/// with serialized data.
/// </para>
/// </remarks>
protected LogException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
#endif
#endregion Protected Instance Constructors
}
}
| 29.423423 | 141 | 0.68616 | [
"MIT"
] | 51Degrees/Dnn.Platform | DNN Platform/DotNetNuke.Log4net/log4net/Core/LogException.cs | 3,266 | C# |
using System;
namespace Default_WebApplication_MVC_IndividualUserAccount.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
} | 22.363636 | 70 | 0.719512 | [
"Apache-2.0"
] | vincoss/NetCoreSamples | AspNetCore-2.0/src/Default_WebApplication_MVC_IndividualUserAccount/Models/ErrorViewModel.cs | 246 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Runtime.InteropServices;
using StarkPlatform.CodeAnalysis;
using StarkPlatform.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using StarkPlatform.VisualStudio.LanguageServices.Implementation.CodeModel.Interop;
using StarkPlatform.VisualStudio.LanguageServices.Implementation.Interop;
namespace StarkPlatform.VisualStudio.LanguageServices.Implementation.CodeModel.Collections
{
[ComVisible(true)]
[ComDefaultInterface(typeof(ICodeElements))]
public sealed class ParameterCollection : AbstractCodeElementCollection
{
internal static EnvDTE.CodeElements Create(
CodeModelState state,
AbstractCodeMember parent)
{
var collection = new ParameterCollection(state, parent);
return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection);
}
private ParameterCollection(
CodeModelState state,
AbstractCodeMember parent)
: base(state, parent)
{
}
private AbstractCodeMember ParentElement
{
get { return (AbstractCodeMember)Parent; }
}
protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element)
{
var parameters = this.ParentElement.GetParameters();
if (index < parameters.Length)
{
var parameter = parameters[index];
element = (EnvDTE.CodeElement)CodeParameter.Create(this.State, this.ParentElement, CodeModelService.GetParameterName(parameter));
return true;
}
element = null;
return false;
}
protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element)
{
var parentNode = this.ParentElement.LookupNode();
if (parentNode != null)
{
if (CodeModelService.TryGetParameterNode(parentNode, name, out var parameterNode))
{
// The name of the CodeElement should be just the identifier name associated with the element
// devoid of the type characters hence we use the just identifier name for both creation and
// later searches
element = (EnvDTE.CodeElement)CodeParameter.Create(this.State, this.ParentElement, name);
return true;
}
}
element = null;
return false;
}
public override int Count
{
get
{
return ParentElement.GetParameters().Length;
}
}
}
}
| 36.769231 | 161 | 0.629358 | [
"Apache-2.0"
] | stark-lang/stark-roslyn | src/VisualStudio/Core/Impl/CodeModel/Collections/ParameterCollection.cs | 2,870 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Compute
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Composite Swagger for Compute Client
/// </summary>
public partial interface IComputeManagementClient : System.IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
Microsoft.Rest.ServiceClientCredentials Credentials { get; }
/// <summary>
/// subscription credentials which uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every
/// service call.
/// </summary>
string SubscriptionId { get; set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running
/// Operations. Default value is 30.
/// </summary>
int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is
/// generated and included in each request. Default is true.
/// </summary>
bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IAvailabilitySetsOperations.
/// </summary>
IAvailabilitySetsOperations AvailabilitySets { get; }
/// <summary>
/// Gets the IVirtualMachineExtensionImagesOperations.
/// </summary>
IVirtualMachineExtensionImagesOperations VirtualMachineExtensionImages { get; }
/// <summary>
/// Gets the IVirtualMachineExtensionsOperations.
/// </summary>
IVirtualMachineExtensionsOperations VirtualMachineExtensions { get; }
/// <summary>
/// Gets the IVirtualMachineImagesOperations.
/// </summary>
IVirtualMachineImagesOperations VirtualMachineImages { get; }
/// <summary>
/// Gets the IUsageOperations.
/// </summary>
IUsageOperations Usage { get; }
/// <summary>
/// Gets the IVirtualMachineSizesOperations.
/// </summary>
IVirtualMachineSizesOperations VirtualMachineSizes { get; }
/// <summary>
/// Gets the IVirtualMachinesOperations.
/// </summary>
IVirtualMachinesOperations VirtualMachines { get; }
/// <summary>
/// Gets the IVirtualMachineScaleSetsOperations.
/// </summary>
IVirtualMachineScaleSetsOperations VirtualMachineScaleSets { get; }
/// <summary>
/// Gets the IVirtualMachineScaleSetVMsOperations.
/// </summary>
IVirtualMachineScaleSetVMsOperations VirtualMachineScaleSetVMs { get; }
/// <summary>
/// Gets the IContainerServiceOperations.
/// </summary>
IContainerServiceOperations ContainerService { get; }
}
}
| 32.897436 | 87 | 0.618862 | [
"MIT"
] | samtoubia/azure-sdk-for-net | src/ResourceManagement/Compute/Microsoft.Azure.Management.Compute/Generated/IComputeManagementClient.cs | 3,849 | C# |
using System;
using Iviz.Core;
using Iviz.Msgs.IvizCommonMsgs;
using Iviz.Resources;
using Unity.Collections;
using Unity.Mathematics;
using UnityEngine;
namespace Iviz.Displays
{
public sealed class OccupancyGridResource : DisplayWrapperResource, ISupportsTint
{
const int MaxSize = 10000;
[SerializeField] int numCellsX;
[SerializeField] int numCellsY;
[SerializeField] float cellSize;
readonly NativeList<float4> pointBuffer = new NativeList<float4>();
MeshListResource resource;
protected override IDisplay Display => resource;
public int NumCellsX
{
get => numCellsX;
set
{
if (value == numCellsX)
{
return;
}
if (value < 0 || value > MaxSize)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
numCellsX = value;
}
}
public int NumCellsY
{
get => numCellsY;
set
{
if (value == numCellsY)
{
return;
}
if (value < 0 || value > MaxSize)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
numCellsY = value;
}
}
public float CellSize
{
get => cellSize;
set
{
if (Mathf.Approximately(value, cellSize))
{
return;
}
cellSize = value;
resource.ElementScale = value;
}
}
public bool OcclusionOnly
{
get => resource.OcclusionOnly;
set => resource.OcclusionOnly = value;
}
public ColormapId Colormap
{
get => resource.Colormap;
set => resource.Colormap = value;
}
public bool FlipMinMax
{
get => resource.FlipMinMax;
set => resource.FlipMinMax = value;
}
public bool IsProcessing { get; private set; }
public int NumValidValues => resource != null ? resource.Size : 0;
void Awake()
{
resource = ResourcePool.RentDisplay<MeshListResource>(transform);
resource.OverrideIntensityBounds = true;
resource.IntensityBounds = new Vector2(0, 1);
NumCellsX = 10;
NumCellsY = 10;
CellSize = 1.0f;
Colormap = ColormapId.gray;
resource.MeshResource = Resource.Displays.Cube;
resource.UseColormap = true;
resource.UseIntensityForScaleY = true;
resource.CastShadows = false; // fix weird shadow bug
Layer = LayerType.IgnoreRaycast;
}
public Color Tint
{
get => resource.Tint;
set => resource.Tint = value;
}
public override void Suspend()
{
base.Suspend();
pointBuffer.Clear();
}
public void SetOccupancy(sbyte[] values, Rect? inBounds, Pose pose)
{
IsProcessing = true;
Rect bounds = inBounds ?? new Rect(0, numCellsX, 0, numCellsY);
pointBuffer.Clear();
float4 mul = new float4(cellSize, cellSize, 0, 0.01f);
for (int v = bounds.YMin; v < bounds.YMax; v++)
{
int i = v * numCellsX + bounds.XMin;
for (int u = bounds.XMin; u < bounds.XMax; u++, i++)
{
sbyte val = values[i];
if (val <= 0)
{
continue;
}
float4 p = new float4(u, v, 0, val) * mul;
pointBuffer.Add(p.Ros2Unity());
}
}
GameThread.PostImmediate(() =>
{
resource.transform.SetLocalPose(pose);
resource.SetDirect(pointBuffer.AsArray());
IsProcessing = false;
});
}
void OnDestroy()
{
pointBuffer.Dispose();
}
public readonly struct Rect
{
public int XMin { get; }
public int XMax { get; }
public int YMin { get; }
public int YMax { get; }
public int Width => XMax - XMin;
public int Height => YMax - YMin;
public Rect(int xMin, int xMax, int yMin, int yMax)
{
XMin = xMin;
XMax = xMax;
YMin = yMin;
YMax = yMax;
}
}
}
}
| 25.465969 | 85 | 0.460321 | [
"MIT"
] | KIT-ISAS/iviz | iviz/Assets/Application/Displays/OccupancyGridResource.cs | 4,866 | C# |
#region BSD License
/*
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE.md file or at
* https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.452/blob/master/LICENSE
*
*/
#endregion
using ComponentFactory.Krypton.Toolkit;
using System;
using System.Windows.Forms;
using ToolkitSettings.Classes.Core;
using ToolkitSettings.Classes.Global;
using ToolkitSettings.Classes.PaletteExplorer;
using ToolkitSettings.Classes.PaletteExplorer.Colours;
namespace Persistence.UX.Options
{
public partial class SettingsManagementOptions : KryptonForm
{
#region Variables
private ColourIntensitySettingsManager _colourBlendingSettingsManager = new ColourIntensitySettingsManager();
private ColourIntegerSettingsManager _colourIntegerSettingsManager = new ColourIntegerSettingsManager();
private AllMergedColourSettingsManager _colourSettingsManager = new AllMergedColourSettingsManager();
private ColourStringSettingsManager _colourStringSettingsManager = new ColourStringSettingsManager();
private GlobalBooleanSettingsManager _globalBooleanSettingsManager = new GlobalBooleanSettingsManager();
private GlobalStringSettingsManager _globalStringSettingsManager = new GlobalStringSettingsManager();
private PaletteTypefaceSettingsManager _paletteTypefaceSettingsManager = new PaletteTypefaceSettingsManager();
#endregion
#region System
private KryptonPanel kryptonPanel2;
private System.Windows.Forms.PictureBox pictureBox1;
private KryptonButton kbtnResetPaletteTypefaceSettings;
private KryptonButton kbtnResetGlobalStringSettings;
private KryptonButton kbtnResetGlobalBooleanSettings;
private KryptonButton kbtnResetColourStringSettings;
private KryptonButton kbtnResetColourSettings;
private KryptonButton kbtnResetColourIntegerSettings;
private KryptonButton kbtnResetColourBlendingSettings;
private KryptonButton kbtnNukeAllSettings;
private KryptonCheckBox kchkAskForConfirmation;
private KryptonButton kbtnCancel;
private KryptonPanel kryptonPanel1;
private void InitializeComponent()
{
this.kryptonPanel1 = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.kryptonPanel2 = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.kbtnNukeAllSettings = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.kbtnResetColourBlendingSettings = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.kbtnResetColourIntegerSettings = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.kbtnResetColourSettings = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.kbtnResetColourStringSettings = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.kbtnResetGlobalBooleanSettings = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.kbtnResetGlobalStringSettings = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.kbtnResetPaletteTypefaceSettings = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.kchkAskForConfirmation = new ComponentFactory.Krypton.Toolkit.KryptonCheckBox();
this.kbtnCancel = new ComponentFactory.Krypton.Toolkit.KryptonButton();
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel1)).BeginInit();
this.kryptonPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel2)).BeginInit();
this.kryptonPanel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// kryptonPanel1
//
this.kryptonPanel1.Controls.Add(this.kbtnResetPaletteTypefaceSettings);
this.kryptonPanel1.Controls.Add(this.kbtnResetGlobalStringSettings);
this.kryptonPanel1.Controls.Add(this.kbtnResetGlobalBooleanSettings);
this.kryptonPanel1.Controls.Add(this.kbtnResetColourStringSettings);
this.kryptonPanel1.Controls.Add(this.kbtnResetColourSettings);
this.kryptonPanel1.Controls.Add(this.kbtnResetColourIntegerSettings);
this.kryptonPanel1.Controls.Add(this.kbtnResetColourBlendingSettings);
this.kryptonPanel1.Controls.Add(this.kbtnNukeAllSettings);
this.kryptonPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryptonPanel1.Location = new System.Drawing.Point(0, 0);
this.kryptonPanel1.Name = "kryptonPanel1";
this.kryptonPanel1.Size = new System.Drawing.Size(714, 535);
this.kryptonPanel1.TabIndex = 0;
//
// kryptonPanel2
//
this.kryptonPanel2.Controls.Add(this.kbtnCancel);
this.kryptonPanel2.Controls.Add(this.kchkAskForConfirmation);
this.kryptonPanel2.Dock = System.Windows.Forms.DockStyle.Bottom;
this.kryptonPanel2.Location = new System.Drawing.Point(0, 483);
this.kryptonPanel2.Name = "kryptonPanel2";
this.kryptonPanel2.Size = new System.Drawing.Size(714, 52);
this.kryptonPanel2.TabIndex = 0;
//
// pictureBox1
//
this.pictureBox1.BackColor = System.Drawing.SystemColors.ControlDarkDark;
this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.pictureBox1.Location = new System.Drawing.Point(0, 481);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(714, 2);
this.pictureBox1.TabIndex = 1;
this.pictureBox1.TabStop = false;
//
// kbtnNukeAllSettings
//
this.kbtnNukeAllSettings.AutoSize = true;
this.kbtnNukeAllSettings.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnNukeAllSettings.Location = new System.Drawing.Point(12, 418);
this.kbtnNukeAllSettings.Name = "kbtnNukeAllSettings";
this.kbtnNukeAllSettings.Size = new System.Drawing.Size(137, 30);
this.kbtnNukeAllSettings.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnNukeAllSettings.TabIndex = 64;
this.kbtnNukeAllSettings.Values.Text = "&Nuke All Settings";
this.kbtnNukeAllSettings.Click += new System.EventHandler(this.kbtnNukeAllSettings_Click);
//
// kbtnResetColourBlendingSettings
//
this.kbtnResetColourBlendingSettings.AutoSize = true;
this.kbtnResetColourBlendingSettings.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnResetColourBlendingSettings.Location = new System.Drawing.Point(12, 12);
this.kbtnResetColourBlendingSettings.Name = "kbtnResetColourBlendingSettings";
this.kbtnResetColourBlendingSettings.Size = new System.Drawing.Size(236, 30);
this.kbtnResetColourBlendingSettings.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnResetColourBlendingSettings.TabIndex = 65;
this.kbtnResetColourBlendingSettings.Values.Text = "Reset Colour &Blending Settings";
this.kbtnResetColourBlendingSettings.Click += new System.EventHandler(this.kbtnResetColourBlendingSettings_Click);
//
// kbtnResetColourIntegerSettings
//
this.kbtnResetColourIntegerSettings.AutoSize = true;
this.kbtnResetColourIntegerSettings.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnResetColourIntegerSettings.Location = new System.Drawing.Point(12, 70);
this.kbtnResetColourIntegerSettings.Name = "kbtnResetColourIntegerSettings";
this.kbtnResetColourIntegerSettings.Size = new System.Drawing.Size(224, 30);
this.kbtnResetColourIntegerSettings.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnResetColourIntegerSettings.TabIndex = 66;
this.kbtnResetColourIntegerSettings.Values.Text = "Reset Colour &Integer Settings";
this.kbtnResetColourIntegerSettings.Click += new System.EventHandler(this.kbtnResetColourIntegerSettings_Click);
//
// kbtnResetColourSettings
//
this.kbtnResetColourSettings.AutoSize = true;
this.kbtnResetColourSettings.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnResetColourSettings.Location = new System.Drawing.Point(12, 128);
this.kbtnResetColourSettings.Name = "kbtnResetColourSettings";
this.kbtnResetColourSettings.Size = new System.Drawing.Size(168, 30);
this.kbtnResetColourSettings.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnResetColourSettings.TabIndex = 67;
this.kbtnResetColourSettings.Values.Text = "Reset &Colour Settings";
this.kbtnResetColourSettings.Click += new System.EventHandler(this.kbtnResetColourSettings_Click);
//
// kbtnResetColourStringSettings
//
this.kbtnResetColourStringSettings.AutoSize = true;
this.kbtnResetColourStringSettings.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnResetColourStringSettings.Location = new System.Drawing.Point(12, 186);
this.kbtnResetColourStringSettings.Name = "kbtnResetColourStringSettings";
this.kbtnResetColourStringSettings.Size = new System.Drawing.Size(215, 30);
this.kbtnResetColourStringSettings.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnResetColourStringSettings.TabIndex = 68;
this.kbtnResetColourStringSettings.Values.Text = "Reset Colour &String Settings";
this.kbtnResetColourStringSettings.Click += new System.EventHandler(this.kbtnResetColourStringSettings_Click);
//
// kbtnResetGlobalBooleanSettings
//
this.kbtnResetGlobalBooleanSettings.AutoSize = true;
this.kbtnResetGlobalBooleanSettings.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnResetGlobalBooleanSettings.Location = new System.Drawing.Point(12, 244);
this.kbtnResetGlobalBooleanSettings.Name = "kbtnResetGlobalBooleanSettings";
this.kbtnResetGlobalBooleanSettings.Size = new System.Drawing.Size(230, 30);
this.kbtnResetGlobalBooleanSettings.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnResetGlobalBooleanSettings.TabIndex = 69;
this.kbtnResetGlobalBooleanSettings.Values.Text = "Reset Global B&oolean Settings";
this.kbtnResetGlobalBooleanSettings.Click += new System.EventHandler(this.kbtnResetGlobalBooleanSettings_Click);
//
// kbtnResetGlobalStringSettings
//
this.kbtnResetGlobalStringSettings.AutoSize = true;
this.kbtnResetGlobalStringSettings.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnResetGlobalStringSettings.Location = new System.Drawing.Point(12, 302);
this.kbtnResetGlobalStringSettings.Name = "kbtnResetGlobalStringSettings";
this.kbtnResetGlobalStringSettings.Size = new System.Drawing.Size(214, 30);
this.kbtnResetGlobalStringSettings.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnResetGlobalStringSettings.TabIndex = 70;
this.kbtnResetGlobalStringSettings.Values.Text = "Reset &Global String Settings";
this.kbtnResetGlobalStringSettings.Click += new System.EventHandler(this.kbtnResetGlobalStringSettings_Click);
//
// kbtnResetPaletteTypefaceSettings
//
this.kbtnResetPaletteTypefaceSettings.AutoSize = true;
this.kbtnResetPaletteTypefaceSettings.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnResetPaletteTypefaceSettings.Location = new System.Drawing.Point(12, 360);
this.kbtnResetPaletteTypefaceSettings.Name = "kbtnResetPaletteTypefaceSettings";
this.kbtnResetPaletteTypefaceSettings.Size = new System.Drawing.Size(238, 30);
this.kbtnResetPaletteTypefaceSettings.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnResetPaletteTypefaceSettings.TabIndex = 71;
this.kbtnResetPaletteTypefaceSettings.Values.Text = "Reset &Palette Typeface Settings";
this.kbtnResetPaletteTypefaceSettings.Click += new System.EventHandler(this.kbtnResetPaletteTypefaceSettings_Click);
//
// kchkAskForConfirmation
//
this.kchkAskForConfirmation.Location = new System.Drawing.Point(12, 14);
this.kchkAskForConfirmation.Name = "kchkAskForConfirmation";
this.kchkAskForConfirmation.Size = new System.Drawing.Size(175, 26);
this.kchkAskForConfirmation.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kchkAskForConfirmation.TabIndex = 0;
this.kchkAskForConfirmation.Values.Text = "&Ask for Confirmation";
//
// kbtnCancel
//
this.kbtnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.kbtnCancel.AutoSize = true;
this.kbtnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.kbtnCancel.Location = new System.Drawing.Point(612, 10);
this.kbtnCancel.Name = "kbtnCancel";
this.kbtnCancel.Size = new System.Drawing.Size(90, 30);
this.kbtnCancel.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnCancel.TabIndex = 4;
this.kbtnCancel.Values.Text = "Ca&ncel";
this.kbtnCancel.Click += new System.EventHandler(this.kbtnCancel_Click);
//
// SettingsManagementOptions
//
this.CancelButton = this.kbtnCancel;
this.ClientSize = new System.Drawing.Size(714, 535);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.kryptonPanel2);
this.Controls.Add(this.kryptonPanel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "SettingsManagementOptions";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Reset Settings";
this.Load += new System.EventHandler(this.SettingsManagementOptions_Load);
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel1)).EndInit();
this.kryptonPanel1.ResumeLayout(false);
this.kryptonPanel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel2)).EndInit();
this.kryptonPanel2.ResumeLayout(false);
this.kryptonPanel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
}
#endregion
#region Constructors
public SettingsManagementOptions()
{
InitializeComponent();
}
#endregion
private void SettingsManagementOptions_Load(object sender, EventArgs e)
{
}
private void kbtnCancel_Click(object sender, EventArgs e)
{
Hide();
}
private void kbtnResetColourBlendingSettings_Click(object sender, EventArgs e)
{
_colourBlendingSettingsManager.ResetColourBlendingValues(kchkAskForConfirmation.Checked);
_colourBlendingSettingsManager.SaveColourBlendingValues(kchkAskForConfirmation.Checked);
kbtnResetColourBlendingSettings.Enabled = false;
}
private void kbtnResetColourIntegerSettings_Click(object sender, EventArgs e)
{
_colourIntegerSettingsManager.ResetColourIntegerSettings(kchkAskForConfirmation.Checked);
_colourIntegerSettingsManager.SaveColourIntegerSettings(kchkAskForConfirmation.Checked);
kbtnResetColourIntegerSettings.Enabled = false;
}
private void kbtnResetColourSettings_Click(object sender, EventArgs e)
{
_colourSettingsManager.ResetToDefaults(); // (kchkAskForConfirmation.Checked);
_colourSettingsManager.SaveAllMergedColourSettings(kchkAskForConfirmation.Checked);
kbtnResetColourSettings.Enabled = false;
}
private void kbtnResetColourStringSettings_Click(object sender, EventArgs e)
{
_colourStringSettingsManager.ResetColourStringSettings(kchkAskForConfirmation.Checked);
_colourStringSettingsManager.SaveColourStringSettings(kchkAskForConfirmation.Checked);
kbtnResetColourStringSettings.Enabled = false;
}
private void kbtnResetGlobalBooleanSettings_Click(object sender, EventArgs e)
{
_globalBooleanSettingsManager.ResetSettings(kchkAskForConfirmation.Checked);
_globalBooleanSettingsManager.SaveBooleanSettings(kchkAskForConfirmation.Checked);
kbtnResetGlobalBooleanSettings.Enabled = false;
}
private void kbtnResetGlobalStringSettings_Click(object sender, EventArgs e)
{
_globalStringSettingsManager.ResetSettings(kchkAskForConfirmation.Checked);
_globalStringSettingsManager.SaveStringSettings(kchkAskForConfirmation.Checked);
kbtnResetGlobalStringSettings.Enabled = false;
}
private void kbtnResetPaletteTypefaceSettings_Click(object sender, EventArgs e)
{
_paletteTypefaceSettingsManager.ResetPaletteTypefaceSettings(kchkAskForConfirmation.Checked);
_paletteTypefaceSettingsManager.SavePaletteTypefaceSettings(kchkAskForConfirmation.Checked);
kchkAskForConfirmation.Enabled = false;
}
private void kbtnNukeAllSettings_Click(object sender, EventArgs e)
{
NukeAllSettings(kchkAskForConfirmation.Checked);
}
private void NukeAllSettings(bool usePrompt)
{
if (usePrompt)
{
DialogResult result = KryptonMessageBox.Show("Warning: This action will reset all settings back to their defaults, and is not reversible!\nDo you want to proceed?", "Nuke All Settings", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
if (result == DialogResult.Yes)
{
_colourBlendingSettingsManager.ResetColourBlendingValues();
_colourBlendingSettingsManager.SaveColourBlendingValues();
kbtnResetColourBlendingSettings.Enabled = false;
_colourIntegerSettingsManager.ResetColourIntegerSettings();
_colourIntegerSettingsManager.SaveColourIntegerSettings();
kbtnResetColourIntegerSettings.Enabled = false;
_colourSettingsManager.ResetToDefaults();
_colourSettingsManager.SaveAllMergedColourSettings();
kbtnResetColourSettings.Enabled = false;
_colourStringSettingsManager.ResetColourStringSettings();
_colourStringSettingsManager.SaveColourStringSettings();
kbtnResetColourStringSettings.Enabled = false;
_globalBooleanSettingsManager.ResetSettings();
_globalBooleanSettingsManager.SaveBooleanSettings();
kbtnResetGlobalBooleanSettings.Enabled = false;
_globalStringSettingsManager.ResetSettings();
_globalStringSettingsManager.SaveStringSettings();
kbtnResetGlobalStringSettings.Enabled = false;
_paletteTypefaceSettingsManager.ResetPaletteTypefaceSettings();
_paletteTypefaceSettingsManager.SavePaletteTypefaceSettings();
kbtnResetPaletteTypefaceSettings.Enabled = false;
kbtnNukeAllSettings.Enabled = false;
}
}
}
}
} | 56.151282 | 284 | 0.698114 | [
"BSD-3-Clause"
] | Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.452 | Source/Krypton Toolkit Suite Extended/Shared/Persistence/UX/Options/SettingsManagementOptions.cs | 21,901 | C# |
using System;
namespace Rigger.Attributes
{
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public class OnEventAttribute : Attribute, ILifecycle
{
public Type Event { get; set; }
public OnEventAttribute (Type evt)
{
this.Event = evt;
}
}
} | 21.066667 | 64 | 0.613924 | [
"Apache-2.0"
] | cyclopunk/Rigger | Rigger.Abstractions/Traits/OnEventAttribute.cs | 318 | C# |
/* Copyright 2016 Mark Waterman
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Threading;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Condensed;
using Condensed.Indexes;
namespace UnitTests
{
[TestClass]
public class Basics
{
[TestMethod]
public void AddAndReadSingle()
{
CondensedCollection<int> dlist = new CondensedCollection<int>();
dlist.Add(42);
Assert.AreEqual(42, dlist[0]);
}
[TestMethod]
public void RemoveSingle()
{
CondensedCollection<string> dlist = new CondensedCollection<string>();
dlist.Add("test");
Assert.AreEqual("test", dlist[0]);
Assert.AreEqual<int>(1, dlist.Count);
Assert.AreEqual<int>(1, dlist.UniqueCount);
dlist.Remove("test");
Assert.AreEqual<int>(0, dlist.Count);
Assert.AreEqual<int>(0, dlist.UniqueCount);
}
[TestMethod]
public void RemoveAtSingle()
{
CondensedCollection<string> dlist = new CondensedCollection<string>();
dlist.Add("test");
Assert.AreEqual("test", dlist[0]);
Assert.AreEqual<int>(1, dlist.Count);
Assert.AreEqual<int>(1, dlist.UniqueCount);
dlist.RemoveAt(0);
Assert.AreEqual<int>(0, dlist.Count);
Assert.AreEqual<int>(0, dlist.UniqueCount);
}
[TestMethod]
public void AddAndReadDuplicates()
{
CondensedCollection<int> dlist = new CondensedCollection<int>();
dlist.Add(43);
dlist.Add(43);
Assert.AreEqual(43, dlist[0]);
Assert.AreEqual(43, dlist[1]);
}
[TestMethod]
public void Add1000()
{
CondensedCollection<int> dlist = new CondensedCollection<int>();
for (int i = 0; i < 1000; ++i)
{
dlist.Add(i);
}
for (int i = 0; i < 1000; ++i)
{
Assert.AreEqual<int>(i, dlist[i]);
}
}
[TestMethod]
public void IndexOf()
{
CondensedCollection<int> dlist = new CondensedCollection<int>();
for (int i = 0; i < 1000; ++i)
{
dlist.Add(i);
}
Assert.AreEqual<int>(444, dlist.IndexOf(444));
Assert.AreEqual<int>(-1, dlist.IndexOf(9999));
}
[TestMethod]
public void MutableStruct()
{
var point = new System.Drawing.Point(42, 42);
var l = new CondensedCollection<System.Drawing.Point>();
l.Add(point);
l.Add(point);
Assert.AreEqual(2, l.Count);
Assert.AreEqual(1, l.UniqueCount);
var p2 = l[0];
p2.X = 43;
l[0] = p2;
Assert.AreEqual(43, l[0].X);
Assert.AreEqual(42, l[1].X);
}
}
}
| 28.690476 | 82 | 0.552974 | [
"Apache-2.0"
] | markwaterman/CondensedDotNet | src/UnitTests-NetFramework/Basics.cs | 3,617 | C# |
using System.Threading.Tasks;
using CollectIt.Database.Entities.Account;
namespace CollectIt.Database.Abstractions.Account.Interfaces;
public interface IResourceAcquisitionService
{
public Task<bool> IsResourceAcquiredByUserAsync(int userId, int resourceId);
/// <summary>
/// Add resource to be available for current user to download
/// </summary>
/// <exception cref="CollectIt.Database.Abstractions.Account.Exceptions.NoSuitableSubscriptionFoundException">No subscription found to acquire required image for required user</exception>
/// <exception cref="CollectIt.Database.Abstractions.Account.Exceptions.UserNotFoundException">User with provided <param name="userId">User Id</param> not found</exception>
/// <exception cref="CollectIt.Database.Abstractions.Account.Exceptions.ResourceNotFoundException">Image with provided <param name="imageId">Image Id</param> not found </exception>
/// <exception cref="CollectIt.Database.Abstractions.Account.Exceptions.UserAlreadyAcquiredResourceException">User already had image acquired</exception>
public Task<AcquiredUserResource> AcquireImageAsync(int userId, int imageId);
public Task<AcquiredUserResource> AcquireMusicAsync(int userId, int musicId);
public Task<AcquiredUserResource> AcquireVideoAsync(int userId, int videoId);
} | 69.842105 | 191 | 0.798794 | [
"Apache-2.0"
] | SamboTrener/collect-it | src/CollectIt.Database/CollectIt.Database.Abstractions/Account/Interfaces/IResourceAcquisitionService.cs | 1,327 | C# |
// Project: Aguafrommars/TheIdServer
// Copyright (c) 2021 @Olivier Lefebvre
using Aguacongas.IdentityServer.Store;
using Aguacongas.IdentityServer.Store.Entity;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
namespace Aguacongas.TheIdServer.Identity
{
/// <summary>
/// Creates a new instance of a persistence store for roles.
/// </summary>
/// <typeparam name="TRole">The type of the class representing a role.</typeparam>
[SuppressMessage("Major Code Smell", "S3881:\"IDisposable\" should be implemented correctly", Justification = "Nothing to dispose")]
[SuppressMessage("Design", "CA1063:Implement IDisposable Correctly", Justification = "Nothing to dispose")]
public class RoleStore<TRole> : IRoleClaimStore<TRole>
where TRole : IdentityRole, new()
{
private readonly IAdminStore<Role> _roleStore;
private readonly IAdminStore<RoleClaim> _claimStore;
private bool _disposed;
/// <summary>
/// Initializes a new instance of the <see cref="RoleStore{TRole, TKey, TUserRole, TRoleClaim}"/> class.
/// </summary>
/// <param name="roleStore">The store.</param>
/// <param name="describer">The describer.</param>
/// <exception cref="System.ArgumentNullException">store</exception>
public RoleStore(IAdminStore<Role> roleStore, IAdminStore<RoleClaim> claimStore, IdentityErrorDescriber describer = null)
{
_roleStore = roleStore ?? throw new ArgumentNullException(nameof(roleStore));
_claimStore = claimStore ?? throw new ArgumentNullException(nameof(claimStore));
ErrorDescriber = describer ?? new IdentityErrorDescriber();
}
/// <summary>
/// Gets or sets the <see cref="IdentityErrorDescriber"/> for any error that occurred with the current operation.
/// </summary>
public IdentityErrorDescriber ErrorDescriber { get; set; }
/// <summary>
/// Creates a new role in a store as an asynchronous operation.
/// </summary>
/// <param name="role">The role to create in the store.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the <see cref="IdentityResult"/> of the asynchronous query.</returns>
public async virtual Task<IdentityResult> CreateAsync(TRole role, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
AssertNotNull(role, nameof(role));
try
{
var created = await _roleStore.CreateAsync(role.ToRole(), cancellationToken).ConfigureAwait(false);
role.Id = created.Id;
return IdentityResult.Success;
}
catch(Exception e)
{
return IdentityResult.Failed(new IdentityError
{
Code = e.GetType().Name,
Description = e.Message
});
}
}
/// <summary>
/// Updates a role in a store as an asynchronous operation.
/// </summary>
/// <param name="role">The role to update in the store.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the <see cref="IdentityResult"/> of the asynchronous query.</returns>
public async virtual Task<IdentityResult> UpdateAsync(TRole role, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
AssertNotNull(role, nameof(role));
try
{
await _roleStore.UpdateAsync(role.ToRole(), cancellationToken).ConfigureAwait(false);
return IdentityResult.Success;
}
catch (Exception e)
{
return IdentityResult.Failed(new IdentityError
{
Code = e.GetType().Name,
Description = e.Message
});
}
}
/// <summary>
/// Deletes a role from the store as an asynchronous operation.
/// </summary>
/// <param name="role">The role to delete from the store.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the <see cref="IdentityResult"/> of the asynchronous query.</returns>
public async virtual Task<IdentityResult> DeleteAsync(TRole role, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
AssertNotNull(role, nameof(role));
try
{
await _roleStore.DeleteAsync(role.Id, cancellationToken).ConfigureAwait(false);
return IdentityResult.Success;
}
catch (Exception e)
{
return IdentityResult.Failed(new IdentityError
{
Code = e.GetType().Name,
Description = e.Message
});
}
}
/// <summary>
/// Gets the ID for a role from the store as an asynchronous operation.
/// </summary>
/// <param name="role">The role whose ID should be returned.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>A <see cref="Task{TResult}"/> that contains the ID of the role.</returns>
public virtual Task<string> GetRoleIdAsync(TRole role, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
AssertNotNull(role, nameof(role));
return Task.FromResult(role.Id);
}
/// <summary>
/// Gets the name of a role from the store as an asynchronous operation.
/// </summary>
/// <param name="role">The role whose name should be returned.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>A <see cref="Task{TResult}"/> that contains the name of the role.</returns>
public virtual Task<string> GetRoleNameAsync(TRole role, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
AssertNotNull(role, nameof(role));
return Task.FromResult(role.Name);
}
/// <summary>
/// Sets the name of a role in the store as an asynchronous operation.
/// </summary>
/// <param name="role">The role whose name should be set.</param>
/// <param name="roleName">The name of the role.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
public virtual Task SetRoleNameAsync(TRole role, string roleName, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
AssertNotNull(role, nameof(role));
role.Name = roleName;
return Task.CompletedTask;
}
/// <summary>
/// Finds the role who has the specified ID as an asynchronous operation.
/// </summary>
/// <param name="roleId">The role ID to look for.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>A <see cref="Task{TResult}"/> that result of the look up.</returns>
public virtual async Task<TRole> FindByIdAsync(string roleId, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
var response = await _roleStore.GetAsync(new PageRequest
{
Filter = $"{nameof(Role.Id)} eq '{roleId}'"
}, cancellationToken).ConfigureAwait(false);
if (response.Count == 1)
{
return response.Items.First().ToIdentityRole<TRole>();
}
return null;
}
/// <summary>
/// Finds the role who has the specified normalized name as an asynchronous operation.
/// </summary>
/// <param name="normalizedRoleName">The normalized role name to look for.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>A <see cref="Task{TResult}"/> that result of the look up.</returns>
public virtual async Task<TRole> FindByNameAsync(string normalizedRoleName, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
var response = await _roleStore.GetAsync(new PageRequest
{
Filter = $"{nameof(Role.NormalizedName)} eq '{normalizedRoleName}'"
}, cancellationToken).ConfigureAwait(false);
if (response.Count == 1)
{
return response.Items.First().ToIdentityRole<TRole>();
}
return default;
}
/// <summary>
/// Get a role's normalized name as an asynchronous operation.
/// </summary>
/// <param name="role">The role whose normalized name should be retrieved.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>A <see cref="Task{TResult}"/> that contains the name of the role.</returns>
public virtual Task<string> GetNormalizedRoleNameAsync(TRole role, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
AssertNotNull(role, nameof(role));
return Task.FromResult(role.NormalizedName);
}
/// <summary>
/// Set a role's normalized name as an asynchronous operation.
/// </summary>
/// <param name="role">The role whose normalized name should be set.</param>
/// <param name="normalizedName">The normalized name to set</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
public virtual Task SetNormalizedRoleNameAsync(TRole role, string normalizedName, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
AssertNotNull(role, nameof(role));
role.NormalizedName = normalizedName;
return Task.CompletedTask;
}
/// <summary>
/// Throws if this class has been disposed.
/// </summary>
protected void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
}
/// <summary>
/// Dispose the stores
/// </summary>
[SuppressMessage("Blocker Code Smell", "S2953:Methods named \"Dispose\" should implement \"IDisposable.Dispose\"", Justification = "<Pending>")]
public void Dispose()
{
_disposed = true;
GC.SuppressFinalize(this);
}
/// <summary>
/// Get the claims associated with the specified <paramref name="role"/> as an asynchronous operation.
/// </summary>
/// <param name="role">The role whose claims should be retrieved.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>A <see cref="Task{TResult}"/> that contains the claims granted to a role.</returns>
public async virtual Task<IList<Claim>> GetClaimsAsync(TRole role, CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
AssertNotNull(role, nameof(role));
var response = await _claimStore.GetAsync(new PageRequest
{
Filter = $"{nameof(RoleClaim.RoleId)} eq '{role.Id}'"
}, cancellationToken).ConfigureAwait(false);
return response.Items.Select(CreateClaim).ToList();
}
/// <summary>
/// Adds the <paramref name="claim"/> given to the specified <paramref name="role"/>.
/// </summary>
/// <param name="role">The role to add the claim to.</param>
/// <param name="claim">The claim to add to the role.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
public virtual async Task AddClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken =default)
{
ThrowIfDisposed();
AssertNotNull(role, nameof(role));
AssertNotNull(claim, nameof(claim));
await _claimStore.CreateAsync(CreateRoleClaim(role, claim), cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Removes the <paramref name="claim"/> given from the specified <paramref name="role"/>.
/// </summary>
/// <param name="role">The role to remove the claim from.</param>
/// <param name="claim">The claim to remove from the role.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
public async virtual Task RemoveClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
AssertNotNull(role, nameof(role));
AssertNotNull(claim, nameof(claim));
var response = await _claimStore.GetAsync(new PageRequest
{
Filter = $"{nameof(RoleClaim.RoleId)} eq '{role.Id}' and {nameof(RoleClaim.ClaimType)} eq '{claim.Type}' and {nameof(RoleClaim.ClaimValue)} eq '{claim.Value}'"
}, cancellationToken).ConfigureAwait(false);
var taskList = new List<Task>(response.Count);
foreach(var roleClaim in response.Items)
{
taskList.Add(_claimStore.DeleteAsync(roleClaim.Id.ToString(), cancellationToken));
}
await Task.WhenAll(taskList).ConfigureAwait(false);
}
/// <summary>
/// Creates an entity representing a role claim.
/// </summary>
/// <param name="role">The associated role.</param>
/// <param name="claim">The associated claim.</param>
/// <returns>The role claim entity.</returns>
protected virtual RoleClaim CreateRoleClaim(TRole role, Claim claim)
=> new RoleClaim { RoleId = role.Id, ClaimType = claim.Type, ClaimValue = claim.Value };
private static void AssertNotNull(object p, string pName)
{
if (p == null)
{
throw new ArgumentNullException(pName);
}
}
private Claim CreateClaim(RoleClaim claim)
{
return new Claim(claim.ClaimType, claim.ClaimValue);
}
}
}
| 46.14011 | 175 | 0.618875 | [
"Apache-2.0"
] | gowerlin/TheIdServer | src/Aguacongas.TheIdServer.Identity/RoleStore.cs | 16,797 | C# |
// Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information.
namespace Remote.Linq.EntityFrameworkCore.ExpressionExecution
{
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
internal sealed class CastingEntityFrameworkCoreAsyncStreamExpressionExecutor<TResult> : EntityFrameworkCoreAsyncStreamExpressionExecutor<TResult?>
where TResult : class
{
[SecuritySafeCritical]
public CastingEntityFrameworkCoreAsyncStreamExpressionExecutor(DbContext dbContext, IExpressionFromRemoteLinqContext? context = null)
: base(dbContext, context)
{
}
public CastingEntityFrameworkCoreAsyncStreamExpressionExecutor(Func<Type, IQueryable> queryableProvider, IExpressionFromRemoteLinqContext? context = null)
: base(queryableProvider, context)
{
}
protected override async IAsyncEnumerable<TResult?> ConvertResult(IAsyncEnumerable<object?> queryResult)
{
await foreach (var item in queryResult)
{
yield return item as TResult;
}
}
}
} | 37.757576 | 162 | 0.707865 | [
"MIT"
] | 6bee/Remote.Linq | src/Remote.Linq.EntityFrameworkCore/ExpressionExecution/CastingEntityFrameworkCoreAsyncStreamExpressionExecutor`1.cs | 1,248 | C# |
namespace JWTDemo.Domain.Dtos
{
public class AuthResultInfo
{
public AuthResultInfo(string email, string name)
{
Email = email;
Name = name;
}
public string Email { get; set; }
public string Name { get; set; }
public string Token { get; set; }
public string RefreshToken { get; set; }
}
}
| 22.529412 | 56 | 0.543081 | [
"Apache-2.0"
] | spaki/jwt-demo | JWTDemo/JWTDemo.Domain/Dtos/AuthResultInfo.cs | 385 | C# |
namespace Develappers.BillomatNet.Types
{
public enum PropertyType
{
Textfield,
Textarea,
Checkbox
}
} | 15.444444 | 40 | 0.597122 | [
"MIT"
] | KuroSeongbae/BillomatNet | Develappers.BillomatNet/Types/PropertyType.cs | 141 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using FlubuCore.Context;
using FlubuCore.Tasks;
using FlubuCore.Tasks.Process;
namespace FlubuCore.Azure.Tasks.Keyvault
{
public partial class AzureKeyvaultKeyImportTask : ExternalProcessTaskBase<AzureKeyvaultKeyImportTask>
{
/// <summary>
/// Import a private key.
/// </summary>
public AzureKeyvaultKeyImportTask(string name = null , string vaultName = null)
{
WithArguments("az keyvault key import");
WithArguments("--name");
if (!string.IsNullOrEmpty(name))
{
WithArguments(name);
}
WithArguments("--vault-name");
if (!string.IsNullOrEmpty(vaultName))
{
WithArguments(vaultName);
}
}
protected override string Description { get; set; }
/// <summary>
/// Create key in disabled state.
/// </summary>
public AzureKeyvaultKeyImportTask Disabled(string disabled = null)
{
WithArguments("--disabled");
if (!string.IsNullOrEmpty(disabled))
{
WithArguments(disabled);
}
return this;
}
/// <summary>
/// Expiration UTC datetime (Y-m-d'T'H:M:S'Z').
/// </summary>
public AzureKeyvaultKeyImportTask Expires(string expires = null)
{
WithArguments("--expires");
if (!string.IsNullOrEmpty(expires))
{
WithArguments(expires);
}
return this;
}
/// <summary>
/// Key not usable before the provided UTC datetime (Y-m-d'T'H:M:S'Z').
/// </summary>
public AzureKeyvaultKeyImportTask NotBefore(string notBefore = null)
{
WithArguments("--not-before");
if (!string.IsNullOrEmpty(notBefore))
{
WithArguments(notBefore);
}
return this;
}
/// <summary>
/// Space-separated list of permitted JSON web key operations.
/// </summary>
public AzureKeyvaultKeyImportTask Ops(string ops = null)
{
WithArguments("--ops");
if (!string.IsNullOrEmpty(ops))
{
WithArguments(ops);
}
return this;
}
/// <summary>
/// Specifies the type of key protection.
/// </summary>
public AzureKeyvaultKeyImportTask Protection(string protection = null)
{
WithArguments("--protection");
if (!string.IsNullOrEmpty(protection))
{
WithArguments(protection);
}
return this;
}
/// <summary>
/// Space-separated tags in 'key[=value]' format. Use "" to clear existing tags.
/// </summary>
public AzureKeyvaultKeyImportTask Tags(string tags = null)
{
WithArguments("--tags");
if (!string.IsNullOrEmpty(tags))
{
WithArguments(tags);
}
return this;
}
/// <summary>
/// BYOK file containing the key to be imported. Must not be password protected.
/// </summary>
public AzureKeyvaultKeyImportTask ByokFile(string byokFile = null)
{
WithArguments("--byok-file");
if (!string.IsNullOrEmpty(byokFile))
{
WithArguments(byokFile);
}
return this;
}
/// <summary>
/// PEM file containing the key to be imported.
/// </summary>
public AzureKeyvaultKeyImportTask PemFile(string pemFile = null)
{
WithArguments("--pem-file");
if (!string.IsNullOrEmpty(pemFile))
{
WithArguments(pemFile);
}
return this;
}
/// <summary>
/// Password of PEM file.
/// </summary>
public AzureKeyvaultKeyImportTask PemPassword(string pemPassword = null)
{
WithArguments("--pem-password");
if (!string.IsNullOrEmpty(pemPassword))
{
WithArguments(pemPassword);
}
return this;
}
}
}
| 27.079755 | 106 | 0.510648 | [
"MIT"
] | flubu-core/FlubuCore.Azure | FlubuCore.Azure/Tasks/Keyvault/AzureKeyvaultKeyImportTask.cs | 4,414 | C# |
using System;
using System.Linq;
using System.Xml.Serialization;
using System.Data;
using System.Windows.Forms;
using System.Collections.Generic;
using taskt.UI.Forms;
using taskt.UI.CustomControls;
using Microsoft.Office.Interop.Outlook;
namespace taskt.Core.Automation.Commands
{
[Serializable]
[Attributes.ClassAttributes.Group("Data Commands")]
[Attributes.ClassAttributes.SubGruop("List")]
[Attributes.ClassAttributes.Description("This command allows you to get the item count of a List")]
[Attributes.ClassAttributes.UsesDescription("Use this command when you want to get the item count of a List.")]
[Attributes.ClassAttributes.ImplementationDescription("")]
public class GetListCountCommand : ScriptCommand
{
[XmlAttribute]
[Attributes.PropertyAttributes.PropertyDescription("Please indicate the List Name.")]
[Attributes.PropertyAttributes.PropertyUIHelper(Attributes.PropertyAttributes.PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)]
[Attributes.PropertyAttributes.InputSpecification("Enter a existing List.")]
[Attributes.PropertyAttributes.SampleUsage("**{{{myData}}}** or **[1,2,3]**")]
[Attributes.PropertyAttributes.Remarks("")]
[Attributes.PropertyAttributes.PropertyShowSampleUsageInDescription(true)]
public string v_ListName { get; set; }
[XmlAttribute]
[Attributes.PropertyAttributes.PropertyDescription("Assign to Variable")]
[Attributes.PropertyAttributes.InputSpecification("Select or provide a variable from the variable list")]
[Attributes.PropertyAttributes.SampleUsage("**vSomeVariable**")]
[Attributes.PropertyAttributes.Remarks("If you have enabled the setting **Create Missing Variables at Runtime** then you are not required to pre-define your variables, however, it is highly recommended.")]
[Attributes.PropertyAttributes.PropertyRecommendedUIControl(Attributes.PropertyAttributes.PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)]
[Attributes.PropertyAttributes.PropertyIsVariablesList(true)]
public string v_UserVariableName { get; set; }
public GetListCountCommand()
{
this.CommandName = "GetListCountCommand";
this.SelectionName = "Get List Count";
this.CommandEnabled = true;
this.CustomRendering = true;
}
public override void RunCommand(object sender)
{
var engine = (Core.Automation.Engine.AutomationEngineInstance)sender;
//get variable by regular name
Script.ScriptVariable listVariable = engine.VariableList.Where(x => x.VariableName == v_ListName).FirstOrDefault();
//user may potentially include brackets []
if (listVariable == null)
{
listVariable = engine.VariableList.Where(x => x.VariableName.ApplyVariableFormatting() == v_ListName).FirstOrDefault();
}
//if still null then throw exception
if (listVariable == null)
{
throw new System.Exception("Complex Variable '" + v_ListName + "' or '" + v_ListName.ApplyVariableFormatting() + "' not found. Ensure the variable exists before attempting to modify it.");
}
dynamic listToCount;
if (listVariable.VariableValue is List<string>)
{
listToCount = (List<string>)listVariable.VariableValue;
}
else if (listVariable.VariableValue is List<MailItem>)
{
listToCount = (List<MailItem>)listVariable.VariableValue;
}
else if (listVariable.VariableValue is List<OpenQA.Selenium.IWebElement>)
{
listToCount = (List<OpenQA.Selenium.IWebElement>)listVariable.VariableValue;
}
else if ((listVariable.VariableValue.ToString().StartsWith("[")) && (listVariable.VariableValue.ToString().EndsWith("]")) && (listVariable.VariableValue.ToString().Contains(",")))
{
//automatically handle if user has given a json array
Newtonsoft.Json.Linq.JArray jsonArray = Newtonsoft.Json.JsonConvert.DeserializeObject(listVariable.VariableValue.ToString()) as Newtonsoft.Json.Linq.JArray;
var itemList = new List<string>();
foreach (var item in jsonArray)
{
var value = (Newtonsoft.Json.Linq.JValue)item;
itemList.Add(value.ToString());
}
listVariable.VariableValue = itemList;
listToCount = itemList;
}
else
{
throw new System.Exception("Complex Variable List Type<T> Not Supported");
}
string count = listToCount.Count.ToString();
count.StoreInUserVariable(sender, v_UserVariableName);
}
public override List<Control> Render(frmCommandEditor editor)
{
base.Render(editor);
//RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_ListName", this, editor));
//RenderedControls.Add(CommandControls.CreateDefaultLabelFor("v_UserVariableName", this));
//var VariableNameControl = CommandControls.CreateStandardComboboxFor("v_UserVariableName", this).AddVariableNames(editor);
//RenderedControls.AddRange(CommandControls.CreateUIHelpersFor("v_UserVariableName", this, new Control[] { VariableNameControl }, editor));
//RenderedControls.Add(VariableNameControl);
RenderedControls.AddRange(CommandControls.MultiCreateInferenceDefaultControlGroupFor(this, editor));
return RenderedControls;
}
public override string GetDisplayValue()
{
return base.GetDisplayValue() + $" [From '{v_ListName}', Store In: '{v_UserVariableName}']";
}
public override bool IsValidate(frmCommandEditor editor)
{
base.IsValidate(editor);
if (String.IsNullOrEmpty(this.v_ListName))
{
this.validationResult += "List Name is empty.\n";
this.IsValid = false;
}
if (String.IsNullOrEmpty(this.v_UserVariableName))
{
this.validationResult += "Variable is empty.\n";
this.IsValid = false;
}
return this.IsValid;
}
}
} | 45.423611 | 213 | 0.649595 | [
"Apache-2.0"
] | admariner/taskt | taskt/Core/Automation/Commands/Data/GetListCountCommand.cs | 6,543 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace primjer_5._2._2
{
class Program
{
static double SafeDivision(double x, double y)
{
if (y == 0)
{
throw new System.DivideByZeroException();
}
return x / y;
}
static void Main(string[] args)
{
double a =0, b = 0;
string operacija = "";
try
{
Console.Write("Unesite 1. prirodan broj: ");
a = double.Parse(Console.ReadLine());
Console.Write("Unesite 2. prirodan broj: ");
b = double.Parse(Console.ReadLine());
Console.Write("Unesite operaciju + - * / ");
operacija = Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("greška 1. "+ex.ToString());
}
finally
{ }
switch (operacija)
{
case "+":
case "plus":
Console.WriteLine("Zbroj je {0} + {1} = {2}", a, b, (a + b));
break;
case "-":
Console.WriteLine("Razlika je {0} - {1} = {2}", a, b, (a - b));
break;
case "*":
case "x":
Console.WriteLine("Umnožak je {0} * {1} = {2}", a, b, (a * b));
break;
default:
try
{
//DivideByZeroException
Console.WriteLine("Kvocijent je {0} / {1} = {2}", a, b, SafeDivision(a, b));
}
catch(DivideByZeroException)
{
Console.WriteLine("Ne možemo djelito s nulom. drugi parametar je 0. ");
}
catch (Exception ex2)
{
Console.WriteLine("greška 2. " + ex2.ToString());
}
break;
}
Console.ReadLine();
}
}
}
| 30.126582 | 104 | 0.365126 | [
"MIT"
] | dklaic3006/AlgebraCSharp2019-1 | ConsoleApp1/primjer_5.2.2.switch/Program.cs | 2,386 | C# |
using NFlags.Commands;
namespace NetMicro.Auth.Jwt.NFlags
{
public class AuthConfiguration : IAuthConfiguration
{
private readonly CommandArgs _commandArgs;
public AuthConfiguration(CommandArgs commandArgs)
{
_commandArgs = commandArgs;
}
public bool DisableAuth => _commandArgs.GetFlag(AuthOptions.DisableAuth);
public string AccessTokenPublicKey => _commandArgs.GetOption<string>(AuthOptions.AccessTokenPublicKey);
public string AccessTokenPrivateKey => _commandArgs.GetOption<string>(AuthOptions.AccessTokenPrivateKey);
public string AccessTokenSecret => _commandArgs.GetOption<string>(AuthOptions.AccessTokenSecret);
public string RefreshTokenPublicKey => _commandArgs.GetOption<string>(AuthOptions.RefreshTokenPublicKey);
public string RefreshTokenPrivateKey => _commandArgs.GetOption<string>(AuthOptions.RefreshTokenPrivateKey);
public string RefreshTokenSecret => _commandArgs.GetOption<string>(AuthOptions.RefreshTokenSecret);
}
} | 45.826087 | 115 | 0.759962 | [
"MIT"
] | NetMicro/NetMicro | NetMicro.Auth.Jwt.NFlags/AuthConfiguration.cs | 1,054 | C# |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
using NetOffice.ExcelApi;
namespace NetOffice.ExcelApi.Behind
{
/// <summary>
/// Interface IOLEDBConnection
/// SupportByVersion Excel, 12,14,15,16
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
[EntityType(EntityType.IsInterface)]
public class IOLEDBConnection : COMObject, NetOffice.ExcelApi.IOLEDBConnection
{
#pragma warning disable
#region Type Information
/// <summary>
/// Contract Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type ContractType
{
get
{
if(null == _contractType)
_contractType = typeof(NetOffice.ExcelApi.IOLEDBConnection);
return _contractType;
}
}
private static Type _contractType;
/// <summary> /// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(IOLEDBConnection);
return _type;
}
}
#endregion
#region Ctor
/// <summary>
/// Stub Ctor, not indented to use
/// </summary>
public IOLEDBConnection() : base()
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual NetOffice.ExcelApi.Application Application
{
get
{
return InvokerService.InvokeInternal.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Application>(this, "Application", typeof(NetOffice.ExcelApi.Application));
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual NetOffice.ExcelApi.Enums.XlCreator Creator
{
get
{
return InvokerService.InvokeInternal.ExecuteEnumPropertyGet<NetOffice.ExcelApi.Enums.XlCreator>(this, "Creator");
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersion("Excel", 12,14,15,16), ProxyResult]
public virtual object Parent
{
get
{
return InvokerService.InvokeInternal.ExecuteReferencePropertyGet(this, "Parent");
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersion("Excel", 12,14,15,16), ProxyResult]
public virtual object ADOConnection
{
get
{
return InvokerService.InvokeInternal.ExecuteReferencePropertyGet(this, "ADOConnection");
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual bool BackgroundQuery
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "BackgroundQuery");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "BackgroundQuery", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual object CommandText
{
get
{
return InvokerService.InvokeInternal.ExecuteVariantPropertyGet(this, "CommandText");
}
set
{
InvokerService.InvokeInternal.ExecuteVariantPropertySet(this, "CommandText", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual NetOffice.ExcelApi.Enums.XlCmdType CommandType
{
get
{
return InvokerService.InvokeInternal.ExecuteEnumPropertyGet<NetOffice.ExcelApi.Enums.XlCmdType>(this, "CommandType");
}
set
{
InvokerService.InvokeInternal.ExecuteEnumPropertySet(this, "CommandType", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual object Connection
{
get
{
return InvokerService.InvokeInternal.ExecuteVariantPropertyGet(this, "Connection");
}
set
{
InvokerService.InvokeInternal.ExecuteVariantPropertySet(this, "Connection", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual bool EnableRefresh
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "EnableRefresh");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "EnableRefresh", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual object LocalConnection
{
get
{
return InvokerService.InvokeInternal.ExecuteVariantPropertyGet(this, "LocalConnection");
}
set
{
InvokerService.InvokeInternal.ExecuteVariantPropertySet(this, "LocalConnection", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual bool MaintainConnection
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "MaintainConnection");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "MaintainConnection", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual DateTime RefreshDate
{
get
{
return InvokerService.InvokeInternal.ExecuteDateTimePropertyGet(this, "RefreshDate");
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual bool Refreshing
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "Refreshing");
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual bool RefreshOnFileOpen
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "RefreshOnFileOpen");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "RefreshOnFileOpen", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual Int32 RefreshPeriod
{
get
{
return InvokerService.InvokeInternal.ExecuteInt32PropertyGet(this, "RefreshPeriod");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "RefreshPeriod", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual NetOffice.ExcelApi.Enums.XlRobustConnect RobustConnect
{
get
{
return InvokerService.InvokeInternal.ExecuteEnumPropertyGet<NetOffice.ExcelApi.Enums.XlRobustConnect>(this, "RobustConnect");
}
set
{
InvokerService.InvokeInternal.ExecuteEnumPropertySet(this, "RobustConnect", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual bool SavePassword
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "SavePassword");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "SavePassword", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual string SourceConnectionFile
{
get
{
return InvokerService.InvokeInternal.ExecuteStringPropertyGet(this, "SourceConnectionFile");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "SourceConnectionFile", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual string SourceDataFile
{
get
{
return InvokerService.InvokeInternal.ExecuteStringPropertyGet(this, "SourceDataFile");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "SourceDataFile", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual bool OLAP
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "OLAP");
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual bool UseLocalConnection
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "UseLocalConnection");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "UseLocalConnection", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual Int32 MaxDrillthroughRecords
{
get
{
return InvokerService.InvokeInternal.ExecuteInt32PropertyGet(this, "MaxDrillthroughRecords");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "MaxDrillthroughRecords", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual bool IsConnected
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "IsConnected");
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual NetOffice.ExcelApi.Enums.XlCredentialsMethod ServerCredentialsMethod
{
get
{
return InvokerService.InvokeInternal.ExecuteEnumPropertyGet<NetOffice.ExcelApi.Enums.XlCredentialsMethod>(this, "ServerCredentialsMethod");
}
set
{
InvokerService.InvokeInternal.ExecuteEnumPropertySet(this, "ServerCredentialsMethod", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual string ServerSSOApplicationID
{
get
{
return InvokerService.InvokeInternal.ExecuteStringPropertyGet(this, "ServerSSOApplicationID");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "ServerSSOApplicationID", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual bool AlwaysUseConnectionFile
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "AlwaysUseConnectionFile");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "AlwaysUseConnectionFile", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual bool ServerFillColor
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "ServerFillColor");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "ServerFillColor", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual bool ServerFontStyle
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "ServerFontStyle");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "ServerFontStyle", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual bool ServerNumberFormat
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "ServerNumberFormat");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "ServerNumberFormat", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual bool ServerTextColor
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "ServerTextColor");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "ServerTextColor", value);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual bool RetrieveInOfficeUILang
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "RetrieveInOfficeUILang");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "RetrieveInOfficeUILang", value);
}
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// Get
/// </summary>
[SupportByVersion("Excel", 14,15,16)]
public virtual NetOffice.ExcelApi.CalculatedMembers CalculatedMembers
{
get
{
return InvokerService.InvokeInternal.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.CalculatedMembers>(this, "CalculatedMembers", typeof(NetOffice.ExcelApi.CalculatedMembers));
}
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Excel", 14,15,16)]
public virtual Int32 LocaleID
{
get
{
return InvokerService.InvokeInternal.ExecuteInt32PropertyGet(this, "LocaleID");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "LocaleID", value);
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual Int32 CancelRefresh()
{
return InvokerService.InvokeInternal.ExecuteInt32MethodGet(this, "CancelRefresh");
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual Int32 MakeConnection()
{
return InvokerService.InvokeInternal.ExecuteInt32MethodGet(this, "MakeConnection");
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual Int32 Refresh()
{
return InvokerService.InvokeInternal.ExecuteInt32MethodGet(this, "Refresh");
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// </summary>
/// <param name="oDCFileName">string oDCFileName</param>
/// <param name="description">optional object description</param>
/// <param name="keywords">optional object keywords</param>
[SupportByVersion("Excel", 12,14,15,16)]
public virtual Int32 SaveAsODC(string oDCFileName, object description, object keywords)
{
return InvokerService.InvokeInternal.ExecuteInt32MethodGet(this, "SaveAsODC", oDCFileName, description, keywords);
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// </summary>
/// <param name="oDCFileName">string oDCFileName</param>
[CustomMethod]
[SupportByVersion("Excel", 12,14,15,16)]
public virtual Int32 SaveAsODC(string oDCFileName)
{
return InvokerService.InvokeInternal.ExecuteInt32MethodGet(this, "SaveAsODC", oDCFileName);
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// </summary>
/// <param name="oDCFileName">string oDCFileName</param>
/// <param name="description">optional object description</param>
[CustomMethod]
[SupportByVersion("Excel", 12,14,15,16)]
public virtual Int32 SaveAsODC(string oDCFileName, object description)
{
return InvokerService.InvokeInternal.ExecuteInt32MethodGet(this, "SaveAsODC", oDCFileName, description);
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
[SupportByVersion("Excel", 14,15,16)]
public virtual Int32 Reconnect()
{
return InvokerService.InvokeInternal.ExecuteInt32MethodGet(this, "Reconnect");
}
#endregion
#pragma warning restore
}
}
| 24.727405 | 185 | 0.67152 | [
"MIT"
] | igoreksiz/NetOffice | Source/Excel/Behind/Interfaces/IOLEDBConnection.cs | 16,965 | C# |
namespace SuperSize.UI.Controls
{
partial class SettingsPage
{
/// <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 Component 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.previewBox = new System.Windows.Forms.PictureBox();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.keybindLabel = new System.Windows.Forms.Label();
this.keybindPreviewLbl = new System.Windows.Forms.Label();
this.keybindChangeBtn = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.testBtn = new System.Windows.Forms.Button();
this.settingsBtn = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.previewBox)).BeginInit();
this.tableLayoutPanel1.SuspendLayout();
this.flowLayoutPanel1.SuspendLayout();
this.SuspendLayout();
//
// previewBox
//
this.previewBox.Dock = System.Windows.Forms.DockStyle.Top;
this.previewBox.Location = new System.Drawing.Point(0, 0);
this.previewBox.Name = "previewBox";
this.previewBox.Size = new System.Drawing.Size(370, 165);
this.previewBox.TabIndex = 0;
this.previewBox.TabStop = false;
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 3;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel1.Controls.Add(this.comboBox1, 1, 1);
this.tableLayoutPanel1.Controls.Add(this.keybindLabel, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.keybindPreviewLbl, 1, 0);
this.tableLayoutPanel1.Controls.Add(this.keybindChangeBtn, 2, 0);
this.tableLayoutPanel1.Controls.Add(this.label3, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.flowLayoutPanel1, 1, 2);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 165);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 4;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 66.66666F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(370, 268);
this.tableLayoutPanel1.TabIndex = 1;
//
// comboBox1
//
this.tableLayoutPanel1.SetColumnSpan(this.comboBox1, 2);
this.comboBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Location = new System.Drawing.Point(119, 32);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(248, 23);
this.comboBox1.TabIndex = 0;
//
// keybindLabel
//
this.keybindLabel.Dock = System.Windows.Forms.DockStyle.Fill;
this.keybindLabel.Location = new System.Drawing.Point(3, 0);
this.keybindLabel.Name = "keybindLabel";
this.keybindLabel.Size = new System.Drawing.Size(110, 29);
this.keybindLabel.TabIndex = 1;
this.keybindLabel.Text = "Keyboard Shortcut:";
this.keybindLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// keybindPreviewLbl
//
this.keybindPreviewLbl.Dock = System.Windows.Forms.DockStyle.Fill;
this.keybindPreviewLbl.Location = new System.Drawing.Point(119, 0);
this.keybindPreviewLbl.Name = "keybindPreviewLbl";
this.keybindPreviewLbl.Size = new System.Drawing.Size(167, 29);
this.keybindPreviewLbl.TabIndex = 2;
this.keybindPreviewLbl.Text = "-";
this.keybindPreviewLbl.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// keybindChangeBtn
//
this.keybindChangeBtn.Location = new System.Drawing.Point(292, 3);
this.keybindChangeBtn.Name = "keybindChangeBtn";
this.keybindChangeBtn.Size = new System.Drawing.Size(75, 23);
this.keybindChangeBtn.TabIndex = 3;
this.keybindChangeBtn.Text = "&Change...";
this.keybindChangeBtn.UseVisualStyleBackColor = true;
this.keybindChangeBtn.Click += new System.EventHandler(this.keybindChangeBtn_Click);
//
// label3
//
this.label3.Dock = System.Windows.Forms.DockStyle.Fill;
this.label3.Location = new System.Drawing.Point(3, 29);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(110, 29);
this.label3.TabIndex = 4;
this.label3.Text = "Logic:";
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.AutoSize = true;
this.tableLayoutPanel1.SetColumnSpan(this.flowLayoutPanel1, 2);
this.flowLayoutPanel1.Controls.Add(this.testBtn);
this.flowLayoutPanel1.Controls.Add(this.settingsBtn);
this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.flowLayoutPanel1.FlowDirection = System.Windows.Forms.FlowDirection.RightToLeft;
this.flowLayoutPanel1.Location = new System.Drawing.Point(116, 58);
this.flowLayoutPanel1.Margin = new System.Windows.Forms.Padding(0);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Size = new System.Drawing.Size(254, 70);
this.flowLayoutPanel1.TabIndex = 5;
//
// testBtn
//
this.testBtn.Location = new System.Drawing.Point(176, 3);
this.testBtn.Name = "testBtn";
this.testBtn.Size = new System.Drawing.Size(75, 23);
this.testBtn.TabIndex = 1;
this.testBtn.Text = "&Test";
this.testBtn.UseVisualStyleBackColor = true;
this.testBtn.Click += new System.EventHandler(this.testBtn_Click);
//
// settingsBtn
//
this.settingsBtn.Location = new System.Drawing.Point(95, 3);
this.settingsBtn.Name = "settingsBtn";
this.settingsBtn.Size = new System.Drawing.Size(75, 23);
this.settingsBtn.TabIndex = 2;
this.settingsBtn.Text = "&Settings...";
this.settingsBtn.UseVisualStyleBackColor = true;
this.settingsBtn.Click += new System.EventHandler(this.settingsBtn_Click_1);
//
// SettingsPage
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.tableLayoutPanel1);
this.Controls.Add(this.previewBox);
this.Name = "SettingsPage";
this.Size = new System.Drawing.Size(370, 433);
this.Load += new System.EventHandler(this.SettingsPage_Load);
this.Enter += new System.EventHandler(this.SettingsPage_Enter);
((System.ComponentModel.ISupportInitialize)(this.previewBox)).EndInit();
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.flowLayoutPanel1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.PictureBox previewBox;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.Label keybindLabel;
private System.Windows.Forms.Label keybindPreviewLbl;
private System.Windows.Forms.Button keybindChangeBtn;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private System.Windows.Forms.Button testBtn;
private System.Windows.Forms.Button settingsBtn;
}
}
| 50.52551 | 135 | 0.624154 | [
"Apache-2.0"
] | thegreatrazz/SuperSize | SuperSize/UI/Controls/SettingsPage.Designer.cs | 9,905 | C# |
using BizHawk.Emulation.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using BizHawk.Common.BizInvoke;
namespace BizHawk.Emulation.Cores.Waterbox
{
/// <summary>
/// a heap that supports basic alloc, free, and realloc calls
/// </summary>
internal sealed class MapHeap : IBinaryStateable, IDisposable
{
public MemoryBlock Memory { get; private set; }
/// <summary>
/// name, used in identifying errors
/// </summary>
public string Name { get; private set; }
/// <summary>
/// total number of bytes allocated
/// </summary>
public ulong Used { get; private set; }
/// <summary>
/// get a page index within the block
/// </summary>
private int GetPage(ulong addr)
{
return (int)((addr - Memory.Start) >> WaterboxUtils.PageShift);
}
/// <summary>
/// get a start address for a page index within the block
/// </summary>
private ulong GetStartAddr(int page)
{
return ((ulong)page << WaterboxUtils.PageShift) + Memory.Start;
}
private const MemoryBlock.Protection FREE = (MemoryBlock.Protection)255;
private readonly MemoryBlock.Protection[] _pages;
private readonly byte[] _pagesAsBytes;
public MapHeap(ulong start, ulong size, string name)
{
size = WaterboxUtils.AlignUp(size);
Memory = new MemoryBlock(start, size);
Name = name;
_pagesAsBytes = new byte[size >> WaterboxUtils.PageShift];
_pages = (MemoryBlock.Protection[])(object)_pagesAsBytes;
for (var i = 0; i < _pages.Length; i++)
_pages[i] = FREE;
Console.WriteLine($"Created {nameof(MapHeap)} `{name}` at {start:x16}:{start + size:x16}");
}
// find consecutive unused pages to map
private int FindConsecutiveFreePages(int count)
{
return FindConsecutiveFreePagesAssumingFreed(count, -1, -1);
}
// find consecutive unused pages to map, pretending that [startPage..startPage + numPages) is free
// used in realloc
private int FindConsecutiveFreePagesAssumingFreed(int count, int startPage, int numPages)
{
var starts = new List<int>();
var sizes = new List<int>();
var currStart = 0;
for (var i = 0; i <= _pages.Length; i++)
{
if (i == _pages.Length || _pages[i] != FREE && (i < startPage || i >= startPage + numPages))
{
if (currStart < i)
{
starts.Add(currStart);
var size = i - currStart;
if (size == count)
return currStart;
sizes.Add(i - currStart);
}
currStart = i + 1;
}
}
int bestIdx = -1;
int bestSize = int.MaxValue;
for (int i = 0; i < sizes.Count; i++)
{
if (sizes[i] < bestSize && sizes[i] >= count)
{
bestSize = sizes[i];
bestIdx = i;
}
}
if (bestIdx != -1)
return starts[bestIdx];
else
return -1;
}
private void ProtectInternal(int startPage, int numPages, MemoryBlock.Protection prot, bool wasUsed)
{
for (var i = startPage; i < startPage + numPages; i++)
_pages[i] = prot;
ulong start = GetStartAddr(startPage);
ulong length = ((ulong)numPages) << WaterboxUtils.PageShift;
if (prot == FREE)
{
Memory.Protect(start, length, MemoryBlock.Protection.RW);
WaterboxUtils.ZeroMemory(Z.US(start), (long)length);
Memory.Protect(start, length, MemoryBlock.Protection.None);
Used -= length;
Console.WriteLine($"Freed {length} bytes on {Name}, utilization {Used}/{Memory.Size} ({100.0 * Used / Memory.Size:0.#}%)");
}
else
{
Memory.Protect(start, length, prot);
if (wasUsed)
{
Console.WriteLine($"Set protection for {length} bytes on {Name} to {prot}");
}
else
{
Used += length;
Console.WriteLine($"Allocated {length} bytes on {Name}, utilization {Used}/{Memory.Size} ({100.0 * Used / Memory.Size:0.#}%)");
}
}
}
private void RefreshProtections(int startPage, int pageCount)
{
int ps = startPage;
for (int i = startPage; i < startPage + pageCount; i++)
{
if (i == startPage + pageCount - 1 || _pages[i] != _pages[i + 1])
{
var p = _pages[i];
ulong zstart = GetStartAddr(ps);
ulong zlength = (ulong)(i - ps + 1) << WaterboxUtils.PageShift;
Memory.Protect(zstart, zlength, p == FREE ? MemoryBlock.Protection.None : p);
ps = i + 1;
}
}
}
private void RefreshAllProtections()
{
RefreshProtections(0, _pages.Length);
}
private bool EnsureMapped(int startPage, int pageCount)
{
for (int i = startPage; i < startPage + pageCount; i++)
if (_pages[i] == FREE)
return false;
return true;
}
public ulong Map(ulong size, MemoryBlock.Protection prot)
{
if (size == 0)
return 0;
int numPages = WaterboxUtils.PagesNeeded(size);
int startPage = FindConsecutiveFreePages(numPages);
if (startPage == -1)
return 0;
var ret = GetStartAddr(startPage);
ProtectInternal(startPage, numPages, prot, false);
return ret;
}
public ulong Remap(ulong start, ulong oldSize, ulong newSize, bool canMove)
{
// TODO: what is the expected behavior when everything requested for remap is allocated,
// but with different protections?
if (start < Memory.Start || start + oldSize > Memory.End || oldSize == 0 || newSize == 0)
return 0;
var oldStartPage = GetPage(start);
var oldNumPages = WaterboxUtils.PagesNeeded(oldSize);
if (!EnsureMapped(oldStartPage, oldNumPages))
return 0;
var oldProt = _pages[oldStartPage];
int newNumPages = WaterboxUtils.PagesNeeded(newSize);
if (!canMove)
{
if (newNumPages <= oldNumPages)
{
if (newNumPages < oldNumPages)
ProtectInternal(oldStartPage + newNumPages, oldNumPages - newNumPages, FREE, true);
return start;
}
else if (newNumPages > oldNumPages)
{
for (var i = oldStartPage + oldNumPages; i < oldStartPage + newNumPages; i++)
if (_pages[i] != FREE)
return 0;
ProtectInternal(oldStartPage + oldNumPages, newNumPages - oldNumPages, oldProt, false);
return start;
}
}
// if moving is allowed, we always move to simplify and defragment when possible
int newStartPage = FindConsecutiveFreePagesAssumingFreed(newNumPages, oldStartPage, oldNumPages);
if (newStartPage == -1)
return 0;
var copyDataLen = Math.Min(oldSize, newSize);
var copyPageLen = Math.Min(oldNumPages, newNumPages);
var data = new byte[copyDataLen];
Memory.Protect(start, copyDataLen, MemoryBlock.Protection.RW);
Marshal.Copy(Z.US(start), data, 0, (int)copyDataLen);
var pages = new MemoryBlock.Protection[copyPageLen];
Array.Copy(_pages, oldStartPage, pages, 0, copyPageLen);
ProtectInternal(oldStartPage, oldNumPages, FREE, true);
ProtectInternal(newStartPage, newNumPages, MemoryBlock.Protection.RW, false);
var ret = GetStartAddr(newStartPage);
Marshal.Copy(data, 0, Z.US(ret), (int)copyDataLen);
Array.Copy(pages, 0, _pages, newStartPage, copyPageLen);
RefreshProtections(newStartPage, copyPageLen);
if (newNumPages > oldNumPages)
ProtectInternal(newStartPage + oldNumPages, newNumPages - oldNumPages, oldProt, true);
return ret;
}
public bool Unmap(ulong start, ulong size)
{
return Protect(start, size, FREE);
}
public bool Protect(ulong start, ulong size, MemoryBlock.Protection prot)
{
if (start < Memory.Start || start + size > Memory.End || size == 0)
return false;
var startPage = GetPage(start);
var numPages = WaterboxUtils.PagesNeeded(size);
if (!EnsureMapped(startPage, numPages))
return false;
ProtectInternal(startPage, numPages, prot, true);
return true;
}
public void Dispose()
{
if (Memory != null)
{
Memory.Dispose();
Memory = null;
}
}
private const ulong MAGIC = 0x1590abbcdeef5910;
public void SaveStateBinary(BinaryWriter bw)
{
bw.Write(Name);
bw.Write(Memory.Size);
bw.Write(Used);
bw.Write(Memory.XorHash);
bw.Write(_pagesAsBytes);
Memory.Protect(Memory.Start, Memory.Size, MemoryBlock.Protection.R);
var srcs = Memory.GetXorStream(Memory.Start, Memory.Size, false);
for (int i = 0, addr = 0; i < _pages.Length; i++, addr += WaterboxUtils.PageSize)
{
if (_pages[i] != FREE)
{
srcs.Seek(addr, SeekOrigin.Begin);
WaterboxUtils.CopySome(srcs, bw.BaseStream, WaterboxUtils.PageSize);
}
}
bw.Write(MAGIC);
RefreshAllProtections();
}
public void LoadStateBinary(BinaryReader br)
{
var name = br.ReadString();
if (name != Name)
throw new InvalidOperationException($"Name did not match for {nameof(MapHeap)} {Name}");
var size = br.ReadUInt64();
if (size != Memory.Size)
throw new InvalidOperationException($"Size did not match for {nameof(MapHeap)} {Name}");
var used = br.ReadUInt64();
var hash = br.ReadBytes(Memory.XorHash.Length);
if (!hash.SequenceEqual(Memory.XorHash))
throw new InvalidOperationException($"Hash did not match for {nameof(MapHeap)} {Name}. Is this the same rom?");
if (br.BaseStream.Read(_pagesAsBytes, 0, _pagesAsBytes.Length) != _pagesAsBytes.Length)
throw new InvalidOperationException("Unexpected error reading!");
Used = 0;
Memory.Protect(Memory.Start, Memory.Size, MemoryBlock.Protection.RW);
var dsts = Memory.GetXorStream(Memory.Start, Memory.Size, true);
for (int i = 0, addr = 0; i < _pages.Length; i++, addr += WaterboxUtils.PageSize)
{
if (_pages[i] != FREE)
{
dsts.Seek(addr, SeekOrigin.Begin);
WaterboxUtils.CopySome(br.BaseStream, dsts, WaterboxUtils.PageSize);
Used += (uint)WaterboxUtils.PageSize;
}
}
if (Used != used)
throw new InvalidOperationException("Internal savestate error");
if (br.ReadUInt64() != MAGIC)
throw new InvalidOperationException("Savestate internal error");
RefreshAllProtections();
}
public static void StressTest()
{
var allocs = new Dictionary<ulong, ulong>();
var mmo = new MapHeap(0x36a00000000, 256 * 1024 * 1024, "ballsacks");
var rnd = new Random(12512);
for (int i = 0; i < 40; i++)
{
ulong siz = (ulong)(rnd.Next(256 * 1024) + 384 * 1024);
siz = siz / 4096 * 4096;
var ptr = mmo.Map(siz, MemoryBlock.Protection.RW);
allocs.Add(ptr, siz);
}
for (int i = 0; i < 20; i++)
{
int idx = rnd.Next(allocs.Count);
var elt = allocs.ElementAt(idx);
mmo.Unmap(elt.Key, elt.Value);
allocs.Remove(elt.Key);
}
for (int i = 0; i < 40; i++)
{
ulong siz = (ulong)(rnd.Next(256 * 1024) + 384 * 1024);
siz = siz / 4096 * 4096;
var ptr = mmo.Map(siz, MemoryBlock.Protection.RW);
allocs.Add(ptr, siz);
}
for (int i = 0; i < 20; i++)
{
int idx = rnd.Next(allocs.Count);
var elt = allocs.ElementAt(idx);
mmo.Unmap(elt.Key, elt.Value);
}
}
}
}
| 29.438692 | 132 | 0.657627 | [
"MIT"
] | Gikkman/BizHawk | BizHawk.Emulation.Cores/Waterbox/MapHeap.cs | 10,806 | C# |
#region License Header
/*
* QUANTLER.COM - Quant Fund Development Platform
* Quantler Core Trading Engine. Copyright 2018 Quantler B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion License Header
using CacheManager.Core;
using System;
namespace Quantler.Brokers.BrokerTools
{
/// <summary>
/// Micro caching, caching of values according to function,
/// in case a value of a function does not fluctuate that often we can return the same value again
/// </summary>
public class MicroCache
{
#region Private Fields
/// <summary>
/// Currently stored items
/// </summary>
private ICacheManager<object> _items;
#endregion Private Fields
#region Public Constructors
/// <summary>
/// Initialize new microcache
/// </summary>
/// <param name="evictionspan">Timespan for values to be valid</param>
public MicroCache(TimeSpan evictionspan)
{
EvictionSpan = evictionspan;
_items = CacheFactory.Build<object>(c => c.WithDictionaryHandle()
.WithExpiration(ExpirationMode.Absolute, evictionspan));
}
#endregion Public Constructors
#region Public Properties
/// <summary>
/// Set eviction timespan (time before values will be replaced)
/// </summary>
public TimeSpan EvictionSpan { get; private set; }
#endregion Public Properties
#region Public Methods
/// <summary>
/// Get value from microcache, if not available, add to cache
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="name">Unique name in cache</param>
/// <param name="release">Function to release current value</param>
/// <param name="evictionspan">Custom period before item is invalidated</param>
/// <returns></returns>
public T GetValue<T>(string name, Func<T> release, TimeSpan? evictionspan = null)
{
//Try get current value
object found = _items.Get(name);
if (found != null)
if (found is T)
return (T)found;
else
throw new Exception("Requested data of unknown type in MicroCache, please ensure cache names are unique!");
//Invoke method to retrieve requested value
var item = release();
if (item == null)
return item;
//Add or update current item
_items.Put(name, item);
return item;
}
#endregion Public Methods
}
} | 33.375 | 127 | 0.609551 | [
"Apache-2.0"
] | Quantler/Core | Quantler.Brokers/BrokerTools/MicroCache.cs | 3,206 | C# |
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using JustFood.Modules.TimeZone;
using System;
namespace JustFood {
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : HttpApplication {
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Zone.SyncZoneInDatabase();
}
}
} | 27.068966 | 70 | 0.704459 | [
"MIT"
] | aukgit/StoreManament | JustFood/Global.asax.cs | 787 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.ApiManagement
{
public static class GetApi
{
/// <summary>
/// Api details.
/// API Version: 2019-12-01.
/// </summary>
public static Task<GetApiResult> InvokeAsync(GetApiArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetApiResult>("azure-nextgen:apimanagement:getApi", args ?? new GetApiArgs(), options.WithVersion());
}
public sealed class GetApiArgs : Pulumi.InvokeArgs
{
/// <summary>
/// API revision identifier. Must be unique in the current API Management service instance. Non-current revision has ;rev=n as a suffix where n is the revision number.
/// </summary>
[Input("apiId", required: true)]
public string ApiId { get; set; } = null!;
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
/// <summary>
/// The name of the API Management service.
/// </summary>
[Input("serviceName", required: true)]
public string ServiceName { get; set; } = null!;
public GetApiArgs()
{
}
}
[OutputType]
public sealed class GetApiResult
{
/// <summary>
/// Describes the Revision of the Api. If no value is provided, default revision 1 is created
/// </summary>
public readonly string? ApiRevision;
/// <summary>
/// Description of the Api Revision.
/// </summary>
public readonly string? ApiRevisionDescription;
/// <summary>
/// Type of API.
/// </summary>
public readonly string? ApiType;
/// <summary>
/// Indicates the Version identifier of the API if the API is versioned
/// </summary>
public readonly string? ApiVersion;
/// <summary>
/// Description of the Api Version.
/// </summary>
public readonly string? ApiVersionDescription;
/// <summary>
/// Version set details
/// </summary>
public readonly Outputs.ApiVersionSetContractDetailsResponse? ApiVersionSet;
/// <summary>
/// A resource identifier for the related ApiVersionSet.
/// </summary>
public readonly string? ApiVersionSetId;
/// <summary>
/// Collection of authentication settings included into this API.
/// </summary>
public readonly Outputs.AuthenticationSettingsContractResponse? AuthenticationSettings;
/// <summary>
/// Description of the API. May include HTML formatting tags.
/// </summary>
public readonly string? Description;
/// <summary>
/// API name. Must be 1 to 300 characters long.
/// </summary>
public readonly string? DisplayName;
/// <summary>
/// Resource ID.
/// </summary>
public readonly string Id;
/// <summary>
/// Indicates if API revision is current api revision.
/// </summary>
public readonly bool? IsCurrent;
/// <summary>
/// Indicates if API revision is accessible via the gateway.
/// </summary>
public readonly bool IsOnline;
/// <summary>
/// Resource name.
/// </summary>
public readonly string Name;
/// <summary>
/// Relative URL uniquely identifying this API and all of its resource paths within the API Management service instance. It is appended to the API endpoint base URL specified during the service instance creation to form a public URL for this API.
/// </summary>
public readonly string Path;
/// <summary>
/// Describes on which protocols the operations in this API can be invoked.
/// </summary>
public readonly ImmutableArray<string> Protocols;
/// <summary>
/// Absolute URL of the backend service implementing this API. Cannot be more than 2000 characters long.
/// </summary>
public readonly string? ServiceUrl;
/// <summary>
/// API identifier of the source API.
/// </summary>
public readonly string? SourceApiId;
/// <summary>
/// Protocols over which API is made available.
/// </summary>
public readonly Outputs.SubscriptionKeyParameterNamesContractResponse? SubscriptionKeyParameterNames;
/// <summary>
/// Specifies whether an API or Product subscription is required for accessing the API.
/// </summary>
public readonly bool? SubscriptionRequired;
/// <summary>
/// Resource type for API Management resource.
/// </summary>
public readonly string Type;
[OutputConstructor]
private GetApiResult(
string? apiRevision,
string? apiRevisionDescription,
string? apiType,
string? apiVersion,
string? apiVersionDescription,
Outputs.ApiVersionSetContractDetailsResponse? apiVersionSet,
string? apiVersionSetId,
Outputs.AuthenticationSettingsContractResponse? authenticationSettings,
string? description,
string? displayName,
string id,
bool? isCurrent,
bool isOnline,
string name,
string path,
ImmutableArray<string> protocols,
string? serviceUrl,
string? sourceApiId,
Outputs.SubscriptionKeyParameterNamesContractResponse? subscriptionKeyParameterNames,
bool? subscriptionRequired,
string type)
{
ApiRevision = apiRevision;
ApiRevisionDescription = apiRevisionDescription;
ApiType = apiType;
ApiVersion = apiVersion;
ApiVersionDescription = apiVersionDescription;
ApiVersionSet = apiVersionSet;
ApiVersionSetId = apiVersionSetId;
AuthenticationSettings = authenticationSettings;
Description = description;
DisplayName = displayName;
Id = id;
IsCurrent = isCurrent;
IsOnline = isOnline;
Name = name;
Path = path;
Protocols = protocols;
ServiceUrl = serviceUrl;
SourceApiId = sourceApiId;
SubscriptionKeyParameterNames = subscriptionKeyParameterNames;
SubscriptionRequired = subscriptionRequired;
Type = type;
}
}
}
| 34.097561 | 254 | 0.598999 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/ApiManagement/GetApi.cs | 6,990 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Maticsoft.Web.m_weixin.message_model.req
{
public class ReqLocationMessage : ReqBaseMessage
{
public String Location_X { get; set; }
public String Location_Y { get; set; }
public String Scale { get; set; }
public String Label { get; set; }
}
} | 25.6 | 52 | 0.674479 | [
"Unlicense"
] | nature-track/wenCollege-CSharp | Web/m_weixin/message_model/req/ReqLocationMessage.cs | 386 | C# |
namespace Machete.X12Schema.V5010
{
using System;
using X12;
public interface FST :
X12Segment
{
Value<decimal> Quantity { get; }
Value<string> ForecastQualifier { get; }
Value<string> TimingQualifier { get; }
Value<DateTime> Date1 { get; }
Value<DateTime> Date2 { get; }
Value<string> DateOrTimeQualifier { get; }
Value<TimeSpan> Time { get; }
Value<string> ReferenceIdentificationQualifier { get; }
Value<string> ReferenceIdentification { get; }
Value<string> PlanningScheduleTypeCode { get; }
Value<string> QuantityQualifier { get; }
Value<string> AdjustmentReasonCode { get; }
Value<string> Description { get; }
}
} | 23.694444 | 63 | 0.546307 | [
"Apache-2.0"
] | ahives/Machete | src/Machete.X12Schema/V5010/Segments/FST.cs | 853 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsModelFlattening.Models
{
using Fixtures.AcceptanceTestsModelFlattening;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// The wrapped produc.
/// </summary>
public partial class WrappedProduct
{
/// <summary>
/// Initializes a new instance of the WrappedProduct class.
/// </summary>
public WrappedProduct()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the WrappedProduct class.
/// </summary>
/// <param name="value">the product value</param>
public WrappedProduct(string value = default(string))
{
Value = value;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the product value
/// </summary>
[JsonProperty(PropertyName = "value")]
public string Value { get; set; }
}
}
| 28.215686 | 90 | 0.606671 | [
"MIT"
] | bloudraak/autorest | src/generator/AutoRest.CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/WrappedProduct.cs | 1,439 | C# |
using BaseballHistory.Domain.Entities;
using BaseballHistory.Domain.Repositories;
using Microsoft.EntityFrameworkCore;
namespace BaseballHistory.Data.Repositories;
public class PlayerPitchingTotalRepository : IPlayerPitchingTotalRepository
{
private readonly BaseballStatsContext _context;
public PlayerPitchingTotalRepository(BaseballStatsContext context)
{
_context = context;
}
public void Dispose() => _context.Dispose();
public Task<int> GetTotalCount()
{
return Task.FromResult(_context.PlayerPitchingTotals.Count());
}
public async Task<List<PlayerPitchingTotal>> GetAll(int pageNumber, int pageSize) => await _context.PlayerPitchingTotals
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize)
.AsNoTrackingWithIdentityResolution().ToListAsync();
public async Task<PlayerPitchingTotal?> GetById(string playerId)
{
return await _context.PlayerPitchingTotals.FirstOrDefaultAsync(p => p.PlayerId == playerId);
}
} | 32.774194 | 124 | 0.746063 | [
"MIT"
] | cwoodruff/baseball-history | BaseballHistoryAPI/BaseballHistory.Data/Repositories/PlayerPitchingTotalRepository.cs | 1,016 | C# |
using System;
using Autofac;
using NUnit.Framework;
namespace DryIoc.IssuesTests
{
[TestFixture]
public class Issue281_MakeAutofacMigrationEasier
{
[Test]
public void Test_CustomDelegate_Autofac()
{
var builder = new ContainerBuilder();
builder.RegisterType<A>();
builder.RegisterType<B>();
builder.RegisterType<C>();
builder.RegisterType<D>();
using (var container = builder.Build())
{
var d = container.Resolve<D>();
var c = d.CreateC();
Assert.IsNotNull(c.A);
Assert.IsNotNull(c.B);
}
}
[Test]
public void Test_CustomDelegate_DryIoc()
{
var container = new Container();
container.Register<A>();
container.Register<B>();
container.Register<C>();
container.RegisterDelegate<C.Factory>(r => a => r.Resolve<Func<A, C>>()(a));
container.Register<D>();
var d = container.Resolve<D>();
var c = d.CreateC();
Assert.IsNotNull(c.A);
Assert.IsNotNull(c.B);
}
[Test]
public void Test_CustomDelegate_of_Singleton_in_DryIoc()
{
var container = new Container();
container.Register<A>();
container.Register<B>();
container.Register<C>(Reuse.Singleton);
container.RegisterDelegate<C.Factory>(r => a => r.Resolve<Func<A, C>>()(a));
container.Register<D>();
var d = container.Resolve<D>();
var c = d.CreateC();
Assert.AreSame(c, container.Resolve<C>());
}
public class A {}
public class B {}
public class C
{
public readonly A A;
public readonly B B;
public delegate C Factory(A a);
public C(A a, B b)
{
A = a;
B = b;
}
}
public class D
{
private readonly A _a;
private readonly C.Factory _factoryC;
public D(A a, C.Factory factoryC)
{
_a = a;
_factoryC = factoryC;
}
public C CreateC()
{
return _factoryC(_a);
}
}
[Test]
public void Test_TypedParameter_Autofac()
{
var builder = new ContainerBuilder();
builder.RegisterType<OperationOne>().Named<IOperation>(nameof(OperationOne));
builder.RegisterType<OperationTwo>().Named<IOperation>(nameof(OperationTwo));
builder.RegisterType<Service>().As<IService>();
using (var container = builder.Build())
{
var operation = container.ResolveNamed<IOperation>(nameof(OperationTwo));
var service = container.Resolve<IService>(new TypedParameter(typeof(IOperation), operation));
Assert.IsInstanceOf<OperationTwo>(((Service)service).Operation);
}
}
[Test]
public void Test_TypedParameter_DryIoc_option_one()
{
var container = new Container();
container.Register<IOperation, OperationOne>(serviceKey: nameof(OperationOne));
container.Register<IOperation, OperationTwo>(serviceKey: nameof(OperationTwo));
container.Register<IService, Service>(made: Parameters.Of.Type<IOperation>(serviceKey: nameof(OperationTwo)));
var service = container.Resolve<IService>();
Assert.IsInstanceOf<OperationTwo>(((Service)service).Operation);
}
[Test]
public void Test_TypedParameter_DryIoc_option_two()
{
var container = new Container();
container.Register<IOperation, OperationOne>(serviceKey: nameof(OperationOne));
container.Register<IOperation, OperationTwo>(serviceKey: nameof(OperationTwo));
container.Register<IService, Service>();
var service =
container.Resolve<Func<IOperation, IService>>()(container.Resolve<IOperation>(nameof(OperationTwo)));
Assert.IsInstanceOf<OperationTwo>(((Service)service).Operation);
}
public interface IOperation {}
public class OperationOne : IOperation {}
public class OperationTwo : IOperation {}
public interface IService {}
public class Service : IService
{
public readonly IOperation Operation;
public Service(IOperation operation)
{
Operation = operation;
}
}
[Test]
public void Test_DryIoc_returns_the_same_singleton_prior_resolved_with_Func()
{
var container = new Container();
container.Register<IService, Service>(Reuse.Singleton);
container.Register<IOperation, OperationOne>();
var serviceFactory = container.Resolve<Func<IOperation, IService>>();
Assert.AreSame(serviceFactory(new OperationOne()), container.Resolve<IService>());
}
}
}
| 30.621469 | 123 | 0.535793 | [
"MIT"
] | thezbyg/DryIoc | Net45/DryIoc.IssuesTests/Issue281_MakeAutofacMigrationEasier.cs | 5,422 | C# |
/***************************************************************************
copyright : (C) 2006 Novell, Inc.
email : Aaron Bockover <abockover@novell.com>
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
* USA *
***************************************************************************/ | 71.25 | 77 | 0.399298 | [
"MIT"
] | rubenv/tripod | src/Libraries/TagLib/TagLib/IntList.cs | 1,425 | C# |
using System;
using System.Collections.Generic;
using System.Net;
namespace EventStore.ClientAPI.Transport.Tcp
{
internal interface ITcpConnection
{
Guid ConnectionId { get; }
IPEndPoint RemoteEndPoint { get; }
IPEndPoint LocalEndPoint { get; }
int SendQueueSize { get; }
bool IsClosed { get; }
void ReceiveAsync(Action<ITcpConnection, IEnumerable<ArraySegment<byte>>> callback);
void EnqueueSend(IEnumerable<ArraySegment<byte>> data);
void Close(string reason);
}
}
| 27.7 | 92 | 0.666065 | [
"Apache-2.0",
"CC0-1.0"
] | BertschiAG/EventStore | src/EventStore.ClientAPI/Transport.Tcp/ITcpConnection.cs | 556 | C# |
using System;
namespace Troublemaker.Xml
{
[XPath("self::Action[@Type='GiveAbility']")]
public sealed class StageActionGiveAbility : StageAction
{
[XPath("@Ability")] public String Ability;
[XPath("Unit")] public StagePointObject Unit;
}
} | 24.818182 | 60 | 0.663004 | [
"MIT"
] | Albeoris/Troublemaker | Troublemaker.Xml/Stage/Actions/StageActionGiveAbility.cs | 275 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Snowflake.Configuration
{
/// <summary>
/// Represents a enumerable collection of configuration values.
/// </summary>
public interface IConfigurationValueCollection
: IEnumerable<(string section, string option, IConfigurationValue value)>
{
/// <summary>
/// The unique GUID for this collection of values.
/// </summary>
Guid Guid { get; }
/// <summary>
/// Retrieve the value in the collection for the given option within the given section.
/// </summary>
/// <param name="descriptor">The descriptor for the section to examine.</param>
/// <param name="option">The option key within the section of the configuration.</param>
/// <returns>The configuration value of the provided option.</returns>
IConfigurationValue? this[IConfigurationSectionDescriptor descriptor, string option] { get; }
/// <summary>
/// Retrieve a read-only view of configuration values for a given configuration section.
/// </summary>
/// <param name="descriptor">The descriptor for the section to examine.</param>
/// <returns>A read-only view of configuration values, keyed on option keys of the provided section.</returns>
IReadOnlyDictionary<string, IConfigurationValue> this[IConfigurationSectionDescriptor descriptor] { get; }
}
}
| 42.970588 | 118 | 0.671458 | [
"MPL-2.0"
] | fossabot/snowflake-1 | src/Snowflake.Framework.Primitives/Configuration/IConfigurationValueCollection.cs | 1,463 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace TextTextures.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.419355 | 151 | 0.582006 | [
"MIT"
] | Macrotitech/WPF-3d-source | Ch30/TextTextures/Properties/Settings.Designer.cs | 1,069 | C# |
using Monkey.Core.Lexing;
using Monkey.Core.Parsing.Statements;
namespace Monkey.Core.Parsing.Expressions
{
public class IdentifierExpression : IExpression
{
private readonly Token _currentToken;
private IdentifierExpression(Token currentToken)
{
_currentToken = currentToken;
}
public string TokenLiteral()
=> _currentToken.Value;
public static IExpression Parse(ExpressionFactory factory, Parser parser)
=> new IdentifierExpression(parser.CurrentToken());
public static IExpression Parse(IExpression left, ExpressionFactory factory, Parser parser)
{
throw new System.NotImplementedException();
}
}
} | 28.461538 | 99 | 0.671622 | [
"MIT"
] | joro550/MoneyNet | src/Monkey.Core/Parsing/Expressions/IdentifierExpression.cs | 740 | C# |
// Copyright (c) 2021 Salim Mayaleh. All Rights Reserved
// Licensed under the BSD-3-Clause License
// Generated at 28.11.2021 16:31:27 by RaynetApiDocToDotnet.ApiDocParser, created by Salim Mayaleh.
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Threading.Tasks;
using Maya.Raynet.Crm.Attribute;
namespace Maya.Raynet.Crm.Request.Post
{
public class PriceUnlock : PostRequest
{
protected override List<string> Actions { get; set; } = new List<string>();
public PriceUnlock(long priceListId)
{
Actions.Add("priceList");
Actions.Add(priceListId.ToString());
Actions.Add("unlock");
}
public async Task<Ext.Unit> ExecuteAsync(ApiClient apiClient)
=> await base.ExecuteNoResultNoBodyAsync(apiClient);
}
}
| 30.107143 | 100 | 0.685647 | [
"BSD-3-Clause"
] | mayaleh/Maya.Raynet.Crm | src/Maya.Raynet.Crm/Request/Post/PriceUnlock.cs | 843 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace Platform2DUtils.MemorySystem
{
public class MemorySystem
{
static string path = $"{Application.persistentDataPath}/myGame.data";
public static void SaveData(GameData gameData)
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(path);
string json = JsonUtility.ToJson(gameData);
bf.Serialize(file, json);
file.Close();
Debug.Log(path);
}
public static bool DataExist
{
get => File.Exists(path);
}
public static GameData LoadData()
{
if(DataExist)
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(path, FileMode.Open);
string json = bf.Deserialize(file) as string;
GameData gameData = JsonUtility.FromJson<GameData>(json);
return gameData;
}
return new GameData();
}
public static void DeleteData()
{
if(DataExist) File.Delete(path);
}
}
}
| 24.54717 | 77 | 0.566487 | [
"MIT"
] | joeldelabra/Proyecto-ulsa-plataform2D | Assets/Scripts/MemorySystem.cs | 1,303 | C# |
#if WITH_GAME
#if PLATFORM_32BITS
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace UnrealEngine
{
public partial class UParticleModuleAccelerationOverLifetime
{
static readonly int AccelOverLife__Offset;
public FRawDistributionVector AccelOverLife
{
get{ CheckIsValid();return (FRawDistributionVector)Marshal.PtrToStructure(_this.Get()+AccelOverLife__Offset, typeof(FRawDistributionVector));}
set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+AccelOverLife__Offset, false);}
}
static UParticleModuleAccelerationOverLifetime()
{
IntPtr NativeClassPtr=GetNativeClassFromName("ParticleModuleAccelerationOverLifetime");
AccelOverLife__Offset=GetPropertyOffset(NativeClassPtr,"AccelOverLife");
}
}
}
#endif
#endif
| 27.266667 | 145 | 0.805623 | [
"MIT"
] | RobertAcksel/UnrealCS | Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile_Game_32bits/UParticleModuleAccelerationOverLifetime_FixSize.cs | 818 | C# |
using Assets.Game.Scripts.Components.Events;
using Assets.Scripts.Components.Tags;
using Unity.Collections;
using Unity.Entities;
namespace Assets.Game.Scripts.Systems
{
public class LevelDestroySystem : SystemBase
{
private EndSimulationEntityCommandBufferSystem _commandSystem;
private EntityQuery _actorsQuery;
protected override void OnCreate()
{
_commandSystem = World.GetOrCreateSystem<EndSimulationEntityCommandBufferSystem>();
_actorsQuery = EntityManager.CreateEntityQuery(new EntityQueryDesc
{
Any = new[]
{
ComponentType.ReadWrite<PlayerTag>(),
ComponentType.ReadWrite<AttackerTag>(),
ComponentType.ReadWrite<DefenderTag>(),
}
});
}
protected override void OnUpdate()
{
// todo: purge EntityEventSystem queues.
// todo: is there a more efficient way to delete entities with children?
// ArgumentException: DestroyEntity(EntityQuery query) is destroying entity Entity(55:1)
// which contains a LinkedEntityGroup and the entity Entity(93:1) in that group is not
// included in the query. If you want to destroy entities using a query all linked
// entities must be contained in the query..
var entities = _actorsQuery.ToEntityArray(Allocator.TempJob);
var buffers = GetBufferFromEntity<LinkedEntityGroup>();
var commands = _commandSystem.CreateCommandBuffer();
Entities.ForEach((in SceneUnloadedEvent e) =>
{
if (e.Category != SceneCategory.Level)
return;
for (int i = 0; i < entities.Length; i++)
{
var entity = entities[i];
if (buffers.Exists(entity))
{
var children = buffers[entity];
for (int j = 0; j < children.Length; j++)
commands.DestroyEntity(children[j].Value);
}
commands.DestroyEntity(entity);
}
}).Run();
entities.Dispose();
}
}
}
| 35.630769 | 101 | 0.559154 | [
"MIT"
] | jeffvella/UnityEcsEvents.Example | EventsExample/Assets/Game.Scripts/Systems/LevelDestroySystem.cs | 2,318 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CifradoCesarCSharp
{
static class Program
{
/// <summary>
/// Punto de entrada principal para la aplicación.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 22.695652 | 65 | 0.62069 | [
"MIT"
] | acevedo318/CifradoCesarCSharp | CifradoCesarCSharp/Program.cs | 525 | C# |
using UnityEngine;
public class CharacterCapability {
public string name;
public Character character;
public Transform transform;
public CharacterCapability(Character character) {
this.character = character;
this.transform = character.transform;
Init();
}
public virtual void Init() { }
public virtual void StateInit(string stateName, string prevStateName) { }
public virtual void StateDeinit(string stateName, string nextStateName) { }
public virtual void Update(float deltaTime) { }
public virtual void OnCollisionEnter(Collision collision) { }
public virtual void OnCollisionStay(Collision collision) { }
public virtual void OnTriggerExit(Collider other) { }
public virtual void OnTriggerEnter(Collider other) { }
public virtual void OnTriggerStay(Collider other) { }
public virtual void OnCollisionExit(Collision collision) { }
} | 38.333333 | 79 | 0.729348 | [
"MIT"
] | heyjoeway/ICBINS1 | Assets/Resources/Character/CharacterCapability.cs | 920 | C# |
namespace Samples.Patterns.Vehicles
{
public class Bus
{
public int Capacity { get; set; }
public int Riders { get; set; }
}
} | 17.333333 | 41 | 0.576923 | [
"MIT"
] | mbernard/csharp8sample | Samples/Samples/Patterns/Vehicles/Bus.cs | 158 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.MySql.Cmdlets
{
using static Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Extensions;
/// <summary>Creates a new firewall rule or updates an existing firewall rule.</summary>
/// <remarks>
/// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMySql/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"
/// </remarks>
[global::Microsoft.Azure.PowerShell.Cmdlets.MySql.InternalExport]
[global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzMySqlFlexibleServerFirewallRule_Update", SupportsShouldProcess = true)]
[global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IFirewallRule))]
[global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Description(@"Creates a new firewall rule or updates an existing firewall rule.")]
[global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Generated]
public partial class UpdateAzMySqlFlexibleServerFirewallRule_Update : global::System.Management.Automation.PSCmdlet,
Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener
{
/// <summary>A unique id generatd for the this cmdlet when it is instantiated.</summary>
private string __correlationId = System.Guid.NewGuid().ToString();
/// <summary>A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet)</summary>
private global::System.Management.Automation.InvocationInfo __invocationInfo;
/// <summary>A unique id generatd for the this cmdlet when ProcessRecord() is called.</summary>
private string __processRecordId;
/// <summary>
/// The <see cref="global::System.Threading.CancellationTokenSource" /> for this operation.
/// </summary>
private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource();
/// <summary>when specified, runs this cmdlet as a PowerShell job</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")]
[global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)]
public global::System.Management.Automation.SwitchParameter AsJob { get; set; }
/// <summary>Wait for .NET debugger to attach</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")]
[global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)]
public global::System.Management.Automation.SwitchParameter Break { get; set; }
/// <summary>The reference to the client API class.</summary>
public Microsoft.Azure.PowerShell.Cmdlets.MySql.MySql Client => Microsoft.Azure.PowerShell.Cmdlets.MySql.Module.Instance.ClientAPI;
/// <summary>
/// The credentials, account, tenant, and subscription used for communication with Azure
/// </summary>
[global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")]
[global::System.Management.Automation.ValidateNotNull]
[global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")]
[global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Azure)]
public global::System.Management.Automation.PSObject DefaultProfile { get; set; }
/// <summary>SendAsync Pipeline Steps to be appended to the front of the pipeline</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")]
[global::System.Management.Automation.ValidateNotNull]
[global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)]
public Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; }
/// <summary>SendAsync Pipeline Steps to be prepended to the front of the pipeline</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")]
[global::System.Management.Automation.ValidateNotNull]
[global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)]
public Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; }
/// <summary>Accessor for our copy of the InvocationInfo.</summary>
public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } }
/// <summary>
/// <see cref="IEventListener" /> cancellation delegate. Stops the cmdlet when called.
/// </summary>
global::System.Action Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel;
/// <summary><see cref="IEventListener" /> cancellation token.</summary>
global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener.Token => _cancellationTokenSource.Token;
/// <summary>Backing field for <see cref="Name" /> property.</summary>
private string _name;
/// <summary>The name of the server firewall rule.</summary>
[global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the server firewall rule.")]
[Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"The name of the server firewall rule.",
SerializedName = @"firewallRuleName",
PossibleTypes = new [] { typeof(string) })]
[global::System.Management.Automation.Alias("FirewallRuleName")]
[global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Path)]
public string Name { get => this._name; set => this._name = value; }
/// <summary>
/// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue
/// asynchronously.
/// </summary>
[global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")]
[global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)]
public global::System.Management.Automation.SwitchParameter NoWait { get; set; }
/// <summary>Backing field for <see cref="Parameter" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IFirewallRule _parameter;
/// <summary>Represents a server firewall rule.</summary>
[global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Represents a server firewall rule.", ValueFromPipeline = true)]
[Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"Represents a server firewall rule.",
SerializedName = @"parameters",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IFirewallRule) })]
public Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IFirewallRule Parameter { get => this._parameter; set => this._parameter = value; }
/// <summary>
/// The instance of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.HttpPipeline" /> that the remote call will use.
/// </summary>
private Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.HttpPipeline Pipeline { get; set; }
/// <summary>The URI for the proxy server to use</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")]
[global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)]
public global::System.Uri Proxy { get; set; }
/// <summary>Credentials for a proxy server to use for the remote call</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")]
[global::System.Management.Automation.ValidateNotNull]
[global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)]
public global::System.Management.Automation.PSCredential ProxyCredential { get; set; }
/// <summary>Use the default credentials for the proxy</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")]
[global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)]
public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; }
/// <summary>Backing field for <see cref="ResourceGroupName" /> property.</summary>
private string _resourceGroupName;
/// <summary>The name of the resource group. The name is case insensitive.</summary>
[global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group. The name is case insensitive.")]
[Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"The name of the resource group. The name is case insensitive.",
SerializedName = @"resourceGroupName",
PossibleTypes = new [] { typeof(string) })]
[global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Path)]
public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; }
/// <summary>Backing field for <see cref="ServerName" /> property.</summary>
private string _serverName;
/// <summary>The name of the server.</summary>
[global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the server.")]
[Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"The name of the server.",
SerializedName = @"serverName",
PossibleTypes = new [] { typeof(string) })]
[global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Path)]
public string ServerName { get => this._serverName; set => this._serverName = value; }
/// <summary>Backing field for <see cref="SubscriptionId" /> property.</summary>
private string _subscriptionId;
/// <summary>The ID of the target subscription.</summary>
[global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription.")]
[Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"The ID of the target subscription.",
SerializedName = @"subscriptionId",
PossibleTypes = new [] { typeof(string) })]
[Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.DefaultInfo(
Name = @"",
Description =@"",
Script = @"(Get-AzContext).Subscription.Id")]
[global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Path)]
public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; }
/// <summary>
/// <c>overrideOnDefault</c> will be called before the regular onDefault has been processed, allowing customization of what
/// happens on that response. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20200701Preview.ICloudErrorAutoGenerated"
/// /> from the remote call</param>
/// <param name="returnNow">/// Determines if the rest of the onDefault method should be processed, or if the method should
/// return immediately (set to true to skip further processing )</param>
partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20200701Preview.ICloudErrorAutoGenerated> response, ref global::System.Threading.Tasks.Task<bool> returnNow);
/// <summary>
/// <c>overrideOnOk</c> will be called before the regular onOk has been processed, allowing customization of what happens
/// on that response. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IFirewallRule"
/// /> from the remote call</param>
/// <param name="returnNow">/// Determines if the rest of the onOk method should be processed, or if the method should return
/// immediately (set to true to skip further processing )</param>
partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IFirewallRule> response, ref global::System.Threading.Tasks.Task<bool> returnNow);
/// <summary>
/// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet)
/// </summary>
protected override void BeginProcessing()
{
Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials);
if (Break)
{
Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.AttachDebugger.Break();
}
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
}
/// <summary>Creates a duplicate instance of this cmdlet (via JSON serialization).</summary>
/// <returns>a duplicate instance of UpdateAzMySqlFlexibleServerFirewallRule_Update</returns>
public Microsoft.Azure.PowerShell.Cmdlets.MySql.Cmdlets.UpdateAzMySqlFlexibleServerFirewallRule_Update Clone()
{
var clone = new UpdateAzMySqlFlexibleServerFirewallRule_Update();
clone.__correlationId = this.__correlationId;
clone.__processRecordId = this.__processRecordId;
clone.DefaultProfile = this.DefaultProfile;
clone.InvocationInformation = this.InvocationInformation;
clone.Proxy = this.Proxy;
clone.Pipeline = this.Pipeline;
clone.AsJob = this.AsJob;
clone.Break = this.Break;
clone.ProxyCredential = this.ProxyCredential;
clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials;
clone.HttpPipelinePrepend = this.HttpPipelinePrepend;
clone.HttpPipelineAppend = this.HttpPipelineAppend;
clone.SubscriptionId = this.SubscriptionId;
clone.ResourceGroupName = this.ResourceGroupName;
clone.ServerName = this.ServerName;
clone.Name = this.Name;
clone.Parameter = this.Parameter;
return clone;
}
/// <summary>Performs clean-up after the command execution</summary>
protected override void EndProcessing()
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
}
/// <summary>Handles/Dispatches events during the call to the REST service.</summary>
/// <param name="id">The message id</param>
/// <param name="token">The message cancellation token. When this call is cancelled, this should be <c>true</c></param>
/// <param name="messageData">Detailed message data for the message event.</param>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the message is completed.
/// </returns>
async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.EventData> messageData)
{
using( NoSynchronizationContext )
{
if (token.IsCancellationRequested)
{
return ;
}
switch ( id )
{
case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.Verbose:
{
WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.Warning:
{
WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.Information:
{
// When an operation supports asjob, Information messages must go thru verbose.
WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.Debug:
{
WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.Error:
{
WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) );
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.DelayBeforePolling:
{
if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait"))
{
var data = messageData();
if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response)
{
var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation");
var location = response.GetFirstHeader(@"Location");
var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation;
WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell.AsyncOperationResponse { Target = uri });
// do nothing more.
data.Cancel();
return;
}
}
break;
}
}
await Microsoft.Azure.PowerShell.Cmdlets.MySql.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null );
if (token.IsCancellationRequested)
{
return ;
}
WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}");
}
}
/// <summary>Performs execution of the command.</summary>
protected override void ProcessRecord()
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
__processRecordId = System.Guid.NewGuid().ToString();
try
{
// work
if (ShouldProcess($"Call remote 'FlexibleServerFirewallRulesCreateOrUpdate' operation"))
{
if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob"))
{
var instance = this.Clone();
var job = new Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel);
JobRepository.Add(job);
var task = instance.ProcessRecordAsync();
job.Monitor(task);
WriteObject(job);
}
else
{
using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token) )
{
asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token);
}
}
}
}
catch (global::System.AggregateException aggregateException)
{
// unroll the inner exceptions to get the root cause
foreach( var innerException in aggregateException.Flatten().InnerExceptions )
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
// Write exception out to error channel.
WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) );
}
}
catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null)
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
// Write exception out to error channel.
WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) );
}
finally
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletProcessRecordEnd).Wait();
}
}
/// <summary>Performs execution of the command, working asynchronously if required.</summary>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
/// </returns>
protected async global::System.Threading.Tasks.Task ProcessRecordAsync()
{
using( NoSynchronizationContext )
{
await ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
await ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MySql.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName);
if (null != HttpPipelinePrepend)
{
Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend);
}
if (null != HttpPipelineAppend)
{
Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend);
}
// get the client instance
try
{
await ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
await this.Client.FlexibleServerFirewallRulesCreateOrUpdate(SubscriptionId, ResourceGroupName, ServerName, Name, Parameter, onOk, onDefault, this, Pipeline);
await ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
}
catch (Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.UndeclaredResponseException urexception)
{
WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,ServerName=ServerName,Name=Name,body=Parameter})
{
ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action }
});
}
finally
{
await ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletProcessRecordAsyncEnd);
}
}
}
/// <summary>Interrupts currently running code within the command.</summary>
protected override void StopProcessing()
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Cancel();
base.StopProcessing();
}
/// <summary>
/// Intializes a new instance of the <see cref="UpdateAzMySqlFlexibleServerFirewallRule_Update" /> cmdlet class.
/// </summary>
public UpdateAzMySqlFlexibleServerFirewallRule_Update()
{
}
/// <summary>
/// a delegate that is called when the remote service returns default (any response code not handled elsewhere).
/// </summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20200701Preview.ICloudErrorAutoGenerated"
/// /> from the remote call</param>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
/// </returns>
private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20200701Preview.ICloudErrorAutoGenerated> response)
{
using( NoSynchronizationContext )
{
var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false);
overrideOnDefault(responseMessage, response, ref _returnNow);
// if overrideOnDefault has returned true, then return right away.
if ((null != _returnNow && await _returnNow))
{
return ;
}
// Error Response : default
var code = (await response)?.Code;
var message = (await response)?.Message;
if ((null == code || null == message))
{
// Unrecognized Response. Create an error record based on what we have.
var ex = new Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.RestException<Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20200701Preview.ICloudErrorAutoGenerated>(responseMessage, await response);
WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ServerName=ServerName, Name=Name, body=Parameter })
{
ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action }
});
}
else
{
WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ServerName=ServerName, Name=Name, body=Parameter })
{
ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty }
});
}
}
}
/// <summary>a delegate that is called when the remote service returns 200 (OK).</summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IFirewallRule"
/// /> from the remote call</param>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
/// </returns>
private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IFirewallRule> response)
{
using( NoSynchronizationContext )
{
var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false);
overrideOnOk(responseMessage, response, ref _returnNow);
// if overrideOnOk has returned true, then return right away.
if ((null != _returnNow && await _returnNow))
{
return ;
}
// onOk - response for 200 / application/json
// (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IFirewallRule
WriteObject((await response));
}
}
}
} | 71.591919 | 451 | 0.660619 | [
"MIT"
] | 3quanfeng/azure-powershell | src/MySql/generated/cmdlets/UpdateAzMySqlFlexibleServerFirewallRule_Update.cs | 34,944 | C# |
namespace navdi2.ADDONS.author {
using navdi2.grid;
using System.Collections.Generic;
public class AuthorState_Edit:State {
AuthorXXI xxi{get{return AuthorXXI.ins;}}
NavdiGrid editGrid;
Ents<AuthorCursor> cursors;
twin[] cursorPositions;
public AuthorState_Edit() : base() {
Add(editGrid = new NavdiGrid(new GridOptions(
name: "authorstate_edit_grid",
entityBank: xxi.authorCellBank,
size_cellsInGrid: new twin(xxi.options.size_gridScreen / xxi.options.size_pixelsInCell),
size_pixelsPerCell: new twin(xxi.options.size_pixelsInCell)
)));
cursorPositions = null;
Add(cursors = new Ents<AuthorCursor>());
}
override public void Activated() {
base.Activated();
cursorPositions = null;
xxi.LoadRoom(editGrid);
}
override public void FrequentStep(){
base.FrequentStep();
twin cursorPos = editGrid.PointToCellPos(xxi.pcam.MouseWorldPoint());
if (xxi.Input_MouseDown_LeftButton() && editGrid.CellPosInBounds(cursorPos)) {
if (cursorPositions == null) cursorPositions = MagicWand(cursorPos);
else cursorPositions = null;
}
if (cursorPositions == null) UpdateCursors(cursorPos);
twin dir;
if (xxi.Input_KeyDown_PushToggle()) {
xxi.SaveRoom(editGrid);
xxi.SetState(xxi.state_play);
} else if (xxi.Input_Key_ShowPalette()) {
xxi.SaveRoom(editGrid);
xxi.SetState(xxi.state_editpalette);
} else if (xxi.Input_KeyDown_Dir(out dir)) {
MoveRoomCoord(dir);
} else {
ushort cellValue;
if (xxi.Input_Key_CellValue(out cellValue)) {
if (cursorPositions != null) { // multi select cursor
foreach(twin pos in cursorPositions) {
Paint(pos, cellValue);
}
} else { // basic hover cursor
Paint(cursorPos, cellValue);
}
}
}
}
//// INTERNAL
void Paint(twin cellPos, ushort cellValue) {
if (editGrid.CellPosInBounds(cellPos)) {
AuthorCell cell = (AuthorCell)editGrid.GetCell(cellPos);
if (cell!=null && cell.GetCellType(cellValue) != (byte)AuthorCell_SuperType.Unused) {
cell.SetValue(cellValue);
}
}
}
void UpdateCursors(params twin[] cursorPoses) {
cursors.Clear();
foreach(twin pos in cursorPoses) {
cursors.Add(xxi.authorCursorBank.Spawn<AuthorCursor>().Setup(position: editGrid.CellPosToPoint(pos), fill:true));
}
}
twin[] MagicWand(twin startingCellPos) {
List<twin> wandedPositions = new List<twin>();
wandedPositions.Add(startingCellPos);
ushort magicValue = editGrid.GetCell(startingCellPos).value;
for (int i = 0; i < wandedPositions.Count; i++) {
twin here = wandedPositions[i];
twin[] ns = new twin[4];
ns[0] = here + twin.right;
ns[1] = here + twin.up;
ns[2] = here + twin.left;
ns[3] = here + twin.down;
foreach(twin n in ns)
if (editGrid.CellPosInBounds(n) && editGrid.GetCell(n).value == magicValue && !wandedPositions.Contains(n))
wandedPositions.Add(n);
}
if (wandedPositions.Count <= 1) return null;
twin[] poses = wandedPositions.ToArray();
UpdateCursors(poses);
return poses;
}
void MoveRoomCoord(twin dir) {
ushort[] edge = CopyGridsEdge(dir, editGrid);
xxi.SetRoomCoord(xxi.currentRoomCoord + dir, editGrid);
if (edge != null) PasteGridsEdge(edge, -dir, editGrid);
}
//// COPY/PASTE FUNCTIONS
ushort[] CopyGridsEdge(twin dirEdge, NavdiGrid grid) {
if ( (dirEdge.x==0) == (dirEdge.y==0) ) return null;
bool copyColumn = (dirEdge.x!=0);
ushort[] edge;
if (copyColumn) edge = CopyCol(dirEdge.x<0?0:-1, grid);
else edge = CopyRow(dirEdge.y<0?0:-1, grid);
return edge;
}
void PasteGridsEdge(ushort[] edgeData, twin dirEdge, NavdiGrid grid) {
if ( (dirEdge.x==0) == (dirEdge.y==0) ) return;
bool pasteColumn = (dirEdge.x!=0);
if (pasteColumn) PasteCol(edgeData, dirEdge.x<0?0:-1, grid);
else PasteRow(edgeData, dirEdge.y<0?0:-1, grid);
}
ushort[] CopyRow(int row, NavdiGrid grid) {
if (row < 0) row = grid.options.size_cellsInGrid.y + row;
ushort[] edge = new ushort[grid.options.size_cellsInGrid.x];
for (int x = 0; x < edge.Length; x++) edge[x] = grid.GetCell(x,row).value;
return edge;
}
ushort[] CopyCol(int col, NavdiGrid grid) {
if (col < 0) col = grid.options.size_cellsInGrid.x + col;
ushort[] edge = new ushort[grid.options.size_cellsInGrid.y];
for (int y = 0; y < edge.Length; y++) edge[y] = grid.GetCell(col,y).value;
return edge;
}
void PasteRow(ushort[] edgeData, int row, NavdiGrid grid) {
if (row < 0) row = grid.options.size_cellsInGrid.y + row;
for (int x = 0; x < edgeData.Length; x++) grid.GetCell(x,row).SetValue(edgeData[x]);
}
void PasteCol(ushort[] edgeData, int col, NavdiGrid grid) {
if (col < 0) col = grid.options.size_cellsInGrid.x + col;
for (int y = 0; y < edgeData.Length; y++) grid.GetCell(col,y).SetValue(edgeData[y]);
}
}
} | 35.152174 | 117 | 0.672026 | [
"MIT"
] | droqen/navdi2 | ADDONS/author/AuthorState_Edit.cs | 4,851 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Bitwise
{
public abstract class Bitwise<T> where T: struct
{
protected int Bit { get; set; }
protected Bitwise()
{
if (typeof(T).GetTypeInfo().BaseType != typeof(Enum) || typeof(T).GetTypeInfo().BaseType != typeof(int))
{
throw new InvalidCastException();
}
}
protected Bitwise(T bit)
{
Bit = Convert.ToInt32(bit);
}
public virtual bool Has(T bit)
{
return (Bit & Convert.ToInt32(bit)) > 0;
}
public virtual bool Is(T bit)
{
return Bit == Convert.ToInt32(bit);
}
public virtual Bitwise<T> Set(T bit)
{
Bit = Convert.ToInt32(bit);
return this;
}
public virtual Bitwise<T> Add(T bit)
{
Bit = Bit | Convert.ToInt32(bit);
return this;
}
public virtual Bitwise<T> Remove(T bit)
{
var convertedBit = Convert.ToInt32(bit);
Bit = (Bit | convertedBit) & convertedBit;
return this;
}
public virtual IEnumerable<T> ToArray()
{
for (var i = 1; i <= Bit; i *= 2)
{
if ((i & Bit) <= 0) continue;
yield return (T)Enum.ToObject(typeof(T), i);
}
}
}
}
| 23.140625 | 116 | 0.478731 | [
"Apache-2.0"
] | st2forget/CommonLibraries | src/Bitwise/Bitwise.cs | 1,483 | C# |
// ------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------------------------------------------
using System;
using Microsoft.CoyoteActors.IO;
namespace Microsoft.CoyoteActors.TestingServices
{
/// <summary>
/// Interface of a Coyote testing engine.
/// </summary>
public interface ITestingEngine
{
/// <summary>
/// Data structure containing information gathered during testing.
/// </summary>
TestReport TestReport { get; }
/// <summary>
/// Interface for registering runtime operations.
/// </summary>
IRegisterRuntimeOperation Reporter { get; }
/// <summary>
/// Runs the Coyote testing engine.
/// </summary>
ITestingEngine Run();
/// <summary>
/// Stops the Coyote testing engine.
/// </summary>
void Stop();
/// <summary>
/// Returns a report with the testing results.
/// </summary>
string GetReport();
/// <summary>
/// Tries to emit the testing traces, if any.
/// </summary>
void TryEmitTraces(string directory, string file);
/// <summary>
/// Registers a callback to invoke at the end of each iteration. The callback
/// takes as a parameter an integer representing the current iteration.
/// </summary>
void RegisterPerIterationCallBack(Action<int> callback);
}
}
| 32.188679 | 100 | 0.528136 | [
"MIT"
] | pdeligia/nekara-artifact | CoyoteActors/Framework/Coyote/Source/TestingServices/Engines/ITestingEngine.cs | 1,708 | C# |
public class Solution {
public int NumTrees(int n) {
var dp = new int[n + 1];
dp[0] = 1;
dp[1] = 1;
for(var i = 2; i <= n; i++){
for(var j = 0; j <= i - 1; j++){
dp[i] += dp[j] * dp[i - 1 - j];
}
}
return dp[n];
}
} | 21.933333 | 47 | 0.316109 | [
"MIT"
] | webigboss/Leetcode | 96. Unique Binary Search Trees/96_Original.cs | 329 | C# |
namespace MicroserviceNET.Monitoring
{
using System.Data.SqlClient;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Dapper;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Logging;
public class MsSqlStartupHealthCheck : IHealthCheck
{
private readonly HttpClient httpClient;
private readonly ILogger logger;
public MsSqlStartupHealthCheck(ILoggerFactory logger)
{
this.httpClient = new HttpClient();
this.logger = logger.CreateLogger<MsSqlStartupHealthCheck>();
}
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken)
{
await using var conn = new SqlConnection("Data Source=localhost;Initial Catalog=master;User Id=SA; Password=yourStrong(!)Password");
var result = await conn.QuerySingleAsync<int>("SELECT 1");
return result == 1
? HealthCheckResult.Healthy()
: HealthCheckResult.Degraded();
}
}
} | 33.258065 | 138 | 0.741998 | [
"MIT"
] | horsdal/microservices-in-dotnet-book-second-edition | Chapter11/MicroserviceNET.Monitoring/MsSqlStartupHealthCheck.cs | 1,031 | C# |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
namespace AmplifyShaderEditor
{
[Serializable]
public class ShaderVariablesNode : ParentNode
{
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
AddOutputPort( WirePortDataType.OBJECT, "Out" );
}
public override string GetIncludes()
{
return Constants.UnityShaderVariables;
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
if( !( dataCollector.IsTemplate && dataCollector.TemplateDataCollectorInstance.IsSRP ) )
dataCollector.AddToIncludes( UniqueId, Constants.UnityShaderVariables );
return string.Empty;
}
}
}
| 28.392857 | 128 | 0.762264 | [
"MIT"
] | 142333lzg/jynew | jyx2/Assets/3rd/AmplifyShaderEditor/Plugins/Editor/Nodes/Constants/ShaderVariables/ShaderVariablesNode.cs | 795 | C# |
using System;
using System.Collections.Generic;
using SF.Core.Errors.Internal;
namespace SF.Core.Errors.Exceptions
{
public class UnauthorizedException : BaseException
{
public UnauthorizedException(string message = Defaults.UnauthorizedException.Title, Exception exception = null, Dictionary<string, IEnumerable<string>> messages = null)
: base(message, exception, messages)
{ }
public UnauthorizedException(string message) : base(Defaults.UnauthorizedException.Title, null, null)
{
base.AddMessage(message);
}
}
}
| 31.315789 | 176 | 0.70084 | [
"Apache-2.0"
] | ZHENGZHENGRONG/SF-Boilerplate | SF.Core/Errors/Exceptions/UnauthorizedException.cs | 597 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.ApiManagement.V20200601Preview.Inputs
{
/// <summary>
/// API Management service resource SKU properties.
/// </summary>
public sealed class ApiManagementServiceSkuPropertiesArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Capacity of the SKU (number of deployed units of the SKU). For Consumption SKU capacity must be specified as 0.
/// </summary>
[Input("capacity", required: true)]
public Input<int> Capacity { get; set; } = null!;
/// <summary>
/// Name of the Sku.
/// </summary>
[Input("name", required: true)]
public Input<string> Name { get; set; } = null!;
public ApiManagementServiceSkuPropertiesArgs()
{
}
}
}
| 30.857143 | 123 | 0.642593 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/ApiManagement/V20200601Preview/Inputs/ApiManagementServiceSkuPropertiesArgs.cs | 1,080 | C# |
// <copyright file="Order.cs" company="Automate The Planet Ltd.">
// Copyright 2016 Automate The Planet Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// <author>Anton Angelov</author>
// <site>http://automatetheplanet.com/</site>
using System;
namespace DesignGridControlAutomatedTestsPartTwo
{
public class Order
{
public Order(string shipName) : this()
{
if (!string.IsNullOrEmpty(shipName))
{
this.ShipName = shipName;
}
}
public Order()
{
Random rand = new Random();
this.OrderId = rand.Next();
this.ShipName = Guid.NewGuid().ToString();
this.Freight = rand.Next();
this.OrderDate = DateTime.Now;
}
public int OrderId { get; set; }
public string ShipName { get; set; }
public double Freight { get; set; }
public DateTime OrderDate { get; set; }
}
}
| 34.651163 | 85 | 0.62953 | [
"Apache-2.0"
] | alihassan5/TestAutomation | WebDriver-Series/DesignGridControlAutomatedTestsPartTwo/Order.cs | 1,492 | C# |
// 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.Runtime.CompilerServices;
using System.Globalization;
/// <summary>
/// ToString
/// </summary>
public class DecimalToString1
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Calling ToString method.");
try
{
decimal d1 = 11111.111m;
CultureInfo myCulture=CultureInfo.CurrentCulture ;
string seperator=myCulture.NumberFormat.CurrencyDecimalSeparator;
string expectValue="11111"+seperator+"111";
string actualValue = d1.ToString();
if (actualValue != expectValue)
{
TestLibrary.TestFramework.LogError("001.1", "ToString should return "+expectValue);
retVal = false;
}
d1 = -11111.111m;
expectValue = "-11111" + seperator + "111";
actualValue = d1.ToString();
if (actualValue != expectValue)
{
TestLibrary.TestFramework.LogError("001.2", "ToString should return " + expectValue);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Calling ToString method and the value is Decimal.MaxValue and Decimal.MinValue.");
try
{
decimal d1 = Decimal.MaxValue;
CultureInfo myCulture = CultureInfo.CurrentCulture;
string seperator = myCulture.NumberFormat.CurrencyDecimalSeparator;
string expectValue = "79228162514264337593543950335";
string actualValue = d1.ToString();
if (actualValue != expectValue)
{
TestLibrary.TestFramework.LogError("002.1", "ToString should return " + expectValue);
retVal = false;
}
d1 = Decimal.MinValue;
expectValue = "-79228162514264337593543950335";
actualValue = d1.ToString();
if (actualValue != expectValue)
{
TestLibrary.TestFramework.LogError("002.2", "ToString should return " + expectValue);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Calling ToString method,the decimal has a long fractional digits.");
try
{
int exponent = 28;
decimal d1 = 1e-28m;
CultureInfo myCulture = CultureInfo.CurrentCulture;
string seperator = myCulture.NumberFormat.CurrencyDecimalSeparator;
string expectValue = "0" + seperator;
for (int i = 1; i < exponent; i++)
{
expectValue += "0";
}
expectValue = expectValue + "1";
string actualValue = d1.ToString();
if (actualValue != expectValue)
{
TestLibrary.TestFramework.LogError("003.1", "ToString should return " + expectValue);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
DecimalToString1 test = new DecimalToString1();
TestLibrary.TestFramework.BeginTestCase("DecimalToString1");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| 31.16129 | 141 | 0.563354 | [
"MIT"
] | AaronRobinsonMSFT/coreclr | tests/src/CoreMangLib/cti/system/decimal/decimaltostring1.cs | 4,830 | C# |
using System;
namespace Signals.Aspects.BackgroundProcessing.TaskConfiguration
{
/// <summary>
/// Advanced configuration for time
/// Ex: Run every 5 seconds;
/// Run every 5 minutes and 30 seconds
/// Run every 1 hour and 30 minutes
/// </summary>
public sealed class TimePartRecurrencePatternConfiguration : RecurrencePatternConfiguration
{
/// <summary>
/// CTOR
/// </summary>
public TimePartRecurrencePatternConfiguration(TimeSpan timePart) : base(PatternType.Second, 1)
{
TimePart = new TimeSpan(0, timePart.Hours, timePart.Minutes, timePart.Seconds);
Value = (int)TimePart.TotalSeconds;
}
}
}
| 27.608696 | 96 | 0.724409 | [
"MIT"
] | EmitKnowledge/Signals | src/05 Aspects/10 Background processing/Signals.Aspects.BackgroundProcessing/TaskConfiguration/TimePartRecurrencePatternConfiguration.cs | 637 | C# |
using UnityEngine;
using Unity.Collections;
using System.Collections.Generic;
using System.IO;
namespace uLipSync
{
[System.Serializable]
public struct MfccCalibrationData
{
public float[] array;
public float this[int i] { get { return array[i]; } }
public int length { get { return array.Length; } }
}
[System.Serializable]
public class MfccData
{
public string name;
public List<MfccCalibrationData> mfccCalibrationDataList = new List<MfccCalibrationData>();
public NativeArray<float> mfccNativeArray;
public MfccData(string name)
{
this.name = name;
}
~MfccData()
{
Deallocate();
}
public void Allocate()
{
if (IsAllocated()) return;
mfccNativeArray = new NativeArray<float>(12, Allocator.Persistent);
}
public void Deallocate()
{
if (!IsAllocated()) return;
mfccNativeArray.Dispose();
}
bool IsAllocated()
{
return mfccNativeArray.IsCreated;
}
public void AddCalibrationData(float[] mfcc)
{
if (mfcc.Length != 12)
{
Debug.LogError("The length of MFCC array should be 12.");
return;
}
mfccCalibrationDataList.Add(new MfccCalibrationData() { array = mfcc });
}
public void RemoveOldCalibrationData(int dataCount)
{
while (mfccCalibrationDataList.Count > dataCount) mfccCalibrationDataList.RemoveAt(0);
}
public void UpdateNativeArray()
{
if (mfccCalibrationDataList.Count == 0) return;
for (int i = 0; i < 12; ++i)
{
mfccNativeArray[i] = 0f;
foreach (var mfcc in mfccCalibrationDataList)
{
mfccNativeArray[i] += mfcc[i];
}
mfccNativeArray[i] /= mfccCalibrationDataList.Count;
}
}
public float GetAverage(int i)
{
return mfccNativeArray[i];
}
}
[CreateAssetMenu(menuName = Common.assetName + "/Profile")]
public class Profile : ScriptableObject
{
[HideInInspector] public string jsonPath = "";
[Tooltip("The number of MFCC data to calculate the average MFCC values")]
public int mfccDataCount = 32;
[Tooltip("The number of Mel Filter Bank channels")]
public int melFilterBankChannels = 24;
[Tooltip("Target sampling rate to apply downsampling")]
public int targetSampleRate = 16000;
[Tooltip("Number of audio samples after downsampling is applied")]
public int sampleCount = 512;
[Tooltip("Min Volume (Log10)")]
[Range(-10f, 0f)] public float minVolume = -4f;
[Tooltip("Max Volume (Log10)")]
[Range(-10f, 0f)] public float maxVolume = -2f;
public List<MfccData> mfccs = new List<MfccData>();
void OnEnable()
{
foreach (var data in mfccs)
{
data.Allocate();
data.RemoveOldCalibrationData(mfccDataCount);
data.UpdateNativeArray();
}
}
void OnDisable()
{
foreach (var data in mfccs)
{
data.Deallocate();
}
}
public string GetPhoneme(int index)
{
if (index < 0 || index >= mfccs.Count) return "";
return mfccs[index].name;
}
public void AddMfcc(string name)
{
var data = new MfccData(name);
data.Allocate();
for (int i = 0; i < mfccDataCount; ++i)
{
data.AddCalibrationData(new float[12]);
}
mfccs.Add(data);
}
public void RemoveMfcc(int index)
{
if (index < 0 || index >= mfccs.Count) return;
var data = mfccs[index];
data.Deallocate();
mfccs.RemoveAt(index);
}
public void UpdateMfcc(int index, NativeArray<float> mfcc, bool calib)
{
if (index < 0 || index >= mfccs.Count) return;
var array = new float[mfcc.Length];
mfcc.CopyTo(array);
var data = mfccs[index];
data.AddCalibrationData(array);
data.RemoveOldCalibrationData(mfccDataCount);
if (calib) data.UpdateNativeArray();
}
public NativeArray<float> GetAverages(int index)
{
return mfccs[index].mfccNativeArray;
}
public void Export(string path)
{
var json = JsonUtility.ToJson(this);
try
{
File.WriteAllText(path, json);
}
catch (System.Exception e)
{
Debug.LogError(e.Message);
}
}
public void Import(string path)
{
string json = "";
try
{
json = File.ReadAllText(path);
}
catch (System.Exception e)
{
Debug.LogError(e.Message);
return;
}
JsonUtility.FromJsonOverwrite(json, this);
}
public Profile Create(string path)
{
var profile = new Profile();
return profile;
}
}
}
| 24.442308 | 96 | 0.559205 | [
"MIT"
] | uezo/uLipSync | Assets/uLipSync/Runtime/Core/Profile.cs | 5,084 | C# |
using System.Dynamic;
using PureDI;
using PureDI.Attributes;
using IOCCTest.TestCode;
namespace IOCCTest.DifficultTypeTestData
{
[Bean]
public class Dynamic : IResultGetter
{
[BeanReference] dynamic anotherDynamic;
public dynamic GetResults()
{
dynamic eo = new ExpandoObject();
return eo;
}
}
[Bean]
public class AnotherDynamic
{
}
} | 17.4 | 47 | 0.604598 | [
"MIT"
] | mikedamay/PureDI | PureDITest/DifficultTypeTestData/Dynamic.cs | 437 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using Hugula.Utils;
using UnityEditor;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
namespace PSDUINewImporter
{
public sealed class ToggleComponentImport : SelectableComponentImport<Toggle>
{
public ToggleComponentImport(PSDComponentImportCtrl ctrl) : base(ctrl)
{
}
protected override void DrawTargetLayer(Layer layer, Toggle target, GameObject parent,int posSizeLayerIndex)
{
var normalImage = (Image)target.targetGraphic;
int normalIdx = DrawBackgroundImage(layer,normalImage,target.gameObject,false); //背景图覆盖size
normalImage.GetComponent<RectTransform>().sizeDelta = target.GetComponent<RectTransform>().sizeDelta;
//寻找check mark Image
var checkImage = (Image)target.graphic;
base.DrawTagImage(layer,checkImage,"",0,checkImage.gameObject);
base.DrawSpriteState(layer,target,target.gameObject,posSizeLayerIndex);
ctrl.DrawLayers(layer.layers, null, target.gameObject);
}
protected override void CheckAddBinder(Layer layer, Toggle input)
{
var binder = PSDImportUtility.AddMissingComponent<Hugula.Databinding.Binder.ToggleBinder>(input.gameObject);
if (binder != null)
{
var txtBinding = binder.GetBinding("isOn");
if(txtBinding == null)
{
txtBinding = new Hugula.Databinding.Binding();
binder.AddBinding(txtBinding);
txtBinding.propertyName = "isOn";
txtBinding.mode = Hugula.Databinding.BindingMode.TwoWay;
}
txtBinding.path = layer.name+"_is_on";
var binding = binder.GetBinding("onValueChangedCommand");
if (binding == null)
{
binding = new Hugula.Databinding.Binding();
binder.AddBinding(binding);
binding.propertyName = "onValueChangedCommand";
}
binding.path = "on_value_changed_" + layer.name;
}
}
}
} | 35.904762 | 120 | 0.608753 | [
"MIT"
] | tenvick/hugula | Client/Assets/Third/PSD2UGUI/Editor/ComponentImport/ToggleComponentImport.cs | 2,276 | C# |
// Copyright (c) 2018 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections.Generic;
using System.Threading;
namespace Alachisoft.NCache.Web.Communication
{
internal class RequestModerator
{
private Dictionary<string, NodeRequestStatus> statusBook;
private Timer cleanupTask;
public RequestModerator()
{
statusBook = new Dictionary<string, NodeRequestStatus>();
cleanupTask = new Timer(Clean, this, 0, 15000);
}
public long RegisterRequest(string address, long currentId)
{
long returnValue = -1;
if (address != null)
{
lock (statusBook)
{
NodeRequestStatus status;
if (!statusBook.TryGetValue(address, out status))
{
status = new NodeRequestStatus();
statusBook.Add(address, status);
}
lock (status.SyncRoot)
{
status.RegisterRequest(currentId);
returnValue = status.LastAcknowledged;
}
}
}
return returnValue;
}
public void UnRegisterRequest(long Id)
{
lock (statusBook)
{
foreach (NodeRequestStatus status in statusBook.Values)
status.Acknowledge(Id);
}
}
private void Clean(object obj)
{
lock (statusBook)
foreach (NodeRequestStatus status in statusBook.Values)
{
status.Clean();
}
}
}
} | 30.493333 | 75 | 0.547442 | [
"Apache-2.0"
] | abayaz61/NCache | Src/NCWebCache/Web/RemoteClient/Communication/RequestModerator.cs | 2,289 | C# |
using System;
using System.Diagnostics.Contracts;
using System.ServiceModel.Dispatcher;
using Ncqrs.Commanding.ServiceModel;
namespace Ncqrs.CommandService.Infrastructure
{
internal class CommandServiceInstanceProvider : IInstanceProvider
{
public CommandServiceInstanceProvider(Type serviceType)
{
if (typeof(CommandWebService).Equals(serviceType) == false)
{
throw new InvalidOperationException("The Provider can only be used with the Ncqrs.CommandService.CommandWebService service type.");
}
}
public object GetInstance(System.ServiceModel.InstanceContext instanceContext, System.ServiceModel.Channels.Message message)
{
Contract.Assume(instanceContext != null);
return new CommandWebService(NcqrsEnvironment.Get<ICommandService>());
}
public object GetInstance(System.ServiceModel.InstanceContext instanceContext)
{
Contract.Assume(instanceContext != null);
return GetInstance(instanceContext, null);
}
public void ReleaseInstance(System.ServiceModel.InstanceContext instanceContext, object instance)
{
}
}
}
| 36 | 148 | 0.67381 | [
"Apache-2.0"
] | adamcogx/ncqrs | Extensions/src/Ncqrs.CommandService/Infrastructure/CommandServiceInstanceProvider.cs | 1,262 | C# |
namespace Dev.DevKit.Shared.Entities
{
public partial class ProductSalesLiterature
{
#region --- PROPERTIES ---
//public DateTime? DateTime { get { return GetAliasedValue<DateTime?>("c.birthdate"); } }
#endregion
#region --- STATIC METHODS ---
#endregion
}
}
| 18.647059 | 97 | 0.596215 | [
"MIT"
] | Kayserheimer/Dynamics-Crm-DevKit | test/v.2.12.31/TestAllEntities/All-DEMO/Dev.DevKit.Shared/Entities/ProductSalesLiterature.cs | 319 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel;
using MongoDB.Bson.Serialization.IdGenerators;
using MongoDB.Bson.Serialization.Serializers;
using System.Numerics;
using Newtonsoft.Json;
namespace NETAPI.Models
{
public class City
{
public const string IDFIELD = "_id";
public const string NAMEFIELD = "name";
public const string ABOUTFIELD = "description";
public const string PHOTOFIELD = "photos";
public const string POSFIELD = "coordinates";
[BsonId(IdGenerator = typeof(BsonObjectIdGenerator))]
[BsonElement(elementName: IDFIELD)]
public BsonObjectId Id { get; set; }
[BsonElement(elementName: NAMEFIELD)]
[BsonRequired]
public string Name { get; set; }
[BsonElement(elementName: ABOUTFIELD)]
public string Description { get; set; }
[BsonElement(elementName: PHOTOFIELD)]
public List<string> Photos { get; set; }
[BsonElement(elementName: POSFIELD)]
[JsonIgnore]
public List<double> Coordinates { get; set; }
}
}
| 33.238095 | 62 | 0.682665 | [
"MIT"
] | BernatskyPavel/NETAPI | NETAPI/Models/City.cs | 1,398 | C# |
public enum FileType
{
vsix,
pkg,
msi
}
| 6.142857 | 20 | 0.651163 | [
"MIT"
] | jonathanpeppers/boots | Boots.Core/FileType.cs | 43 | C# |
using TGC.Core.BoundingVolumes;
using TGC.Core.Collision;
using TGC.Core.Mathematica;
namespace TGC.Examples.Collision.ElipsoidCollision
{
/// <summary>
/// Collider a base de un BoundingBox
/// </summary>
public class BoundingBoxCollider : Collider
{
private readonly TgcBoundingAxisAlignBox eAABB;
public BoundingBoxCollider()
{
eAABB = new TgcBoundingAxisAlignBox();
}
/// <summary>
/// BoundingBox
/// </summary>
public TgcBoundingAxisAlignBox Aabb { get; set; }
/// <summary>
/// Crear Collider a partir de BoundingBox.
/// Crea el BoundingSphere del Collider.
/// </summary>
/// <param name="mesh">BoundingBox</param>
/// <returns>Collider creado</returns>
public static BoundingBoxCollider fromBoundingBox(TgcBoundingAxisAlignBox aabb)
{
var collider = new BoundingBoxCollider();
collider.Aabb = aabb;
collider.BoundingSphere = TgcBoundingSphere.computeFromPoints(aabb.computeCorners()).toClass();
return collider;
}
/// <summary>
/// Colisiona un Elipsoide en movimiento contra el BoundingBox.
/// Si hay colision devuelve el instante t de colision, el punto q de colision y el vector normal n de la superficie
/// contra la que
/// se colisiona.
/// Todo se devuelve en Elipsoid space.
/// El BoundingBox se pasa a Elipsoid space para comparar.
/// </summary>
/// <param name="eSphere">BoundingSphere de radio 1 en Elipsoid space</param>
/// <param name="eMovementVector">movimiento en Elipsoid space</param>
/// <param name="eRadius">radio del Elipsoide</param>
/// <param name="movementSphere">
/// BoundingSphere que abarca el sphere en su punto de origen mas el sphere en su punto final
/// deseado
/// </param>
/// <param name="t">Menor instante de colision, en Elipsoid space</param>
/// <param name="q">Punto mas cercano de colision, en Elipsoid space</param>
/// <param name="n">Vector normal de la superficie contra la que se colisiona</param>
/// <returns>True si hay colision</returns>
public override bool intersectMovingElipsoid(TgcBoundingSphere eSphere, TGCVector3 eMovementVector, TGCVector3 eRadius,
TgcBoundingSphere movementSphere, out float t, out TGCVector3 q, out TGCVector3 n)
{
//Pasar AABB a Elipsoid Space
eAABB.setExtremes(TGCVector3.Div(Aabb.PMin, eRadius), TGCVector3.Div(Aabb.PMax, eRadius));
t = -1f;
q = TGCVector3.Empty;
n = TGCVector3.Empty;
// Compute the AABB resulting from expanding b by sphere radius r
var e = eAABB.toStruct();
e.min.X -= eSphere.Radius;
e.min.Y -= eSphere.Radius;
e.min.Z -= eSphere.Radius;
e.max.X += eSphere.Radius;
e.max.Y += eSphere.Radius;
e.max.Z += eSphere.Radius;
// Intersect ray against expanded AABB e. Exit with no intersection if ray
// misses e, else get intersection point p and time t as result
TGCVector3 p;
var ray = new TgcRay.RayStruct();
ray.origin = eSphere.Center;
ray.direction = eMovementVector;
if (!intersectRayAABB(ray, e, out t, out p) || t > 1.0f)
return false;
// Compute which min and max faces of b the intersection point p lies
// outside of. Note, u and v cannot have the same bits set and
// they must have at least one bit set among them
var i = 0;
var sign = new int[3];
if (p.X < eAABB.PMin.X)
{
sign[0] = -1;
i++;
}
if (p.X > eAABB.PMax.X)
{
sign[0] = 1;
i++;
}
if (p.Y < eAABB.PMin.Y)
{
sign[1] = -1;
i++;
}
if (p.Y > eAABB.PMax.Y)
{
sign[1] = 1;
i++;
}
if (p.Z < eAABB.PMin.Z)
{
sign[2] = -1;
i++;
}
if (p.Z > eAABB.PMax.Z)
{
sign[2] = 1;
i++;
}
//Face
if (i == 1)
{
n = new TGCVector3(sign[0], sign[1], sign[2]);
q = eSphere.Center + t * eMovementVector - eSphere.Radius * n;
return true;
}
// Define line segment [c, c+d] specified by the sphere movement
var seg = new Segment(eSphere.Center, eSphere.Center + eMovementVector);
//Box extent and center
var extent = eAABB.calculateAxisRadius();
var center = eAABB.PMin + extent;
//Edge
if (i == 2)
{
//Generar los dos puntos extremos del Edge
float[] extentDir = { sign[0], sign[1], sign[2] };
var zeroIndex = sign[0] == 0 ? 0 : (sign[1] == 0 ? 1 : 2);
extentDir[zeroIndex] = 1;
var capsuleA = center + new TGCVector3(extent.X * extentDir[0], extent.Y * extentDir[1], extent.Z * extentDir[2]);
extentDir[zeroIndex] = -1;
var capsuleB = center + new TGCVector3(extent.X * extentDir[0], extent.Y * extentDir[1], extent.Z * extentDir[2]);
//Colision contra el Edge hecho Capsula
if (intersectSegmentCapsule(seg, new Capsule(capsuleA, capsuleB, eSphere.Radius), out t))
{
n = new TGCVector3(sign[0], sign[1], sign[2]);
n.Normalize();
q = eSphere.Center + t * eMovementVector - eSphere.Radius * n;
return true;
}
}
//Vertex
if (i == 3)
{
var tmin = float.MaxValue;
var capsuleA = center + new TGCVector3(extent.X * sign[0], extent.Y * sign[1], extent.Z * sign[2]);
TGCVector3 capsuleB;
capsuleB = center + new TGCVector3(extent.X * -sign[0], extent.Y * sign[1], extent.Z * sign[2]);
if (intersectSegmentCapsule(seg, new Capsule(capsuleA, capsuleB, eSphere.Radius), out t))
tmin = TgcCollisionUtils.min(t, tmin);
capsuleB = center + new TGCVector3(extent.X * sign[0], extent.Y * -sign[1], extent.Z * sign[2]);
if (intersectSegmentCapsule(seg, new Capsule(capsuleA, capsuleB, eSphere.Radius), out t))
tmin = TgcCollisionUtils.min(t, tmin);
capsuleB = center + new TGCVector3(extent.X * sign[0], extent.Y * sign[1], extent.Z * -sign[2]);
if (intersectSegmentCapsule(seg, new Capsule(capsuleA, capsuleB, eSphere.Radius), out t))
tmin = TgcCollisionUtils.min(t, tmin);
if (tmin == float.MaxValue) return false; // No intersection
t = tmin;
n = new TGCVector3(sign[0], sign[1], sign[2]);
n.Normalize();
q = eSphere.Center + t * eMovementVector - eSphere.Radius * n;
return true; // Intersection at time t == tmin
}
return false;
}
/// <summary>
/// Detectar colision entre un Segmento de recta y una Capsula.
/// </summary>
/// <param name="seg">Segmento</param>
/// <param name="capsule">Capsula</param>
/// <param name="t">Menor instante de colision</param>
/// <returns>True si hay colision</returns>
private bool intersectSegmentCapsule(Segment seg, Capsule capsule, out float t)
{
var ray = new TgcRay.RayStruct();
ray.origin = seg.a;
ray.direction = seg.dir;
if (intersectRayCapsule(ray, capsule, out t))
{
if (t >= 0.0f && t <= seg.length)
{
t /= seg.length;
return true;
}
}
return false;
}
/// <summary>
/// Detectar colision entre un Ray y una Capsula
/// Basado en: http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrLine3Capsule3.cpp
/// </summary>
/// <param name="ray">Ray</param>
/// <param name="capsule">Capsula</param>
/// <param name="t">Menor instante de colision</param>
/// <returns>True si hay colision</returns>
private bool intersectRayCapsule(TgcRay.RayStruct ray, Capsule capsule, out float t)
{
t = -1;
var origin = ray.origin;
var dir = ray.direction;
// Create a coordinate system for the capsule. In this system, the
// capsule segment center C is the origin and the capsule axis direction
// W is the z-axis. U and V are the other coordinate axis directions.
// If P = x*U+y*V+z*W, the cylinder containing the capsule wall is
// x^2 + y^2 = r^2, where r is the capsule radius. The finite cylinder
// that makes up the capsule minus its hemispherical end caps has z-values
// |z| <= e, where e is the extent of the capsule segment. The top
// hemisphere cap is x^2+y^2+(z-e)^2 = r^2 for z >= e, and the bottom
// hemisphere cap is x^2+y^2+(z+e)^2 = r^2 for z <= -e.
var U = capsule.segment.dir;
var V = U;
var W = U;
generateComplementBasis(ref U, ref V, W);
var rSqr = capsule.radius * capsule.radius;
var extent = capsule.segment.extent;
// Convert incoming line origin to capsule coordinates.
var diff = origin - capsule.segment.center;
var P = new TGCVector3(TGCVector3.Dot(U, diff), TGCVector3.Dot(V, diff), TGCVector3.Dot(W, diff));
// Get the z-value, in capsule coordinates, of the incoming line's unit-length direction.
var dz = TGCVector3.Dot(W, dir);
if (FastMath.Abs(dz) >= 1f - float.Epsilon)
{
// The line is parallel to the capsule axis. Determine whether the line intersects the capsule hemispheres.
var radialSqrDist = rSqr - P.X * P.X - P.Y * P.Y;
if (radialSqrDist < 0f)
{
// Line outside the cylinder of the capsule, no intersection.
return false;
}
// line intersects the hemispherical caps
var zOffset = FastMath.Sqrt(radialSqrDist) + extent;
if (dz > 0f)
{
t = -P.Z - zOffset;
}
else
{
t = P.Z - zOffset;
}
return true;
}
// Convert incoming line unit-length direction to capsule coordinates.
var D = new TGCVector3(TGCVector3.Dot(U, dir), TGCVector3.Dot(V, dir), dz);
// Test intersection of line P+t*D with infinite cylinder x^2+y^2 = r^2.
// This reduces to computing the roots of a quadratic equation. If
// P = (px,py,pz) and D = (dx,dy,dz), then the quadratic equation is
// (dx^2+dy^2)*t^2 + 2*(px*dx+py*dy)*t + (px^2+py^2-r^2) = 0
var a0 = P.X * P.X + P.Y * P.Y - rSqr;
var a1 = P.X * D.X + P.Y * D.Y;
var a2 = D.X * D.X + D.Y * D.Y;
var discr = a1 * a1 - a0 * a2;
if (discr < 0f)
{
// Line does not intersect infinite cylinder.
return false;
}
float root, inv, tValue, zValue;
var quantity = 0;
if (discr > float.Epsilon)
{
// Line intersects infinite cylinder in two places.
root = FastMath.Sqrt(discr);
inv = 1f / a2;
tValue = (-a1 - root) * inv;
zValue = P.Z + tValue * D.Z;
if (FastMath.Abs(zValue) <= extent)
{
quantity++;
t = tValue;
}
tValue = (-a1 + root) * inv;
zValue = P.Z + tValue * D.Z;
if (FastMath.Abs(zValue) <= extent)
{
quantity++;
t = TgcCollisionUtils.min(t, tValue);
}
if (quantity == 2)
{
// Line intersects capsule wall in two places.
return true;
}
}
else
{
// Line is tangent to infinite cylinder.
tValue = -a1 / a2;
zValue = P.Z + tValue * D.Z;
if (FastMath.Abs(zValue) <= extent)
{
t = tValue;
return true;
}
}
// Test intersection with bottom hemisphere. The quadratic equation is
// t^2 + 2*(px*dx+py*dy+(pz+e)*dz)*t + (px^2+py^2+(pz+e)^2-r^2) = 0
// Use the fact that currently a1 = px*dx+py*dy and a0 = px^2+py^2-r^2.
// The leading coefficient is a2 = 1, so no need to include in the
// construction.
var PZpE = P.Z + extent;
a1 += PZpE * D.Z;
a0 += PZpE * PZpE;
discr = a1 * a1 - a0;
if (discr > float.Epsilon)
{
root = FastMath.Sqrt(discr);
tValue = -a1 - root;
zValue = P.Z + tValue * D.Z;
if (zValue <= -extent)
{
quantity++;
t = TgcCollisionUtils.min(t, tValue);
if (quantity == 2)
{
return true;
}
}
tValue = -a1 + root;
zValue = P.Z + tValue * D.Z;
if (zValue <= -extent)
{
quantity++;
t = TgcCollisionUtils.min(t, tValue);
if (quantity == 2)
{
return true;
}
}
}
else if (FastMath.Abs(discr) <= float.Epsilon)
{
tValue = -a1;
zValue = P.Z + tValue * D.Z;
if (zValue <= -extent)
{
quantity++;
t = TgcCollisionUtils.min(t, tValue);
if (quantity == 2)
{
return true;
}
}
}
// Test intersection with top hemisphere. The quadratic equation is
// t^2 + 2*(px*dx+py*dy+(pz-e)*dz)*t + (px^2+py^2+(pz-e)^2-r^2) = 0
// Use the fact that currently a1 = px*dx+py*dy+(pz+e)*dz and
// a0 = px^2+py^2+(pz+e)^2-r^2. The leading coefficient is a2 = 1, so
// no need to include in the construction.
a1 -= 2f * extent * D.Z;
a0 -= 4 * extent * P.Z;
discr = a1 * a1 - a0;
if (discr > float.Epsilon)
{
root = FastMath.Sqrt(discr);
tValue = -a1 - root;
zValue = P.Z + tValue * D.Z;
if (zValue >= extent)
{
quantity++;
t = TgcCollisionUtils.min(t, tValue);
if (quantity == 2)
{
return true;
}
}
tValue = -a1 + root;
zValue = P.Z + tValue * D.Z;
if (zValue >= extent)
{
quantity++;
t = TgcCollisionUtils.min(t, tValue);
if (quantity == 2)
{
return true;
}
}
}
else if (FastMath.Abs(discr) <= float.Epsilon)
{
tValue = -a1;
zValue = P.Z + tValue * D.Z;
if (zValue >= extent)
{
quantity++;
t = TgcCollisionUtils.min(t, tValue);
if (quantity == 2)
{
return true;
}
}
}
return quantity > 0;
}
/// <summary>
/// Input W must be a unit-length vector. The output vectors {U,V} are
/// unit length and mutually perpendicular, and {U,V,W} is an orthonormal basis.
/// </summary>
private void generateComplementBasis(ref TGCVector3 u, ref TGCVector3 v, TGCVector3 w)
{
float invLength;
if (FastMath.Abs(w.X) >= FastMath.Abs(w.Y))
{
// W.x or W.z is the largest magnitude component, swap them
invLength = FastMath.InvSqrt(w.X * w.X + w.Z * w.Z);
u.X = -w.Z * invLength;
u.Y = 0f;
u.Z = +w.X * invLength;
v.X = w.Y * u.Z;
v.Y = w.Z * u.X - w.X * u.Z;
v.Z = -w.Y * u.X;
}
else
{
// W.y or W.z is the largest magnitude component, swap them
invLength = FastMath.InvSqrt(w.Y * w.Y + w.Z * w.Z);
u.X = 0f;
u.Y = +w.Z * invLength;
u.Z = -w.Y * invLength;
v.X = w.Y * u.Z - w.Z * u.Y;
v.Y = -w.X * u.Z;
v.Z = w.X * u.Y;
}
}
/// <summary>
/// Interseccion entre un Ray y un AABB
/// </summary>
/// <param name="ray">Ray</param>
/// <param name="aabb">AABB</param>
/// <param name="tmin">Instante minimo de colision</param>
/// <param name="q">Punto minimo de colision</param>
/// <returns>True si hay colision</returns>
private bool intersectRayAABB(TgcRay.RayStruct ray, TgcBoundingAxisAlignBox.AABBStruct aabb, out float tmin,
out TGCVector3 q)
{
var aabbMin = TgcCollisionUtils.toArray(aabb.min);
var aabbMax = TgcCollisionUtils.toArray(aabb.max);
var p = TgcCollisionUtils.toArray(ray.origin);
var d = TgcCollisionUtils.toArray(ray.direction);
tmin = 0.0f; // set to -FLT_MAX to get first hit on line
var tmax = float.MaxValue; // set to max distance ray can travel (for segment)
q = TGCVector3.Empty;
// For all three slabs
for (var i = 0; i < 3; i++)
{
if (FastMath.Abs(d[i]) < float.Epsilon)
{
// Ray is parallel to slab. No hit if origin not within slab
if (p[i] < aabbMin[i] || p[i] > aabbMax[i]) return false;
}
else
{
// Compute intersection t value of ray with near and far plane of slab
var ood = 1.0f / d[i];
var t1 = (aabbMin[i] - p[i]) * ood;
var t2 = (aabbMax[i] - p[i]) * ood;
// Make t1 be intersection with near plane, t2 with far plane
if (t1 > t2) TgcCollisionUtils.swap(ref t1, ref t2);
// Compute the intersection of slab intersection intervals
tmin = TgcCollisionUtils.max(tmin, t1);
tmax = TgcCollisionUtils.min(tmax, t2);
// Exit with no collision as soon as slab intersection becomes empty
if (tmin > tmax) return false;
}
}
// Ray intersects all 3 slabs. Return point (q) and intersection t value (tmin)
q = ray.origin + ray.direction * tmin;
return true;
}
/// <summary>
/// Estructura para segmento de recta
/// </summary>
private struct Segment
{
public Segment(TGCVector3 a, TGCVector3 b)
{
this.a = a;
this.b = b;
dir = b - a;
center = (a + b) * 0.5f;
length = dir.Length();
extent = length * 0.5f;
dir.Normalize();
}
public readonly TGCVector3 a;
public TGCVector3 b;
public readonly TGCVector3 center;
public readonly TGCVector3 dir;
public readonly float extent;
public readonly float length;
}
/// <summary>
/// Estructura para Capsula
/// </summary>
private struct Capsule
{
public Capsule(TGCVector3 a, TGCVector3 b, float radius)
{
segment = new Segment(a, b);
this.radius = radius;
}
public Segment segment;
public readonly float radius;
}
/*
private bool intersectSegmentCapsule(Segment seg, Capsule capsule, out float t)
{
TgcRay.RayStruct ray = new TgcRay.RayStruct();
ray.origin = seg.a;
ray.direction = seg.b - seg.a;
float minT = float.MaxValue;
if (intersectSegmentCylinderNoEndcap(seg.a, seg.b, capsule.segment.a, capsule.segment.b, capsule.radius, out t))
{
minT = TgcCollisionUtils.min(t, minT);
}
TgcBoundingSphere.SphereStruct s = new TgcBoundingSphere.SphereStruct();
s.center = capsule.segment.a;
s.radius = capsule.radius;
if (intersectRaySphere(ray, s, out t) && t <= 1.0f)
{
minT = TgcCollisionUtils.min(t, minT);
}
s.center = capsule.segment.b;
if (intersectRaySphere(ray, s, out t) && t <= 1.0f)
{
minT = TgcCollisionUtils.min(t, minT);
}
if (minT != float.MaxValue)
{
t = minT;
return true;
}
return false;
}
/// <summary>
/// Indica si un Ray colisiona con un BoundingSphere.
/// </summary>
public static bool intersectRaySphere(TgcRay.RayStruct ray, TgcBoundingSphere.SphereStruct sphere, out float t)
{
t = -1;
TGCVector3 m = ray.origin - sphere.center;
float b = TGCVector3.Dot(m, ray.direction);
float c = TGCVector3.Dot(m, m) - sphere.radius * sphere.radius;
// Exit if r’s origin outside s (c > 0) and r pointing away from s (b > 0)
if (c > 0.0f && b > 0.0f) return false;
float discr = b * b - c;
// A negative discriminant corresponds to ray missing sphere
if (discr < 0.0f) return false;
// Ray now found to intersect sphere, compute smallest t value of intersection
t = -b - FastMath.Sqrt(discr);
// If t is negative, ray started inside sphere so clamp t to zero
if (t < 0.0f) t = 0.0f;
return true;
}
/// <summary>
/// Indica si un cilindro colisiona con un segmento.
/// El cilindro se especifica con dos puntos centrales "cylinderInit" y "cylinderEnd" que forman una recta y con un radio "radius".
/// Si hay colision se devuelve el instante de colision "t".
/// No chequear EndCaps
/// </summary>
/// <param name="segmentInit">Punto de inicio del segmento</param>
/// <param name="segmentEnd">Punto de fin del segmento</param>
/// <param name="cylinderInit">Punto inicial del cilindro</param>
/// <param name="cylinderEnd">Punto final del cilindro</param>
/// <param name="radius">Radio del cilindro</param>
/// <param name="t">Instante de colision</param>
/// <returns>True si hay colision</returns>
private static bool intersectSegmentCylinderNoEndcap(TGCVector3 segmentInit, TGCVector3 segmentEnd, TGCVector3 cylinderInit, TGCVector3 cylinderEnd, float radius, out float t)
{
t = -1;
TGCVector3 d = cylinderEnd - cylinderInit, m = segmentInit - cylinderInit, n = segmentEnd - segmentInit;
float md = TGCVector3.Dot(m, d);
float nd = TGCVector3.Dot(n, d);
float dd = TGCVector3.Dot(d, d);
// Test if segment fully outside either endcap of cylinder
if (md < 0.0f && md + nd < 0.0f) return false; // Segment outside ’p’ side of cylinder
if (md > dd && md + nd > dd) return false; // Segment outside ’q’ side of cylinder
float nn = TGCVector3.Dot(n, n);
float mn = TGCVector3.Dot(m, n);
float a = dd * nn - nd * nd;
float k = TGCVector3.Dot(m, m) - radius * radius;
float c = dd * k - md * md;
if (FastMath.Abs(a) < float.Epsilon)
{
// Segment runs parallel to cylinder axis
if (c > 0.0f) return false; // 'a' and thus the segment lie outside cylinder
// Now known that segment intersects cylinder; figure out how it intersects
if (md < 0.0f) t = -mn / nn; // Intersect segment against 'p' endcap
else if (md > dd) t = (nd - mn) / nn; // Intersect segment against ’q’ endcap
else t = 0.0f; // ’a’ lies inside cylinder
return true;
}
float b = dd * mn - nd * md;
float discr = b * b - a * c;
if (discr < 0.0f) return false; // No real roots; no intersection
t = (-b - FastMath.Sqrt(discr)) / a;
if (t < 0.0f || t > 1.0f) return false; // Intersection lies outside segment
//No chequear EndCaps
// Segment intersects cylinder between the endcaps; t is correct
return true;
}
*/
}
} | 40.052711 | 183 | 0.481218 | [
"MIT"
] | Javier-Rotelli/tgc-viewer | TGC.Examples/Collision/ElipsoidCollision/BoundingBoxCollider.cs | 26,615 | C# |
using System;
using System.Threading.Tasks;
using Localization.Resources.AbpUi;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using EasyAbp.FileManagement.Localization;
using Volo.Abp.UI.Navigation;
using Volo.Abp.Users;
namespace EasyAbp.FileManagement
{
public class FileManagementWebHostMenuContributor : IMenuContributor
{
private readonly IConfiguration _configuration;
public FileManagementWebHostMenuContributor(IConfiguration configuration)
{
_configuration = configuration;
}
public Task ConfigureMenuAsync(MenuConfigurationContext context)
{
if (context.Menu.Name == StandardMenus.User)
{
AddLogoutItemToMenu(context);
}
return Task.CompletedTask;
}
private void AddLogoutItemToMenu(MenuConfigurationContext context)
{
var currentUser = context.ServiceProvider.GetRequiredService<ICurrentUser>();
var l = context.GetLocalizer<FileManagementResource>();
if (currentUser.IsAuthenticated)
{
context.Menu.Items.Add(new ApplicationMenuItem(
"Account.Manage",
l["ManageYourProfile"],
$"{_configuration["AuthServer:Authority"].EnsureEndsWith('/')}Account/Manage",
icon: "fa fa-cog",
order: int.MaxValue - 1001,
null,
"_blank")
);
context.Menu.Items.Add(new ApplicationMenuItem(
"Account.Logout",
l["Logout"],
"~/Account/Logout",
"fas fa-power-off",
order: int.MaxValue - 1000
));
}
}
}
}
| 31.491803 | 98 | 0.580947 | [
"MIT"
] | Frunck8206/FileManagement | host/EasyAbp.FileManagement.Web.Host/FileManagementWebHostMenuContributor.cs | 1,923 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* 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 TencentCloud.Tag.V20180813.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeTagsResponse : AbstractModel
{
/// <summary>
/// 结果总数
/// </summary>
[JsonProperty("TotalCount")]
public ulong? TotalCount{ get; set; }
/// <summary>
/// 数据位移偏量
/// </summary>
[JsonProperty("Offset")]
public ulong? Offset{ get; set; }
/// <summary>
/// 每页大小
/// </summary>
[JsonProperty("Limit")]
public ulong? Limit{ get; set; }
/// <summary>
/// 标签列表
/// </summary>
[JsonProperty("Tags")]
public TagWithDelete[] Tags{ get; set; }
/// <summary>
/// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "TotalCount", this.TotalCount);
this.SetParamSimple(map, prefix + "Offset", this.Offset);
this.SetParamSimple(map, prefix + "Limit", this.Limit);
this.SetParamArrayObj(map, prefix + "Tags.", this.Tags);
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 30.25 | 81 | 0.599174 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Tag/V20180813/Models/DescribeTagsResponse.cs | 2,272 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ssm-2014-11-06.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.SimpleSystemsManagement.Model
{
/// <summary>
/// Container for the parameters to the DescribeMaintenanceWindowTasks operation.
/// Lists the tasks in a maintenance window.
/// </summary>
public partial class DescribeMaintenanceWindowTasksRequest : AmazonSimpleSystemsManagementRequest
{
private List<MaintenanceWindowFilter> _filters = new List<MaintenanceWindowFilter>();
private int? _maxResults;
private string _nextToken;
private string _windowId;
/// <summary>
/// Gets and sets the property Filters.
/// <para>
/// Optional filters used to narrow down the scope of the returned tasks. The supported
/// filter keys are WindowTaskId, TaskArn, Priority, and TaskType.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=5)]
public List<MaintenanceWindowFilter> Filters
{
get { return this._filters; }
set { this._filters = value; }
}
// Check to see if Filters property is set
internal bool IsSetFilters()
{
return this._filters != null && this._filters.Count > 0;
}
/// <summary>
/// Gets and sets the property MaxResults.
/// <para>
/// The maximum number of items to return for this call. The call also returns a token
/// that you can specify in a subsequent call to get the next set of results.
/// </para>
/// </summary>
[AWSProperty(Min=10, Max=100)]
public int MaxResults
{
get { return this._maxResults.GetValueOrDefault(); }
set { this._maxResults = value; }
}
// Check to see if MaxResults property is set
internal bool IsSetMaxResults()
{
return this._maxResults.HasValue;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// The token for the next set of items to return. (You received this token from a previous
/// call.)
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
/// <summary>
/// Gets and sets the property WindowId.
/// <para>
/// The ID of the maintenance window whose tasks should be retrieved.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=20, Max=20)]
public string WindowId
{
get { return this._windowId; }
set { this._windowId = value; }
}
// Check to see if WindowId property is set
internal bool IsSetWindowId()
{
return this._windowId != null;
}
}
} | 32.266667 | 101 | 0.602789 | [
"Apache-2.0"
] | NGL321/aws-sdk-net | sdk/src/Services/SimpleSystemsManagement/Generated/Model/DescribeMaintenanceWindowTasksRequest.cs | 3,872 | C# |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using VOU.EntityFrameworkCore;
namespace VOU.Migrations
{
[DbContext(typeof(VOUDbContext))]
[Migration("20170804083601_Upgraded_To_Abp_v2.2.2")]
partial class Upgraded_To_Abp_v222
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.1.2")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Abp.Application.Editions.Edition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(64);
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32);
b.HasKey("Id");
b.ToTable("AbpEditions");
});
modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Discriminator")
.IsRequired();
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("Value")
.IsRequired()
.HasMaxLength(2000);
b.HasKey("Id");
b.ToTable("AbpFeatures");
b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting");
});
modelBuilder.Entity("Abp.Auditing.AuditLog", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("BrowserInfo")
.HasMaxLength(256);
b.Property<string>("ClientIpAddress")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasMaxLength(128);
b.Property<string>("CustomData")
.HasMaxLength(2000);
b.Property<string>("Exception")
.HasMaxLength(2000);
b.Property<int>("ExecutionDuration");
b.Property<DateTime>("ExecutionTime");
b.Property<int?>("ImpersonatorTenantId");
b.Property<long?>("ImpersonatorUserId");
b.Property<string>("MethodName")
.HasMaxLength(256);
b.Property<string>("Parameters")
.HasMaxLength(1024);
b.Property<string>("ServiceName")
.HasMaxLength(256);
b.Property<int?>("TenantId");
b.Property<long?>("UserId");
b.HasKey("Id");
b.HasIndex("TenantId", "ExecutionDuration");
b.HasIndex("TenantId", "ExecutionTime");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpAuditLogs");
});
modelBuilder.Entity("Abp.Authorization.PermissionSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Discriminator")
.IsRequired();
b.Property<bool>("IsGranted");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpPermissions");
b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<int>("RoleId");
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("RoleId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpRoleClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("EmailAddress");
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastLoginTime");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.Property<long?>("UserLinkId");
b.Property<string>("UserName");
b.HasKey("Id");
b.HasIndex("EmailAddress");
b.HasIndex("UserName");
b.HasIndex("TenantId", "EmailAddress");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "UserName");
b.ToTable("AbpUserAccounts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpUserClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("LoginProvider")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.IsRequired()
.HasMaxLength(256);
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "LoginProvider", "ProviderKey");
b.ToTable("AbpUserLogins");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("BrowserInfo")
.HasMaxLength(256);
b.Property<string>("ClientIpAddress")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime");
b.Property<byte>("Result");
b.Property<string>("TenancyName")
.HasMaxLength(64);
b.Property<int?>("TenantId");
b.Property<long?>("UserId");
b.Property<string>("UserNameOrEmailAddress")
.HasMaxLength(255);
b.HasKey("Id");
b.HasIndex("UserId", "TenantId");
b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result");
b.ToTable("AbpUserLoginAttempts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<bool>("IsDeleted");
b.Property<long>("OrganizationUnitId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("TenantId", "OrganizationUnitId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserOrganizationUnits");
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<int>("RoleId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "RoleId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserRoles");
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.Property<string>("Value");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserTokens");
});
modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<bool>("IsAbandoned");
b.Property<string>("JobArgs")
.IsRequired()
.HasMaxLength(1048576);
b.Property<string>("JobType")
.IsRequired()
.HasMaxLength(512);
b.Property<DateTime?>("LastTryTime");
b.Property<DateTime>("NextTryTime");
b.Property<byte>("Priority");
b.Property<short>("TryCount");
b.HasKey("Id");
b.HasIndex("IsAbandoned", "NextTryTime");
b.ToTable("AbpBackgroundJobs");
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(256);
b.Property<int?>("TenantId");
b.Property<long?>("UserId");
b.Property<string>("Value")
.HasMaxLength(2000);
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpSettings");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(64);
b.Property<string>("Icon")
.HasMaxLength(128);
b.Property<bool>("IsDeleted");
b.Property<bool>("IsDisabled");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(10);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpLanguages");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(256);
b.Property<string>("LanguageName")
.IsRequired()
.HasMaxLength(10);
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Source")
.IsRequired()
.HasMaxLength(128);
b.Property<int?>("TenantId");
b.Property<string>("Value")
.IsRequired()
.HasMaxLength(67108864);
b.HasKey("Id");
b.HasIndex("TenantId", "Source", "LanguageName", "Key");
b.ToTable("AbpLanguageTexts");
});
modelBuilder.Entity("Abp.Notifications.NotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Data")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasMaxLength(250);
b.Property<string>("ExcludedUserIds")
.HasMaxLength(131072);
b.Property<string>("NotificationName")
.IsRequired()
.HasMaxLength(96);
b.Property<byte>("Severity");
b.Property<string>("TenantIds")
.HasMaxLength(131072);
b.Property<string>("UserIds")
.HasMaxLength(131072);
b.HasKey("Id");
b.ToTable("AbpNotifications");
});
modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("EntityId")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.HasMaxLength(96);
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId");
b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId");
b.ToTable("AbpNotificationSubscriptions");
});
modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Data")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.IsRequired()
.HasMaxLength(96);
b.Property<byte>("Severity");
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("TenantId");
b.ToTable("AbpTenantNotifications");
});
modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<int>("State");
b.Property<int?>("TenantId");
b.Property<Guid>("TenantNotificationId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId", "State", "CreationTime");
b.ToTable("AbpUserNotifications");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(95);
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(128);
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<long?>("ParentId");
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("ParentId");
b.HasIndex("TenantId", "Code");
b.ToTable("AbpOrganizationUnits");
});
modelBuilder.Entity("VOU.Authorization.Roles.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("Description")
.HasMaxLength(5000);
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(64);
b.Property<bool>("IsDefault");
b.Property<bool>("IsDeleted");
b.Property<bool>("IsStatic");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32);
b.Property<string>("NormalizedName")
.IsRequired()
.HasMaxLength(32);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedName");
b.ToTable("AbpRoles");
});
modelBuilder.Entity("VOU.Authorization.Users.User", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<string>("AuthenticationSource")
.HasMaxLength(64);
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("EmailAddress")
.IsRequired()
.HasMaxLength(256);
b.Property<string>("EmailConfirmationCode")
.HasMaxLength(328);
b.Property<bool>("IsActive");
b.Property<bool>("IsDeleted");
b.Property<bool>("IsEmailConfirmed");
b.Property<bool>("IsLockoutEnabled");
b.Property<bool>("IsPhoneNumberConfirmed");
b.Property<bool>("IsTwoFactorEnabled");
b.Property<DateTime?>("LastLoginTime");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<DateTime?>("LockoutEndDateUtc");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32);
b.Property<string>("NormalizedEmailAddress")
.IsRequired()
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.IsRequired()
.HasMaxLength(32);
b.Property<string>("Password")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("PasswordResetCode")
.HasMaxLength(328);
b.Property<string>("PhoneNumber");
b.Property<string>("SecurityStamp");
b.Property<string>("Surname")
.IsRequired()
.HasMaxLength(32);
b.Property<int?>("TenantId");
b.Property<string>("UserName")
.IsRequired()
.HasMaxLength(32);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedEmailAddress");
b.HasIndex("TenantId", "NormalizedUserName");
b.ToTable("AbpUsers");
});
modelBuilder.Entity("VOU.MultiTenancy.Tenant", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConnectionString")
.HasMaxLength(1024);
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<int?>("EditionId");
b.Property<bool>("IsActive");
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("TenancyName")
.IsRequired()
.HasMaxLength(64);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("EditionId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenancyName");
b.ToTable("AbpTenants");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.Property<int>("EditionId");
b.HasIndex("EditionId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("EditionFeatureSetting");
});
modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.Property<int>("TenantId");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("TenantFeatureSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<int>("RoleId");
b.HasIndex("RoleId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("RolePermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<long>("UserId");
b.HasIndex("UserId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("UserPermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.HasOne("VOU.Authorization.Roles.Role")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.HasOne("VOU.Authorization.Users.User")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.HasOne("VOU.Authorization.Users.User")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.HasOne("VOU.Authorization.Users.User")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.HasOne("VOU.Authorization.Users.User")
.WithMany("Tokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.HasOne("VOU.Authorization.Users.User")
.WithMany("Settings")
.HasForeignKey("UserId");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.HasOne("Abp.Organizations.OrganizationUnit", "Parent")
.WithMany("Children")
.HasForeignKey("ParentId");
});
modelBuilder.Entity("VOU.Authorization.Roles.Role", b =>
{
b.HasOne("VOU.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("VOU.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("VOU.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("VOU.Authorization.Users.User", b =>
{
b.HasOne("VOU.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("VOU.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("VOU.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("VOU.MultiTenancy.Tenant", b =>
{
b.HasOne("VOU.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("VOU.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId");
b.HasOne("VOU.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasOne("VOU.Authorization.Roles.Role")
.WithMany("Permissions")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasOne("VOU.Authorization.Users.User")
.WithMany("Permissions")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| 31.571429 | 117 | 0.437339 | [
"MIT"
] | BugBear96/VOU | aspnet-core/src/VOU.EntityFrameworkCore/Migrations/20170804083601_Upgraded_To_Abp_v2.2.2.Designer.cs | 34,920 | C# |
using Connect.DNN.Powershell.Core.Commands;
using Connect.DNN.Powershell.Framework.Models;
using System.Management.Automation;
namespace Connect.DNN.Powershell.Commands.TaskScheduler
{
[Cmdlet("List", "Tasks")]
public class ListTasks : DnnPromptPortalCmdLet
{
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)]
public bool? Enabled { get; set; }
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)]
public string TaskName { get; set; }
protected override void ProcessRecord()
{
base.ProcessRecord();
if (CmdSite == null || CmdPortal == null) { return; };
WriteVerbose(string.Format("list-tasks on {0} portal {1}", CmdSite.Url, CmdPortal.PortalId));
var response = TaskSchedulerCommands.ListTasks(CmdSite, CmdPortal.PortalId, Enabled, TaskName);
WriteArray(response);
}
}
}
| 36.423077 | 107 | 0.665259 | [
"MIT"
] | DNN-Connect/Dnn-Powershell | Connect.DNN.Powershell/Commands/TaskScheduler/ListTasks.cs | 949 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HPMSdk;
using Hansoft.ObjectWrapper.CustomColumnValues;
namespace Hansoft.ObjectWrapper
{
/// <summary>
/// Represents an item in the Product Backlog in Hansoft.
/// </summary>
public class ProductBacklogItem : Task
{
internal static ProductBacklogItem GetProductBacklogItem(HPMUniqueID uniqueID, HPMUniqueID uniqueTaskID)
{
return new ProductBacklogItem(uniqueID, uniqueTaskID);
}
/// <summary>
/// General constructor
/// </summary>
/// <param name="uniqueID">The TaskRef ID of the item</param>
/// <param name="uniqueTaskID">The Task ID of the item</param>
internal ProductBacklogItem(HPMUniqueID uniqueID, HPMUniqueID uniqueTaskID)
: base(uniqueID, uniqueTaskID)
{
}
/// <summary>
/// The project view that this product backlog item belongs to.
/// </summary>
public override ProjectView ProjectView
{
get
{
return Project.ProductBacklog;
}
}
/// <summary>
/// The assignment percentage of a particular user that is assigned to this product backlog item.
/// </summary>
/// <param name="user">The name of the user.</param>
/// <returns>The assignment percentage.</returns>
public int GetAssignmentPercentage(User user)
{
return TaskHelper.GetAssignmentPercentage(this, user);
}
/// <summary>
/// True if this product backlog item is assigned, False otherwise.
/// </summary>
public bool IsAssigned
{
get
{
return TaskHelper.IsAssigned(this);
}
}
/// <summary>
/// The sprint that this product backlog item is committed to (if any), or null.
/// </summary>
public Sprint CommittedToSprint
{
get
{
return TaskHelper.GetCommittedToSprint(this);
}
}
/// <summary>
/// The product backlog priority of this product backlog item.
/// </summary>
public override HansoftEnumValue Priority
{
get
{
return new HansoftEnumValue(MainProjectID, EHPMProjectDefaultColumn.BacklogPriority, Session.TaskGetBacklogPriority(UniqueTaskID), (int)Session.TaskGetBacklogPriority(UniqueTaskID));
}
set
{
if (Priority != value)
Session.TaskSetBacklogPriority(UniqueTaskID, (EHPMTaskAgilePriorityCategory)value.Value);
}
}
private int absolutePriority;
internal int AbsolutePriority
{
get
{
return absolutePriority;
}
set
{
absolutePriority = value;
}
}
/// <summary>
/// The aggregated status value over all children as it is displayed in the Hansoft client
/// </summary>
public override HansoftEnumValue AggregatedStatus
{
get
{
HPMUniqueID proxyID = Session.TaskGetProxy(UniqueTaskID);
if (proxyID.m_ID != -1 && proxyID.m_ID != UniqueID.m_ID)
{
// This is a bit of a hack to compensate for that TaskRefSummary in the SDK does not account
// for if a product backlog item is committed to the schedule and roken down there.
Task proxy = Task.GetTask(proxyID);
return proxy.AggregatedStatus;
}
else
return base.AggregatedStatus;
}
}
/// <summary>
/// The aggregated points value over all children as it is displayed in the Hansoft client
/// </summary>
public override int AggregatedPoints
{
get
{
HPMUniqueID proxyID = Session.TaskGetProxy(UniqueTaskID);
if (proxyID.m_ID == this.UniqueID.m_ID) // This is an item in the schedule and we will use the base implementation
return base.AggregatedPoints;
else if (proxyID.m_ID != -1) // If it is an item in the product backlog with a proxy we use the proxies summary, hence ignoring breakdown of committed items in the PBL
return Task.GetTask(proxyID).AggregatedPoints;
else if (!HasChildren) // It is a leaf
return base.AggregatedPoints;
else // It is a parent item which is not committed and hence we will iterate over the children.
{
int aggregatedPoints = 0;
foreach (ProductBacklogItem item in DeepLeaves)
{
proxyID = Session.TaskGetProxy(item.UniqueTaskID);
if (proxyID.m_ID != -1)
aggregatedPoints += Task.GetTask(proxyID).AggregatedPoints;
else
aggregatedPoints += item.Points;
}
return aggregatedPoints;
}
}
}
/// <summary>
/// The aggregated work remaining value over all children as it is displayed in the Hansoft client
/// </summary>
public override double AggregatedWorkRemaining
{
get
{
HPMUniqueID proxyID = Session.TaskGetProxy(UniqueTaskID);
if (proxyID.m_ID == this.UniqueID.m_ID) // This is an item in the schedule and we will use the base implementation
return base.AggregatedWorkRemaining;
else if (proxyID.m_ID != -1) // If it is an item in the product backlog with a proxy we use the proxies summary, hence ignoring breakdown of committed items in the PBL
return Task.GetTask(proxyID).AggregatedWorkRemaining;
else if (!HasChildren) // It is a leaf
return base.AggregatedWorkRemaining;
else // It is a parent item which is not committed and hence we will iterate over the children.
{
double aggregatedWorkRemaining = 0;
foreach (ProductBacklogItem item in DeepLeaves)
{
proxyID = Session.TaskGetProxy(item.UniqueTaskID);
if (proxyID.m_ID != -1)
aggregatedWorkRemaining += Task.GetTask(proxyID).AggregatedWorkRemaining;
else
{
if (!double.IsInfinity(item.WorkRemaining))
aggregatedWorkRemaining += item.WorkRemaining;
}
}
return aggregatedWorkRemaining;
}
}
}
/// <summary>
/// The aggregated estimated days value over all children as it is displayed in the Hansoft client
/// </summary>
public override double AggregatedEstimatedDays
{
get
{
HPMUniqueID proxyID = Session.TaskGetProxy(UniqueTaskID);
if (proxyID.m_ID == this.UniqueID.m_ID) // This is an item in the schedule and we will use the base implementation
return base.AggregatedEstimatedDays;
else if (proxyID.m_ID != -1) // If it is an item in the product backlog with a proxy we use the proxies summary, hence ignoring breakdown of committed items in the PBL
return Task.GetTask(proxyID).AggregatedEstimatedDays;
else if (!HasChildren) // It is a leaf
return base.AggregatedEstimatedDays;
else // It is a parent item which is not committed and hence we will iterate over the children.
{
double aggregatedEstimatedDays = 0;
foreach (ProductBacklogItem item in DeepLeaves)
{
proxyID = Session.TaskGetProxy(item.UniqueTaskID);
if (proxyID.m_ID != -1)
aggregatedEstimatedDays += Task.GetTask(proxyID).AggregatedEstimatedDays;
else
aggregatedEstimatedDays += item.EstimatedDays;
}
return aggregatedEstimatedDays;
}
}
}
internal override CustomColumnValue GetAggregatedCustomColumnValue(HPMProjectCustomColumnsColumn customColumn)
{
HPMUniqueID proxyID = Session.TaskGetProxy(UniqueTaskID);
if (proxyID.m_ID == this.UniqueID.m_ID) // This is an item in the schedule and we will use the base implementation
return base.GetAggregatedCustomColumnValue(customColumn);
else if (proxyID.m_ID != -1) // If it is an item in the product backlog with a proxy we use the proxies summary, hence ignoring breakdown of committed items in the PBL
return Task.GetTask(proxyID).GetAggregatedCustomColumnValue(customColumn);
else if (!HasChildren) // It is a leaf
return base.GetAggregatedCustomColumnValue(customColumn);
else // It is a parent item which is not committed and hence we will iterate over the children.
{
if (customColumn.m_Type == EHPMProjectCustomColumnsColumnType.IntegerNumber)
{
long aggregatedInt = 0;
foreach (ProductBacklogItem item in DeepLeaves)
{
proxyID = Session.TaskGetProxy(item.UniqueTaskID);
if (proxyID.m_ID != -1)
aggregatedInt += Task.GetTask(proxyID).GetAggregatedCustomColumnValue(customColumn).ToInt();
else
aggregatedInt += item.GetCustomColumnValue(customColumn).ToInt();
}
return IntegerNumberValue.FromInteger(this, customColumn, aggregatedInt);
}
else if (customColumn.m_Type == EHPMProjectCustomColumnsColumnType.FloatNumber)
{
double aggregatedFloat = 0;
foreach (ProductBacklogItem item in DeepLeaves)
{
proxyID = Session.TaskGetProxy(item.UniqueTaskID);
if (proxyID.m_ID != -1)
aggregatedFloat += Task.GetTask(proxyID).GetAggregatedCustomColumnValue(customColumn).ToDouble();
else
aggregatedFloat += item.GetCustomColumnValue(customColumn).ToDouble();
}
return FloatNumberValue.FromFloat(this, customColumn, aggregatedFloat);
}
else
{
double aggregatedTime = 0;
foreach (ProductBacklogItem item in DeepLeaves)
{
proxyID = Session.TaskGetProxy(item.UniqueTaskID);
if (proxyID.m_ID != -1)
aggregatedTime += Task.GetTask(proxyID).GetAggregatedCustomColumnValue(customColumn).ToDouble();
else
aggregatedTime += item.GetCustomColumnValue(customColumn).ToDouble();
}
return AccumulatedTimeValue.FromFloat(this, customColumn, aggregatedTime);
}
}
}
}
}
| 43.871324 | 198 | 0.545378 | [
"MIT"
] | Hansoft/Hansoft-ObjectWrapper | ProductBacklogItem.cs | 11,935 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace NR.RTS.Units
{
public class UnitStats : ScriptableObject
{
[System.Serializable]
public class Base
{
public enum UnitPopulationType
{
TierOne,
TierTwo
}
public int cost;
public UnitPopulationType populationType;
public int armor;
public int defence;
public float health;
public float speed;
public float range;
public bool canRepair;
public bool canWork;
[Space(15)]
[Header("Unit Melee Stats")]
public float meleeAttack;
public int meleeArmorPiercing;
[Space(15)]
[Header("Unit Ranged Stats")]
public float rangedAttack;
public int rangedArmorPiercing;
public int precission;
public float shootingSpeed;
[Space(15)]
[Header("Unit Audio Effects")]
public AudioClip[] firingSounds;
public AudioClip[] fightingSounds;
public AudioClip[] damagedSounds;
public AudioClip[] selectionSounds;
public AudioClip[] orderSounds;
public AudioClip[] workingSounds;
}
}
}
| 26.711538 | 53 | 0.545716 | [
"MIT"
] | Nikolar1/Seminarski_rad_C_RTS_Igra | RTS/Assets/_Scripts/Units/UnitStats.cs | 1,389 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using Amazon.S3;
using DocumentsApi.V1.Boundary.Request;
using DocumentsApi.V1.Boundary.Response.Exceptions;
using DocumentsApi.V1.UseCase.Interfaces;
using Microsoft.AspNetCore.Mvc;
namespace DocumentsApi.V1.Controllers
{
[ApiController]
[Route("api/v1/documents")]
[Produces("application/json")]
[ApiVersion("1.0")]
public class DocumentsController : BaseController
{
private readonly IUploadDocumentUseCase _uploadDocumentUseCase;
private readonly IDownloadDocumentUseCase _downloadDocumentUseCase;
public DocumentsController(
IUploadDocumentUseCase uploadDocumentUseCase,
IDownloadDocumentUseCase downloadDocumentUseCase)
{
_uploadDocumentUseCase = uploadDocumentUseCase;
_downloadDocumentUseCase = downloadDocumentUseCase;
}
/// <summary>
/// Uploads the document to S3
/// </summary>
/// <response code="200">Uploaded</response>
/// <response code="400">Request contains invalid parameters</response>
/// <response code="401">Request lacks valid API token</response>
/// <response code="500">Amazon S3 exception</response>
/// <response code="500">Document upload exception</response>
[HttpPost]
[Route("{id}")]
public IActionResult UploadDocument([FromRoute][Required] Guid id, [FromBody][Required] DocumentUploadRequest request)
{
try
{
_uploadDocumentUseCase.Execute(id, request);
return Ok();
}
catch (NotFoundException ex)
{
return NotFound(ex.Message);
}
catch (BadRequestException ex)
{
return BadRequest(ex.Message);
}
catch (AmazonS3Exception e)
{
return StatusCode(500, e.Message);
}
catch (DocumentUploadException e)
{
return StatusCode(500, e.Message);
}
}
/// <summary>
/// Retrieves the document in base64 representation
/// </summary>
/// <response code="200">Found</response>
/// <response code="400">Request contains invalid parameters</response>
/// <response code="401">Request lacks valid API token</response>
/// <response code="500">Amazon S3 exception</response>
[HttpGet]
[Route("{documentId}")]
[Produces("application/json")]
public IActionResult GetDocument([FromRoute] Guid documentId)
{
try
{
var result = _downloadDocumentUseCase.Execute(documentId);
return Ok(result);
}
catch (NotFoundException ex)
{
return NotFound(ex.Message);
}
catch (AmazonS3Exception e)
{
return StatusCode(500, e.Message);
}
}
}
}
| 33.456522 | 126 | 0.581871 | [
"MIT"
] | LBHackney-IT/documents-api | DocumentsApi/V1/Controllers/DocumentsController.cs | 3,078 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Spreadsheet.Core;
using Spreadsheet.Core.Cells;
using Spreadsheet.Core.Cells.Expressions;
using Spreadsheet.Core.Parsers;
using Spreadsheet.Core.Parsers.Operators;
using Spreadsheet.Core.Parsers.Tokenizers;
using Spreadsheet.Core.Utils;
using Spreadsheet.Tests.Mocks;
using static Spreadsheet.Tests.Utils.TestExtensions;
namespace Spreadsheet.Tests
{
[TestFixture]
public class SpreadsheetStreamParserTests
{
private IEnumerable<IExpression> GetExpressions(params Token[] tokens)
{
var parser = new SpreadsheetStreamParser(new SpreadsheetTokenizerMock(tokens));
IExpression expression;
do
{
expression = parser.ReadExpression();
if (expression != null)
yield return expression;
} while (expression != null);
}
private object Parse(params Token[] tokens)
{
//TODO: not optimal, may need optimization in future
var list = tokens.ToList();
list.Add(new Token(TokenType.EndOfStream));
return GetExpressions(list.ToArray()).SingleOrDefault();
}
private T Parse<T>(params Token[] tokens)
{
return Cast<T>(Parse(tokens));
}
[Test]
public void TestEmptyCell()
{
var expression = Parse<ConstantExpression>(new Token(TokenType.EndOfCell));
Assert.IsNull(expression.Value);
}
[Test]
public void TestNothing()
{
Assert.IsNull(Parse());
}
[Test]
public void WorngContentNotSeparatorErrorTest()
{
Assert.That(() => Parse(new Token(1), new Token(2)), Throws.ArgumentNullException);
}
[Test]
public void WorngContentUnexpectedTokenErrorTest()
{
Assert.That(() => Parse(new Token(TokenType.RightParenthesis)), Throws.ArgumentNullException);
}
[Test]
public void WorngExpressionTest()
{
Assert.That(() => Parse(new Token(TokenType.ExpressionStart),
new Token(45),
new Token(TokenType.LeftParenthesis)), Throws.ArgumentNullException);
}
[Test]
public void WorngExpressionNoCloseParentsisTest()
{
Assert.That(() => Parse(new Token(TokenType.ExpressionStart),
new Token(TokenType.LeftParenthesis),
new Token(63)), Throws.ArgumentNullException);
}
[Test]
public void WorngExpressionUnknownTokenTest()
{
Assert.That(() => Parse(new Token(TokenType.ExpressionStart),
new Token(83),
new Token(TokenType.ExpressionStart)), Throws.ArgumentNullException);
}
[Test]
[TestCase(123)]
[TestCase(3712496)]
[TestCase(-780)]
public void TestInteger(int value)
{
Assert.AreEqual(value, Parse<ConstantExpression>(new Token(value)).Value);
}
[Test]
[TestCase("test1 string")]
[TestCase("'+test2")]
[TestCase("12+test3")]
public void TestStringValue(string expect)
{
Assert.AreEqual(expect, Parse<ConstantExpression>(new Token($"{expect}")).Value);
}
[Test]
[TestCase("A13")]
[TestCase("BVC197")]
public void TestExpressionReference(string expect)
{
var expression = Parse<CellRefereceExpression>(
new Token(TokenType.ExpressionStart),
new Token(CellAddressConverter.FromString(expect)));
Assert.AreEqual(expect, expression.Address.ToString());
}
[Test]
[TestCase('+')]
[TestCase('-')]
public void UnaryOperationTest(char character)
{
var @operator = OperatorManager.Default.Operators[character];
var expression = Parse<UnaryExpression>(
new Token(TokenType.ExpressionStart),
new Token(@operator),
new Token(38));
Assert.AreEqual(38, expression.Value.Evaluate(null));
Assert.AreEqual(@operator, expression.Operation);
}
[Test]
public void BinaryExpressionPriorityTest()
{
//=197-98/3");
var expression = Parse<BinaryExpression>(
new Token(TokenType.ExpressionStart),
new Token(197),
new Token(OperatorManager.Default.Operators['-']),
new Token(98),
new Token(OperatorManager.Default.Operators['/']),
new Token(3));
Assert.AreEqual(197, Cast<ConstantExpression>(expression.Left).Value);
Assert.AreEqual('-', expression.Operation.OperatorCharacter);
var right = Cast<BinaryExpression>(expression.Right);
Assert.AreEqual(98, Cast<ConstantExpression>(right.Left).Value);
Assert.AreEqual('/', right.Operation.OperatorCharacter);
Assert.AreEqual(3, Cast<ConstantExpression>(right.Right).Value);
}
[Test]
public void ParantsisTest()
{
//=18/(3-1);
var expression = Parse<BinaryExpression>(
new Token(TokenType.ExpressionStart),
new Token(18),
new Token(OperatorManager.Default.Operators['/']),
new Token(TokenType.LeftParenthesis),
new Token(3),
new Token(OperatorManager.Default.Operators['-']),
new Token(1),
new Token(TokenType.RightParenthesis));
Assert.AreEqual(18, Cast<ConstantExpression>(expression.Left).Value);
Assert.AreEqual('/', expression.Operation.OperatorCharacter);
var right = Cast<BinaryExpression>(expression.Right);
Assert.AreEqual(3, Cast<ConstantExpression>(right.Left).Value);
Assert.AreEqual('-', right.Operation.OperatorCharacter);
Assert.AreEqual(1, Cast<ConstantExpression>(right.Right).Value);
}
}
}
| 34.28022 | 97 | 0.593204 | [
"MIT"
] | AndreyTretyak/SpreadsheetSimulator | Spreadsheet.Tests/SpreadsheetStreamParserTests.cs | 6,241 | C# |
// <copyright file="PrompDialogRichTextBoxUserControl.xaml.cs" company="CodePlex">
// https://testcasemanager.codeplex.com/ All rights reserved.
// </copyright>
// <author>Anton Angelov</author>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using FirstFloor.ModernUI.Windows;
using FirstFloor.ModernUI.Windows.Controls;
using TestCaseManagerCore;
using TestCaseManagerCore.BusinessLogic.Managers;
using TestCaseManagerCore.ViewModels;
namespace TestCaseManagerApp.Views
{
/// <summary>
/// Contains logic related to the shared step name prompt dialog
/// </summary>
public partial class PrompDialogRichTextBoxUserControl : UserControl
{
/// <summary>
/// Initializes a new instance of the <see cref="PrompDialogRichTextBoxUserControl"/> class.
/// </summary>
public PrompDialogRichTextBoxUserControl()
{
this.InitializeComponent();
}
/// <summary>
/// Gets or sets the prompt dialog view model.
/// </summary>
/// <value>
/// The prompt dialog view model.
/// </value>
public PromptDialogViewModel PromptDialogViewModel { get; set; }
/// <summary>
/// Handles the Loaded event of the UserControl control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
RegistryManager.WriteIsWindowClosedFromX(true);
this.PromptDialogViewModel = new PromptDialogViewModel();
this.DataContext = this.PromptDialogViewModel;
}
/// <summary>
/// Handles the Click event of the ButtonOk control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
private void ButtonOk_Click(object sender, RoutedEventArgs e)
{
PromptDialogViewModel.IsCanceled = false;
RegistryManager.WriteIsWindowClosedFromX(false);
Window window = Window.GetWindow(this);
window.Close();
}
/// <summary>
/// Handles the Click event of the btnCancel control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
PromptDialogViewModel.IsCanceled = true;
RegistryManager.WriteIsWindowClosedFromX(false);
PromptDialogViewModel.Content = string.Empty;
Window window = Window.GetWindow(this);
window.Close();
}
/// <summary>
/// Handles the KeyUp event of the rtbComment control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="KeyEventArgs"/> instance containing the event data.</param>
private void rtbComment_KeyUp(object sender, KeyEventArgs e)
{
this.PromptDialogViewModel.Content = rtbComment.GetText();
if (!string.IsNullOrEmpty(this.PromptDialogViewModel.Content) && !string.IsNullOrWhiteSpace(this.PromptDialogViewModel.Content) && this.PromptDialogViewModel.Content != Environment.NewLine.ToString())
{
btnOk.IsEnabled = true;
}
else
{
btnOk.IsEnabled = false;
}
}
}
} | 38.838095 | 212 | 0.642962 | [
"Apache-2.0"
] | FrancielleWN/AutomateThePlanet-Learning-Series | TestCaseManager/TestCaseManager/Views/PrompDialogRichTextBoxUserControl.xaml.cs | 4,080 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.ComponentModel;
using System.Threading;
using System.Web.Script.Serialization;
using System.Collections;
using Microsoft.Silverlight.Testing;
namespace PubNub_Messaging
{
[TestClass]
public class WhenGetRequestServerTime : SilverlightTest
{
bool isTimeStamp = false;
bool timeReceived = false;
[TestMethod]
[Asynchronous]
public void ThenItShouldReturnTimeStamp()
{
Pubnub pubnub = new Pubnub("demo", "demo", "", "", false);
EnqueueCallback(() => pubnub.time<string>(ReturnTimeStampCallback));
EnqueueConditional(() => isTimeStamp);
EnqueueCallback(() => Assert.IsTrue(timeReceived, "time() Failed"));
EnqueueTestComplete();
}
[Asynchronous]
private void ReturnTimeStampCallback(string result)
{
if (!string.IsNullOrWhiteSpace(result))
{
JavaScriptSerializer js = new JavaScriptSerializer();
IList receivedObj = (IList)js.DeserializeObject(result);
if (receivedObj is object[])
{
string time = receivedObj[0].ToString();
if (time.Length > 0)
{
timeReceived = true;
}
}
}
isTimeStamp = true;
}
[TestMethod]
public void TranslateDateTimeToUnixTime()
{
//Test for 26th June 2012 GMT
DateTime dt = new DateTime(2012,6,26,0,0,0,DateTimeKind.Utc);
long nanosecTime = Pubnub.translateDateTimeToPubnubUnixNanoSeconds(dt);
Assert.AreEqual<long>(13406688000000000, nanosecTime);
}
[TestMethod]
public void TranslateUnixTimeToDateTime()
{
//Test for 26th June 2012 GMT
DateTime expectedDt = new DateTime(2012, 6, 26, 0, 0, 0, DateTimeKind.Utc);
DateTime actualDt = Pubnub.translatePubnubUnixNanoSecondsToDateTime(13406688000000000);
Assert.AreEqual<DateTime>(expectedDt, actualDt);
}
}
}
| 32.728571 | 99 | 0.593191 | [
"MIT"
] | drubin/c-sharp | silverlight/3.3.0.1/PubnubSilverlight.Example/UnitTest/WhenGetRequestServerTime.cs | 2,293 | C# |
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace CompeTournament.Backend.Migrations
{
public partial class InitIdentity : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
Name = table.Column<string>(maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
UserName = table.Column<string>(maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
Email = table.Column<string>(maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
PasswordHash = table.Column<string>(nullable: true),
SecurityStamp = table.Column<string>(nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
TwoFactorEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
LockoutEnabled = table.Column<bool>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false),
Name = table.Column<string>(maxLength: 50, nullable: false),
Lastname = table.Column<string>(maxLength: 50, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
RoleId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(nullable: false),
ProviderKey = table.Column<string>(nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
LoginProvider = table.Column<string>(nullable: false),
Name = table.Column<string>(nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true,
filter: "[NormalizedName] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true,
filter: "[NormalizedUserName] IS NOT NULL");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}
| 43.152466 | 122 | 0.497974 | [
"MIT"
] | 132329/TorneoPredicciones | CompeTournament.Backend/Migrations/20190623194523_InitIdentity.cs | 9,625 | C# |
using Microsoft.IdentityModel.Tokens;
using System.Security.Cryptography;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ON.Crypto
{
public static class JwkExtension
{
public static JsonWebKey DecodeJsonWebKey(this string encodedJWK)
{
return new JsonWebKey(Base64UrlEncoder.Decode(encodedJWK));
}
public static string ToPrivateEncodedJsonWebKey(this ECDsa eckey)
{
var parameters = eckey.ExportParameters(true);
var jwk = new JsonWebKey()
{
Kty = JsonWebAlgorithmsKeyTypes.EllipticCurve,
Use = "sig",
X = Base64UrlEncoder.Encode(parameters.Q.X),
Y = Base64UrlEncoder.Encode(parameters.Q.Y),
D = Base64UrlEncoder.Encode(parameters.D),
Crv = JsonWebKeyECTypes.P256,
Alg = "ES256"
};
return Base64UrlEncoder.Encode(System.Text.Json.JsonSerializer.Serialize(jwk));
}
public static string ToPublicEncodedJsonWebKey(this ECDsa eckey)
{
var parameters = eckey.ExportParameters(false);
var jwk = new JsonWebKey()
{
Kty = JsonWebAlgorithmsKeyTypes.EllipticCurve,
Use = "sig",
X = Base64UrlEncoder.Encode(parameters.Q.X),
Y = Base64UrlEncoder.Encode(parameters.Q.Y),
Crv = JsonWebKeyECTypes.P256,
Alg = "ES256"
};
return Base64UrlEncoder.Encode(System.Text.Json.JsonSerializer.Serialize(jwk));
}
}
}
| 31.518519 | 91 | 0.594595 | [
"MIT"
] | NodeFederation/NodeInstall | src/ON.Crypto/ON.Crypto/JwkExtension.cs | 1,704 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Microsoft.Extensions.DependencyModel
{
public class DependencyContext
{
private static readonly Lazy<DependencyContext> _defaultContext = new Lazy<DependencyContext>(LoadDefault);
public DependencyContext(TargetInfo target,
CompilationOptions compilationOptions,
IEnumerable<CompilationLibrary> compileLibraries,
IEnumerable<RuntimeLibrary> runtimeLibraries,
IEnumerable<RuntimeFallbacks> runtimeGraph)
{
if (target == null)
{
throw new ArgumentNullException(nameof(target));
}
if (compilationOptions == null)
{
throw new ArgumentNullException(nameof(compilationOptions));
}
if (compileLibraries == null)
{
throw new ArgumentNullException(nameof(compileLibraries));
}
if (runtimeLibraries == null)
{
throw new ArgumentNullException(nameof(runtimeLibraries));
}
if (runtimeGraph == null)
{
throw new ArgumentNullException(nameof(runtimeGraph));
}
Target = target;
CompilationOptions = compilationOptions;
CompileLibraries = compileLibraries.ToArray();
RuntimeLibraries = runtimeLibraries.ToArray();
RuntimeGraph = runtimeGraph.ToArray();
}
public static DependencyContext Default => _defaultContext.Value;
public TargetInfo Target { get; }
public CompilationOptions CompilationOptions { get; }
public IReadOnlyList<CompilationLibrary> CompileLibraries { get; }
public IReadOnlyList<RuntimeLibrary> RuntimeLibraries { get; }
public IReadOnlyList<RuntimeFallbacks> RuntimeGraph { get; }
public DependencyContext Merge(DependencyContext other)
{
if (other == null)
{
throw new ArgumentNullException(nameof(other));
}
return new DependencyContext(
Target,
CompilationOptions,
CompileLibraries.Union(other.CompileLibraries, new LibraryMergeEqualityComparer<CompilationLibrary>()),
RuntimeLibraries.Union(other.RuntimeLibraries, new LibraryMergeEqualityComparer<RuntimeLibrary>()),
RuntimeGraph.Union(other.RuntimeGraph)
);
}
private static DependencyContext LoadDefault()
{
return DependencyContextLoader.Default.Load(Assembly.GetEntryAssembly());
}
public static DependencyContext Load(Assembly assembly)
{
return DependencyContextLoader.Default.Load(assembly);
}
private class LibraryMergeEqualityComparer<T> : IEqualityComparer<T> where T : Library
{
public bool Equals(T x, T y)
{
return string.Equals(x.Name, y.Name, StringComparison.Ordinal);
}
public int GetHashCode(T obj)
{
return obj.Name.GetHashCode();
}
}
}
}
| 34.188119 | 119 | 0.611932 | [
"MIT"
] | joshfree/cli | src/Microsoft.Extensions.DependencyModel/DependencyContext.cs | 3,455 | C# |
using Castle.DynamicProxy;
using Nito.AsyncEx;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Jose;
using Newtonsoft.Json;
namespace Domain0.Api.Client
{
internal class TokenChangeManager : IDisposable
{
public TokenChangeManager(AuthenticationContext authContext, ILoginInfoStorage storage)
{
domain0AuthenticationContext = authContext;
loginInfoStorage = storage;
if (domain0AuthenticationContext.AutoRefreshEnabled)
refreshTokenTimer = new RefreshTokenTimer(authContext);
}
public event Action<AccessTokenResponse> AccessTokenChanged;
internal TClient AttachClientEnvironment<TClient>(IClientScope<TClient> scope)
where TClient : class
{
using (tokenChangeLock.WriterLock())
{
attachedClients.Add(
new WeakReference<ITokenStore>(scope));
scope.Token = loginInfo?.AccessToken;
var proxyClient = new ProxyGenerator()
.CreateInterfaceProxyWithTargetInterface(
scope.Client,
new RefreshTokenInterceptor(domain0AuthenticationContext, scope));
return proxyClient;
}
}
internal bool DetachClientEnvironment<TClient>(IClientScope<TClient> clientEnvironment)
where TClient : class
{
return RemoveTokenStore(clientEnvironment);
}
internal void AttachTokenStore(ITokenStore tokenStore)
{
using (tokenChangeLock.WriterLock())
{
attachedClients.Add(
new WeakReference<ITokenStore>(tokenStore));
tokenStore.Token = loginInfo?.AccessToken;
}
}
internal bool DetachTokenStore(ITokenStore tokenStore)
{
return RemoveTokenStore(tokenStore);
}
private bool shouldRemember;
public bool ShouldRemember
{
get
{
using (tokenChangeLock.ReaderLock())
{
return shouldRemember;
}
}
set
{
using (tokenChangeLock.WriterLock())
{
shouldRemember = value;
loginInfoStorage.Delete();
}
}
}
private DateTime? accessTokenValidTo;
private DateTime? refreshTokenValidTo;
private HashSet<string> permissions;
public bool IsLoggedIn
{
get
{
using (tokenChangeLock.ReaderLock())
{
return CheckIsLoggedIsLoggedIn();
}
}
}
internal AccessTokenResponse GetSuitableToUpdateLoginInfo()
{
using (tokenChangeLock.ReaderLock())
{
if (loginInfo?.RefreshToken == null)
return null;
// no need refresh
if (accessTokenValidTo >= DateTime.UtcNow.AddSeconds(domain0AuthenticationContext.ReserveTimeToUpdate))
return null;
// can't refresh
if (refreshTokenValidTo?.AddSeconds(domain0AuthenticationContext.ReserveTimeToUpdate) <= DateTime.UtcNow)
return null;
return loginInfo;
}
}
internal bool HavePermissions(IEnumerable<string> permissionsToCheck)
{
using (tokenChangeLock.ReaderLock())
{
if (!CheckIsLoggedIsLoggedIn())
{
throw new AuthenticationContextException("not logged in");
}
return permissionsToCheck.All(p => permissions?.Contains(p) == true);
}
}
internal bool HavePermission(string permissionToCheck)
{
using (tokenChangeLock.ReaderLock())
{
if (!CheckIsLoggedIsLoggedIn())
{
throw new AuthenticationContextException("not logged in");
}
return permissions?.Contains(permissionToCheck) == true;
}
}
private AccessTokenResponse loginInfo;
internal AccessTokenResponse LoginInfo
{
get
{
using (tokenChangeLock.ReaderLock())
{
return loginInfo;
}
}
set
{
using (tokenChangeLock.WriterLock())
{
loginInfo = value;
if (loginInfo != null)
{
ReadTokenData();
SetToken();
if (shouldRemember)
loginInfoStorage.Save(loginInfo);
}
else
{
ReadTokenData();
SetToken();
loginInfoStorage.Delete();
}
if (domain0AuthenticationContext.AutoRefreshEnabled)
{
refreshTokenTimer.NextRefreshTime =
accessTokenValidTo?.AddSeconds(-domain0AuthenticationContext.ReserveTimeToUpdate);
}
}
AccessTokenChanged?.Invoke(value);
}
}
internal void RestoreLoginInfo()
{
var value = loginInfoStorage.Load();
using (tokenChangeLock.WriterLock())
{
loginInfo = value;
ReadTokenData();
SetToken();
}
AccessTokenChanged?.Invoke(value);
}
private void SetToken()
{
var token = loginInfo?.AccessToken;
domain0AuthenticationContext.Domain0Scope.Token = token;
var aliveClients = GetAliveAttachedClients();
foreach (var client in aliveClients)
{
try
{
client.Token = token;
}
catch (Exception ex)
{
Trace.TraceError($"Could not setToken for { client.GetType() } error: { ex }");
}
}
}
private ITokenStore[] GetAliveAttachedClients()
{
if (!attachedClients.Any())
return new ITokenStore[0];
var aliveClients = new List<ITokenStore>();
var toRemoveClients = new List<WeakReference<ITokenStore>>();
foreach (var c in attachedClients)
{
if (c.TryGetTarget(out ITokenStore client))
{
aliveClients.Add(client);
}
else
{
toRemoveClients.Add(c);
}
}
foreach (var r in toRemoveClients)
{
attachedClients.Remove(r);
}
return aliveClients.ToArray();
}
private bool RemoveTokenStore(ITokenStore tokenStore)
{
using (tokenChangeLock.WriterLock())
{
var toDelete = attachedClients.FirstOrDefault(wc =>
{
if (wc.TryGetTarget(out ITokenStore client))
{
if (client == tokenStore)
return true;
}
return false;
});
if (toDelete == null)
return false;
return attachedClients.Remove(toDelete);
}
}
internal class TokenPrams
{
public long? Exp { get; set; }
public string Permissions { get; set; }
public DateTime? ValidTo
{
get
{
if (Exp.HasValue)
{
return UnixTimeStampToDateTime(Exp.Value);
}
return null;
}
}
public HashSet<string> PermissionSet
{
get
{
return new HashSet<string>(
string.IsNullOrWhiteSpace(Permissions)
? Enumerable.Empty<string>()
: JsonConvert.DeserializeObject<IEnumerable<string>>(Permissions));
}
}
public static DateTime UnixTimeStampToDateTime(long unixTimeStamp)
{
var dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
return dtDateTime.AddSeconds(unixTimeStamp);
}
}
private void ReadTokenData()
{
if (loginInfo != null)
{
var accessTokenInfo = JsonConvert.DeserializeObject<TokenPrams>(
JWT.Payload(loginInfo.AccessToken));
accessTokenValidTo = accessTokenInfo.ValidTo;
permissions = accessTokenInfo.PermissionSet;
var refreshTokenInfo = JsonConvert.DeserializeObject<TokenPrams>(
JWT.Payload(loginInfo.RefreshToken));
refreshTokenValidTo = refreshTokenInfo.ValidTo;
}
else
{
accessTokenValidTo = null;
refreshTokenValidTo = null;
permissions = null;
}
}
private bool CheckIsLoggedIsLoggedIn()
{
if (loginInfo == null)
return false;
if (accessTokenValidTo > DateTime.UtcNow.AddSeconds(domain0AuthenticationContext.ReserveTimeToUpdate))
return true;
if (refreshTokenValidTo > DateTime.UtcNow.AddSeconds(domain0AuthenticationContext.ReserveTimeToUpdate))
return true;
return false;
}
public void Dispose()
{
refreshTokenTimer?.Dispose();
AccessTokenChanged = null;
}
private readonly List<WeakReference<ITokenStore>> attachedClients = new List<WeakReference<ITokenStore>>();
private readonly AuthenticationContext domain0AuthenticationContext;
private readonly ILoginInfoStorage loginInfoStorage;
private readonly RefreshTokenTimer refreshTokenTimer;
private readonly AsyncReaderWriterLock tokenChangeLock = new AsyncReaderWriterLock();
}
} | 30.512676 | 121 | 0.497784 | [
"MIT"
] | LavrentyAfanasiev/domain0 | src/Domain0.Client.AuthContext/TokenChangeManager.cs | 10,832 | C# |
using MingweiSamuel.TokenBucket;
using System;
namespace Camille.RiotGames.Util
{
public delegate ITokenBucket TokenBucketFactory(TimeSpan timeSpan, int totalLimit, float concurrentInstanceFactor, float overheadFactor);
}
| 28.5 | 141 | 0.833333 | [
"Apache-2.0",
"MIT-0",
"MIT"
] | MingweiSamuel/Camille | Camille.RiotGames/src/Util/TokenBucketFactory.cs | 230 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EnhanceNav : MonoBehaviour
{
[SerializeField]
Scrollbar scroll;
[SerializeField]
Button[] auraInvent; // Includes all auras
Button[] unlockedAuraInvent; // Filtered aura select buttons so only can navigate through unlocked auras
[SerializeField]
RectTransform auraList;
int selectedBtn; // Selected btn index to navigate the filtered aura select buttons
int selectedAuraNumber; // Same as aura.auraNumber, used to determine which aura to enhance
[SerializeField]
Sprite selectedSprite;
[SerializeField]
Sprite unselectedSprite;
bool axisDown; // To treat axis input as key down
[SerializeField]
EnhanceManager enhanceManager;
public int SelectedBtn { get { return selectedBtn; } }
// Start is called before the first frame update
void Start()
{
// Get size of unlocked
int count = 0;
foreach (Button b in auraInvent)
{
if (b.gameObject.activeInHierarchy)
{
count++;
}
}
// Add unlocked auras to unlockedAuraInvent
unlockedAuraInvent = new Button[count];
int index = 0;
foreach (Button b in auraInvent)
{
if (b.gameObject.activeInHierarchy)
{
unlockedAuraInvent[index] = b;
index++;
}
}
// Adjust the size of aura list so it scrolls when there are enough unlocked auras
// 5 auras can be displayed without scrolling so with more than 5 auras, increase aura list size so that navigating through auras scrolls
// Otherwise, will not increase aura list size and leave the aura list with no scrolling
int extraAuras = unlockedAuraInvent.Length - 5;
if (extraAuras > 0)
{
float extraSpace = extraAuras == 1 ? 40 : 45;
auraList.anchoredPosition = new Vector2(auraList.anchoredPosition.x, auraList.anchoredPosition.y - extraSpace);
auraList.sizeDelta = new Vector2(auraList.sizeDelta.x, auraList.sizeDelta.y + extraSpace);
extraAuras--;
}
while (extraAuras > 0)
{
auraList.anchoredPosition = new Vector2(auraList.anchoredPosition.x, auraList.anchoredPosition.y - 36f);
auraList.sizeDelta = new Vector2(auraList.sizeDelta.x, auraList.sizeDelta.y + 36);
extraAuras--;
}
NavAuras(0, 0);
}
// Update is called once per frame
void Update()
{
// Do not allow input while leaving scene
if (enhanceManager.IsLeaving)
{
return;
}
if (Input.GetKeyDown(ControlsManager.ControlInstance.Keybinds["DownButton"]) || Input.GetAxisRaw("Vertical") == -1)
{
if (!axisDown)
{
axisDown = true;
NavAuras(selectedBtn, selectedBtn + 1);
SoundManager.SoundInstance.PlaySound("ButtonNav");
}
}
else if (Input.GetKeyDown(ControlsManager.ControlInstance.Keybinds["UpButton"]) || Input.GetAxisRaw("Vertical") == 1)
{
if (!axisDown)
{
axisDown = true;
NavAuras(selectedBtn, selectedBtn - 1);
SoundManager.SoundInstance.PlaySound("ButtonNav");
}
}
else
{
axisDown = false; // Reset axisDown
}
// Pressing jump will attempt to enhance the aura of selectedAuraNumber
if (Input.GetKeyDown(ControlsManager.ControlInstance.Keybinds["JumpButton"]) || Input.GetKeyDown(ControlsManager.ControlInstance.Padbinds["JumpPad"]))
{
// Uses selectedAuraNumber which is index of all auras (aura.auraNumber), selectedBtn is only the index of each button which is not accurate since
// it only includes auras unlocked
enhanceManager.BuyEnhance(selectedAuraNumber);
}
}
// Navigate aura buttons
public void NavAuras(int lastButton, int button)
{
// If next button goes past last button, wrap back to beginning. If goes before first button, wrap to last button
if (button > unlockedAuraInvent.Length - 1)
{
button = 0;
}
else if (button < 0)
{
button = unlockedAuraInvent.Length - 1;
}
selectedBtn = button;
scroll.value = (1f - ((float)button / (unlockedAuraInvent.Length)));
// Change sprite of button, reset last one
unlockedAuraInvent[lastButton].GetComponent<Image>().sprite = unselectedSprite;
unlockedAuraInvent[button].GetComponent<Image>().sprite = selectedSprite;
// Invoke onClick to display enhance aura info and set selected aura
unlockedAuraInvent[selectedBtn].onClick.Invoke();
}
// OnClick button, set the selected aura number equal to the corresponding button's aura
public void SetSelectedAura(int index)
{
selectedAuraNumber = index;
}
}
| 33.733766 | 158 | 0.613282 | [
"MIT"
] | calsf/aura | Assets/Scripts/Shop/EnhanceNav.cs | 5,197 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
namespace CSharpMongoDB
{
class Program
{
static void Main(string[] args)
{
try
{
int count = 1;
Console.WriteLine("***Connecting to mongodb://localhost:27017....***");
MongoClient client = new MongoClient("mongodb://localhost:27017");
List <BsonDocument> listDatabase = client.ListDatabases().ToList();
Console.WriteLine("***List of exiting Database***");
foreach (var item in listDatabase)
{
Console.WriteLine(count+": "+item["name"]);
count++;
}
Console.ReadKey();
}
catch (Exception)
{
Console.WriteLine("***Incorrect address***");
}
}
}
}
| 26.692308 | 87 | 0.491835 | [
"MIT"
] | DevelopHack/CSharp-with-MongoDB | CSharpMongoDB/Program.cs | 1,043 | C# |
using PdfSharp.Pdf.Advanced;
using System;
namespace PdfSharp.Pdf.Annotations
{
/// <summary>
/// Represent a file that is attached to the PDF
/// </summary>
public class PdfFileAttachmentAnnotation : PdfAnnotation
{
/// <summary>
/// Name of icons used in displaying the annotation.
/// </summary>
public enum IconType
{
Graph,
PushPin,
Paperclip,
Tag
}
/// <summary>
/// Initializes a new instance of the <see cref="PdfFileAttachmentAnnotation"/> class.
/// </summary>
public PdfFileAttachmentAnnotation()
{
Elements.SetName(Keys.Subtype, "/FileAttachment");
}
/// <summary>
/// Initializes a new instance of the <see cref="PdfFileAttachmentAnnotation"/> class.
/// </summary>
public PdfFileAttachmentAnnotation(PdfDocument document)
: base(document)
{
Elements.SetName(Keys.Subtype, "/FileAttachment");
Flags = PdfAnnotationFlags.Locked;
}
public IconType Icon
{
get
{
var iconName = Elements.GetName(Keys.Name);
if (iconName == null)
return IconType.PushPin;
return (IconType)(Enum.Parse(typeof(IconType), iconName));
}
set { Elements.SetName(Keys.Name, value.ToString()); }
}
public PdfFileSpecification File
{
get
{
var reference = Elements.GetReference(Keys.FS);
return reference?.Value as PdfFileSpecification;
}
set
{
if (value == null)
{
Elements.Remove(Keys.FS);
}
else
{
if (!value.IsIndirect)
Owner._irefTable.Add(value);
Elements.SetReference(Keys.FS, value);
}
}
}
/// <summary>
/// Predefined keys of this dictionary.
/// </summary>
internal new class Keys : PdfAnnotation.Keys
{
/// <summary>
/// (Required) The file associated with this annotation.
/// </summary>
[KeyInfo(KeyType.Dictionary | KeyType.Required)]
public const string FS = "/FS";
/// <summary>
/// (Optional) The name of an icon to be used in displaying the annotation.
/// Viewer applications should provide predefined icon appearances for at least
/// the following standard names:
///
/// Graph
/// PushPin
/// Paperclip
/// Tag
///
/// Additional names may be supported as well. Default value: PushPin.
/// Note: The annotation dictionary’s AP entry, if present, takes precedence over
/// the Name entry; see Table 8.15 on page 606 and Section 8.4.4, “Appearance Streams.”
/// </summary>
[KeyInfo(KeyType.Name | KeyType.Optional)]
public const string Name = "/Name";
/// <summary>
/// Gets the KeysMeta for these keys.
/// </summary>
public static DictionaryMeta Meta
{
get
{
if (Keys.meta == null)
Keys.meta = CreateMeta(typeof(Keys));
return Keys.meta;
}
}
static DictionaryMeta meta;
}
/// <summary>
/// Gets the KeysMeta of this dictionary type.
/// </summary>
internal override DictionaryMeta Meta
{
get { return Keys.Meta; }
}
}
}
| 30.069231 | 99 | 0.486314 | [
"MIT"
] | brunoserrano/PDFsharp | src/PdfSharp/Pdf.Annotations/PdfFileAttachmentAnnotation.cs | 3,917 | C# |
//Problem 12. Remove words
//Write a program that removes from a text file all words listed in given another text file.
//Handle all possible exceptions in your methods.
using System;
using System.IO;
using System.Text;
using System.Linq;
class RemoveWords
{
static void Main()
{
try
{
string text = ReadText();
string[] words = ReadWords();
RemoveListedWords(text, words);
Console.WriteLine("Words are removed.");
}
catch (FileNotFoundException fnf)
{
Console.WriteLine(fnf.Message);
}
catch (DirectoryNotFoundException dnf)
{
Console.WriteLine(dnf.Message);
}
catch (PathTooLongException ptl)
{
Console.WriteLine(ptl.Message);
}
catch (IOException io)
{
Console.WriteLine(io.Message);
}
catch (UnauthorizedAccessException ua)
{
Console.WriteLine(ua.Message);
}
catch (OverflowException oe)
{
Console.WriteLine(oe.Message);
}
catch (OutOfMemoryException oom)
{
Console.WriteLine(oom.Message);
}
catch (ArgumentException ae)
{
Console.WriteLine(ae.Message);
}
}
static string ReadText()
{
string text = string.Empty;
using (StreamReader reader = new StreamReader(@"..\..\text.txt"))
{
text = reader.ReadToEnd();
}
return text;
}
static string[] ReadWords()
{
string[] words;
using (StreamReader reader = new StreamReader(@"..\..\words.txt"))
{
words = reader.ReadToEnd().Replace("\r\n", " ").Split(' ');
}
return words;
}
static void RemoveListedWords(string text, string[] words)
{
for (int i = 0; i < words.Length; i++)
{
text = text.Replace(words[i], "");
}
using (StreamWriter writer = new StreamWriter(@"..\..\text.txt"))
{
writer.Write(text);
}
}
}
| 22.893617 | 92 | 0.523234 | [
"MIT"
] | enchev-93/Telerik-Academy | 02.C Sharp part 2/08.TextFiles/RemoveWords/RemoveWords.cs | 2,154 | C# |
using Newtonsoft.Json;
namespace Mopidy.Models.JsonRpcs
{
[JsonObject(MemberSerialization.OptIn)]
internal abstract class JsonRpcQuery : JsonRpcBase
{
}
}
| 17.2 | 54 | 0.732558 | [
"MIT"
] | ume05rw/MopidySharp | MopidySharp/Models/JsonRpcs/JsonRpcQuery.cs | 172 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Recognition_of_Handwritten_Digits.Model
{
class DigitModel
{
public byte Digit;
public byte[] DigitRepresentation;
public DigitModel(byte digit, byte[] digitRepresentation)
{
Digit = digit;
DigitRepresentation = digitRepresentation;
}
public DigitModel(byte digit, int pixelsCount)
{
Digit = digit;
DigitRepresentation = new byte[pixelsCount];
}
}
}
| 22.37037 | 65 | 0.634106 | [
"MIT"
] | dkoprowski/Recognition-of-Handwritten-Digits | Recognition-of-Handwritten-Digits/Model/DigitModel.cs | 606 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Web.Razor.Tokenizer.Symbols
{
public enum HtmlSymbolType
{
Unknown,
Text, // Text which isn't one of the below
WhiteSpace, // Non-newline Whitespace
NewLine, // Newline
OpenAngle, // <
Bang, // !
Solidus, // /
QuestionMark, // ?
DoubleHyphen, // --
LeftBracket, // [
CloseAngle, // >
RightBracket, // ]
Equals, // =
DoubleQuote, // "
SingleQuote, // '
Transition, // @
Colon,
RazorComment,
RazorCommentStar,
RazorCommentTransition
}
}
| 26.172414 | 133 | 0.552042 | [
"Apache-2.0"
] | Darth-Fx/AspNetMvcStack | src/System.Web.Razor/Tokenizer/Symbols/HtmlSymbolType.cs | 761 | C# |
using System.Collections.Generic;
using Newtonsoft.Json;
namespace CosmosApi.Models
{
public class UnbondingDelegation
{
/// <summary>
/// Initializes a new instance of the UnbondingDelegation class.
/// </summary>
public UnbondingDelegation()
{
}
/// <summary>
/// Initializes a new instance of the UnbondingDelegation class.
/// </summary>
public UnbondingDelegation(string delegatorAddress, string validatorAddress, IList<UnbondingDelegationEntry> entries)
{
DelegatorAddress = delegatorAddress;
ValidatorAddress = validatorAddress;
Entries = entries;
}
/// <summary>
/// Delegator.
/// </summary>
[JsonProperty(PropertyName = "delegator_address")]
public string DelegatorAddress { get; set; } = null!;
/// <summary>
/// Validator unbonding from operator addr.
/// </summary>
[JsonProperty(PropertyName = "validator_address")]
public string ValidatorAddress { get; set; } = null!;
/// <summary>
/// unbonding delegation entries
/// </summary>
[JsonProperty("entries")]
public IList<UnbondingDelegationEntry> Entries { get; set; } = null!;
}
}
| 29.244444 | 125 | 0.594225 | [
"Apache-2.0"
] | usetech-llc/cosmos_api_dotnet | src/CosmosApi/Models/UnbondingDelegation.cs | 1,316 | C# |
using Rabbit.Rpc.Address;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Rabbit.Rpc.Runtime.Client.Address.Resolvers.Implementation.Selectors.Implementation
{
/// <summary>
/// 轮询的地址选择器。
/// </summary>
public class PollingAddressSelector : AddressSelectorBase
{
private readonly ConcurrentDictionary<string, AddressEntry> _concurrent = new ConcurrentDictionary<string, AddressEntry>();
#region Overrides of AddressSelectorBase
/// <summary>
/// 选择一个地址。
/// </summary>
/// <param name="context">地址选择上下文。</param>
/// <returns>地址模型。</returns>
protected override Task<AddressModel> SelectAsync(AddressSelectContext context)
{
var key = context.ServiceRoute.ServiceDescriptor.Id;
//根据服务id缓存服务地址。
var address = _concurrent.AddOrUpdate(key, k => new AddressEntry(context.ServiceRoute.Address), (k, currentEntry) =>
{
var newAddress = context.ServiceRoute.Address.ToArray();
var currentAddress = currentEntry.Address;
var unionAddress = currentEntry.Address.Union(newAddress).ToArray();
if (unionAddress.Length != currentAddress.Length)
return new AddressEntry(newAddress);
if (unionAddress.Any(addressModel => !newAddress.Contains(addressModel)))
{
return new AddressEntry(newAddress);
}
return currentEntry;
});
return Task.FromResult(address.GetAddress());
}
#endregion Overrides of AddressSelectorBase
#region Help Class
protected class AddressEntry
{
#region Field
private int _index;
private int _lock;
private readonly int _maxIndex;
#endregion Field
#region Constructor
public AddressEntry(IEnumerable<AddressModel> address)
{
Address = address.ToArray();
_maxIndex = Address.Length - 1;
}
#endregion Constructor
#region Property
public AddressModel[] Address { get; set; }
#endregion Property
#region Public Method
public AddressModel GetAddress()
{
while (true)
{
//如果无法得到锁则等待
if (Interlocked.Exchange(ref _lock, 1) != 0)
continue;
var address = Address[_index];
//设置为下一个
if (_maxIndex > _index)
_index++;
else
_index = 0;
//释放锁
Interlocked.Exchange(ref _lock, 0);
return address;
}
}
#endregion Public Method
}
#endregion Help Class
}
} | 29.046296 | 131 | 0.536181 | [
"Apache-2.0"
] | cnark/Rpc | src/Rabbit.Rpc/Runtime/Client/Address/Resolvers/Implementation/Selectors/Implementation/PollingAddressSelector.cs | 3,257 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Panosen.CodeDom.Tag.Vue.Element
{
/// <summary>
/// el-header
/// </summary>
public class ElHeaderComponent : ElementComponent
{
/// <summary>
/// el-header
/// </summary>
public override string Name { get; set; } = "el-header";
}
}
| 20.85 | 64 | 0.616307 | [
"MIT"
] | panosen/panosen-codedom-tag-vue | Panosen.CodeDom.Tag.Vue.Element/ElHeaderComponent.cs | 419 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Analytics.Synapse.AccessControl.Models;
using Azure.Core;
using Azure.Core.Pipeline;
namespace Azure.Analytics.Synapse.AccessControl
{
/// <summary> The AccessControl service client. </summary>
public partial class AccessControlClient
{
private readonly ClientDiagnostics _clientDiagnostics;
private readonly HttpPipeline _pipeline;
internal AccessControlRestClient RestClient { get; }
/// <summary> Initializes a new instance of AccessControlClient for mocking. </summary>
protected AccessControlClient()
{
}
/// <summary> Initializes a new instance of AccessControlClient. </summary>
/// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="endpoint"> The workspace development endpoint, for example https://myworkspace.dev.azuresynapse.net. </param>
/// <param name="apiVersion"> Api Version. </param>
internal AccessControlClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string endpoint, string apiVersion = "2020-02-01-preview")
{
RestClient = new AccessControlRestClient(clientDiagnostics, pipeline, endpoint, apiVersion);
_clientDiagnostics = clientDiagnostics;
_pipeline = pipeline;
}
/// <summary> Create role assignment. </summary>
/// <param name="createRoleAssignmentOptions"> Details of role id and object id. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<RoleAssignmentDetails>> CreateRoleAssignmentAsync(RoleAssignmentOptions createRoleAssignmentOptions, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("AccessControlClient.CreateRoleAssignment");
scope.Start();
try
{
return await RestClient.CreateRoleAssignmentAsync(createRoleAssignmentOptions, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Create role assignment. </summary>
/// <param name="createRoleAssignmentOptions"> Details of role id and object id. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<RoleAssignmentDetails> CreateRoleAssignment(RoleAssignmentOptions createRoleAssignmentOptions, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("AccessControlClient.CreateRoleAssignment");
scope.Start();
try
{
return RestClient.CreateRoleAssignment(createRoleAssignmentOptions, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> List role assignments. </summary>
/// <param name="roleId"> Synapse Built-In Role Id. </param>
/// <param name="principalId"> Object ID of the AAD principal or security-group. </param>
/// <param name="continuationToken"> Continuation token. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<IReadOnlyList<RoleAssignmentDetails>>> GetRoleAssignmentsAsync(string roleId = null, string principalId = null, string continuationToken = null, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("AccessControlClient.GetRoleAssignments");
scope.Start();
try
{
return await RestClient.GetRoleAssignmentsAsync(roleId, principalId, continuationToken, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> List role assignments. </summary>
/// <param name="roleId"> Synapse Built-In Role Id. </param>
/// <param name="principalId"> Object ID of the AAD principal or security-group. </param>
/// <param name="continuationToken"> Continuation token. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<IReadOnlyList<RoleAssignmentDetails>> GetRoleAssignments(string roleId = null, string principalId = null, string continuationToken = null, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("AccessControlClient.GetRoleAssignments");
scope.Start();
try
{
return RestClient.GetRoleAssignments(roleId, principalId, continuationToken, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Get role assignment by role assignment Id. </summary>
/// <param name="roleAssignmentId"> The ID of the role assignment. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<RoleAssignmentDetails>> GetRoleAssignmentByIdAsync(string roleAssignmentId, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("AccessControlClient.GetRoleAssignmentById");
scope.Start();
try
{
return await RestClient.GetRoleAssignmentByIdAsync(roleAssignmentId, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Get role assignment by role assignment Id. </summary>
/// <param name="roleAssignmentId"> The ID of the role assignment. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<RoleAssignmentDetails> GetRoleAssignmentById(string roleAssignmentId, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("AccessControlClient.GetRoleAssignmentById");
scope.Start();
try
{
return RestClient.GetRoleAssignmentById(roleAssignmentId, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Delete role assignment by role assignment Id. </summary>
/// <param name="roleAssignmentId"> The ID of the role assignment. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response> DeleteRoleAssignmentByIdAsync(string roleAssignmentId, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("AccessControlClient.DeleteRoleAssignmentById");
scope.Start();
try
{
return await RestClient.DeleteRoleAssignmentByIdAsync(roleAssignmentId, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Delete role assignment by role assignment Id. </summary>
/// <param name="roleAssignmentId"> The ID of the role assignment. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response DeleteRoleAssignmentById(string roleAssignmentId, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("AccessControlClient.DeleteRoleAssignmentById");
scope.Start();
try
{
return RestClient.DeleteRoleAssignmentById(roleAssignmentId, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> List role assignments of the caller. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<IReadOnlyList<string>>> GetCallerRoleAssignmentsAsync(CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("AccessControlClient.GetCallerRoleAssignments");
scope.Start();
try
{
return await RestClient.GetCallerRoleAssignmentsAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> List role assignments of the caller. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<IReadOnlyList<string>> GetCallerRoleAssignments(CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("AccessControlClient.GetCallerRoleAssignments");
scope.Start();
try
{
return RestClient.GetCallerRoleAssignments(cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Get role by role Id. </summary>
/// <param name="roleId"> Synapse Built-In Role Id. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<SynapseRole>> GetRoleDefinitionByIdAsync(string roleId, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("AccessControlClient.GetRoleDefinitionById");
scope.Start();
try
{
return await RestClient.GetRoleDefinitionByIdAsync(roleId, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Get role by role Id. </summary>
/// <param name="roleId"> Synapse Built-In Role Id. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<SynapseRole> GetRoleDefinitionById(string roleId, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("AccessControlClient.GetRoleDefinitionById");
scope.Start();
try
{
return RestClient.GetRoleDefinitionById(roleId, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> List roles. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual AsyncPageable<SynapseRole> GetRoleDefinitionsAsync(CancellationToken cancellationToken = default)
{
async Task<Page<SynapseRole>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("AccessControlClient.GetRoleDefinitions");
scope.Start();
try
{
var response = await RestClient.GetRoleDefinitionsAsync(cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<SynapseRole>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("AccessControlClient.GetRoleDefinitions");
scope.Start();
try
{
var response = await RestClient.GetRoleDefinitionsNextPageAsync(nextLink, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> List roles. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Pageable<SynapseRole> GetRoleDefinitions(CancellationToken cancellationToken = default)
{
Page<SynapseRole> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("AccessControlClient.GetRoleDefinitions");
scope.Start();
try
{
var response = RestClient.GetRoleDefinitions(cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<SynapseRole> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("AccessControlClient.GetRoleDefinitions");
scope.Start();
try
{
var response = RestClient.GetRoleDefinitionsNextPage(nextLink, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
}
}
| 45.260479 | 234 | 0.604088 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/synapse/Azure.Analytics.Synapse.AccessControl/src/Generated/AccessControlClient.cs | 15,117 | C# |
#region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2020 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific language governing permissions
and limitations under the License.
Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md
----------------------------------------------------------------*/
#endregion Apache License Version 2.0
/*----------------------------------------------------------------
Copyright (C) 2020 Senparc
文件名:ScanTicketCheckJsonResult.cs
文件功能描述: 检查wxticket参数的返回结果
创建标识:Senparc - 20160520
----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Senparc.Weixin.Entities;
namespace Senparc.Weixin.MP.AdvancedAPIs.Scan
{
/// <summary>
/// 检查wxticket参数的返回结果
/// </summary>
public class ScanTicketCheckJsonResult : WxJsonResult
{
/// <summary>
/// 商品编码标准。
/// </summary>
public string keystandard { get; set; }
/// <summary>
/// 商品编码内容。
/// </summary>
public string keystr { get; set; }
/// <summary>
/// 当前访问者的openid,可唯一标识用户。
/// </summary>
public string openid { get; set; }
/// <summary>
/// 打开商品主页的场景,scan为扫码,others为其他场景,可能是会话、收藏或朋友圈。
/// </summary>
public string scene { get; set; }
/// <summary>
/// 该条码(二维码)是否被扫描,true为是,false为否。
/// </summary>
public string is_check { get; set; }
/// <summary>
/// 是否关注公众号,true为已关注,false为未关注。
/// </summary>
public string is_contact { get; set; }
}
}
| 31.521127 | 90 | 0.571492 | [
"Apache-2.0"
] | 103556710/WeiXinMPSDK | src/Senparc.Weixin.MP/Senparc.Weixin.MP/AdvancedAPIs/Scan/ScanJson/ScanTicketCheckJsonResult.cs | 2,508 | C# |
using MidnightLizard.Commons.Domain.Model;
using MidnightLizard.Impressions.Domain.FavoritesAggregate.Events;
using MidnightLizard.Impressions.Domain.ImpressionsAggregate;
using MidnightLizard.Impressions.Domain.ImpressionsAggregate.Events;
using System.Collections.Generic;
namespace MidnightLizard.Impressions.Domain.FavoritesAggregate
{
public class Favorites : ImpressionsAggregate.Impressions<FavoritesId>
{
protected Favorites() : base() { }
public Favorites(FavoritesId aggregateId) : base(aggregateId) { }
public IReadOnlyCollection<UserId> FavoritedBy
{
get => this._Impressionists;
private set => this._Impressionists = new HashSet<UserId>(value);
}
protected override ImpressionAddedEvent<FavoritesId> CreateImpressionAddedEvent(ImpressionsObjectType objectType)
{
return new AddedToFavoritesEvent(this.Id, objectType);
}
protected override ImpressionRemovedEvent<FavoritesId> CreateImpressionRemovedEvent(ImpressionsObjectType objectType)
{
return new RemovedFromFavoritesEvent(this.Id, objectType);
}
protected override ImpressionsChangedEvent<FavoritesId> CreateImpressionsChangedEvent()
{
return new FavoritesChangedEvent(this.Id, this.ObjectType, this.FavoritedBy);
}
}
}
| 38.277778 | 125 | 0.730769 | [
"MIT"
] | Midnight-Lizard/Impression-Processor | domain/FavoritesAggregate/Favorites.cs | 1,380 | C# |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.Project
{
public class BuildDependency : IVsBuildDependency
{
Guid referencedProjectGuid = Guid.Empty;
ProjectNode projectMgr = null;
[CLSCompliant(false)]
public BuildDependency(ProjectNode projectMgr, Guid projectReference)
{
this.referencedProjectGuid = projectReference;
this.projectMgr = projectMgr;
}
#region IVsBuildDependency methods
public int get_CanonicalName(out string canonicalName)
{
canonicalName = null;
return VSConstants.S_OK;
}
public int get_Type(out System.Guid guidType)
{
// All our dependencies are build projects
guidType = VSConstants.GUID_VS_DEPTYPE_BUILD_PROJECT;
return VSConstants.S_OK;
}
public int get_Description(out string description)
{
description = null;
return VSConstants.S_OK;
}
[CLSCompliant(false)]
public int get_HelpContext(out uint helpContext)
{
helpContext = 0;
return VSConstants.E_NOTIMPL;
}
public int get_HelpFile(out string helpFile)
{
helpFile = null;
return VSConstants.E_NOTIMPL;
}
public int get_MustUpdateBefore(out int mustUpdateBefore)
{
// Must always update dependencies
mustUpdateBefore = 1;
return VSConstants.S_OK;
}
public int get_ReferredProject(out object unknownProject)
{
unknownProject = null;
unknownProject = this.GetReferencedHierarchy();
// If we cannot find the referenced hierarchy return S_FALSE.
return (unknownProject == null) ? VSConstants.S_FALSE : VSConstants.S_OK;
}
#endregion
#region helper methods
private IVsHierarchy GetReferencedHierarchy()
{
IVsHierarchy hierarchy = null;
if(this.referencedProjectGuid == Guid.Empty || this.projectMgr == null || this.projectMgr.IsClosed)
{
return hierarchy;
}
return VsShellUtilities.GetHierarchy(this.projectMgr.Site, this.referencedProjectGuid);
}
#endregion
}
}
| 26.933333 | 103 | 0.67256 | [
"Apache-2.0"
] | DavidMoore/Foundation | Code/Foundation.Build.VisualBasic6.VisualStudioIntegration/ProjectBase/BuildDependency.cs | 2,828 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the redshift-2012-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Redshift.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.Redshift.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for EventCategoriesMap Object
/// </summary>
public class EventCategoriesMapUnmarshaller : IUnmarshaller<EventCategoriesMap, XmlUnmarshallerContext>, IUnmarshaller<EventCategoriesMap, JsonUnmarshallerContext>
{
public EventCategoriesMap Unmarshall(XmlUnmarshallerContext context)
{
EventCategoriesMap unmarshalledObject = new EventCategoriesMap();
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
if (context.TestExpression("Events/EventInfoMap", targetDepth))
{
var unmarshaller = EventInfoMapUnmarshaller.Instance;
var item = unmarshaller.Unmarshall(context);
unmarshalledObject.Events.Add(item);
continue;
}
if (context.TestExpression("SourceType", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.SourceType = unmarshaller.Unmarshall(context);
continue;
}
}
else if (context.IsEndElement && context.CurrentDepth < originalDepth)
{
return unmarshalledObject;
}
}
return unmarshalledObject;
}
public EventCategoriesMap Unmarshall(JsonUnmarshallerContext context)
{
return null;
}
private static EventCategoriesMapUnmarshaller _instance = new EventCategoriesMapUnmarshaller();
public static EventCategoriesMapUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.527473 | 167 | 0.61862 | [
"Apache-2.0"
] | ermshiperete/aws-sdk-net | AWSSDK_DotNet35/Amazon.Redshift/Model/Internal/MarshallTransformations/EventCategoriesMapUnmarshaller.cs | 3,233 | C# |
using System.Threading.Tasks;
namespace CP.Final.Mincifra.SharedKernel.Interfaces
{
public interface IHandle<in T> where T : BaseDomainEvent
{
Task Handle(T domainEvent);
}
} | 21.777778 | 60 | 0.709184 | [
"MIT",
"Unlicense"
] | nkiruhin/CP.Final.Mincifra | CP.Final.Mincifra/src/CP.Final.Mincifra.SharedKernel/Interfaces/IHandle.cs | 198 | C# |
using System.IO;
using ApprovalTests.Core;
namespace ApprovalTests.Tests
{
public class CleanupReporter : IApprovalFailureReporter
{
public void Report(string approved, string received)
{
File.Delete(received);
}
public bool ApprovedWhenReported()
{
return false;
}
}
} | 20.722222 | 61 | 0.576408 | [
"Apache-2.0"
] | GerHobbelt/ApprovalTests.Net | src/ApprovalTests.Tests/CleanupReporter.cs | 358 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.