prefix
stringlengths
82
32.6k
middle
stringlengths
5
470
suffix
stringlengths
0
81.2k
file_path
stringlengths
6
168
repo_name
stringlengths
16
77
context
listlengths
5
5
lang
stringclasses
4 values
ground_truth
stringlengths
5
470
#nullable enable using System.Collections.Generic; using Mochineko.FacialExpressions.LipSync; using Mochineko.VOICEVOX_API.QueryCreation; namespace Mochineko.FacialExpressions.Extensions.VOICEVOX { /// <summary> /// Provides converting from <see cref="AudioQuery"/> to collection of <see cref="LipAnimationFrame"/>. /// </summary> public static class AudioQueryConverter { private static readonly IReadOnlyDictionary<string,
Viseme> VisemeMap = new Dictionary<string, Viseme> {
// Vowels ["pau"] = Viseme.sil, ["cl"] = Viseme.sil, ["a"] = Viseme.aa, ["A"] = Viseme.aa, ["i"] = Viseme.ih, ["I"] = Viseme.ih, ["u"] = Viseme.ou, ["U"] = Viseme.ou, ["e"] = Viseme.E, ["E"] = Viseme.E, ["o"] = Viseme.oh, ["O"] = Viseme.oh, ["N"] = Viseme.nn, // Consonants ["y"] = Viseme.sil, ["p"] = Viseme.PP, ["py"] = Viseme.PP, ["b"] = Viseme.PP, ["by"] = Viseme.PP, ["m"] = Viseme.PP, ["my"] = Viseme.PP, ["f"] = Viseme.FF, ["v"] = Viseme.FF, ["w"] = Viseme.FF, ["h"] = Viseme.FF, ["hy"] = Viseme.FF, ["d"] = Viseme.DD, ["dy"] = Viseme.DD, ["t"] = Viseme.DD, ["ty"] = Viseme.DD, ["ts"] = Viseme.DD, ["k"] = Viseme.kk, ["kw"] = Viseme.kk, ["ky"] = Viseme.kk, ["g"] = Viseme.kk, ["gy"] = Viseme.kk, ["ch"] = Viseme.CH, ["sh"] = Viseme.CH, ["j"] = Viseme.CH, ["z"] = Viseme.SS, ["s"] = Viseme.SS, ["n"] = Viseme.nn, ["ny"] = Viseme.nn, ["r"] = Viseme.RR, ["ry"] = Viseme.RR, }; /// <summary> /// Converts <see cref="AudioQuery"/> to collection of <see cref="LipAnimationFrame"/>. /// </summary> /// <param name="audioQuery"></param> /// <returns></returns> public static IEnumerable<LipAnimationFrame> ConvertToSequentialAnimationFrames( AudioQuery audioQuery) { var frames = new List<LipAnimationFrame>(); frames.Add(new LipAnimationFrame( new LipSample(Viseme.sil, weight: 0f), audioQuery.PrePhonemeLength / audioQuery.SpeedScale)); foreach (var phase in audioQuery.AccentPhases) { foreach (var mora in phase.Moras) { var duration = mora.VowelLength; if (mora.ConsonantLength is not null) { duration += mora.ConsonantLength.Value; } frames.Add(new LipAnimationFrame( new LipSample(VisemeMap[mora.Vowel], weight: 1f), duration / audioQuery.SpeedScale)); frames.Add(new LipAnimationFrame( new LipSample(VisemeMap[mora.Vowel], weight: 0f), durationSeconds: 0f)); } if (phase.PauseMora is not null) { frames.Add(new LipAnimationFrame( new LipSample(Viseme.sil, weight: 0f), durationSeconds: phase.PauseMora.VowelLength / audioQuery.SpeedScale)); } } frames.Add(new LipAnimationFrame( new LipSample(Viseme.sil, weight: 0f), audioQuery.PostPhonemeLength / audioQuery.SpeedScale)); return frames; } } }
Assets/Mochineko/FacialExpressions.Extensions/VOICEVOX/AudioQueryConverter.cs
mochi-neko-facial-expressions-unity-ab0d020
[ { "filename": "Assets/Mochineko/FacialExpressions.Extensions/uLipSync/ULipSyncAnimator.cs", "retrieved_chunk": " /// </summary>\n public sealed class ULipSyncAnimator : IFramewiseLipAnimator, IDisposable\n {\n private readonly FollowingLipAnimator followingLipAnimator;\n private readonly global::uLipSync.uLipSync uLipSync;\n private readonly IReadOnlyDictionary<string, Viseme> phonomeMap;\n private readonly IDisposable disposable;\n /// <summary>\n /// Creates a new instance of <see cref=\"ULipSyncAnimator\"/>.\n /// </summary>", "score": 0.8506065011024475 }, { "filename": "Assets/Mochineko/FacialExpressions.Extensions/VRM/VRMEmotionMorpher.cs", "retrieved_chunk": " // ReSharper disable once InconsistentNaming\n public sealed class VRMEmotionMorpher<TEmotion> :\n IEmotionMorpher<TEmotion>\n where TEmotion: Enum\n {\n private readonly Vrm10RuntimeExpression expression;\n private readonly IReadOnlyDictionary<TEmotion, ExpressionKey> keyMap;\n /// <summary>\n /// Creates a new instance of <see cref=\"VRMEmotionMorpher\"/>.\n /// </summary>", "score": 0.8314980864524841 }, { "filename": "Assets/Mochineko/FacialExpressions/LipSync/CompletionFunction.cs", "retrieved_chunk": "#nullable enable\nusing System;\nnamespace Mochineko.FacialExpressions.LipSync\n{\n /// <summary>\n /// Provides completion functions.\n /// </summary>\n public static class CompletionFunction\n {\n /// <summary>", "score": 0.8211427927017212 }, { "filename": "Assets/Mochineko/FacialExpressions/LipSync/AnimatorLipMorpher.cs", "retrieved_chunk": " private readonly Animator animator;\n private readonly IReadOnlyDictionary<Viseme, int> idMap;\n /// <summary>\n /// Creates a new instance of <see cref=\"AnimatorLipMorpher\"/>.\n /// </summary>\n /// <param name=\"animator\">Target animator.</param>\n /// <param name=\"idMap\">Map of viseme to animator float key.</param>\n public AnimatorLipMorpher(\n Animator animator,\n IReadOnlyDictionary<Viseme, int> idMap)", "score": 0.8195713758468628 }, { "filename": "Assets/Mochineko/FacialExpressions/LipSync/IFramewiseLipAnimator.cs", "retrieved_chunk": "#nullable enable\nnamespace Mochineko.FacialExpressions.LipSync\n{\n /// <summary>\n /// Defines an animator to update lip animation per game engine frame.\n /// </summary>\n public interface IFramewiseLipAnimator\n {\n /// <summary>\n /// Updates animation.", "score": 0.8189646005630493 } ]
csharp
Viseme> VisemeMap = new Dictionary<string, Viseme> {
// ReSharper disable once RedundantUsingDirective using System.Collections.Generic; // can't alias namespace CsvParsing { public class CsvDictionaryReader { private readonly
CsvReader _reader;
private List<string>? _header; private Dictionary<string, string>? _dictionary; public CsvDictionaryReader(CsvReader reader) { _reader = reader; } /** * <summary>Read the header from the reader.</summary> * <returns>Error, if any.</returns> */ public string? ReadHeader() { if (_header != null) { throw new System.InvalidOperationException( "The header has been already read" ); } var (row, error) = _reader.ReadRow(10); if (error != null) { return error; } if (row == null) { return "Expected a header row, but got end-of-stream"; } _header = row; return null; } public IReadOnlyList<string> Header { get { if (_header == null) { throw new System.InvalidOperationException( "Unexpected null header; have you read it before?" ); } return _header; } } /** * <summary>Read a single row of the table, after the header.</summary> * <remarks>Use <see cref="Row" /> to access the read row.</remarks> * <returns>Error, if any.</returns> */ public string? ReadRow() { if (_header == null) { throw new System.InvalidOperationException( "The header has not been read yet" ); } var (row, error) = _reader.ReadRow(_header.Count); if (error != null) { return error; } if (row == null) { _dictionary = null; return null; } if (row.Count != _header.Count) { return $"Expected {_header.Count} cell(s), but got {row.Count} cell(s)"; } _dictionary ??= new Dictionary<string, string>(); for (int i = 0; i < _header.Count; i++) { _dictionary[_header[i]] = row[i]; } return null; } /** * <summary>Get the current row.</summary> * <returns>The row, or null if reached the end-of-stream.</returns> */ public IReadOnlyDictionary<string, string>? Row => _dictionary; } }
src/CsvParsing/CsvDictionaryReader.cs
aas-core-works-aas-core3.0-cli-swiss-knife-eb9a3ef
[ { "filename": "src/CsvParsing.Tests/TestCsvDictionaryReader.cs", "retrieved_chunk": "using System.Collections.Generic; // can't alias\nusing NUnit.Framework; // can't alias\nnamespace CsvParsing.Tests\n{\n public class TestCsvDictionaryReader\n {\n private static (List<IReadOnlyDictionary<string, string>>?, string?) ReadTable(\n CsvDictionaryReader csv\n )\n {", "score": 0.8533691167831421 }, { "filename": "src/CsvParsing/CsvReader.cs", "retrieved_chunk": "// ReSharper disable once RedundantUsingDirective\nusing System.Collections.Generic; // can't alias\nnamespace CsvParsing\n{\n public class CsvReader\n {\n private readonly TextReaderWhichIgnoresReturnCarrier _reader;\n public CsvReader(System.IO.TextReader reader)\n {\n _reader = new TextReaderWhichIgnoresReturnCarrier(reader);", "score": 0.8468514084815979 }, { "filename": "src/CsvParsing.Tests/TestCsvReader.cs", "retrieved_chunk": "using System.Collections.Generic; // can't alias\nusing NUnit.Framework; // can't alias\nnamespace CsvParsing.Tests\n{\n public class TestCsvReader\n {\n private static (List<List<string>>?, string?) ReadTable(CsvReader csv)\n {\n var table = new List<List<string>>();\n while (true)", "score": 0.8378016948699951 }, { "filename": "src/EnvironmentFromCsvConceptDescriptions/ParsingConceptDescriptions.cs", "retrieved_chunk": "using Aas = AasCore.Aas3_0; // renamed\nusing System.Collections.Generic; // can't alias\nnamespace EnvironmentFromCsvConceptDescriptions\n{\n internal static class ParsingConceptDescriptions\n {\n internal static class ColumnNames\n {\n internal const string Id = \"ID\";\n internal const string PreferredName = \"Preferred Name\";", "score": 0.8371405005455017 }, { "filename": "src/EnvironmentFromCsvShellsAndSubmodels/ParsingAssetAdministrationShellsAndSubmodels.cs", "retrieved_chunk": "using Aas = AasCore.Aas3_0; // renamed\nusing System.Collections.Generic; // can't alias\nusing System.Linq; // can't alias\nnamespace EnvironmentFromCsvShellsAndSubmodels\n{\n internal static class ParsingAssetAdministrationShellsAndSubmodels\n {\n private static class ColumnNames\n {\n internal const string AssetAdministrationShellId =", "score": 0.8345780968666077 } ]
csharp
CsvReader _reader;
/* Copyright 2023 Carl Foghammar Nömtak 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 Microsoft; using Microsoft.CodeAnalysis.Completion; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; using Microsoft.VisualStudio.Text; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Diagnostics; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using VSIntelliSenseTweaks.Utilities; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; namespace VSIntelliSenseTweaks { // TODO: How to make a user setting that stops the MEF export of this? [Export(typeof(IAsyncCompletionItemManagerProvider))] [Name(nameof(VSIntelliSenseTweaksCompletionItemManagerProvider))] [ContentType("CSharp")] [ContentType("CSS")] [ContentType("XAML")] [ContentType("XML")] [TextViewRole(PredefinedTextViewRoles.PrimaryDocument)] internal class VSIntelliSenseTweaksCompletionItemManagerProvider : IAsyncCompletionItemManagerProvider { public IAsyncCompletionItemManager GetOrCreate(ITextView textView) { VSIntelliSenseTweaksPackage.EnsurePackageLoaded(); var settings = VSIntelliSenseTweaksPackage.Settings; return new CompletionItemManager(settings); } } internal class CompletionItemManager : IAsyncCompletionItemManager2 { static readonly ImmutableArray<Span> noSpans = ImmutableArray<Span>.Empty; const int textFilterMaxLength = 256; IAsyncCompletionSession session; AsyncCompletionSessionInitialDataSnapshot initialData; AsyncCompletionSessionDataSnapshot currentData; CancellationToken cancellationToken; VSCompletionItem[] completions; CompletionItemKey[] keys; int n_completions; WordScorer scorer = new WordScorer(256); CompletionFilterManager filterManager; bool hasFilterManager; bool includeDebugSuffix; bool disableSoftSelection; bool boostEnumMemberScore; public CompletionItemManager(GeneralSettings settings) { this.includeDebugSuffix = settings.IncludeDebugSuffix; this.disableSoftSelection = settings.DisableSoftSelection; this.boostEnumMemberScore = settings.BoostEnumMemberScore; } public Task<ImmutableArray<VSCompletionItem>> SortCompletionListAsync(IAsyncCompletionSession session, AsyncCompletionSessionInitialDataSnapshot data, CancellationToken token) { // I think this method is not used, but required for the interface. throw new NotImplementedException(); } public Task<CompletionList<VSCompletionItem>> SortCompletionItemListAsync(IAsyncCompletionSession session, AsyncCompletionSessionInitialDataSnapshot data, CancellationToken token) { // Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Implementation.AsyncCompletionSession this.session = session; this.initialData = data; this.cancellationToken = token; var sortTask = Task.Factory.StartNew(SortCompletionList, token, TaskCreationOptions.None, TaskScheduler.Current); return sortTask; } public Task<FilteredCompletionModel> UpdateCompletionListAsync(IAsyncCompletionSession session, AsyncCompletionSessionDataSnapshot data, CancellationToken token) { Debug.Assert(this.session == session); Debug.Assert(this.cancellationToken == token); this.currentData = data; var updateTask = Task.Factory.StartNew(UpdateCompletionList, token, TaskCreationOptions.None, TaskScheduler.Current); return updateTask; } public CompletionList<VSCompletionItem> SortCompletionList() { using (new Measurement(nameof(SortCompletionList))) { var initialCompletions = initialData.InitialItemList; this.n_completions = initialCompletions.Count; Debug.WriteLine($"Allocating for {n_completions} completions"); this.completions = new VSCompletionItem[n_completions]; this.keys = new CompletionItemKey[n_completions]; this.hasFilterManager = false; for (int i = 0; i < n_completions; i++) { completions[i] = initialCompletions[i]; } using (new Measurement("Sort")) Array.Sort(completions, new InitialComparer()); using (new Measurement(nameof(session.CreateCompletionList))) { var completionList = session.CreateCompletionList(completions); return completionList; } } } public FilteredCompletionModel UpdateCompletionList() { using (new Measurement(nameof(UpdateCompletionList))) { var textFilter = session.ApplicableToSpan.GetText(currentData.Snapshot); bool hasTextFilter = textFilter.Length > 0; if (ShouldDismiss()) return null; var filterStates = currentData.SelectedFilters; // The types of filters displayed in the IntelliSense widget. if (!hasFilterManager) { this.filterManager = new CompletionFilterManager(filterStates); this.hasFilterManager = true; } filterManager.UpdateActiveFilters(filterStates); int n_eligibleCompletions = 0; using (new Measurement(nameof(DetermineEligibleCompletions))) DetermineEligibleCompletions(); var highlighted = CreateHighlightedCompletions(n_eligibleCompletions); var selectionKind = GetSelectionKind(n_eligibleCompletions, hasTextFilter); var result = new FilteredCompletionModel ( items: highlighted, selectedItemIndex: 0, filters: filterStates, selectionHint: selectionKind, centerSelection: false, uniqueItem: null ); Debug.Assert(!cancellationToken.IsCancellationRequested); return result; bool ShouldDismiss() { // Dismisses if first char in pattern is a number and not after a '.'. int position = session.ApplicableToSpan.GetStartPoint(currentData.Snapshot).Position; return hasTextFilter && char.IsNumber(currentData.Snapshot[position]) && position > 0 && currentData.Snapshot[position - 1] != '.'; } void DetermineEligibleCompletions() { var initialCompletions = currentData.InitialSortedItemList; var defaults = currentData.Defaults; Debug.Assert(n_completions == initialCompletions.Count); int patternLength = Math.Min(textFilter.Length, textFilterMaxLength); var pattern = textFilter.AsSpan(0, patternLength); ReadOnlySpan<char> roslynPreselectedItemFilterText = null; BitField64 availableFilters = default; for (int i = 0; i < n_completions; i++) { var completion = initialCompletions[i]; int patternScore; ImmutableArray<Span> matchedSpans; if (hasTextFilter) { var word = completion.FilterText.AsSpan(); int displayTextOffset = Math.Max(0, completion.DisplayText.AsSpan().IndexOf(word)); patternScore = scorer.ScoreWord(word, pattern, displayTextOffset, out matchedSpans); if (patternScore == int.MinValue) continue; } else { patternScore = int.MinValue; matchedSpans = noSpans; } var filterMask = filterManager.CreateFilterMask(completion.Filters); var blacklistFilters = filterManager.blacklist & filterMask; availableFilters |= blacklistFilters; // Announce available blacklist filters. if (filterManager.HasActiveBlacklistFilter(filterMask)) continue; var whitelistFilters = filterManager.whitelist & filterMask; availableFilters |= whitelistFilters; // Announce available whitelist filters. if (filterManager.HasActiveWhitelist && !filterManager.HasActiveWhitelistFilter(filterMask)) continue; int defaultIndex = defaults.IndexOf(completion.FilterText) & int.MaxValue; // AND operation turns any negative value to int.MaxValue so we can sort properly if (blacklistFilters != default) { // We penalize items that have any inactive blacklist filters. // The current filter settings allow these items to be shown but they should be of lesser value than items without any blacklist filters. // Currently the only type of blacklist filter that exist in VS is 'add items from unimported namespaces'. patternScore -= 64 * pattern.Length; } int roslynScore = boostEnumMemberScore ? GetBoostedRoslynScore(completion, ref roslynPreselectedItemFilterText) : GetRoslynScore(completion); patternScore += CalculateRoslynScoreBonus(roslynScore, pattern.Length); var key = new CompletionItemKey { patternScore = patternScore, defaultIndex = defaultIndex, roslynScore = roslynScore, initialIndex = i, matchedSpans = matchedSpans, }; if (this.includeDebugSuffix) { AddDebugSuffix(ref completion, in key); } this.completions[n_eligibleCompletions] = completion; this.keys[n_eligibleCompletions] = key; n_eligibleCompletions++; } using (new Measurement("Sort")) Array.Sort(keys, completions, 0, n_eligibleCompletions); filterStates = UpdateFilterStates(filterStates, availableFilters); } } } UpdateSelectionHint GetSelectionKind(int n_eligibleCompletions, bool hasTextFilter) { if (n_eligibleCompletions == 0) return UpdateSelectionHint.NoChange; if (IsSoftSelectionDisabled()) return UpdateSelectionHint.Selected; if (hasTextFilter && !currentData.DisplaySuggestionItem) return UpdateSelectionHint.Selected; var bestKey = keys[0]; if (bestKey.roslynScore >= MatchPriority.Preselect) return UpdateSelectionHint.Selected; //if (bestKey.defaultIndex < int.MaxValue) // return UpdateSelectionHint.Selected; return UpdateSelectionHint.SoftSelected; bool IsSoftSelectionDisabled() { // User setting to disable soft-selection. if (disableSoftSelection) { // If the user prefers hard-selection, we can disable soft-selection under the following circumstances. return currentData.InitialTrigger.Reason == CompletionTriggerReason.InvokeAndCommitIfUnique || currentData.InitialTrigger.Character.Equals('.'); } return false; } } ImmutableArray<CompletionItemWithHighlight> CreateHighlightedCompletions(int n_eligibleCompletions) { var builder = ImmutableArray.CreateBuilder<CompletionItemWithHighlight>(n_eligibleCompletions); builder.Count = n_eligibleCompletions; for (int i = 0; i < n_eligibleCompletions; i++) { builder[i] = new CompletionItemWithHighlight(completions[i], keys[i].matchedSpans); } return builder.MoveToImmutable(); } private int CalculateRoslynScoreBonus(int roslynScore, int patternLength) { const int roslynScoreClamper = 1 << 22; int clampedRoslynScore = Math.Max(Math.Min(roslynScore, roslynScoreClamper), -roslynScoreClamper); return clampedRoslynScore * patternLength / 64; } /// <summary> /// Returns the normal roslyn score but gives additional score to enum members if the enum type was preselected by roslyn. /// </summary> private int GetBoostedRoslynScore(VSCompletionItem completion, ref ReadOnlySpan<char> roslynPreselectedItemFilterText) { int roslynScore = GetRoslynScore(completion); if (roslynScore >= MatchPriority.Preselect) { roslynPreselectedItemFilterText = completion.DisplayText.AsSpan(); } else if (roslynPreselectedItemFilterText != null) { var word = completion.DisplayText.AsSpan(); int preselectedLength = roslynPreselectedItemFilterText.Length; if (word.Length > preselectedLength && word.Slice(0, preselectedLength).SequenceEqual(roslynPreselectedItemFilterText)) { if (word[preselectedLength] == '.') { roslynScore = MatchPriority.Preselect / 2; } } else { roslynPreselectedItemFilterText = null; } } return roslynScore; } private int GetRoslynScore(VSCompletionItem completion) { if (completion.Properties.TryGetProperty("RoslynCompletionItemData", out object roslynObject)) { var roslynCompletion = GetRoslynItemProperty(roslynObject); int roslynScore = roslynCompletion.Rules.MatchPriority; return roslynScore; } return 0; } // Since we do not have compile time access the class type; // "Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion.CompletionItemData", // we have to use reflection or expressions to access it. private static Func<object, RoslynCompletionItem> RoslynCompletionItemGetter = null; private RoslynCompletionItem GetRoslynItemProperty(object roslynObject) { if (RoslynCompletionItemGetter == null) { // Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion.CompletionItemData var roslynType = roslynObject.GetType(); var input = Expression.Parameter(typeof(object)); var casted = Expression.Convert(input, roslynType); var property = Expression.PropertyOrField(casted, "RoslynItem"); var lambda = Expression.Lambda(property, input); RoslynCompletionItemGetter = (Func<object, RoslynCompletionItem>)lambda.Compile(); } return RoslynCompletionItemGetter.Invoke(roslynObject); } private ImmutableArray<CompletionFilterWithState> UpdateFilterStates(ImmutableArray<CompletionFilterWithState> filterStates, BitField64 availableFilters) { int n_filterStates = filterStates.Length; var builder = ImmutableArray.CreateBuilder<CompletionFilterWithState>(n_filterStates); builder.Count = n_filterStates; for (int i = 0; i < n_filterStates; i++) { var filterState = filterStates[i]; builder[i] = new CompletionFilterWithState(filterState.Filter, availableFilters.GetBit(i), filterState.IsSelected); } return builder.MoveToImmutable(); } struct InitialComparer : IComparer<VSCompletionItem> { public int Compare(VSCompletionItem x, VSCompletionItem y) { var a = x.SortText.AsSpan(); var b = y.SortText.AsSpan(); int comp = 0; if (a.Length > 0 && b.Length > 0) { comp = GetUnderscoreCount(a) - GetUnderscoreCount(b); } if (comp == 0) { comp = a.SequenceCompareTo(b); } return comp; } private int GetUnderscoreCount(ReadOnlySpan<char> str) { int i = 0; while (i < str.Length && str[i] == '_') { i++; } return i; } } struct CompletionItemKey : IComparable<CompletionItemKey> { public int patternScore; public int defaultIndex; public int roslynScore; public int initialIndex; public ImmutableArray<Span> matchedSpans; public int CompareTo(CompletionItemKey other) { int comp = other.patternScore - patternScore; if (comp == 0) { comp = defaultIndex - other.defaultIndex; } if (comp == 0) { comp = other.roslynScore - roslynScore; } if (comp == 0) // If score is same, preserve initial ordering. { comp = initialIndex - other.initialIndex; } return comp; } } struct CompletionFilterManager { CompletionFilter[] filters; public readonly BitField64 blacklist; public readonly BitField64 whitelist; BitField64 activeBlacklist; BitField64 activeWhitelist; /// <summary> /// True when there is an active whitelist to perform checks against. /// </summary> public bool HasActiveWhitelist => activeWhitelist != default; enum CompletionFilterKind { Null, Blacklist, Whitelist } public CompletionFilterManager(ImmutableArray<CompletionFilterWithState> filterStates) { Assumes.True(filterStates.Length < 64); filters = new CompletionFilter[filterStates.Length]; blacklist = default; whitelist = default; activeBlacklist = default; activeWhitelist = default; for (int i = 0; i < filterStates.Length; i++) { var filterState = filterStates[i]; var filter = filterState.Filter; this.filters[i] = filter; var filterKind = GetFilterKind(i, filter); switch (filterKind) { case CompletionFilterKind.Blacklist: blacklist.SetBit(i); break; case CompletionFilterKind.Whitelist: whitelist.SetBit(i); break; default: throw new Exception(); } } CompletionFilterKind GetFilterKind(int index, CompletionFilter filter) { // Is there a safer rule to determine what kind of filter it is? return index == 0 ? CompletionFilterKind.Blacklist : CompletionFilterKind.Whitelist; } } public void UpdateActiveFilters(ImmutableArray<CompletionFilterWithState> filterStates) { Debug.Assert(filterStates.Length == filters.Length); BitField64 selection = default; for (int i = 0; i < filterStates.Length; i++) { if (filterStates[i].IsSelected) { selection.SetBit(i); } } activeBlacklist = ~selection & blacklist; activeWhitelist = selection & whitelist; } public BitField64 CreateFilterMask(ImmutableArray<CompletionFilter> completionFilters) { BitField64 mask = default; for (int i = 0; i < completionFilters.Length; i++) { int index = Array.IndexOf(filters, completionFilters[i]); Debug.Assert(index >= 0); mask.SetBit(index); } return mask; } public bool HasActiveBlacklistFilter(BitField64 completionFilters) { bool isOnBlacklist = (activeBlacklist & completionFilters) != default; return isOnBlacklist; } public bool HasActiveWhitelistFilter(BitField64 completionFilters) { Debug.Assert(HasActiveWhitelist); bool isOnWhitelist = (activeWhitelist & completionFilters) != default; return isOnWhitelist; } public bool PassesActiveFilters(
BitField64 completionFilters) {
return !HasActiveBlacklistFilter(completionFilters) && HasActiveWhitelistFilter(completionFilters); } } private void AddDebugSuffix(ref VSCompletionItem completion, in CompletionItemKey key) { var patternScoreString = key.patternScore == int.MinValue ? "-" : key.patternScore.ToString(); var defaultIndexString = key.defaultIndex == int.MaxValue ? "-" : key.defaultIndex.ToString(); var roslynScoreString = key.roslynScore == 0 ? "-" : key.roslynScore.ToString(); var debugSuffix = $" (pattScr: {patternScoreString}, dfltIdx: {defaultIndexString}, roslScr: {roslynScoreString}, initIdx: {key.initialIndex})"; var modifiedCompletion = new VSCompletionItem ( completion.DisplayText, completion.Source, completion.Icon, completion.Filters, completion.Suffix + debugSuffix, completion.InsertText, completion.SortText, completion.FilterText, completion.AutomationText, completion.AttributeIcons, completion.CommitCharacters, completion.ApplicableToSpan, completion.IsCommittedAsSnippet, completion.IsPreselected ); foreach (var property in completion.Properties.PropertyList) { modifiedCompletion.Properties.AddProperty(property.Key, property.Value); } completion = modifiedCompletion; } } }
VSIntelliSenseTweaks/CompletionItemManager.cs
cfognom-VSIntelliSenseTweaks-4099741
[ { "filename": "VSIntelliSenseTweaks/Utilities/WordScorer.cs", "retrieved_chunk": " public int End => Start + length;\n public int EndInPattern => startInPattern + length;\n public int Length => length;\n public bool IsSubwordStart => IsSubwordStart_AsInt == 1;\n public int IsSubwordStart_AsInt => isSubwordStart_start >> 15;\n public MatchedSpan(int start, int startInPattern, int length, bool isSubwordStart)\n {\n Debug.Assert(start >= 0);\n Debug.Assert(start < 1 << 15);\n Debug.Assert(startInPattern >= 0);", "score": 0.7963376045227051 }, { "filename": "VSIntelliSenseTweaks/Utilities/WordScorer.cs", "retrieved_chunk": " {\n public short minPos;\n public short maxPos;\n public bool IsInRange(int index)\n {\n return minPos <= index && index <= maxPos;\n }\n }\n static bool Prospect(ReadOnlySpan<char> word, ReadOnlySpan<char> pattern, Span<CharRange> ranges)\n {", "score": 0.7827476263046265 }, { "filename": "VSIntelliSenseTweaks/Utilities/WordScorer.cs", "retrieved_chunk": " }\n private struct MatchedSpan\n {\n // Kept small to decrease allocation size.\n ushort isSubwordStart_start;\n byte startInPattern;\n byte length;\n public bool IsValid => length != 0;\n public int Start => isSubwordStart_start & ((1 << 15) - 1);\n public int StartInPattern => startInPattern;", "score": 0.7804279923439026 }, { "filename": "VSIntelliSenseTweaks/Utilities/BitSpan.cs", "retrieved_chunk": " return (n_bits - 1) / 32 + 1;\n }\n public BitSpan(Span<int> data)\n {\n this.data = data;\n }\n public bool this[int index]\n {\n get => GetBit(index);\n set", "score": 0.7795082330703735 }, { "filename": "VSIntelliSenseTweaks/Utilities/WordScorer.cs", "retrieved_chunk": " }\n public Span ToSpan()\n {\n return new Span(Start, Length);\n }\n public MatchedSpan TrimFront(int count)\n {\n Debug.Assert(count < length);\n return new MatchedSpan(Start + count, StartInPattern + count, Length - count, false);\n }", "score": 0.7775248289108276 } ]
csharp
BitField64 completionFilters) {
using HarmonyLib; using Mono.Cecil; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Text; using UnityEngine; namespace Ultrapain.Patches { /* u = initial, f = final, d = delta, s = speed multiplier u = 40f * Time.deltaTime f = 40f * S * Time.deltaTime d = 40f * Time.deltaTime * (S - 1) revCharge += 40f * Time.deltaTime * (S - 1f) * (alt ? 0.5f : 1f) */ class Revolver_Update { static bool Prefix(Revolver __instance) { if(__instance.gunVariation == 0 && __instance.pierceCharge < 100f) { __instance.pierceCharge = Mathf.Min(100f, __instance.pierceCharge + 40f * Time.deltaTime * (ConfigManager.chargedRevRegSpeedMulti.value - 1f) * (__instance.altVersion ? 0.5f : 1f)); } return true; } } public class Revolver_Shoot { public static void RevolverBeamEdit(RevolverBeam beam) { beam.damage -= beam.strongAlt ? 1.25f : 1f; beam.damage += beam.strongAlt ? ConfigManager.revolverAltDamage.value : ConfigManager.revolverDamage.value; } public static void RevolverBeamSuperEdit(RevolverBeam beam) { if (beam.gunVariation == 0) { beam.damage -= beam.strongAlt ? 1.25f : 1f; beam.damage += beam.strongAlt ? ConfigManager.chargedAltRevDamage.value : ConfigManager.chargedRevDamage.value; beam.hitAmount = beam.strongAlt ? ConfigManager.chargedAltRevTotalHits.value : ConfigManager.chargedRevTotalHits.value; beam.maxHitsPerTarget = beam.strongAlt ? ConfigManager.chargedAltRevMaxHitsPerTarget.value : ConfigManager.chargedRevMaxHitsPerTarget.value; } else if (beam.gunVariation == 2) { beam.damage -= beam.strongAlt ? 1.25f : 1f; beam.damage += beam.strongAlt ? ConfigManager.sharpshooterAltDamage.value : ConfigManager.sharpshooterDamage.value; beam.maxHitsPerTarget = beam.strongAlt ? ConfigManager.sharpshooterAltMaxHitsPerTarget.value : ConfigManager.sharpshooterMaxHitsPerTarget.value; } } static FieldInfo f_RevolverBeam_gunVariation = typeof(RevolverBeam).GetField("gunVariation", UnityUtils.instanceFlag); static MethodInfo m_Revolver_Shoot_RevolverBeamEdit = typeof(Revolver_Shoot).GetMethod("RevolverBeamEdit", UnityUtils.staticFlag); static MethodInfo m_Revolver_Shoot_RevolverBeamSuperEdit = typeof(Revolver_Shoot).GetMethod("RevolverBeamSuperEdit", UnityUtils.staticFlag); static MethodInfo m_GameObject_GetComponent_RevolverBeam = typeof(GameObject).GetMethod("GetComponent", new Type[0], new ParameterModifier[0]).MakeGenericMethod(new Type[1] { typeof(RevolverBeam) }); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); object normalBeamLocalIndex = null; object superBeamLocalIndex = null; // Get local indexes of components for RevolverBeam references for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Callvirt && code[i].OperandIs(m_GameObject_GetComponent_RevolverBeam)) { object localIndex = ILUtils.GetLocalIndex(code[i + 1]); if (localIndex == null) continue; if (normalBeamLocalIndex == null) { normalBeamLocalIndex = localIndex; } else { superBeamLocalIndex = localIndex; break; } } } Debug.Log($"Normal beam index: {normalBeamLocalIndex}"); Debug.Log($"Super beam index: {superBeamLocalIndex}"); // Modify normal beam for (int i = 3; i < code.Count; i++) { if (code[i].opcode == OpCodes.Stfld && code[i].OperandIs(f_RevolverBeam_gunVariation)) { object localIndex = ILUtils.GetLocalIndex(code[i - 3]); if (localIndex == null) continue; if (localIndex.Equals(normalBeamLocalIndex)) { Debug.Log($"Patching normal beam"); i += 1; code.Insert(i, ILUtils.LoadLocalInstruction(localIndex)); i += 1; code.Insert(i, new CodeInstruction(OpCodes.Call, m_Revolver_Shoot_RevolverBeamEdit)); break; } } } // Modify super beam for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Stfld && code[i].OperandIs(f_RevolverBeam_gunVariation)) { object localIndex = ILUtils.GetLocalIndex(code[i - 3]); if (localIndex == null) continue; if (localIndex.Equals(superBeamLocalIndex)) { Debug.Log($"Patching super beam"); i += 1; code.Insert(i, ILUtils.LoadLocalInstruction(localIndex)); i += 1; code.Insert(i, new CodeInstruction(OpCodes.Call, m_Revolver_Shoot_RevolverBeamSuperEdit)); break; } } } return code.AsEnumerable(); } } public class Shotgun_Shoot { public static void ModifyShotgunPellet(Projectile proj, Shotgun shotgun, int primaryCharge) { if (shotgun.variation == 0) { proj.damage = ConfigManager.shotgunBlueDamagePerPellet.value; } else { if (primaryCharge == 0) proj.damage = ConfigManager.shotgunGreenPump1Damage.value; else if (primaryCharge == 1) proj.damage = ConfigManager.shotgunGreenPump2Damage.value; else if (primaryCharge == 2) proj.damage = ConfigManager.shotgunGreenPump3Damage.value; } } public static void ModifyPumpExplosion(Explosion exp) { exp.damage = ConfigManager.shotgunGreenExplosionDamage.value; exp.playerDamageOverride = ConfigManager.shotgunGreenExplosionPlayerDamage.value; float sizeMulti = ConfigManager.shotgunGreenExplosionSize.value / 9f; exp.maxSize *= sizeMulti; exp.speed *= sizeMulti; exp.speed *= ConfigManager.shotgunGreenExplosionSpeed.value; } static MethodInfo m_GameObject_GetComponent_Projectile = typeof(GameObject).GetMethod("GetComponent", new Type[0], new ParameterModifier[0]).MakeGenericMethod(new Type[1] { typeof(Projectile) }); static MethodInfo m_GameObject_GetComponentsInChildren_Explosion = typeof(GameObject).GetMethod("GetComponentsInChildren", new Type[0], new ParameterModifier[0]).MakeGenericMethod(new Type[1] { typeof(Explosion) }); static MethodInfo m_Shotgun_Shoot_ModifyShotgunPellet = typeof(Shotgun_Shoot).GetMethod("ModifyShotgunPellet", UnityUtils.staticFlag); static MethodInfo m_Shotgun_Shoot_ModifyPumpExplosion = typeof(Shotgun_Shoot).GetMethod("ModifyPumpExplosion", UnityUtils.staticFlag); static FieldInfo f_Shotgun_primaryCharge = typeof(Shotgun).GetField("primaryCharge", UnityUtils.instanceFlag); static FieldInfo f_Explosion_damage = typeof(Explosion).GetField("damage", UnityUtils.instanceFlag); static bool Prefix(Shotgun __instance, int ___primaryCharge) { if (__instance.variation == 0) { __instance.spread = ConfigManager.shotgunBlueSpreadAngle.value; } else { if (___primaryCharge == 0) __instance.spread = ConfigManager.shotgunGreenPump1Spread.value * 1.5f; else if (___primaryCharge == 1) __instance.spread = ConfigManager.shotgunGreenPump2Spread.value; else if (___primaryCharge == 2) __instance.spread = ConfigManager.shotgunGreenPump3Spread.value / 2f; } return true; } static void Postfix(Shotgun __instance) { __instance.spread = 10f; } static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); CodeInstruction pelletStoreInst = new CodeInstruction(OpCodes.Stloc_0); int pelletCodeIndex = 0; // Find pellet local variable index for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Ldc_I4_S && code[i].OperandIs(12)) { if (ConfigManager.shotgunBluePelletCount.value > sbyte.MaxValue) code[i].opcode = OpCodes.Ldc_I4; code[i].operand = ConfigManager.shotgunBluePelletCount.value; i += 1; pelletCodeIndex = i; pelletStoreInst = code[i]; break; } } // Debug.Log($"Pellet store instruction: {ILUtils.TurnInstToString(pelletStoreInst)}"); // Modify pellet counts for (int i = pelletCodeIndex + 1; i < code.Count; i++) { if (code[i].opcode == pelletStoreInst.opcode && (pelletStoreInst.operand == null ? true : pelletStoreInst.operand.Equals(code[i].operand)) && ILUtils.IsConstI4LoadWithOperand(code[i - 1].opcode)) { int constIndex = i - 1; int pelletCount = ILUtils.GetI4LoadOperand(code[constIndex]); if (pelletCount == 10) pelletCount = ConfigManager.shotgunGreenPump1Count.value; else if (pelletCount == 16) pelletCount = ConfigManager.shotgunGreenPump2Count.value; else if (pelletCount == 24) pelletCount = ConfigManager.shotgunGreenPump3Count.value; if (ILUtils.TryEfficientLoadI4(pelletCount, out OpCode efficientOpcode)) { code[constIndex].operand = null; code[constIndex].opcode = efficientOpcode; } else { if (pelletCount > sbyte.MaxValue) code[constIndex].opcode = OpCodes.Ldc_I4; else code[constIndex].opcode = OpCodes.Ldc_I4_S; code[constIndex].operand = pelletCount; } } } // Modify projectile damage for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Callvirt && code[i].OperandIs(m_GameObject_GetComponent_Projectile)) { i += 1; // Duplicate component (arg 0) code.Insert(i, new CodeInstruction(OpCodes.Dup)); i += 1; // Add instance to stack (arg 1) code.Insert(i, new CodeInstruction(OpCodes.Ldarg_0)); i += 1; // Load instance then get primary field (arg 2) code.Insert(i, new CodeInstruction(OpCodes.Ldarg_0)); i += 1; code.Insert(i, new CodeInstruction(OpCodes.Ldfld, f_Shotgun_primaryCharge)); i += 1; // Call the static method code.Insert(i, new CodeInstruction(OpCodes.Call, m_Shotgun_Shoot_ModifyShotgunPellet)); break; } } // Modify pump explosion int pumpExplosionIndex = 0; while (code[pumpExplosionIndex].opcode != OpCodes.Callvirt && !code[pumpExplosionIndex].OperandIs(m_GameObject_GetComponentsInChildren_Explosion)) pumpExplosionIndex += 1; for (int i = pumpExplosionIndex; i < code.Count; i++) { if (code[i].opcode == OpCodes.Stfld) { if (code[i].OperandIs(f_Explosion_damage)) { // Duplicate before damage assignment code.Insert(i - 1, new CodeInstruction(OpCodes.Dup)); i += 2; // Argument 0 already loaded, call the method code.Insert(i, new CodeInstruction(OpCodes.Call, m_Shotgun_Shoot_ModifyPumpExplosion)); // Stack is now clear break; } } } return code.AsEnumerable(); } } // Core eject class Shotgun_ShootSinks { public static void ModifyCoreEject(GameObject core) { GrenadeExplosionOverride ovr = core.AddComponent<GrenadeExplosionOverride>(); ovr.normalMod = true; ovr.normalDamage = (float)ConfigManager.shotgunCoreExplosionDamage.value / 35f; ovr.normalSize = (float)ConfigManager.shotgunCoreExplosionSize.value / 6f * ConfigManager.shotgunCoreExplosionSpeed.value; ovr.normalPlayerDamageOverride = ConfigManager.shotgunCoreExplosionPlayerDamage.value; ovr.superMod = true; ovr.superDamage = (float)ConfigManager.shotgunCoreExplosionDamage.value / 35f; ovr.superSize = (float)ConfigManager.shotgunCoreExplosionSize.value / 6f * ConfigManager.shotgunCoreExplosionSpeed.value; ovr.superPlayerDamageOverride = ConfigManager.shotgunCoreExplosionPlayerDamage.value; } static FieldInfo f_Grenade_sourceWeapon = typeof(Grenade).GetField("sourceWeapon", UnityUtils.instanceFlag); static MethodInfo m_Shotgun_ShootSinks_ModifyCoreEject = typeof(Shotgun_ShootSinks).GetMethod("ModifyCoreEject", UnityUtils.staticFlag); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Stfld && code[i].OperandIs(f_Grenade_sourceWeapon)) { i += 1; // Add arg 0 code.Insert(i, new CodeInstruction(OpCodes.Dup)); i += 1; // Call mod method code.Insert(i, new CodeInstruction(OpCodes.Call, m_Shotgun_ShootSinks_ModifyCoreEject)); break; } } return code.AsEnumerable(); } } class Nailgun_Shoot { static FieldInfo f_Nailgun_heatSinks = typeof(Nailgun).GetField("heatSinks", UnityUtils.instanceFlag); static FieldInfo f_Nailgun_heatUp = typeof(Nailgun).GetField("heatUp", UnityUtils.instanceFlag); public static void ModifyNail(Nailgun inst,
GameObject nail) {
Nail comp = nail.GetComponent<Nail>(); if (inst.altVersion) { // Blue saw launcher if (inst.variation == 1) { comp.damage = ConfigManager.sawBlueDamage.value; comp.hitAmount = ConfigManager.sawBlueHitAmount.value; } // Green saw launcher else { comp.damage = ConfigManager.sawGreenDamage.value; float maxHit = ConfigManager.sawGreenHitAmount.value; float heatSinks = (float)f_Nailgun_heatSinks.GetValue(inst); float heatUp = (float)f_Nailgun_heatUp.GetValue(inst); if (heatSinks >= 1) comp.hitAmount = Mathf.Lerp(maxHit, Mathf.Max(1f, maxHit), (maxHit - 2f) * heatUp); else comp.hitAmount = 1f; } } else { // Blue nailgun if (inst.variation == 1) { comp.damage = ConfigManager.nailgunBlueDamage.value; } else { if (comp.heated) comp.damage = ConfigManager.nailgunGreenBurningDamage.value; else comp.damage = ConfigManager.nailgunGreenDamage.value; } } } static FieldInfo f_Nailgun_nail = typeof(Nailgun).GetField("nail", UnityUtils.instanceFlag); static MethodInfo m_Nailgun_Shoot_ModifyNail = typeof(Nailgun_Shoot).GetMethod("ModifyNail", UnityUtils.staticFlag); static MethodInfo m_Transform_set_forward = typeof(Transform).GetProperty("forward", UnityUtils.instanceFlag).GetSetMethod(); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); CodeInstruction localObjectStoreInst = null; for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Ldfld && code[i].OperandIs(f_Nailgun_nail)) { for (; i < code.Count; i++) if (ILUtils.IsStoreLocalOpcode(code[i].opcode)) break; localObjectStoreInst = code[i]; } } Debug.Log($"Nail local reference: {ILUtils.TurnInstToString(localObjectStoreInst)}"); int insertIndex = 0; for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Callvirt && code[i].OperandIs(m_Transform_set_forward)) { insertIndex = i + 1; break; } } // Push instance reference code.Insert(insertIndex, new CodeInstruction(OpCodes.Ldarg_0)); insertIndex += 1; // Push local nail object code.Insert(insertIndex, new CodeInstruction(ILUtils.GetLoadLocalFromStoreLocal(localObjectStoreInst.opcode), localObjectStoreInst.operand)); insertIndex += 1; // Call the method code.Insert(insertIndex, new CodeInstruction(OpCodes.Call, m_Nailgun_Shoot_ModifyNail)); return code.AsEnumerable(); } } class Nailgun_SuperSaw { public static void ModifySupersaw(GameObject supersaw) { Nail saw = supersaw.GetComponent<Nail>(); saw.damage = ConfigManager.sawGreenBurningDamage.value; saw.hitAmount = ConfigManager.sawGreenBurningHitAmount.value; } static FieldInfo f_Nailgun_heatedNail = typeof(Nailgun).GetField("heatedNail", UnityUtils.instanceFlag); static MethodInfo m_Nailgun_SuperSaw_ModifySupersaw = typeof(Nailgun_SuperSaw).GetMethod("ModifySupersaw", UnityUtils.staticFlag); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); CodeInstruction localObjectStoreInst = null; for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Ldfld && code[i].OperandIs(f_Nailgun_heatedNail)) { for (; i < code.Count; i++) if (ILUtils.IsStoreLocalOpcode(code[i].opcode)) break; localObjectStoreInst = code[i]; } } Debug.Log($"Supersaw local reference: {ILUtils.TurnInstToString(localObjectStoreInst)}"); int insertIndex = code.Count - 1; // Push local nail object code.Insert(insertIndex, new CodeInstruction(ILUtils.GetLoadLocalFromStoreLocal(localObjectStoreInst.opcode), localObjectStoreInst.operand)); insertIndex += 1; // Call the method code.Insert(insertIndex, new CodeInstruction(OpCodes.Call, m_Nailgun_SuperSaw_ModifySupersaw)); return code.AsEnumerable(); } } class NailGun_Update { static bool Prefix(Nailgun __instance, ref float ___heatSinks) { if(__instance.variation == 0) { float maxSinks = (__instance.altVersion ? 1f : 2f); float multi = (__instance.altVersion ? ConfigManager.sawHeatsinkRegSpeedMulti.value : ConfigManager.nailgunHeatsinkRegSpeedMulti.value); float rate = 0.125f; if (___heatSinks < maxSinks && multi != 1) ___heatSinks = Mathf.Min(maxSinks, ___heatSinks + Time.deltaTime * rate * (multi - 1f)); } return true; } } class NewMovement_Update { static bool Prefix(NewMovement __instance, int ___difficulty) { if (__instance.boostCharge < 300f && !__instance.sliding && !__instance.slowMode) { float multi = 1f; if (___difficulty == 1) multi = 1.5f; else if (___difficulty == 0f) multi = 2f; __instance.boostCharge = Mathf.Min(300f, __instance.boostCharge + Time.deltaTime * 70f * multi * (ConfigManager.staminaRegSpeedMulti.value - 1f)); } return true; } } class WeaponCharges_Charge { static bool Prefix(WeaponCharges __instance, float __0) { if (__instance.rev1charge < 400f) __instance.rev1charge = Mathf.Min(400f, __instance.rev1charge + 25f * __0 * (ConfigManager.coinRegSpeedMulti.value - 1f)); if (__instance.rev2charge < 300f) __instance.rev2charge = Mathf.Min(300f, __instance.rev2charge + (__instance.rev2alt ? 35f : 15f) * __0 * (ConfigManager.sharpshooterRegSpeedMulti.value - 1f)); if(!__instance.naiAmmoDontCharge) { if (__instance.naiAmmo < 100f) __instance.naiAmmo = Mathf.Min(100f, __instance.naiAmmo + __0 * 3.5f * (ConfigManager.nailgunAmmoRegSpeedMulti.value - 1f)); ; if (__instance.naiSaws < 10f) __instance.naiSaws = Mathf.Min(10f, __instance.naiSaws + __0 * 0.5f * (ConfigManager.sawAmmoRegSpeedMulti.value - 1f)); } if (__instance.raicharge < 5f) __instance.raicharge = Mathf.Min(5f, __instance.raicharge + __0 * 0.25f * (ConfigManager.railcannonRegSpeedMulti.value - 1f)); if (!__instance.rocketFrozen && __instance.rocketFreezeTime < 5f) __instance.rocketFreezeTime = Mathf.Min(5f, __instance.rocketFreezeTime + __0 * 0.5f * (ConfigManager.rocketFreezeRegSpeedMulti.value - 1f)); if (__instance.rocketCannonballCharge < 1f) __instance.rocketCannonballCharge = Mathf.Min(1f, __instance.rocketCannonballCharge + __0 * 0.125f * (ConfigManager.rocketCannonballRegSpeedMulti.value - 1f)); return true; } } class NewMovement_GetHurt { static bool Prefix(NewMovement __instance, out float __state) { __state = __instance.antiHp; return true; } static void Postfix(NewMovement __instance, float __state) { float deltaAnti = __instance.antiHp - __state; if (deltaAnti <= 0) return; deltaAnti *= ConfigManager.hardDamagePercent.normalizedValue; __instance.antiHp = __state + deltaAnti; } static FieldInfo hpField = typeof(NewMovement).GetField("hp"); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Ldfld && (FieldInfo)code[i].operand == hpField) { i += 1; if (code[i].opcode == OpCodes.Ldc_I4_S) { code[i] = new CodeInstruction(OpCodes.Ldc_I4, (Int32)ConfigManager.maxPlayerHp.value); } } else if (code[i].opcode == OpCodes.Ldc_R4 && (Single)code[i].operand == (Single)99f) { code[i] = new CodeInstruction(OpCodes.Ldc_R4, (Single)(ConfigManager.maxPlayerHp.value - 1)); } } return code.AsEnumerable(); } } class HookArm_FixedUpdate { static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Ldc_R4 && (Single)code[i].operand == 66f) { code[i] = new CodeInstruction(OpCodes.Ldc_R4, (Single)(66f * (ConfigManager.maxPlayerHp.value / 100f) * ConfigManager.whiplashHardDamageSpeed.value)); } else if (code[i].opcode == OpCodes.Ldc_R4 && (Single)code[i].operand == 50f) { code[i] = new CodeInstruction(OpCodes.Ldc_R4, (Single)(ConfigManager.whiplashHardDamageCap.value)); } } return code.AsEnumerable(); } } class NewMovement_ForceAntiHP { static FieldInfo hpField = typeof(NewMovement).GetField("hp"); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Ldfld && (FieldInfo)code[i].operand == hpField) { i += 1; if (i < code.Count && code[i].opcode == OpCodes.Ldc_I4_S && (SByte)code[i].operand == (SByte)100) { code[i] = new CodeInstruction(OpCodes.Ldc_I4, (Int32)ConfigManager.maxPlayerHp.value); } } else if (code[i].opcode == OpCodes.Ldarg_1) { i += 2; if (i < code.Count && code[i].opcode == OpCodes.Ldc_R4 && (Single)code[i].operand == 99f) { code[i] = new CodeInstruction(OpCodes.Ldc_R4, (Single)(ConfigManager.maxPlayerHp.value - 1)); } } else if (code[i].opcode == OpCodes.Ldc_R4 && (Single)code[i].operand == 100f) { code[i] = new CodeInstruction(OpCodes.Ldc_R4, (Single)ConfigManager.maxPlayerHp.value); } else if (code[i].opcode == OpCodes.Ldc_R4 && (Single)code[i].operand == 50f) { code[i] = new CodeInstruction(OpCodes.Ldc_R4, (Single)ConfigManager.maxPlayerHp.value / 2); } else if (code[i].opcode == OpCodes.Ldc_I4_S && (SByte)code[i].operand == (SByte)100) { code[i] = new CodeInstruction(OpCodes.Ldc_I4, (Int32)ConfigManager.maxPlayerHp.value); } } return code.AsEnumerable(); } } class NewMovement_GetHealth { static bool Prefix(NewMovement __instance, int __0, bool __1, ref AudioSource ___greenHpAud, Canvas ___fullHud) { if (__instance.dead || __instance.exploded) return false; int maxHp = Mathf.RoundToInt(ConfigManager.maxPlayerHp.value - __instance.antiHp); int maxDelta = maxHp - __instance.hp; if (maxDelta <= 0) return true; if (!__1 && __0 > 5 && MonoSingleton<PrefsManager>.Instance.GetBoolLocal("bloodEnabled", false)) { GameObject.Instantiate<GameObject>(__instance.scrnBlood, ___fullHud.transform); } __instance.hp = Mathf.Min(maxHp, __instance.hp + __0); __instance.hpFlash.Flash(1f); if (!__1 && __0 > 5) { if (___greenHpAud == null) { ___greenHpAud = __instance.hpFlash.GetComponent<AudioSource>(); } ___greenHpAud.Play(); } return false; } } class NewMovement_SuperCharge { static bool Prefix(NewMovement __instance) { __instance.hp = Mathf.Max(ConfigManager.maxPlayerHp.value, ConfigManager.playerHpSupercharge.value); return false; } } class NewMovement_Respawn { static void Postfix(NewMovement __instance) { __instance.hp = ConfigManager.maxPlayerHp.value; } } class NewMovement_DeltaHpComp : MonoBehaviour { public static NewMovement_DeltaHpComp instance; private NewMovement player; private AudioSource hurtAud; private bool levelMap = false; private void Awake() { instance = this; player = NewMovement.Instance; hurtAud = player.hurtScreen.GetComponent<AudioSource>(); levelMap = SceneHelper.CurrentLevelNumber > 0; UpdateEnabled(); } public void UpdateEnabled() { if (!ConfigManager.playerHpDeltaToggle.value) enabled = false; if (SceneHelper.CurrentScene == "uk_construct") enabled = ConfigManager.playerHpDeltaSandbox.value; else if (SceneHelper.CurrentScene == "Endless") enabled = ConfigManager.playerHpDeltaCybergrind.value; else { enabled = SceneHelper.CurrentLevelNumber > 0; } } public void ResetCooldown() { deltaCooldown = ConfigManager.playerHpDeltaDelay.value; } public float deltaCooldown = ConfigManager.playerHpDeltaDelay.value; public void Update() { if (player.dead || !ConfigManager.playerHpDeltaToggle.value || !StatsManager.Instance.timer) { ResetCooldown(); return; } if (levelMap) { // Calm if (MusicManager.Instance.requestedThemes == 0) { if (!ConfigManager.playerHpDeltaCalm.value) { ResetCooldown(); return; } } // Combat else { if (!ConfigManager.playerHpDeltaCombat.value) { ResetCooldown(); return; } } } deltaCooldown = Mathf.MoveTowards(deltaCooldown, 0f, Time.deltaTime); if (deltaCooldown == 0f) { ResetCooldown(); int deltaHp = ConfigManager.playerHpDeltaAmount.value; int limit = ConfigManager.playerHpDeltaLimit.value; if (deltaHp == 0) return; if (deltaHp > 0) { if (player.hp > limit) return; player.GetHealth(deltaHp, true); } else { if (player.hp < limit) return; if (player.hp - deltaHp <= 0) player.GetHurt(-deltaHp, false, 0, false, false); else { player.hp += deltaHp; if (ConfigManager.playerHpDeltaHurtAudio.value) { hurtAud.pitch = UnityEngine.Random.Range(0.8f, 1f); hurtAud.PlayOneShot(hurtAud.clip); } } } } } } class NewMovement_Start { static void Postfix(NewMovement __instance) { __instance.gameObject.AddComponent<NewMovement_DeltaHpComp>(); __instance.hp = ConfigManager.maxPlayerHp.value; } } class HealthBarTracker : MonoBehaviour { public static List<HealthBarTracker> instances = new List<HealthBarTracker>(); private HealthBar hb; private void Awake() { if (hb == null) hb = GetComponent<HealthBar>(); instances.Add(this); for (int i = instances.Count - 1; i >= 0; i--) { if (instances[i] == null) instances.RemoveAt(i); } } private void OnDestroy() { if (instances.Contains(this)) instances.Remove(this); } public void SetSliderRange() { if (hb == null) hb = GetComponent<HealthBar>(); if (hb.hpSliders.Length != 0) { hb.hpSliders[0].maxValue = hb.afterImageSliders[0].maxValue = ConfigManager.maxPlayerHp.value; hb.hpSliders[1].minValue = hb.afterImageSliders[1].minValue = ConfigManager.maxPlayerHp.value; hb.hpSliders[1].maxValue = hb.afterImageSliders[1].maxValue = Mathf.Max(ConfigManager.maxPlayerHp.value, ConfigManager.playerHpSupercharge.value); hb.antiHpSlider.maxValue = ConfigManager.maxPlayerHp.value; } } } class HealthBar_Start { static void Postfix(HealthBar __instance) { __instance.gameObject.AddComponent<HealthBarTracker>().SetSliderRange(); } } class HealthBar_Update { static FieldInfo f_HealthBar_hp = typeof(HealthBar).GetField("hp", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); static FieldInfo f_HealthBar_antiHp = typeof(HealthBar).GetField("antiHp", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); for (int i = 0; i < code.Count; i++) { CodeInstruction inst = code[i]; if (inst.opcode == OpCodes.Ldc_R4 && code[i - 1].OperandIs(f_HealthBar_hp)) { float operand = (Single)inst.operand; if (operand == 30f) code[i].operand = (Single)(ConfigManager.maxPlayerHp.value * 0.3f); else if (operand == 50f) code[i].operand = (Single)(ConfigManager.maxPlayerHp.value * 0.5f); } else if (inst.opcode == OpCodes.Ldstr) { string operand = (string)inst.operand; if (operand == "/200") code[i].operand = $"/{ConfigManager.playerHpSupercharge}"; } else if (inst.opcode == OpCodes.Ldc_R4 && i + 2 < code.Count && code[i + 2].OperandIs(f_HealthBar_antiHp)) { code[i].operand = (Single)ConfigManager.maxPlayerHp.value; } } return code.AsEnumerable(); } } }
Ultrapain/Patches/PlayerStatTweaks.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/V2Second.cs", "retrieved_chunk": " //readonly static FieldInfo maliciousIgnorePlayer = typeof(RevolverBeam).GetField(\"maliciousIgnorePlayer\", BindingFlags.NonPublic | BindingFlags.Instance);\n Transform shootPoint;\n public Transform v2trans;\n public float cooldown = 0f;\n static readonly string debugTag = \"[V2][MalCannonShoot]\";\n void Awake()\n {\n shootPoint = UnityUtils.GetChildByNameRecursively(transform, \"Shootpoint\");\n }\n void PrepareFire()", "score": 0.7973393201828003 }, { "filename": "Ultrapain/Patches/Cerberus.cs", "retrieved_chunk": " ___eid.health -= ConfigManager.cerberusParryDamage.value;\n MonoSingleton<FistControl>.Instance.currentPunch.Parry(false, ___eid);\n return true;\n }\n }\n class StatueBoss_StopDash_Patch\n {\n public static void Postfix(StatueBoss __instance, ref int ___tackleChance)\n {\n CerberusFlag flag = __instance.GetComponent<CerberusFlag>();", "score": 0.7755454778671265 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public Sprite sprite;\n public Color color;\n public ConfigField field;\n private GameObject currentUI;\n private Image currentImage;\n private static FieldInfo f_IntField_currentUi = typeof(IntField).GetField(\"currentUi\", UnityUtils.instanceFlag);\n private static FieldInfo f_FloatField_currentUi = typeof(FloatField).GetField(\"currentUi\", UnityUtils.instanceFlag);\n private static FieldInfo f_StringField_currentUi = typeof(StringField).GetField(\"currentUi\", UnityUtils.instanceFlag);\n private const float textAnchorX = 40f;\n private const float fieldAnchorX = 230f;", "score": 0.7735682129859924 }, { "filename": "Ultrapain/Patches/Turret.cs", "retrieved_chunk": " else\n flag.shootCountRemaining = ConfigManager.turretBurstFireCount.value;\n return true;\n }\n }\n class TurretAim\n {\n static void Postfix(Turret __instance)\n {\n TurretFlag flag = __instance.GetComponent<TurretFlag>();", "score": 0.773161768913269 }, { "filename": "Ultrapain/Patches/Whiplash.cs", "retrieved_chunk": "using HarmonyLib;\nusing System.Collections.Generic;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class HookArm_FixedUpdate_Patch\n {\n static bool Prefix(HookArm __instance, ref Grenade ___caughtGrenade, ref Vector3 ___caughtPoint, ref Vector3 ___hookPoint, ref float ___cooldown, ref List<Rigidbody> ___caughtObjects)\n {\n if (___caughtGrenade != null && ___caughtGrenade.rocket && !___caughtGrenade.playerRiding && MonoSingleton<WeaponCharges>.Instance.rocketFrozen)", "score": 0.7681694030761719 } ]
csharp
GameObject nail) {
using System; using System.Collections.Generic; using System.Linq; using System.Text; using AssemblyCacheHelper.DTO; using System.Threading; using System.Threading.Tasks; using System.Resources; namespace AssemblyCacheHelper { using System.IO; using System.Reflection; using System.Diagnostics; using System.Text.RegularExpressions; public class NetAssemblies { static List<
NetAssembly> _netAssemblyCache = new List<NetAssembly>();
public static List<NetAssembly> NetAssemblyCache { get { if (_netAssemblyCache.Count() == 0) { if (File.Exists("NetAssemblyCache.xml")) { StreamReader sr = new StreamReader("NetAssemblyCache.xml"); _netAssemblyCache = AssemblyCacheHelper.Serialization.DeserializeObject<List<NetAssembly>>(sr.ReadToEnd()); sr.Close(); } else { Stream stm = Assembly.GetExecutingAssembly().GetManifestResourceStream("AssemblyCacheHelper.Resources.NetAssemblyCache.xml"); StreamReader sr = new StreamReader(stm); _netAssemblyCache = AssemblyCacheHelper.Serialization.DeserializeObject<List<NetAssembly>>(sr.ReadToEnd()); sr.Close(); } } return _netAssemblyCache; } } public static NetAssembly GetAssemblyInfo(string assemblyFullPath, string runtimeVersion) { NetAssembly netAssembly = new NetAssembly(); FileInfo fi = new FileInfo(assemblyFullPath); netAssembly.ModifiedDate = fi.LastWriteTime.ToString("dd/MM/yyyy HH:mm:ss"); netAssembly.FileSize = fi.Length.ToString("###,###,##0.###"); netAssembly.AssemblyFilename = assemblyFullPath; var asmCache = (from asm in NetAssemblyCache where asm.ModifiedDate == netAssembly.ModifiedDate && asm.FileSize == netAssembly.FileSize && asm.AssemblyFilename == netAssembly.AssemblyFilename select asm).FirstOrDefault(); if (asmCache != null) { netAssembly.FileVersion = asmCache.FileVersion; netAssembly.FileDescription = asmCache.FileDescription; netAssembly.Company = asmCache.Company; netAssembly.ProductName = asmCache.ProductName; netAssembly.AssemblyName = asmCache.AssemblyName; netAssembly.AssemblyFullName = asmCache.AssemblyFullName; netAssembly.ProcessorArchitecture = asmCache.AssemblyFullName; netAssembly.RuntimeVersion = asmCache.RuntimeVersion; netAssembly.AssemblyVersion = asmCache.AssemblyVersion; netAssembly.Culture = asmCache.Culture; netAssembly.PublicKeyToken = asmCache.PublicKeyToken; } else { FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assemblyFullPath); netAssembly.FileVersion = fvi.FileVersion; netAssembly.FileDescription = fvi.FileDescription; netAssembly.Company = fvi.CompanyName; netAssembly.ProductName = fvi.ProductName; AssemblyName asmName = AssemblyName.GetAssemblyName(assemblyFullPath); netAssembly.AssemblyName = asmName.Name; netAssembly.AssemblyFullName = asmName.FullName; netAssembly.ProcessorArchitecture = asmName.ProcessorArchitecture.ToString(); netAssembly.RuntimeVersion = runtimeVersion; string asmFullName = asmName.FullName; string[] s = asmFullName.Split(','); netAssembly.AssemblyVersion = s[1].Replace(" Version=", ""); netAssembly.Culture = s[2].Replace(" Culture=", ""); netAssembly.PublicKeyToken = s[3].Replace(" PublicKeyToken=", ""); } return netAssembly; } public static string GetImageRuntimeVersion(string assemblyFullPath) { AppDomain appDomain = null; string assemblyVersion = ""; try { byte[] buffer = File.ReadAllBytes(assemblyFullPath); appDomain = AppDomain.CreateDomain("TempAppDomain"); Assembly assembly = appDomain.Load(buffer); assemblyVersion = assembly.ImageRuntimeVersion; } catch { } finally { if (appDomain != null) AppDomain.Unload(appDomain); } return assemblyVersion; } } }
AssemblyCacheHelper/NetAssemblies.cs
peterbaccaro-assembly-cache-explorer-a5dae15
[ { "filename": "AssemblyCacheHelper/DTO/NetAssemblyFile.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nnamespace AssemblyCacheHelper.DTO\n{\n public class NetAssemblyFile\n {\n public string AssemblyFilename { get; set; }\n public string RuntimeVersion { get; set; } ", "score": 0.8767970204353333 }, { "filename": "AssemblyCacheHelper/GACUtil.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nnamespace AssemblyCacheHelper\n{\n public class GACUtil\n {\n public static string AssemblyInstall(string gacUtilFullPath, string assemblyFullPath, bool force)\n {", "score": 0.8722655773162842 }, { "filename": "AssemblyCacheHelper/Serialization.cs", "retrieved_chunk": "using System;\nusing System.IO;\nusing System.Text;\nusing System.Xml;\nusing System.Xml.Serialization;\nnamespace AssemblyCacheHelper\n{\n public class Serialization\n {\n public static T DeserializeObject<T>(string xml)", "score": 0.8640013933181763 }, { "filename": "AssemblyCacheHelper/Utilities.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Diagnostics;\nusing System.IO;\nnamespace AssemblyCacheHelper\n{\n public class Utilities\n {", "score": 0.8633816242218018 }, { "filename": "AssemblyCacheHelper/DTO/NetAssembly.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nnamespace AssemblyCacheHelper.DTO\n{\n public class NetAssembly\n {\n public string AssemblyName { get; set; }\n public string AssemblyFullName { get; set; }", "score": 0.8629197478294373 } ]
csharp
NetAssembly> _netAssemblyCache = new List<NetAssembly>();
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace TreeifyTask { public class TaskNode : ITaskNode { private static Random rnd = new Random(); private readonly List<Task> taskObjects = new(); private readonly List<
ITaskNode> childTasks = new();
private bool hasCustomAction; private Func<IProgressReporter, CancellationToken, Task> action = async (rep, tok) => await Task.Yield(); public event ProgressReportingEventHandler Reporting; private bool seriesRunnerIsBusy; private bool concurrentRunnerIsBusy; public TaskNode() { this.Id = rnd.Next() + string.Empty; this.Reporting += OnSelfReporting; } public TaskNode(string Id) : this() { this.Id = Id ?? rnd.Next() + string.Empty; } public TaskNode(string Id, Func<IProgressReporter, CancellationToken, Task> cancellableProgressReportingAsyncFunction) : this(Id) { this.SetAction(cancellableProgressReportingAsyncFunction); } #region Props public string Id { get; set; } public double ProgressValue { get; private set; } public object ProgressState { get; private set; } public TaskStatus TaskStatus { get; private set; } public ITaskNode Parent { get; set; } public IEnumerable<ITaskNode> ChildTasks => this.childTasks; #endregion Props public void AddChild(ITaskNode childTask) { childTask = childTask ?? throw new ArgumentNullException(nameof(childTask)); childTask.Parent = this; // Ensure this after setting its parent as this EnsureNoCycles(childTask); childTask.Reporting += OnChildReporting; childTasks.Add(childTask); } private class ActionReport { public ActionReport() { this.TaskStatus = TaskStatus.NotStarted; this.ProgressValue = 0; this.ProgressState = null; } public ActionReport(ITaskNode task) { this.Id = task.Id; this.TaskStatus = task.TaskStatus; this.ProgressState = task.ProgressState; this.ProgressValue = task.ProgressValue; } public string Id { get; set; } public TaskStatus TaskStatus { get; set; } public double ProgressValue { get; set; } public object ProgressState { get; set; } public override string ToString() { return $"Id={Id},({TaskStatus}, {ProgressValue}, {ProgressState})"; } } private ActionReport selfActionReport = new(); private void OnSelfReporting(object sender, ProgressReportingEventArgs eventArgs) { TaskStatus = selfActionReport.TaskStatus = eventArgs.TaskStatus; ProgressValue = selfActionReport.ProgressValue = eventArgs.ProgressValue; ProgressState = selfActionReport.ProgressState = eventArgs.ProgressState; } private void OnChildReporting(object sender, ProgressReportingEventArgs eventArgs) { // Child task that reports var cTask = sender as ITaskNode; var allReports = childTasks.Select(t => new ActionReport(t)); if (hasCustomAction) { allReports = allReports.Append(selfActionReport); } this.TaskStatus = allReports.Any(v => v.TaskStatus == TaskStatus.InDeterminate) ? TaskStatus.InDeterminate : TaskStatus.InProgress; this.TaskStatus = allReports.Any(v => v.TaskStatus == TaskStatus.Failed) ? TaskStatus.Failed : this.TaskStatus; if (this.TaskStatus == TaskStatus.Failed) { this.ProgressState = new AggregateException($"{Id}: One or more error occurred in child tasks.", childTasks.Where(v => v.TaskStatus == TaskStatus.Failed && v.ProgressState is Exception) .Select(c => c.ProgressState as Exception)); } this.ProgressValue = allReports.Select(t => t.ProgressValue).Average(); SafeRaiseReportingEvent(this, new ProgressReportingEventArgs { ProgressValue = this.ProgressValue, TaskStatus = this.TaskStatus, ChildTasksRunningInParallel = concurrentRunnerIsBusy, ProgressState = seriesRunnerIsBusy ? cTask.ProgressState : this.ProgressState }); } public async Task ExecuteConcurrently(CancellationToken cancellationToken, bool throwOnError) { if (concurrentRunnerIsBusy || seriesRunnerIsBusy) return; concurrentRunnerIsBusy = true; ResetChildrenProgressValues(); foreach (var child in childTasks) { taskObjects.Add(child.ExecuteConcurrently(cancellationToken, throwOnError)); } taskObjects.Add(ExceptionHandledAction(cancellationToken, throwOnError)); if (taskObjects.Any()) { await Task.WhenAll(taskObjects); } if (throwOnError && taskObjects.Any(t => t.IsFaulted)) { var exs = taskObjects.Where(t => t.IsFaulted).Select(t => t.Exception); throw new AggregateException($"Internal error occurred while executing task - {Id}.", exs); } concurrentRunnerIsBusy = false; if (TaskStatus != TaskStatus.Failed) { if (cancellationToken.IsCancellationRequested) Report(TaskStatus.Cancelled, 0); else Report(TaskStatus.Completed, 100); } } private async Task ExceptionHandledAction(CancellationToken cancellationToken, bool throwOnError) { try { await action(this, cancellationToken); } catch (OperationCanceledException) { // Don't throw this as an error as we have to come out of await. } catch (Exception ex) { this.Report(TaskStatus.Failed, this.ProgressValue, ex); if (throwOnError) { throw new AggregateException($"Internal error occurred while executing the action of task - {Id}.", ex); } } } public async Task ExecuteInSeries(CancellationToken cancellationToken, bool throwOnError) { if (seriesRunnerIsBusy || concurrentRunnerIsBusy) return; seriesRunnerIsBusy = true; ResetChildrenProgressValues(); try { foreach (var child in childTasks) { if (cancellationToken.IsCancellationRequested) break; await child.ExecuteInSeries(cancellationToken, throwOnError); } await ExceptionHandledAction(cancellationToken, throwOnError); } catch (Exception ex) { if (throwOnError) { throw new AggregateException($"Internal error occurred while executing task - {Id}.", ex); } } seriesRunnerIsBusy = false; if (TaskStatus != TaskStatus.Failed) { if (cancellationToken.IsCancellationRequested) Report(TaskStatus.Cancelled, 0); else Report(TaskStatus.Completed, 100); } } public IEnumerable<ITaskNode> ToFlatList() { return FlatList(this); } private void SafeRaiseReportingEvent(object sender, ProgressReportingEventArgs args) { this.Reporting?.Invoke(sender, args); } private void ResetChildrenProgressValues() { taskObjects.Clear(); foreach (var task in childTasks) { task.ResetStatus(); } } /// <summary> /// Throws <see cref="AsyncTasksCycleDetectedException"/> /// </summary> /// <param name="newTask"></param> private void EnsureNoCycles(ITaskNode newTask) { var thisNode = this as ITaskNode; HashSet<ITaskNode> hSet = new HashSet<ITaskNode>(); while (true) { if (thisNode.Parent is null) { break; } if (hSet.Contains(thisNode)) { throw new TaskNodeCycleDetectedException(thisNode, newTask); } hSet.Add(thisNode); thisNode = thisNode.Parent; } var existingTask = FlatList(thisNode).FirstOrDefault(t => t == newTask); if (existingTask != null) { throw new TaskNodeCycleDetectedException(newTask, existingTask.Parent); } } private IEnumerable<ITaskNode> FlatList(ITaskNode root) { yield return root; foreach (var ct in root.ChildTasks) { foreach (var item in FlatList(ct)) yield return item; } } public void RemoveChild(ITaskNode childTask) { childTask.Reporting -= OnChildReporting; childTasks.Remove(childTask); } public void Report(TaskStatus taskStatus, double progressValue, object progressState = null) { SafeRaiseReportingEvent(this, new ProgressReportingEventArgs { ChildTasksRunningInParallel = concurrentRunnerIsBusy, TaskStatus = taskStatus, ProgressValue = progressValue, ProgressState = progressState }); } public void SetAction(Func<IProgressReporter, CancellationToken, Task> cancellableProgressReportingAction) { cancellableProgressReportingAction = cancellableProgressReportingAction ?? throw new ArgumentNullException(nameof(cancellableProgressReportingAction)); hasCustomAction = true; action = cancellableProgressReportingAction; } public void ResetStatus() { this.TaskStatus = TaskStatus.NotStarted; this.ProgressState = null; this.ProgressValue = 0; } public override string ToString() { return $"Id={Id},({TaskStatus}, {ProgressValue}, {ProgressState})"; } } }
Source/TreeifyTask/TaskTree/TaskNode.cs
intuit-TreeifyTask-4b124d4
[ { "filename": "Source/TreeifyTask.WpfSample/TaskNodeViewModel.cs", "retrieved_chunk": "using TreeifyTask;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nnamespace TreeifyTask.Sample\n{\n public class TaskNodeViewModel : INotifyPropertyChanged\n {\n private readonly ITaskNode baseTaskNode;\n private ObservableCollection<TaskNodeViewModel> _childTasks;\n private TaskStatus _taskStatus;", "score": 0.8895419239997864 }, { "filename": "Source/TreeifyTask/TaskTree/TaskNodeCycleDetectedException.cs", "retrieved_chunk": "using System;\nusing System.Runtime.Serialization;\nnamespace TreeifyTask\n{\n [Serializable]\n public class TaskNodeCycleDetectedException : Exception\n {\n public ITaskNode NewTask { get; }\n public ITaskNode ParentTask { get; }\n public string MessageStr { get; private set; }", "score": 0.874008059501648 }, { "filename": "Source/TreeifyTask/TaskTree/ITaskNode.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nnamespace TreeifyTask\n{\n public interface ITaskNode : IProgressReporter\n {\n string Id { get; set; }\n double ProgressValue { get; }", "score": 0.8681371808052063 }, { "filename": "Source/TreeifyTask.BlazorSample/TaskDataModel/code.cs", "retrieved_chunk": "using System;\nusing System.Threading.Tasks;\nnamespace TreeifyTask.BlazorSample\n{\n delegate Task CancellableAsyncActionDelegate(Pr reporter, Tk token);\n class Pr\n {\n public void report() { }\n }\n struct Tk", "score": 0.837279200553894 }, { "filename": "Source/TreeifyTask/TaskTree/IProgressReporter.cs", "retrieved_chunk": "namespace TreeifyTask\n{\n public interface IProgressReporter\n {\n void Report(TaskStatus taskStatus, double progressValue, object progressState = default);\n event ProgressReportingEventHandler Reporting;\n }\n}", "score": 0.8062661290168762 } ]
csharp
ITaskNode> childTasks = new();
using GraphNotifications.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Graph; namespace GraphNotifications.Services { public class GraphNotificationService : IGraphNotificationService { private readonly ILogger _logger; private readonly string _notificationUrl; private readonly
IGraphClientService _graphClientService;
private readonly ICertificateService _certificateService; public GraphNotificationService(IGraphClientService graphClientService, ICertificateService certificateService, IOptions<AppSettings> settings, ILogger<GraphNotificationService> logger) { _graphClientService = graphClientService; _certificateService = certificateService ?? throw new ArgumentException(nameof(certificateService)); _logger = logger; _notificationUrl = settings.Value.NotificationUrl ?? throw new ArgumentException(nameof(settings.Value.NotificationUrl)); } public async Task<Subscription> AddSubscriptionAsync(string userAccessToken, SubscriptionDefinition subscriptionDefinition) { // Create the subscription request var subscription = new Subscription { ChangeType = string.Join(',', subscriptionDefinition.ChangeTypes), //"created", NotificationUrl = _notificationUrl, Resource = subscriptionDefinition.Resource, // "me/mailfolders/inbox/messages", ClientState = Guid.NewGuid().ToString(), IncludeResourceData = subscriptionDefinition.ResourceData, ExpirationDateTime = subscriptionDefinition.ExpirationTime }; if (subscriptionDefinition.ResourceData) { // Get the encryption certificate (public key) var encryptionCertificate = await _certificateService.GetEncryptionCertificate(); subscription.EncryptionCertificateId = encryptionCertificate.Subject; // To get resource data, we must provide a public key that // Microsoft Graph will use to encrypt their key // See https://docs.microsoft.com/graph/webhooks-with-resource-data#creating-a-subscription subscription.AddPublicEncryptionCertificate(encryptionCertificate); } _logger.LogInformation("Getting GraphService with accesstoken for Graph onbehalf of user"); var graphUserClient = _graphClientService.GetUserGraphClient(userAccessToken); _logger.LogInformation("Create graph subscription"); return await graphUserClient.Subscriptions.Request().AddAsync(subscription); } public async Task<Subscription> RenewSubscriptionAsync(string userAccessToken, string subscriptionId, DateTimeOffset expirationTime) { var subscription = new Subscription { ExpirationDateTime = expirationTime }; _logger.LogInformation("Getting GraphService with accesstoken for Graph onbehalf of user"); var graphUserClient = _graphClientService.GetUserGraphClient(userAccessToken); _logger.LogInformation($"Renew graph subscription: {subscriptionId}"); return await graphUserClient.Subscriptions[subscriptionId].Request().UpdateAsync(subscription); } public async Task<Subscription> GetSubscriptionAsync(string userAccessToken, string subscriptionId) { _logger.LogInformation("Getting GraphService with accesstoken for Graph onbehalf of user"); var graphUserClient = _graphClientService.GetUserGraphClient(userAccessToken); _logger.LogInformation($"Get graph subscription: {subscriptionId}"); return await graphUserClient.Subscriptions[subscriptionId].Request().GetAsync(); } } }
Services/GraphNotificationService.cs
microsoft-GraphNotificationBroker-b1564aa
[ { "filename": "Functions/GraphNotificationsHub.cs", "retrieved_chunk": "using Microsoft.Extensions.Options;\nusing Azure.Messaging.EventHubs;\nusing System.Text;\nusing Newtonsoft.Json;\nnamespace GraphNotifications.Functions\n{\n public class GraphNotificationsHub : ServerlessHub\n {\n private readonly ITokenValidationService _tokenValidationService;\n private readonly IGraphNotificationService _graphNotificationService;", "score": 0.908135712146759 }, { "filename": "Services/TokenValidationService.cs", "retrieved_chunk": "using Microsoft.IdentityModel.Protocols;\nusing Microsoft.IdentityModel.Protocols.OpenIdConnect;\nusing Microsoft.IdentityModel.Tokens;\nnamespace GraphNotifications.Services\n{\n public class TokenValidationService : ITokenValidationService\n {\n private TokenValidationParameters? _validationParameters;\n private readonly AppSettings _settings;\n private readonly ILogger _logger;", "score": 0.869550347328186 }, { "filename": "Services/IRedisFactory.cs", "retrieved_chunk": "using StackExchange.Redis;\nnamespace GraphNotifications.Services\n{\n public interface IRedisFactory : IDisposable\n {\n IDatabase GetCache();\n void ForceReconnect();\n }\n}", "score": 0.8297686576843262 }, { "filename": "Services/GraphClientService.cs", "retrieved_chunk": " {\n private readonly AppSettings _settings;\n private readonly ILogger _logger;\n public GraphClientService(IOptions<AppSettings> options, ILogger<GraphClientService> logger)\n {\n _settings = options.Value;\n _logger = logger;\n }\n public GraphServiceClient GetUserGraphClient(string userAssertion)\n {", "score": 0.8281509876251221 }, { "filename": "Functions/TestClient.cs", "retrieved_chunk": "using System.Net.Http.Headers;\nusing ExecutionContext = Microsoft.Azure.WebJobs.ExecutionContext;\nnamespace GraphNotifications.Functions\n{\n public static class Client\n {\n [FunctionName(\"TestClient\")]\n public static HttpResponseMessage Run(\n [HttpTrigger(AuthorizationLevel.Anonymous, \"get\", Route = \"/\")] HttpRequest req,\n ILogger log, ExecutionContext context)", "score": 0.8169264793395996 } ]
csharp
IGraphClientService _graphClientService;
using HarmonyLib; using Sandbox; using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.AI; namespace Ultrapain.Patches { class MinosPrimeCharge { static GameObject decoy; public static void CreateDecoy() { if (decoy != null || Plugin.minosPrime == null) return; decoy = GameObject.Instantiate(Plugin.minosPrime, Vector3.zero, Quaternion.identity); decoy.SetActive(false); GameObject.Destroy(decoy.GetComponent<MinosPrime>()); GameObject.Destroy(decoy.GetComponent<Machine>()); GameObject.Destroy(decoy.GetComponent<BossHealthBar>()); GameObject.Destroy(decoy.GetComponent<EventOnDestroy>()); GameObject.Destroy(decoy.GetComponent<BossIdentifier>()); GameObject.Destroy(decoy.GetComponent<EnemyIdentifier>()); GameObject.Destroy(decoy.GetComponent<BasicEnemyDataRelay>()); GameObject.Destroy(decoy.GetComponent<Rigidbody>()); GameObject.Destroy(decoy.GetComponent<CapsuleCollider>()); GameObject.Destroy(decoy.GetComponent<AudioSource>()); GameObject.Destroy(decoy.GetComponent<NavMeshAgent>()); foreach (SkinnedMeshRenderer renderer in UnityUtils.GetComponentsInChildrenRecursively<SkinnedMeshRenderer>(decoy.transform)) { renderer.material = new Material(Plugin.gabrielFakeMat); } SandboxEnemy sbe = decoy.GetComponent<SandboxEnemy>(); if (sbe != null) GameObject.Destroy(sbe); MindflayerDecoy comp = decoy.AddComponent<MindflayerDecoy>(); comp.fadeSpeed = 1f; //decoy.GetComponent<Animator>().StopPlayback(); //decoy.GetComponent<Animator>().Update(100f); GameObject.Destroy(decoy.transform.Find("SwingCheck").gameObject); GameObject.Destroy(decoy.transform.Find("Capsule").gameObject); GameObject.Destroy(decoy.transform.Find("Point Light").gameObject); foreach (EnemyIdentifierIdentifier eii in UnityUtils.GetComponentsInChildrenRecursively<EnemyIdentifierIdentifier>(decoy.transform)) GameObject.Destroy(eii); } static void DrawTrail(MinosPrime instance, Animator anim, Vector3 startPosition, Vector3 targetPosition) { if(decoy == null) { CreateDecoy(); return; } targetPosition = Vector3.MoveTowards(targetPosition, startPosition, 5f); Vector3 currentPosition = startPosition; float distance = Vector3.Distance(startPosition, targetPosition); if (distance < 2.5f) return; float deltaDistance = 2.5f; float fadeSpeed = 1f / ConfigManager.minosPrimeTeleportTrailDuration.value; AnimatorStateInfo currentAnimatorStateInfo = anim.GetCurrentAnimatorStateInfo(0); int maxIterations = Mathf.CeilToInt(distance / deltaDistance); float currentTransparency = 0.1f; float deltaTransparencyPerIteration = 1f / maxIterations; while (currentPosition != targetPosition) { GameObject gameObject = GameObject.Instantiate(decoy, currentPosition, instance.transform.rotation); gameObject.SetActive(true); Animator componentInChildren = gameObject.GetComponentInChildren<Animator>(); componentInChildren.Play(currentAnimatorStateInfo.shortNameHash, 0, currentAnimatorStateInfo.normalizedTime); componentInChildren.speed = 0f; MindflayerDecoy comp = gameObject.GetComponent<MindflayerDecoy>(); comp.fadeSpeed = fadeSpeed; currentTransparency += deltaTransparencyPerIteration; comp.fadeOverride = Mathf.Min(1f, currentTransparency); currentPosition = Vector3.MoveTowards(currentPosition, targetPosition, deltaDistance); } } static void Postfix(MinosPrime __instance, Animator ___anim) { string stateName = ___anim.GetCurrentAnimatorClipInfo(0)[0].clip.name; MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (stateName == "Combo" || (flag != null && flag.throwingProjectile)) return; Transform player = MonoSingleton<PlayerTracker>.Instance.GetPlayer(); float min = ConfigManager.minosPrimeRandomTeleportMinDistance.value; float max = ConfigManager.minosPrimeRandomTeleportMaxDistance.value; Vector3 unitSphere = UnityEngine.Random.onUnitSphere; unitSphere.y = Mathf.Abs(unitSphere.y); float distance = UnityEngine.Random.Range(min, max); Ray ray = new Ray(player.position, unitSphere); LayerMask mask = new LayerMask(); mask.value |= 256 | 16777216; if (Physics.Raycast(ray, out RaycastHit hit, max, mask, QueryTriggerInteraction.Ignore)) { if (hit.distance < min) return; Vector3 point = ray.GetPoint(hit.distance - 5); __instance.Teleport(point, __instance.transform.position); } else { Vector3 point = ray.GetPoint(distance); __instance.Teleport(point, __instance.transform.position); } } static void TeleportPostfix(MinosPrime __instance, Animator ___anim, Vector3 __0, Vector3 __1) { DrawTrail(__instance, ___anim, __1, __0); } } class MinosPrimeFlag : MonoBehaviour { void Start() { } public void ComboExplosion() { GameObject explosion = Instantiate(Plugin.lightningStrikeExplosive, transform.position, Quaternion.identity); foreach(Explosion e in explosion.GetComponentsInChildren<Explosion>()) { e.toIgnore.Add(EnemyType.MinosPrime); e.maxSize *= ConfigManager.minosPrimeComboExplosionSize.value; e.speed *= ConfigManager.minosPrimeComboExplosionSize.value; e.damage = (int)(e.damage * ConfigManager.minosPrimeComboExplosionDamage.value); } } public void BigExplosion() { GameObject explosion = Instantiate(Plugin.lightningStrikeExplosive, transform.position, Quaternion.identity); foreach (Explosion e in explosion.GetComponentsInChildren<Explosion>()) { e.toIgnore.Add(EnemyType.MinosPrime); e.maxSize *= ConfigManager.minosPrimeExplosionSize.value; e.speed *= ConfigManager.minosPrimeExplosionSize.value; e.damage = (int)(e.damage * ConfigManager.minosPrimeExplosionDamage.value); } } public bool throwingProjectile = false; public string plannedAttack = ""; public bool explosionAttack = false; } class MinosPrime_Start { static void Postfix(MinosPrime __instance, Animator ___anim, ref bool ___enraged) { if (ConfigManager.minosPrimeEarlyPhaseToggle.value) ___enraged = true; __instance.gameObject.AddComponent<MinosPrimeFlag>(); if (ConfigManager.minosPrimeComboExplosionToggle.value) { AnimationClip boxing = ___anim.runtimeAnimatorController.animationClips.Where(item => item.name == "Boxing").First(); List<UnityEngine.AnimationEvent> boxingEvents = boxing.events.ToList(); boxingEvents.Insert(15, new UnityEngine.AnimationEvent() { time = 2.4f, functionName = "ComboExplosion", messageOptions = SendMessageOptions.RequireReceiver }); boxing.events = boxingEvents.ToArray(); } } } class MinosPrime_StopAction { static void Postfix(MinosPrime __instance, EnemyIdentifier ___eid) { MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (flag == null) return; if (flag.plannedAttack != "") { __instance.SendMessage(flag.plannedAttack); flag.plannedAttack = ""; } } } // aka JUDGEMENT class MinosPrime_Dropkick { static bool Prefix(MinosPrime __instance, EnemyIdentifier ___eid, ref bool ___inAction, Animator ___anim) { MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (flag == null) return true; if (!flag.throwingProjectile) { if (ConfigManager.minosPrimeExplosionToggle.value && UnityEngine.Random.Range(0, 99.9f) < ConfigManager.minosPrimeExplosionChance.value) { __instance.TeleportAnywhere(); ___inAction = true; flag.explosionAttack = true; ___anim.speed = ___eid.totalSpeedModifier * ConfigManager.minosPrimeExplosionWindupSpeed.value; ___anim.Play("Outro", 0, 0.5f); __instance.PlayVoice(new AudioClip[] { __instance.phaseChangeVoice }); return false; } if (ConfigManager.minosPrimeComboToggle.value) { flag.throwingProjectile = true; flag.plannedAttack = "Dropkick"; __instance.SendMessage("ProjectilePunch"); } return false; } else { if (ConfigManager.minosPrimeComboToggle.value) { flag.plannedAttack = "ProjectilePunch"; flag.throwingProjectile = false; } } return true; } } // aka PREPARE THYSELF class MinosPrime_Combo { static float timing = 3f; static void Postfix(MinosPrime __instance, EnemyIdentifier ___eid) { if (!ConfigManager.minosPrimeComboToggle.value) return; MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (flag == null) return; flag.plannedAttack = "Uppercut"; } } // aka DIE class MinosPrime_RiderKick { static bool Prefix(MinosPrime __instance, ref bool ___previouslyRiderKicked) { if (UnityEngine.Random.Range(0, 99.9f) > ConfigManager.minosPrimeCrushAttackChance.value) return true; ___previouslyRiderKicked = true; Vector3 vector = MonoSingleton<PlayerTracker>.Instance.PredictPlayerPosition(0.5f); Transform target = MonoSingleton<PlayerTracker>.Instance.GetPlayer(); if (vector.y < target.position.y) { vector.y = target.position.y; } __instance.Teleport(vector + Vector3.up * 25f, __instance.transform.position); __instance.SendMessage("DropAttack"); return false; } } // End of PREPARE THYSELF class MinosPrime_ProjectileCharge { static bool Prefix(MinosPrime __instance, Animator ___anim) { string clipname = ___anim.GetCurrentAnimatorClipInfo(0)[0].clip.name; if (clipname != "Combo" || UnityEngine.Random.Range(0, 99.9f) > ConfigManager.minosPrimeComboExplosiveEndChance.value) return true; ___anim.Play("Dropkick", 0, (1.0815f - 0.4279f) / 2.65f); return false; } } class MinosPrime_Ascend { static bool Prefix(
MinosPrime __instance, EnemyIdentifier ___eid, Animator ___anim, ref bool ___vibrating) {
if (___eid.health <= 0) return true; MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (flag == null) return true; if (!flag.explosionAttack) return true; ___anim.speed = ___eid.totalSpeedModifier; ___vibrating = false; flag.explosionAttack = false; flag.BigExplosion(); __instance.Invoke("Uppercut", 0.5f); return false; } } class MinosPrime_Death { static bool Prefix(MinosPrime __instance, Animator ___anim, ref bool ___vibrating) { MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (flag == null) return true; if (!flag.explosionAttack) return true; flag.explosionAttack = false; ___vibrating = false; ___anim.speed = 1f; ___anim.Play("Walk", 0, 0f); return true; } } }
Ultrapain/Patches/MinosPrime.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Mindflayer.cs", "retrieved_chunk": " }\n else\n patch.swingComboLeft = 2;*/\n }\n }\n class Mindflayer_MeleeTeleport_Patch\n {\n public static Vector3 deltaPosition = new Vector3(0, -10, 0);\n static bool Prefix(Mindflayer __instance, ref EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___goingLeft, ref Animator ___anim, ref bool ___enraged)\n {", "score": 0.8586143255233765 }, { "filename": "Ultrapain/Patches/Leviathan.cs", "retrieved_chunk": " }\n return false;\n }\n }\n class Leviathan_ProjectileBurst\n {\n static bool Prefix(LeviathanHead __instance, Animator ___anim,\n ref int ___projectilesLeftInBurst, ref float ___projectileBurstCooldown, ref bool ___inAction)\n {\n if (!__instance.active)", "score": 0.8480528593063354 }, { "filename": "Ultrapain/Patches/Panopticon.cs", "retrieved_chunk": " foreach (Text t in temp.textInstances)\n t.text = ConfigManager.obamapticonName.value;\n }\n }\n }\n }\n class Panopticon_SpawnInsignia\n {\n static bool Prefix(FleshPrison __instance, ref bool ___inAction, Statue ___stat, float ___maxHealth, int ___difficulty,\n ref float ___fleshDroneCooldown, EnemyIdentifier ___eid)", "score": 0.8355450630187988 }, { "filename": "Ultrapain/Patches/PlayerStatTweaks.cs", "retrieved_chunk": " }\n }\n return code.AsEnumerable();\n }\n }\n class NewMovement_GetHealth\n {\n static bool Prefix(NewMovement __instance, int __0, bool __1, ref AudioSource ___greenHpAud, Canvas ___fullHud)\n {\n if (__instance.dead || __instance.exploded)", "score": 0.8342095613479614 }, { "filename": "Ultrapain/Patches/Leviathan.cs", "retrieved_chunk": " class Leviathan_FixedUpdate\n {\n public static float projectileForward = 10f;\n static bool Roll(float chancePercent)\n {\n return UnityEngine.Random.Range(0, 99.9f) <= chancePercent;\n }\n static bool Prefix(LeviathanHead __instance, LeviathanController ___lcon, ref bool ___projectileBursting, float ___projectileBurstCooldown,\n Transform ___shootPoint, ref bool ___trackerIgnoreLimits, Animator ___anim, ref int ___previousAttack)\n {", "score": 0.8329688310623169 } ]
csharp
MinosPrime __instance, EnemyIdentifier ___eid, Animator ___anim, ref bool ___vibrating) {
using HarmonyLib; using UnityEngine; using UnityEngine.AI; namespace Ultrapain.Patches { public class StrayFlag : MonoBehaviour { //public int extraShotsRemaining = 6; private Animator anim; private EnemyIdentifier eid; public GameObject standardProjectile; public GameObject standardDecorativeProjectile; public int comboRemaining = ConfigManager.strayShootCount.value; public bool inCombo = false; public float lastSpeed = 1f; public enum AttackMode { ProjectileCombo, FastHoming } public AttackMode currentMode = AttackMode.ProjectileCombo; public void Awake() { anim = GetComponent<Animator>(); eid = GetComponent<EnemyIdentifier>(); } public void Update() { if(eid.dead) { Destroy(this); return; } if (inCombo) { anim.speed = ZombieProjectile_ThrowProjectile_Patch.animSpeed; anim.SetFloat("Speed", ZombieProjectile_ThrowProjectile_Patch.animSpeed); } } } public class ZombieProjectile_Start_Patch1 { static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid) { if (___eid.enemyType != EnemyType.Stray) return; StrayFlag flag = __instance.gameObject.AddComponent<StrayFlag>(); flag.standardProjectile = __instance.projectile; flag.standardDecorativeProjectile = __instance.decProjectile; flag.currentMode = StrayFlag.AttackMode.ProjectileCombo; /*__instance.projectile = Plugin.homingProjectile; __instance.decProjectile = Plugin.decorativeProjectile2;*/ } } public class ZombieProjectile_ThrowProjectile_Patch { public static float normalizedTime = 0f; public static float animSpeed = 20f; public static float projectileSpeed = 75; public static float turnSpeedMultiplier = 0.45f; public static int projectileDamage = 10; public static int explosionDamage = 20; public static float coreSpeed = 110f; static void Postfix(ZombieProjectiles __instance, ref
EnemyIdentifier ___eid, ref Animator ___anim, ref GameObject ___currentProjectile , ref NavMeshAgent ___nma, ref Zombie ___zmb) {
if (___eid.enemyType != EnemyType.Stray) return; StrayFlag flag = __instance.gameObject.GetComponent<StrayFlag>(); if (flag == null) return; if (flag.currentMode == StrayFlag.AttackMode.FastHoming) { Projectile proj = ___currentProjectile.GetComponent<Projectile>(); if (proj != null) { proj.target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); proj.speed = projectileSpeed * ___eid.totalSpeedModifier; proj.turningSpeedMultiplier = turnSpeedMultiplier; proj.safeEnemyType = EnemyType.Stray; proj.damage = projectileDamage * ___eid.totalDamageModifier; } flag.currentMode = StrayFlag.AttackMode.ProjectileCombo; __instance.projectile = flag.standardProjectile; __instance.decProjectile = flag.standardDecorativeProjectile; } else if(flag.currentMode == StrayFlag.AttackMode.ProjectileCombo) { flag.comboRemaining -= 1; if (flag.comboRemaining == 0) { flag.comboRemaining = ConfigManager.strayShootCount.value; //flag.currentMode = StrayFlag.AttackMode.FastHoming; flag.inCombo = false; ___anim.speed = flag.lastSpeed; ___anim.SetFloat("Speed", flag.lastSpeed); //__instance.projectile = Plugin.homingProjectile; //__instance.decProjectile = Plugin.decorativeProjectile2; } else { flag.inCombo = true; __instance.swinging = true; __instance.seekingPlayer = false; ___nma.updateRotation = false; __instance.transform.LookAt(new Vector3(___zmb.target.position.x, __instance.transform.position.y, ___zmb.target.position.z)); flag.lastSpeed = ___anim.speed; //___anim.Play("ThrowProjectile", 0, ZombieProjectile_ThrowProjectile_Patch.normalizedTime); ___anim.speed = ConfigManager.strayShootSpeed.value; ___anim.SetFloat("Speed", ConfigManager.strayShootSpeed.value); ___anim.SetTrigger("Swing"); //___anim.SetFloat("AttackType", 0f); //___anim.StopPlayback(); //flag.Invoke("LateCombo", 0.01f); //___anim.runtimeAnimatorController.animationClips.Where(clip => clip.name == "ThrowProjectile").First(). //___anim.fireEvents = true; } } } } class Swing { static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid) { if (___eid.enemyType != EnemyType.Stray) return; ___eid.weakPoint = null; } } /*[HarmonyPatch(typeof(ZombieProjectiles), "Swing")] class Swing { static void Postfix() { Debug.Log("Swing()"); } }*/ class SwingEnd { static bool Prefix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid) { if (___eid.enemyType != EnemyType.Stray) return true; StrayFlag flag = __instance.gameObject.GetComponent<StrayFlag>(); if (flag == null) return true; if (flag.inCombo) return false; return true; } } /*[HarmonyPatch(typeof(ZombieProjectiles), "DamageStart")] class DamageStart { static void Postfix() { Debug.Log("DamageStart()"); } }*/ class DamageEnd { static bool Prefix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid) { if (___eid.enemyType != EnemyType.Stray) return true; StrayFlag flag = __instance.gameObject.GetComponent<StrayFlag>(); if (flag == null) return true; if (flag.inCombo) return false; return true; } } }
Ultrapain/Patches/Stray.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Mindflayer.cs", "retrieved_chunk": " //___eid.SpeedBuff();\n }\n }\n class Mindflayer_ShootProjectiles_Patch\n {\n public static float maxProjDistance = 5;\n public static float initialProjectileDistance = -1f;\n public static float distancePerProjShot = 0.2f;\n static bool Prefix(Mindflayer __instance, ref EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___enraged)\n {", "score": 0.8992680907249451 }, { "filename": "Ultrapain/Patches/Leviathan.cs", "retrieved_chunk": " class Leviathan_FixedUpdate\n {\n public static float projectileForward = 10f;\n static bool Roll(float chancePercent)\n {\n return UnityEngine.Random.Range(0, 99.9f) <= chancePercent;\n }\n static bool Prefix(LeviathanHead __instance, LeviathanController ___lcon, ref bool ___projectileBursting, float ___projectileBurstCooldown,\n Transform ___shootPoint, ref bool ___trackerIgnoreLimits, Animator ___anim, ref int ___previousAttack)\n {", "score": 0.8876947164535522 }, { "filename": "Ultrapain/Plugin.cs", "retrieved_chunk": " public static GameObject maliciousRailcannon;\n // Variables\n public static float SoliderShootAnimationStart = 1.2f;\n public static float SoliderGrenadeForce = 10000f;\n public static float SwordsMachineKnockdownTimeNormalized = 0.8f;\n public static float SwordsMachineCoreSpeed = 80f;\n public static float MinGrenadeParryVelocity = 40f;\n public static GameObject _lighningBoltSFX;\n public static GameObject lighningBoltSFX\n {", "score": 0.8837421536445618 }, { "filename": "Ultrapain/Patches/CommonComponents.cs", "retrieved_chunk": " public float superSize = 1f;\n public float superSpeed = 1f;\n public float superDamage = 1f;\n public int superPlayerDamageOverride = -1;\n struct StateInfo\n {\n public GameObject tempHarmless;\n public GameObject tempNormal;\n public GameObject tempSuper;\n public StateInfo()", "score": 0.8677048087120056 }, { "filename": "Ultrapain/Patches/Leviathan.cs", "retrieved_chunk": " {\n private LeviathanHead comp;\n private Animator anim;\n //private Collider col;\n private LayerMask envMask = new LayerMask() { value = 1 << 8 | 1 << 24 };\n public float playerRocketRideTracker = 0;\n private GameObject currentProjectileEffect;\n private AudioSource currentProjectileAud;\n private Transform shootPoint;\n public float currentProjectileSize = 0;", "score": 0.8599923253059387 } ]
csharp
EnemyIdentifier ___eid, ref Animator ___anim, ref GameObject ___currentProjectile , ref NavMeshAgent ___nma, ref Zombie ___zmb) {
/* Copyright (c) 2023 Xavier Arpa López Thomas Peter ('Kingdox') Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; namespace Kingdox.UniFlux.Core.Internal { /// <summary> /// The `FuncFluxParam` class represents a flux that stores functions with one parameter of type `TParam` and a return value of type `TReturn`. /// It provides a dictionary to store the functions and methods to subscribe and trigger the stored functions. /// </summary> /// <typeparam name="TKey">The type of the keys used to store the functions in the dictionary.</typeparam> /// <typeparam name="TParam">The type of the parameter passed to the functions stored in the dictionary.</typeparam> /// <typeparam name="TReturn">The return type of the functions stored in the dictionary.</typeparam> internal sealed class FuncFluxParam<TKey, TParam, TReturn> : IFluxParamReturn<TKey, TParam, TReturn, Func<TParam, TReturn>> { /// <summary> /// A dictionary that stores functions with one parameter of type `TParam` and a return value of type `TReturn`. /// </summary> internal readonly Dictionary<TKey, Func<TParam, TReturn>> dictionary = new Dictionary<TKey, Func<TParam, TReturn>>(); /// <summary> /// Subscribes the provided function to the dictionary with the specified key when `condition` is true. /// If `condition` is false and the dictionary contains the specified key, the function is removed from the dictionary. /// </summary> void
IStore<TKey, Func<TParam, TReturn>>.Store(in bool condition, TKey key, Func<TParam, TReturn> func) {
if(dictionary.TryGetValue(key, out var values)) { if (condition) dictionary[key] += func; else { values -= func; if (values is null) dictionary.Remove(key); else dictionary[key] = values; } } else if (condition) dictionary.Add(key, func); } /// <summary> /// Triggers the function stored in the dictionary with the specified key and parameter, and returns its return value. /// If the dictionary does not contain the specified key, returns the default value of type `TReturn`. /// </summary> TReturn IFluxParamReturn<TKey, TParam, TReturn, Func<TParam, TReturn>>.Dispatch(TKey key, TParam param) { if(dictionary.TryGetValue(key, out var _actions)) { return _actions.Invoke(param); } return default; } } }
Runtime/Core/Internal/FuncFluxParam.cs
xavierarpa-UniFlux-a2d46de
[ { "filename": "Runtime/Core/Internal/FuncFlux.cs", "retrieved_chunk": " /// <summary>\n /// A dictionary that stores functions with no parameters and a return value of type `TReturn`.\n /// </summary>\n internal readonly Dictionary<TKey, Func<TReturn>> dictionary = new Dictionary<TKey, Func<TReturn>>();\n /// <summary>\n /// Subscribes the provided function to the dictionary with the specified key when `condition` is true. \n /// If `condition` is false and the dictionary contains the specified key, the function is removed from the dictionary.\n /// </summary>\n void IStore<TKey, Func<TReturn>>.Store(in bool condition, TKey key, Func<TReturn> func) \n {", "score": 0.975041389465332 }, { "filename": "Runtime/Core/Internal/FuncFlux.cs", "retrieved_chunk": " else if (condition) dictionary.Add(key, func);\n }\n // <summary>\n /// Triggers the function stored in the dictionary with the specified key and returns its return value. \n /// If the dictionary does not contain the specified key, returns the default value of type `TReturn`.\n /// </summary>\n TReturn IFluxReturn<TKey, TReturn, Func<TReturn>>.Dispatch(TKey key)\n {\n if(dictionary.TryGetValue(key, out var _actions)) \n {", "score": 0.9106224179267883 }, { "filename": "Runtime/Core/Internal/FuncFlux.cs", "retrieved_chunk": "namespace Kingdox.UniFlux.Core.Internal\n{\n /// <summary>\n /// The `FuncFlux` class represents a flux that stores functions with no parameters and a return value of type `TReturn`.\n /// It provides a dictionary to store the functions and methods to subscribe and trigger the stored functions.\n /// </summary>\n /// <typeparam name=\"TKey\">The type of the keys used to store the functions in the dictionary.</typeparam>\n /// <typeparam name=\"TReturn\">The return type of the functions stored in the dictionary.</typeparam>\n internal sealed class FuncFlux<TKey, TReturn> : IFluxReturn<TKey, TReturn, Func<TReturn>>\n {", "score": 0.8978565335273743 }, { "filename": "Runtime/Core/Internal/IFlux.cs", "retrieved_chunk": " /// <summary>\n /// TKey TParam TReturn\n /// </summary>\n internal interface IFluxParamReturn<in TKey, in TParam, out TReturn, in TStorage> : IStore<TKey, TStorage>\n {\n /// <summary>\n /// Dispatch the TKey with TParam and return TReturn\n /// </summary>\n TReturn Dispatch(TKey key, TParam param);\n }", "score": 0.8778162002563477 }, { "filename": "Runtime/Core/Internal/FluxParamReturn_T_T2_T3.cs", "retrieved_chunk": " ///<summary>\n /// Defines a static method that subscribes a function with a parameter that returns a value to a key with a condition\n ///</summary>\n internal static void Store(in T key, in Func<T2, T3> action, in bool condition) => flux_func_param.Store(in condition, key, action);\n ///<summary>\n /// Defines a static method that triggers a function with a parameter with a key and returns the result\n ///</summary>\n internal static T3 Dispatch(in T key, in T2 @param) => flux_func_param.Dispatch(key, @param);\n }\n}", "score": 0.8767011761665344 } ]
csharp
IStore<TKey, Func<TParam, TReturn>>.Store(in bool condition, TKey key, Func<TParam, TReturn> func) {
using NAK.AASEmulator.Runtime; using UnityEditor; using UnityEngine; using static ABI.CCK.Scripts.CVRAdvancedSettingsEntry; using static NAK.AASEmulator.Runtime.AASEmulatorRuntime; using static NAK.AASEmulator.Runtime.AASMenu; namespace NAK.AASEmulator.Editor { [CustomEditor(typeof(AASMenu))] public class AASMenuEditor : UnityEditor.Editor { #region Variables private
AASMenu _targetScript;
#endregion #region Unity / GUI Methods private void OnEnable() { OnRequestRepaint -= Repaint; OnRequestRepaint += Repaint; _targetScript = (AASMenu)target; } private void OnDisable() => OnRequestRepaint -= Repaint; public override void OnInspectorGUI() { if (_targetScript == null) return; Draw_ScriptWarning(); Draw_AASMenus(); } #endregion Unity / GUI Methods #region Drawing Methods private void Draw_ScriptWarning() { if (_targetScript.isInitializedExternally) return; EditorGUILayout.HelpBox("Warning: Do not upload this script with your avatar!\nThis script is prevented from saving to scenes & prefabs.", MessageType.Warning); EditorGUILayout.HelpBox("This script will automatically be added if you enable AASEmulator from the Tools menu (Tools > Enable AAS Emulator).", MessageType.Info); } private void Draw_AASMenus() { foreach (AASMenuEntry t in _targetScript.entries) DisplayMenuEntry(t); } private void DisplayMenuEntry(AASMenuEntry entry) { GUILayout.BeginVertical("box"); EditorGUILayout.LabelField("Menu Name", entry.menuName); EditorGUILayout.LabelField("Machine Name", entry.machineName); EditorGUILayout.LabelField("Settings Type", entry.settingType.ToString()); switch (entry.settingType) { case SettingsType.GameObjectDropdown: int oldIndex = (int)entry.valueX; int newIndex = EditorGUILayout.Popup("Value", oldIndex, entry.menuOptions); if (newIndex != oldIndex) { _targetScript.AnimatorManager.SetParameter(entry.machineName, newIndex); entry.valueX = newIndex; } break; case SettingsType.GameObjectToggle: bool oldValue = entry.valueX >= 0.5f; bool newValue = EditorGUILayout.Toggle("Value", oldValue); if (newValue != oldValue) { _targetScript.AnimatorManager.SetParameter(entry.machineName, newValue); entry.valueX = newValue ? 1f : 0f; } break; case SettingsType.Slider: float oldSliderValue = entry.valueX; float newSliderValue = EditorGUILayout.Slider("Value", oldSliderValue, 0f, 1f); if (newSliderValue != oldSliderValue) { _targetScript.AnimatorManager.SetParameter(entry.machineName, newSliderValue); entry.valueX = newSliderValue; } break; case SettingsType.InputSingle: float oldSingleValue = entry.valueX; float newSingleValue = EditorGUILayout.FloatField("Value", oldSingleValue); if (newSingleValue != oldSingleValue) { _targetScript.AnimatorManager.SetParameter(entry.machineName, newSingleValue); entry.valueX = newSingleValue; } break; case SettingsType.InputVector2: Vector2 oldVector2Value = new Vector2(entry.valueX, entry.valueY); Vector2 newVector2Value = EditorGUILayout.Vector2Field("Value", oldVector2Value); if (newVector2Value != oldVector2Value) { _targetScript.AnimatorManager.SetParameter(entry.machineName, newVector2Value); entry.valueX = newVector2Value.x; entry.valueY = newVector2Value.y; } break; case SettingsType.InputVector3: Vector3 oldVector3Value = new Vector3(entry.valueX, entry.valueY, entry.valueZ); Vector3 newVector3Value = EditorGUILayout.Vector3Field("Value", oldVector3Value); if (newVector3Value != oldVector3Value) { _targetScript.AnimatorManager.SetParameter(entry.machineName, newVector3Value); entry.valueX = newVector3Value.x; entry.valueY = newVector3Value.y; entry.valueZ = newVector3Value.z; } break; // TODO: AAAAAAAAAAAA case SettingsType.MaterialColor: case SettingsType.Joystick2D: case SettingsType.Joystick3D: default: break; } GUILayout.EndVertical(); } #endregion } }
Editor/AASMenuEditor.cs
NotAKidOnSteam-AASEmulator-aacd289
[ { "filename": "Editor/AASEmulatorRuntimeEditor.cs", "retrieved_chunk": "using System;\nusing NAK.AASEmulator.Runtime;\nusing UnityEditor;\nusing UnityEngine;\nusing static NAK.AASEmulator.Editor.EditorExtensions;\nusing static NAK.AASEmulator.Runtime.AASEmulatorRuntime;\nnamespace NAK.AASEmulator.Editor\n{\n [CustomEditor(typeof(AASEmulatorRuntime))]\n public class AASEmulatorRuntimeEditor : UnityEditor.Editor", "score": 0.915833055973053 }, { "filename": "Runtime/Scripts/AASMenu.cs", "retrieved_chunk": "using ABI.CCK.Scripts;\nusing NAK.AASEmulator.Runtime.SubSystems;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing static ABI.CCK.Scripts.CVRAdvancedSettingsEntry;\nnamespace NAK.AASEmulator.Runtime\n{\n [AddComponentMenu(\"\")]\n public class AASMenu : EditorOnlyMonoBehaviour\n {", "score": 0.872969388961792 }, { "filename": "Editor/AASEmulatorSupport.cs", "retrieved_chunk": "using System.Linq;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\nnamespace NAK.AASEmulator.Support\n{\n [InitializeOnLoad]\n public static class AASEmulatorSupport\n {\n static AASEmulatorSupport()", "score": 0.8669967651367188 }, { "filename": "Runtime/Scripts/AASEmulatorRuntime.cs", "retrieved_chunk": "using ABI.CCK.Components;\nusing NAK.AASEmulator.Runtime.SubSystems;\nusing System;\nusing UnityEngine;\nnamespace NAK.AASEmulator.Runtime\n{\n [AddComponentMenu(\"\")]\n [HelpURL(\"https://github.com/NotAKidOnSteam/AASEmulator\")]\n public class AASEmulatorRuntime : EditorOnlyMonoBehaviour\n {", "score": 0.8377482295036316 }, { "filename": "Runtime/Scripts/AASEmulator.cs", "retrieved_chunk": "using ABI.CCK.Components;\nusing System.Collections.Generic;\nusing System.Linq;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\nnamespace NAK.AASEmulator.Runtime\n{\n public class AASEmulator : MonoBehaviour\n {\n #region Support Delegates", "score": 0.8121213912963867 } ]
csharp
AASMenu _targetScript;
using HarmonyLib; using UnityEngine; namespace Ultrapain.Patches { class Solider_Start_Patch { static void Postfix(ZombieProjectiles __instance, ref GameObject ___decProjectile, ref GameObject ___projectile, ref EnemyIdentifier ___eid, ref Animator ___anim) { if (___eid.enemyType != EnemyType.Soldier) return; /*___projectile = Plugin.soliderBullet; if (Plugin.decorativeProjectile2.gameObject != null) ___decProjectile = Plugin.decorativeProjectile2.gameObject;*/ __instance.gameObject.AddComponent<SoliderShootCounter>(); } } class Solider_SpawnProjectile_Patch { static void Postfix(
ZombieProjectiles __instance, ref EnemyIdentifier ___eid, ref GameObject ___origWP) {
if (___eid.enemyType != EnemyType.Soldier) return; ___eid.weakPoint = null; } } class SoliderGrenadeFlag : MonoBehaviour { public GameObject tempExplosion; } class Solider_ThrowProjectile_Patch { static void Postfix(ZombieProjectiles __instance, ref GameObject ___currentProjectile, ref EnemyIdentifier ___eid, ref GameObject ___player, ref Animator ___anim, ref float ___coolDown) { if (___eid.enemyType != EnemyType.Soldier) return; ___currentProjectile.GetComponent<ProjectileSpread>().spreadAmount = 10; ___currentProjectile.SetActive(true); SoliderShootCounter counter = __instance.gameObject.GetComponent<SoliderShootCounter>(); if (counter.remainingShots > 0) { counter.remainingShots -= 1; if (counter.remainingShots != 0) { ___anim.Play("Shoot", 0, Plugin.SoliderShootAnimationStart / 2f); ___anim.fireEvents = true; __instance.DamageStart(); ___coolDown = 0; } else { counter.remainingShots = ConfigManager.soliderShootCount.value; if (ConfigManager.soliderShootGrenadeToggle.value) { GameObject grenade = GameObject.Instantiate(Plugin.shotgunGrenade.gameObject, ___currentProjectile.transform.position, ___currentProjectile.transform.rotation); grenade.transform.Translate(Vector3.forward * 0.5f); Vector3 targetPos = Plugin.PredictPlayerPosition(__instance.GetComponent<Collider>(), ___eid.totalSpeedModifier); grenade.transform.LookAt(targetPos); Rigidbody rb = grenade.GetComponent<Rigidbody>(); //rb.maxAngularVelocity = 10000; //foreach (Rigidbody r in grenade.GetComponentsInChildren<Rigidbody>()) // r.maxAngularVelocity = 10000; rb.AddForce(grenade.transform.forward * Plugin.SoliderGrenadeForce); //rb.velocity = ___currentProjectile.transform.forward * Plugin.instance.SoliderGrenadeForce; rb.useGravity = false; grenade.GetComponent<Grenade>().enemy = true; grenade.GetComponent<Grenade>().CanCollideWithPlayer(true); grenade.AddComponent<SoliderGrenadeFlag>(); } } } //counter.remainingShots = ConfigManager.soliderShootCount.value; } } class Grenade_Explode_Patch { static bool Prefix(Grenade __instance, out bool __state) { __state = false; SoliderGrenadeFlag flag = __instance.GetComponent<SoliderGrenadeFlag>(); if (flag == null) return true; flag.tempExplosion = GameObject.Instantiate(__instance.explosion); __state = true; foreach(Explosion e in flag.tempExplosion.GetComponentsInChildren<Explosion>()) { e.damage = ConfigManager.soliderGrenadeDamage.value; e.maxSize *= ConfigManager.soliderGrenadeSize.value; e.speed *= ConfigManager.soliderGrenadeSize.value; } __instance.explosion = flag.tempExplosion; return true; } static void Postfix(Grenade __instance, bool __state) { if (!__state) return; SoliderGrenadeFlag flag = __instance.GetComponent<SoliderGrenadeFlag>(); GameObject.Destroy(flag.tempExplosion); } } class SoliderShootCounter : MonoBehaviour { public int remainingShots = ConfigManager.soliderShootCount.value; } }
Ultrapain/Patches/Solider.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Schism.cs", "retrieved_chunk": " class ZombieProjectile_Start_Patch\n {\n static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid)\n {\n if (___eid.enemyType != EnemyType.Schism)\n return;\n __instance.projectile = Plugin.homingProjectile;\n __instance.decProjectile = Plugin.decorativeProjectile2;\n }\n }*/", "score": 0.8839574456214905 }, { "filename": "Ultrapain/Patches/Drone.cs", "retrieved_chunk": " {\n static void Postfix(Drone __instance, ref EnemyIdentifier ___eid)\n {\n if (___eid.enemyType != EnemyType.Drone)\n return;\n __instance.gameObject.AddComponent<DroneFlag>();\n }\n }\n class Drone_PlaySound_Patch\n {", "score": 0.871465802192688 }, { "filename": "Ultrapain/Patches/Screwdriver.cs", "retrieved_chunk": " if (!__instance.drill)\n return;\n DrillFlag flag = __instance.gameObject.AddComponent<DrillFlag>();\n flag.drill = __instance;\n }\n }\n class Harpoon_Punched\n {\n static void Postfix(Harpoon __instance, EnemyIdentifierIdentifier ___target)\n {", "score": 0.8631705045700073 }, { "filename": "Ultrapain/Patches/Schism.cs", "retrieved_chunk": "using HarmonyLib;\nusing System.ComponentModel;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class ZombieProjectile_ShootProjectile_Patch\n {\n static void Postfix(ZombieProjectiles __instance, ref GameObject ___currentProjectile, Animator ___anim, EnemyIdentifier ___eid)\n {\n /*Projectile proj = ___currentProjectile.GetComponent<Projectile>();", "score": 0.8596973419189453 }, { "filename": "Ultrapain/Patches/HideousMass.cs", "retrieved_chunk": " flag.damageBuf = ___eid.totalDamageModifier;\n flag.speedBuf = ___eid.totalSpeedModifier;\n return true;\n }\n static void Postfix(Mass __instance)\n {\n GameObject.Destroy(__instance.explosiveProjectile);\n __instance.explosiveProjectile = Plugin.hideousMassProjectile;\n }\n }", "score": 0.8582082986831665 } ]
csharp
ZombieProjectiles __instance, ref EnemyIdentifier ___eid, ref GameObject ___origWP) {
using LassoProcessManager.Models.Rules; namespace ProcessManager.Models.Configs { public class ManagerConfig { /// <summary> /// Indicates to auto apply default profile for processes when no profiles are assigned. /// </summary> public bool AutoApplyDefaultProfile { get; set; } /// <summary> /// Default lasso profile. /// </summary> public string DefaultProfile { get; set; } /// <summary> /// Available Lasso profiles. /// </summary> public
LassoProfile[] Profiles {
get; set; } /// <summary> /// List of process rules. /// </summary> public ProcessRule[] ProcessRules { get; set; } /// <summary> /// List of folders rules. /// </summary> public FolderRule[] FolderRules { get; set; } } }
ProcessManager/Models/Configs/ManagerConfig.cs
kenshinakh1-LassoProcessManager-bcc481f
[ { "filename": "ProcessManager/Models/Configs/LassoProfile.cs", "retrieved_chunk": " public string AffinityMaskHex { get; set; }\n /// <summary>\n /// Delay in milliseconds for setting profile.\n /// </summary>\n public int DelayMS { get; set; }\n /// <summary>\n /// Get Parsed affinity mask in UInt64.\n /// </summary>\n /// <returns></returns>\n public UInt64 GetAffinityMask()", "score": 0.8824240565299988 }, { "filename": "ProcessManager/Models/Rules/BaseRule.cs", "retrieved_chunk": "using System.Diagnostics;\nnamespace LassoProcessManager.Models.Rules\n{\n public abstract class BaseRule\n {\n /// <summary>\n /// Lasso Profile name for the rule to use.\n /// </summary>\n public string Profile { get; set; }\n public abstract bool IsMatchForRule(Process process);", "score": 0.873113751411438 }, { "filename": "ProcessManager/Providers/IConfigProvider.cs", "retrieved_chunk": " ManagerConfig GetManagerConfig();\n /// <summary>\n /// Geth the list of lasso rules.\n /// </summary>\n /// <returns></returns>\n List<BaseRule> GetRules();\n Dictionary<string, LassoProfile> GetLassoProfiles();\n }\n}", "score": 0.8693220615386963 }, { "filename": "ProcessManager/Models/Configs/LassoProfile.cs", "retrieved_chunk": "namespace ProcessManager.Models.Configs\n{\n public class LassoProfile\n {\n private UInt64 affinityMask;\n public string Name { get; set; }\n public string Description { get; set; }\n /// <summary>\n /// Hex string format of processor affinity mask.\n /// </summary>", "score": 0.8662872910499573 }, { "filename": "ProcessManager/Providers/ILogProvider.cs", "retrieved_chunk": "namespace ProcessManager.Providers\n{\n public interface ILogProvider\n {\n /// <summary>\n /// Simple log function.\n /// </summary>\n /// <param name=\"message\"></param>\n void Log(string message);\n }", "score": 0.8268198370933533 } ]
csharp
LassoProfile[] Profiles {
#nullable enable using System; using System.Collections.Generic; using System.Threading; using Cysharp.Threading.Tasks; using Mochineko.Relent.Result; namespace Mochineko.RelentStateMachine { public sealed class StackStateMachine<TContext> : IStackStateMachine<TContext> { private readonly IStateStore<TContext> stateStore; public TContext Context { get; } private readonly Stack<IStackState<TContext>> stack = new(); public bool IsCurrentState<TState>() where TState : IStackState<TContext> => stack.Peek() is TState; private readonly SemaphoreSlim semaphore = new( initialCount: 1, maxCount: 1); private readonly TimeSpan semaphoreTimeout; private const float DefaultSemaphoreTimeoutSeconds = 30f; public static async UniTask<StackStateMachine<TContext>> CreateAsync( IStateStore<TContext> stateStore, TContext context, CancellationToken cancellationToken, TimeSpan? semaphoreTimeout = null) { var instance = new StackStateMachine<TContext>( stateStore, context, semaphoreTimeout); await instance.stack.Peek() .EnterAsync(context, cancellationToken); return instance; } private StackStateMachine( IStateStore<TContext> stateStore, TContext context, TimeSpan? semaphoreTimeout = null) { this.stateStore = stateStore; this.Context = context; this.stack.Push(this.stateStore.InitialState); this.semaphoreTimeout = semaphoreTimeout ?? TimeSpan.FromSeconds(DefaultSemaphoreTimeoutSeconds); } public void Dispose() { semaphore.Dispose(); stack.Clear(); stateStore.Dispose(); } public async UniTask<IResult<IPopToken>> PushAsync<TState>( CancellationToken cancellationToken) where TState : IStackState<TContext> { // Make stack thread-safe. try { await semaphore.WaitAsync(semaphoreTimeout, cancellationToken); } catch (OperationCanceledException exception) { semaphore.Release(); return Results.Fail<IPopToken>( $"Cancelled to wait semaphore because of {exception}."); } var nextState = stateStore.Get<TState>(); try { await nextState.EnterAsync(Context, cancellationToken); stack.Push(nextState); return Results.Succeed(PopToken.Publish(this)); } finally { semaphore.Release(); } } public async UniTask UpdateAsync(CancellationToken cancellationToken) { var currentState = stack.Peek(); await currentState.UpdateAsync(Context, cancellationToken); } private sealed class PopToken : IPopToken { private readonly StackStateMachine<TContext> publisher; private bool popped = false; public static
IPopToken Publish(StackStateMachine<TContext> publisher) => new PopToken(publisher);
private PopToken(StackStateMachine<TContext> publisher) { this.publisher = publisher; } public async UniTask<IResult> PopAsync(CancellationToken cancellationToken) { if (popped) { throw new InvalidOperationException( $"Failed to pop because of already popped."); } if (publisher.stack.Count is 0) { throw new InvalidOperationException( $"Failed to pop because of stack is empty."); } // Make stack thread-safe. try { await publisher.semaphore .WaitAsync(publisher.semaphoreTimeout, cancellationToken); } catch (OperationCanceledException exception) { publisher.semaphore.Release(); return Results.Fail( $"Cancelled to wait semaphore because of {exception}."); } popped = true; var currentState = publisher.stack.Peek(); try { await currentState .ExitAsync(publisher.Context, cancellationToken); publisher.stack.Pop(); return Results.Succeed(); } finally { publisher.semaphore.Release(); } } } } }
Assets/Mochineko/RelentStateMachine/StackStateMachine.cs
mochi-neko-RelentStateMachine-64762eb
[ { "filename": "Assets/Mochineko/RelentStateMachine/FiniteStateMachine.cs", "retrieved_chunk": " private readonly ITransitionMap<TEvent, TContext> transitionMap;\n public TContext Context { get; }\n private IState<TEvent, TContext> currentState;\n public bool IsCurrentState<TState>()\n where TState : IState<TEvent, TContext>\n => currentState is TState;\n private readonly SemaphoreSlim semaphore = new(\n initialCount: 1,\n maxCount: 1);\n private readonly TimeSpan semaphoreTimeout;", "score": 0.8682781457901001 }, { "filename": "Assets/Mochineko/RelentStateMachine.Tests/StackStateMachineTest.cs", "retrieved_chunk": " [TestFixture]\n internal sealed class StackStateMachineTest\n {\n [Test]\n [RequiresPlayMode(false)]\n public async Task StateMachineShouldTransitByEvent()\n {\n // NOTE: Initial state is specified at constructor.\n var stateStore = StateStoreBuilder<MockStackContext>\n .Create<BaseStackState>();", "score": 0.8415372371673584 }, { "filename": "Assets/Mochineko/RelentStateMachine.Tests/PopupStackState.cs", "retrieved_chunk": " }\n public async UniTask UpdateAsync(MockStackContext context, CancellationToken cancellationToken)\n {\n }\n public async UniTask ExitAsync(MockStackContext context, CancellationToken cancellationToken)\n {\n }\n public void Dispose()\n {\n }", "score": 0.8208467960357666 }, { "filename": "Assets/Mochineko/RelentStateMachine.Tests/OverlayStackState.cs", "retrieved_chunk": " }\n public async UniTask UpdateAsync(MockStackContext context, CancellationToken cancellationToken)\n {\n }\n public async UniTask ExitAsync(MockStackContext context, CancellationToken cancellationToken)\n {\n }\n public void Dispose()\n {\n }", "score": 0.8207452297210693 }, { "filename": "Assets/Mochineko/RelentStateMachine.Tests/FirstStackState.cs", "retrieved_chunk": " }\n public async UniTask UpdateAsync(MockStackContext context, CancellationToken cancellationToken)\n {\n }\n public async UniTask ExitAsync(MockStackContext context, CancellationToken cancellationToken)\n {\n }\n public void Dispose()\n {\n }", "score": 0.8207452297210693 } ]
csharp
IPopToken Publish(StackStateMachine<TContext> publisher) => new PopToken(publisher);
using DotNetDevBadgeWeb.Common; using Newtonsoft.Json; namespace DotNetDevBadgeWeb.Model { public class User { private const int AVATAR_SIZE = 128; [JsonProperty("id")] public int Id { get; set; } [JsonProperty("username")] public string Username { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("avatar_template")] public string AvatarTemplate { get; set; } [
JsonProperty("flair_name")] public object FlairName {
get; set; } [JsonProperty("trust_level")] public int TrustLevel { get; set; } [JsonProperty("admin")] public bool? Admin { get; set; } [JsonProperty("moderator")] public bool? Moderator { get; set; } public ELevel Level => TrustLevel switch { 3 => ELevel.Silver, 4 => ELevel.Gold, _ => ELevel.Bronze, }; public string AvatarEndPoint => AvatarTemplate?.Replace("{size}", AVATAR_SIZE.ToString()) ?? string.Empty; } }
src/dotnetdev-badge/dotnetdev-badge.web/Model/User.cs
chanos-dev-dotnetdev-badge-5740a40
[ { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Model/UserSummary.cs", "retrieved_chunk": " public int TimeRead { get; set; }\n [JsonProperty(\"recent_time_read\")]\n public int RecentTimeRead { get; set; }\n [JsonProperty(\"bookmark_count\")]\n public int BookmarkCount { get; set; }\n [JsonProperty(\"can_see_summary_stats\")]\n public bool CanSeeSummaryStats { get; set; }\n [JsonProperty(\"solved_count\")]\n public int SolvedCount { get; set; }\n }", "score": 0.8432067632675171 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Model/UserSummary.cs", "retrieved_chunk": " public int TopicsEntered { get; set; }\n [JsonProperty(\"posts_read_count\")]\n public int PostsReadCount { get; set; }\n [JsonProperty(\"days_visited\")]\n public int DaysVisited { get; set; }\n [JsonProperty(\"topic_count\")]\n public int TopicCount { get; set; }\n [JsonProperty(\"post_count\")]\n public int PostCount { get; set; }\n [JsonProperty(\"time_read\")]", "score": 0.8200035691261292 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Model/UserSummary.cs", "retrieved_chunk": "using Newtonsoft.Json;\nnamespace DotNetDevBadgeWeb.Model\n{\n public class UserSummary\n {\n [JsonProperty(\"likes_given\")]\n public int LikesGiven { get; set; }\n [JsonProperty(\"likes_received\")]\n public int LikesReceived { get; set; }\n [JsonProperty(\"topics_entered\")]", "score": 0.810092568397522 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Common/Palette.cs", "retrieved_chunk": " _ => \"CD7F32\",\n };\n }\n internal class ColorSet\n {\n internal string FontColor { get; private set; }\n internal string BackgroundColor { get; private set; }\n internal ColorSet(string fontColor, string backgroundColor)\n {\n FontColor = fontColor;", "score": 0.7794821858406067 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Interfaces/IProvider.cs", "retrieved_chunk": "using DotNetDevBadgeWeb.Model;\nnamespace DotNetDevBadgeWeb.Interfaces\n{\n public interface IProvider\n {\n Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n }\n}", "score": 0.7356230020523071 } ]
csharp
JsonProperty("flair_name")] public object FlairName {
using System; using System.Collections.Generic; using System.Text; using UnityEngine; namespace Ultrapain.Patches { class Idol_Death_Patch { static void Postfix(
Idol __instance) {
if(ConfigManager.idolExplodionType.value == ConfigManager.IdolExplosionType.Sand) { GameObject.Instantiate(Plugin.sandExplosion, __instance.transform.position, Quaternion.identity); return; } GameObject tempExplosion = null; switch(ConfigManager.idolExplodionType.value) { case ConfigManager.IdolExplosionType.Normal: tempExplosion = Plugin.explosion; break; case ConfigManager.IdolExplosionType.Big: tempExplosion = Plugin.bigExplosion; break; case ConfigManager.IdolExplosionType.Ligthning: tempExplosion = Plugin.lightningStrikeExplosive; break; case ConfigManager.IdolExplosionType.Sisyphean: tempExplosion = Plugin.sisyphiusPrimeExplosion; break; } GameObject explosion = GameObject.Instantiate(tempExplosion, __instance.gameObject.transform.position, Quaternion.identity); foreach (Explosion exp in explosion.GetComponentsInChildren<Explosion>()) { exp.enemy = true; exp.canHit = AffectedSubjects.All; exp.hitterWeapon = ""; exp.maxSize *= ConfigManager.idolExplosionSizeMultiplier.value; exp.speed *= ConfigManager.idolExplosionSizeMultiplier.value; exp.damage = (int)(exp.damage * ConfigManager.idolExplosionDamageMultiplier.value); exp.enemyDamageMultiplier = ConfigManager.idolExplosionEnemyDamagePercent.value / 100f; } } } }
Ultrapain/Patches/Idol.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/FleshPrison.cs", "retrieved_chunk": "using HarmonyLib;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing UnityEngine;\nusing UnityEngine.UI;\nnamespace Ultrapain.Patches\n{\n class FleshObamium_Start\n {\n static bool Prefix(FleshPrison __instance)", "score": 0.8942480087280273 }, { "filename": "Ultrapain/Patches/EnrageEffect.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class EnrageEffect_Start\n {\n static void Postfix(EnrageEffect __instance)", "score": 0.8938179612159729 }, { "filename": "Ultrapain/Patches/StreetCleaner.cs", "retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class StreetCleaner_Start_Patch\n {\n static void Postfix(Streetcleaner __instance, ref EnemyIdentifier ___eid)\n {\n ___eid.weakPoint = null;\n }", "score": 0.8744291067123413 }, { "filename": "Ultrapain/Patches/GlobalEnemyTweaks.cs", "retrieved_chunk": "using HarmonyLib;\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nusing UnityEngine;\nusing static Ultrapain.ConfigManager;\nnamespace Ultrapain.Patches\n{\n // EID\n class EnemyIdentifier_UpdateModifiers", "score": 0.872955322265625 }, { "filename": "Ultrapain/Patches/CommonComponents.cs", "retrieved_chunk": "using HarmonyLib;\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n /*public class ObjectActivator : MonoBehaviour\n {\n public int originalInstanceID = 0;", "score": 0.8652305603027344 } ]
csharp
Idol __instance) {
using HarmonyLib; using System; using System.Collections.Generic; using System.Reflection.Emit; using System.Text; using UnityEngine; namespace Ultrapain { public static class ILUtils { public static string TurnInstToString(
CodeInstruction inst) {
return $"{inst.opcode}{(inst.operand == null ? "" : $" : ({inst.operand.GetType()}){inst.operand}")}"; } public static OpCode LoadLocalOpcode(int localIndex) { if (localIndex == 0) return OpCodes.Ldloc_0; if (localIndex == 1) return OpCodes.Ldloc_1; if (localIndex == 2) return OpCodes.Ldloc_2; if (localIndex == 3) return OpCodes.Ldloc_3; if (localIndex <= byte.MaxValue) return OpCodes.Ldloc_S; return OpCodes.Ldloc; } public static CodeInstruction LoadLocalInstruction(int localIndex) { if (localIndex == 0) return new CodeInstruction(OpCodes.Ldloc_0); if (localIndex == 1) return new CodeInstruction(OpCodes.Ldloc_1); if (localIndex == 2) return new CodeInstruction(OpCodes.Ldloc_2); if (localIndex == 3) return new CodeInstruction(OpCodes.Ldloc_3); if (localIndex <= byte.MaxValue) return new CodeInstruction(OpCodes.Ldloc_S, (byte) localIndex); return new CodeInstruction(OpCodes.Ldloc, localIndex); } public static CodeInstruction LoadLocalInstruction(object localIndex) { if (localIndex is int intIndex) return LoadLocalInstruction(intIndex); // Wish I could access LocalBuilder, this is just a logic bomb // I hope they don't use more than 255 local variables return new CodeInstruction(OpCodes.Ldloc_S, localIndex); } public static OpCode StoreLocalOpcode(int localIndex) { if (localIndex == 0) return OpCodes.Stloc_0; if (localIndex == 1) return OpCodes.Stloc_1; if (localIndex == 2) return OpCodes.Stloc_2; if (localIndex == 3) return OpCodes.Stloc_3; if (localIndex <= byte.MaxValue) return OpCodes.Stloc_S; return OpCodes.Stloc; } public static CodeInstruction StoreLocalInstruction(int localIndex) { if (localIndex <= 3) return new CodeInstruction(StoreLocalOpcode(localIndex)); return new CodeInstruction(StoreLocalOpcode(localIndex), localIndex); } public static CodeInstruction StoreLocalInstruction(object localIndex) { if (localIndex is int integerIndex) return StoreLocalInstruction(integerIndex); // Another logic bomb return new CodeInstruction(OpCodes.Stloc_S, localIndex); } public static object GetLocalIndex(CodeInstruction inst) { if (inst.opcode == OpCodes.Ldloc_0 || inst.opcode == OpCodes.Stloc_0) return 0; if (inst.opcode == OpCodes.Ldloc_1 || inst.opcode == OpCodes.Stloc_1) return 1; if (inst.opcode == OpCodes.Ldloc_2 || inst.opcode == OpCodes.Stloc_2) return 2; if (inst.opcode == OpCodes.Ldloc_3 || inst.opcode == OpCodes.Stloc_3) return 3; // Return the local builder object (which is not defined in mscorlib for some reason, so cannot access members) if (inst.opcode == OpCodes.Ldloc_S || inst.opcode == OpCodes.Stloc_S || inst.opcode == OpCodes.Ldloc || inst.opcode == OpCodes.Stloc) return inst.operand; return null; } public static bool IsConstI4LoadWithOperand(OpCode code) { return code == OpCodes.Ldc_I4_S || code == OpCodes.Ldc_I4 || code == OpCodes.Ldc_I8; } public static bool IsStoreLocalOpcode(OpCode code) { return code == OpCodes.Stloc || code == OpCodes.Stloc_S || code == OpCodes.Stloc_0 || code == OpCodes.Stloc_1 || code == OpCodes.Stloc_2 || code == OpCodes.Stloc_3; } public static OpCode GetLoadLocalFromStoreLocal(OpCode code) { if (code == OpCodes.Stloc_0) return OpCodes.Ldloc_0; if (code == OpCodes.Stloc_1) return OpCodes.Ldloc_1; if (code == OpCodes.Stloc_2) return OpCodes.Ldloc_2; if (code == OpCodes.Stloc_3) return OpCodes.Ldloc_3; if (code == OpCodes.Stloc_S) return OpCodes.Ldloc_S; if (code == OpCodes.Stloc) return OpCodes.Ldloc; throw new ArgumentException($"{code} is not a valid store local opcode"); } public static int GetI4LoadOperand(CodeInstruction code) { if (code.opcode == OpCodes.Ldc_I4_S) return (sbyte)code.operand; if (code.opcode == OpCodes.Ldc_I4) return (int)code.operand; if (code.opcode == OpCodes.Ldc_I4_0) return 0; if (code.opcode == OpCodes.Ldc_I4_1) return 1; if (code.opcode == OpCodes.Ldc_I4_2) return 2; if (code.opcode == OpCodes.Ldc_I4_3) return 3; if (code.opcode == OpCodes.Ldc_I4_4) return 4; if (code.opcode == OpCodes.Ldc_I4_5) return 5; if (code.opcode == OpCodes.Ldc_I4_6) return 6; if (code.opcode == OpCodes.Ldc_I4_7) return 7; if (code.opcode == OpCodes.Ldc_I4_8) return 8; if (code.opcode == OpCodes.Ldc_I4_M1) return -1; throw new ArgumentException($"{code.opcode} is not a valid i4 load constant opcode"); } private static OpCode[] efficientI4 = new OpCode[] { OpCodes.Ldc_I4_M1, OpCodes.Ldc_I4_0, OpCodes.Ldc_I4_1, OpCodes.Ldc_I4_2, OpCodes.Ldc_I4_3, OpCodes.Ldc_I4_4, OpCodes.Ldc_I4_5, OpCodes.Ldc_I4_6, OpCodes.Ldc_I4_7, OpCodes.Ldc_I4_8 }; // Get an efficient version of constant i4 load opcode which does not require an operand public static bool TryEfficientLoadI4(int value, out OpCode efficientOpcode) { if (value <= 8 && value >= -1) { efficientOpcode = efficientI4[value + 1]; return true; } efficientOpcode = OpCodes.Ldc_I4; return false; } public static bool IsCodeSequence(List<CodeInstruction> code, int index, List<CodeInstruction> seq) { if (index + seq.Count > code.Count) return false; for (int i = 0; i < seq.Count; i++) { if (seq[i].opcode != code[i + index].opcode) return false; else if (code[i + index].operand != null && !code[i + index].OperandIs(seq[i].operand)) return false; } return true; } } }
Ultrapain/ILUtils.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/V2Common.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n public static class V2Utils\n {\n public static Transform GetClosestGrenade()\n {", "score": 0.8739292621612549 }, { "filename": "Ultrapain/Patches/CommonComponents.cs", "retrieved_chunk": "using HarmonyLib;\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n /*public class ObjectActivator : MonoBehaviour\n {\n public int originalInstanceID = 0;", "score": 0.8513760566711426 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": "using System.IO;\nusing PluginConfig.API.Functionals;\nusing System.Reflection;\nusing System.Text;\nusing static Ultrapain.ConfigManager;\nnamespace Ultrapain\n{\n // Adds an image next to the given input field\n public class ImageInputField : CustomConfigField\n {", "score": 0.8445616960525513 }, { "filename": "Ultrapain/Patches/Stray.cs", "retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nusing UnityEngine.AI;\nnamespace Ultrapain.Patches\n{\n public class StrayFlag : MonoBehaviour\n {\n //public int extraShotsRemaining = 6;\n private Animator anim;\n private EnemyIdentifier eid;", "score": 0.8441638946533203 }, { "filename": "Ultrapain/Patches/MaliciousFace.cs", "retrieved_chunk": "using HarmonyLib;\nusing System;\nusing System.ComponentModel;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class MaliciousFaceFlag : MonoBehaviour\n {\n public bool charging = false;\n }", "score": 0.8421517014503479 } ]
csharp
CodeInstruction inst) {
using Newtonsoft.Json; namespace Gum.InnerThoughts { public class CharacterScript { /// <summary> /// List of tasks or events that the <see cref="Situations"/> may do. /// </summary> [JsonProperty] private readonly SortedList<int, Situation> _situations = new(); private readonly Dictionary<string, int> _situationNames = new(); [JsonProperty] private int _nextId = 0; public readonly string Name; public CharacterScript(string name) { Name = name; } private Situation? _currentSituation; public Situation CurrentSituation => _currentSituation ?? throw new InvalidOperationException("☠️ Unable to fetch an active situation."); public bool HasCurrentSituation => _currentSituation != null; public bool AddNewSituation(ReadOnlySpan<char> name) { int id = _nextId++; string situationName = name.TrimStart().TrimEnd().ToString(); if (_situationNames.ContainsKey(situationName)) { return false; } _currentSituation = new Situation(id, situationName); _situations.Add(id, _currentSituation); _situationNames.Add(situationName, id); return true; } public
Situation? FetchSituation(int id) {
if (_situations.TryGetValue(id, out Situation? value)) { return value; } return null; } public int? FetchSituationId(string name) { if (_situationNames.TryGetValue(name, out int id)) { return id; } return null; } public string[] FetchAllNames() => _situationNames.Keys.ToArray(); public IEnumerable<Situation> FetchAllSituations() => _situations.Values; } }
src/Gum/InnerThoughts/CharacterScript.cs
isadorasophia-gum-032cb2d
[ { "filename": "src/Gum.Tests/Bungee.cs", "retrieved_chunk": " public void TestSingleSentence()\n {\n const string situationText = @\"\n=Encounter\n I just have one sentence.\";\n CharacterScript? script = Read(situationText);\n Assert.IsTrue(script != null);\n Situation? situation = script.FetchSituation(id: 0);\n Assert.IsTrue(situation != null);\n Edge target = situation.Edges[0];", "score": 0.7901812195777893 }, { "filename": "src/Gum.Tests/Bungee.cs", "retrieved_chunk": " [Happy += 5]\n Or yes?\n (...)\n No.\n -> exit!\";\n CharacterScript? script = Read(situationText);\n Assert.IsTrue(script != null);\n Situation? situation = script.FetchSituation(id: 0);\n Assert.IsTrue(situation != null);\n Edge target = situation.Edges[0];", "score": 0.7819923162460327 }, { "filename": "src/Gum.Tests/Bungee.cs", "retrieved_chunk": " [Happy += 5]\n (...)\n No.\n -> exit!\";\n CharacterScript? script = Read(situationText);\n Assert.IsTrue(script != null);\n Situation? situation = script.FetchSituation(id: 0);\n Assert.IsTrue(situation != null);\n Edge target = situation.Edges[0];\n Assert.AreEqual(EdgeKind.Next, target.Kind);", "score": 0.7771463990211487 }, { "filename": "src/Gum.Tests/Bungee.cs", "retrieved_chunk": " (!Meet and !Greet) \n @order\n - I will go now.\n + Hello!?\n -> exit!\";\n CharacterScript? script = Read(situationText);\n Assert.IsTrue(script != null);\n Situation? situation = script.FetchSituation(id: 0);\n Assert.IsTrue(situation != null);\n Edge target = situation.Edges[0];", "score": 0.7742705345153809 }, { "filename": "src/Gum.Tests/Bungee.cs", "retrieved_chunk": " thief: I am simply existing here.\n Bye.\n=Bye\";\n CharacterScript? script = Read(situationText);\n Assert.IsTrue(script != null);\n Situation? situation = script.FetchSituation(id: 0);\n Assert.IsTrue(situation != null);\n Edge target = situation.Edges[0];\n Assert.AreEqual(EdgeKind.Next, target.Kind);\n Assert.AreEqual(0, target.Owner);", "score": 0.766851544380188 } ]
csharp
Situation? FetchSituation(int id) {
using System.Text.Json.Serialization; namespace LibreDteDotNet.RestRequest.Models.Request { internal class ReqLibroResumen { // Root myDeserializedClass = JsonSerializer.Deserialize<Root>(myJsonResponse); [JsonPropertyName("metaData")] public ReqMetaDataLibroResumen? MetaData { get; set; } [JsonPropertyName("data")] public
ReqDataLibroResumen? Data {
get; set; } public ReqLibroResumen(ReqMetaDataLibroResumen? metaData, ReqDataLibroResumen? data) { MetaData = metaData; Data = data; } } }
LibreDteDotNet.RestRequest/Models/Request/ReqLibroResumen.cs
sergiokml-LibreDteDotNet.RestRequest-6843109
[ { "filename": "LibreDteDotNet.RestRequest/Models/Response/ResLibroResumen.cs", "retrieved_chunk": "using System.Text.Json.Serialization;\nnamespace LibreDteDotNet.RestRequest.Models.Response\n{\n public class ResLibroResumen\n {\n [JsonPropertyName(\"data\")]\n public ResDataLibroResumen? Data { get; set; }\n [JsonPropertyName(\"metaData\")]\n public ResMetaDataLibroResumen? MetaData { get; set; }\n [JsonPropertyName(\"respEstado\")]", "score": 0.9306405186653137 }, { "filename": "LibreDteDotNet.RestRequest/Models/Request/ReqLibroResumenCsv.cs", "retrieved_chunk": "using System.Text.Json.Serialization;\nusing LibreDteDotNet.RestRequest.Models.Response;\nnamespace LibreDteDotNet.RestRequest.Models.Request\n{\n public class ReqLibroResumenCsv\n {\n [JsonPropertyName(\"data\")]\n public List<string>? Data { get; set; }\n [JsonPropertyName(\"metaData\")]\n public ResMetaDataLibroResumen? MetaData { get; set; }", "score": 0.9185669422149658 }, { "filename": "LibreDteDotNet.RestRequest/Models/Request/ReqLibroDetalle.cs", "retrieved_chunk": "using System.Text.Json.Serialization;\nnamespace LibreDteDotNet.RestRequest.Models.Request\n{\n public class ReqLibroDetalle\n {\n [JsonPropertyName(\"metaData\")]\n public ReqMetaDataLibroDetalle? MetaData { get; set; }\n [JsonPropertyName(\"data\")]\n public ReqDataLibroDetalle? Data { get; set; }\n public ReqLibroDetalle(ReqMetaDataLibroDetalle? metaData, ReqDataLibroDetalle? data)", "score": 0.9116818904876709 }, { "filename": "LibreDteDotNet.RestRequest/Models/Response/ResLibroDetalle.cs", "retrieved_chunk": "using System.Text.Json.Serialization;\nnamespace LibreDteDotNet.RestRequest.Models.Response\n{\n public class ResLibroDetalle\n {\n [JsonPropertyName(\"data\")]\n public object Data { get; set; }\n [JsonPropertyName(\"dataResp\")]\n public DataResp DataResp { get; set; }\n [JsonPropertyName(\"dataReferencias\")]", "score": 0.8985769748687744 }, { "filename": "LibreDteDotNet.RestRequest/Models/Request/ReqMetaDataLibroResumen.cs", "retrieved_chunk": "using System.Text.Json.Serialization;\nnamespace LibreDteDotNet.RestRequest.Models.Request\n{\n public class ReqMetaDataLibroResumen\n {\n [JsonPropertyName(\"conversationId\")]\n public string? ConversationId { get; set; }\n [JsonPropertyName(\"transactionId\")]\n public string? TransactionId { get; set; }\n [JsonPropertyName(\"namespace\")]", "score": 0.8851399421691895 } ]
csharp
ReqDataLibroResumen? Data {
using BepInEx; using UnityEngine; using UnityEngine.SceneManagement; using System; using HarmonyLib; using System.IO; using Ultrapain.Patches; using System.Linq; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Reflection; using Steamworks; using Unity.Audio; using System.Text; using System.Collections.Generic; using UnityEngine.AddressableAssets; using UnityEngine.AddressableAssets.ResourceLocators; using UnityEngine.ResourceManagement.ResourceLocations; using UnityEngine.UIElements; using PluginConfig.API; namespace Ultrapain { [BepInPlugin(PLUGIN_GUID, PLUGIN_NAME, PLUGIN_VERSION)] [BepInDependency("com.eternalUnion.pluginConfigurator", "1.6.0")] public class Plugin : BaseUnityPlugin { public const string PLUGIN_GUID = "com.eternalUnion.ultraPain"; public const string PLUGIN_NAME = "Ultra Pain"; public const string PLUGIN_VERSION = "1.1.0"; public static Plugin instance; private static bool addressableInit = false; public static T LoadObject<T>(string path) { if (!addressableInit) { Addressables.InitializeAsync().WaitForCompletion(); addressableInit = true; } return Addressables.LoadAssetAsync<T>(path).WaitForCompletion(); } public static Vector3 PredictPlayerPosition(Collider safeCollider, float speedMod) { Transform target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f) return target.position; RaycastHit raycastHit; if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == safeCollider) return target.position; else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide)) { return raycastHit.point; } else { Vector3 projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod; return new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z); } } public static GameObject projectileSpread; public static GameObject homingProjectile; public static GameObject hideousMassProjectile; public static GameObject decorativeProjectile2; public static GameObject shotgunGrenade; public static GameObject beam; public static GameObject turretBeam; public static GameObject lightningStrikeExplosiveSetup; public static GameObject lightningStrikeExplosive; public static GameObject lighningStrikeWindup; public static GameObject explosion; public static GameObject bigExplosion; public static GameObject sandExplosion; public static GameObject virtueInsignia; public static GameObject rocket; public static GameObject revolverBullet; public static GameObject maliciousCannonBeam; public static GameObject lightningBoltSFX; public static GameObject revolverBeam; public static GameObject blastwave; public static GameObject cannonBall; public static GameObject shockwave; public static GameObject sisyphiusExplosion; public static GameObject sisyphiusPrimeExplosion; public static GameObject explosionWaveKnuckleblaster; public static GameObject chargeEffect; public static GameObject maliciousFaceProjectile; public static GameObject hideousMassSpear; public static GameObject coin; public static GameObject sisyphusDestroyExplosion; //public static GameObject idol; public static GameObject ferryman; public static GameObject minosPrime; //public static GameObject maliciousFace; public static GameObject somethingWicked; public static Turret turret; public static GameObject turretFinalFlash; public static GameObject enrageEffect; public static GameObject v2flashUnparryable; public static GameObject ricochetSfx; public static GameObject parryableFlash; public static AudioClip cannonBallChargeAudio; public static Material gabrielFakeMat; public static Sprite blueRevolverSprite; public static Sprite greenRevolverSprite; public static Sprite redRevolverSprite; public static Sprite blueShotgunSprite; public static Sprite greenShotgunSprite; public static Sprite blueNailgunSprite; public static Sprite greenNailgunSprite; public static Sprite blueSawLauncherSprite; public static Sprite greenSawLauncherSprite; public static
GameObject rocketLauncherAlt;
public static GameObject maliciousRailcannon; // Variables public static float SoliderShootAnimationStart = 1.2f; public static float SoliderGrenadeForce = 10000f; public static float SwordsMachineKnockdownTimeNormalized = 0.8f; public static float SwordsMachineCoreSpeed = 80f; public static float MinGrenadeParryVelocity = 40f; public static GameObject _lighningBoltSFX; public static GameObject lighningBoltSFX { get { if (_lighningBoltSFX == null) _lighningBoltSFX = ferryman.gameObject.transform.Find("LightningBoltChimes").gameObject; return _lighningBoltSFX; } } private static bool loadedPrefabs = false; public void LoadPrefabs() { if (loadedPrefabs) return; loadedPrefabs = true; // Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab projectileSpread = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab homingProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab decorativeProjectile2 = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab"); // Assets/Prefabs/Attacks and Projectiles/Grenade.prefab shotgunGrenade = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Grenade.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab turretBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab beam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab lightningStrikeExplosiveSetup = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab"); // Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab lighningStrikeWindup = LoadObject<GameObject>("Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab"); //[bundle-0][assets/prefabs/enemies/idol.prefab] //idol = LoadObject<GameObject>("assets/prefabs/enemies/idol.prefab"); // Assets/Prefabs/Enemies/Ferryman.prefab ferryman = LoadObject<GameObject>("Assets/Prefabs/Enemies/Ferryman.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab explosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab bigExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab sandExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab"); // Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab virtueInsignia = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab hideousMassProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab"); // Assets/Particles/Enemies/RageEffect.prefab enrageEffect = LoadObject<GameObject>("Assets/Particles/Enemies/RageEffect.prefab"); // Assets/Particles/Flashes/V2FlashUnparriable.prefab v2flashUnparryable = LoadObject<GameObject>("Assets/Particles/Flashes/V2FlashUnparriable.prefab"); // Assets/Prefabs/Attacks and Projectiles/Rocket.prefab rocket = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Rocket.prefab"); // Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab revolverBullet = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab maliciousCannonBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab revolverBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab blastwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab"); // Assets/Prefabs/Enemies/MinosPrime.prefab minosPrime = LoadObject<GameObject>("Assets/Prefabs/Enemies/MinosPrime.prefab"); // Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab cannonBall = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab"); // get from Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab cannonBallChargeAudio = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab").transform.Find("RocketLauncher/Armature/Body_Bone/HologramDisplay").GetComponent<AudioSource>().clip; // Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab shockwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab sisyphiusExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab sisyphiusPrimeExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab explosionWaveKnuckleblaster = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab - [bundle-0][assets/prefabs/explosionlightning variant.prefab] lightningStrikeExplosive = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab"); // Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab rocketLauncherAlt = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab"); // Assets/Prefabs/Weapons/Railcannon Malicious.prefab maliciousRailcannon = LoadObject<GameObject>("Assets/Prefabs/Weapons/Railcannon Malicious.prefab"); //Assets/Particles/SoundBubbles/Ricochet.prefab ricochetSfx = LoadObject<GameObject>("Assets/Particles/SoundBubbles/Ricochet.prefab"); //Assets/Particles/Flashes/Flash.prefab parryableFlash = LoadObject<GameObject>("Assets/Particles/Flashes/Flash.prefab"); //Assets/Prefabs/Attacks and Projectiles/Spear.prefab hideousMassSpear = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Spear.prefab"); //Assets/Prefabs/Enemies/Wicked.prefab somethingWicked = LoadObject<GameObject>("Assets/Prefabs/Enemies/Wicked.prefab"); //Assets/Textures/UI/SingleRevolver.png blueRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/SingleRevolver.png"); //Assets/Textures/UI/RevolverSpecial.png greenRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSpecial.png"); //Assets/Textures/UI/RevolverSharp.png redRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSharp.png"); //Assets/Textures/UI/Shotgun.png blueShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun.png"); //Assets/Textures/UI/Shotgun1.png greenShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun1.png"); //Assets/Textures/UI/Nailgun2.png blueNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Nailgun2.png"); //Assets/Textures/UI/NailgunOverheat.png greenNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/NailgunOverheat.png"); //Assets/Textures/UI/SawbladeLauncher.png blueSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncher.png"); //Assets/Textures/UI/SawbladeLauncherOverheat.png greenSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncherOverheat.png"); //Assets/Prefabs/Attacks and Projectiles/Coin.prefab coin = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Coin.prefab"); //Assets/Materials/GabrielFake.mat gabrielFakeMat = LoadObject<Material>("Assets/Materials/GabrielFake.mat"); //Assets/Prefabs/Enemies/Turret.prefab turret = LoadObject<GameObject>("Assets/Prefabs/Enemies/Turret.prefab").GetComponent<Turret>(); //Assets/Particles/Flashes/GunFlashDistant.prefab turretFinalFlash = LoadObject<GameObject>("Assets/Particles/Flashes/GunFlashDistant.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab sisyphusDestroyExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab"); //Assets/Prefabs/Effects/Charge Effect.prefab chargeEffect = LoadObject<GameObject>("Assets/Prefabs/Effects/Charge Effect.prefab"); //Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab maliciousFaceProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab"); } public static bool ultrapainDifficulty = false; public static bool realUltrapainDifficulty = false; public static GameObject currentDifficultyButton; public static GameObject currentDifficultyPanel; public static Text currentDifficultyInfoText; public void OnSceneChange(Scene before, Scene after) { StyleIDs.RegisterIDs(); ScenePatchCheck(); string mainMenuSceneName = "b3e7f2f8052488a45b35549efb98d902"; string bootSequenceSceneName = "4f8ecffaa98c2614f89922daf31fa22d"; string currentSceneName = SceneManager.GetActiveScene().name; if (currentSceneName == mainMenuSceneName) { LoadPrefabs(); //Canvas/Difficulty Select (1)/Violent Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Difficulty Select (1)"); GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect); currentDifficultyButton = ultrapainButton; ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value; ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5; RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>(); ultrapainTrans.anchoredPosition = new Vector2(20f, -104f); //Canvas/Difficulty Select (1)/Violent Info GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect); currentDifficultyPanel = info; currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>(); currentDifficultyInfoText.text = ConfigManager.pluginInfo.value; Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>(); currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--"; currentDifficultyHeaderText.resizeTextForBestFit = true; currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap; currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate; info.SetActive(false); EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>(); evt.triggers.Clear(); /*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(false));*/ EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit }; trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false)); evt.triggers.Add(trigger1); evt.triggers.Add(trigger2); foreach(EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>()) { if (trigger.gameObject == ultrapainButton) continue; EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false)); trigger.triggers.Add(closeTrigger); } } else if(currentSceneName == bootSequenceSceneName) { LoadPrefabs(); //Canvas/Difficulty Select (1)/Violent Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Intro/Difficulty Select"); GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect); currentDifficultyButton = ultrapainButton; ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value; ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5; RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>(); ultrapainTrans.anchoredPosition = new Vector2(20f, -104f); //Canvas/Difficulty Select (1)/Violent Info GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect); currentDifficultyPanel = info; currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>(); currentDifficultyInfoText.text = ConfigManager.pluginInfo.value; Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>(); currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--"; currentDifficultyHeaderText.resizeTextForBestFit = true; currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap; currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate; info.SetActive(false); EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>(); evt.triggers.Clear(); /*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(false));*/ EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit }; trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false)); evt.triggers.Add(trigger1); evt.triggers.Add(trigger2); foreach (EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>()) { if (trigger.gameObject == ultrapainButton) continue; EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false)); trigger.triggers.Add(closeTrigger); } } // LOAD CUSTOM PREFABS HERE TO AVOID MID GAME LAG MinosPrimeCharge.CreateDecoy(); GameObject shockwaveSisyphus = SisyphusInstructionist_Start.shockwave; } public static class StyleIDs { private static bool registered = false; public static void RegisterIDs() { registered = false; if (MonoSingleton<StyleHUD>.Instance == null) return; MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.grenadeBoostStyleText.guid, ConfigManager.grenadeBoostStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.rocketBoostStyleText.guid, ConfigManager.rocketBoostStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverStyleText.guid, ConfigManager.orbStrikeRevolverStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverChargedStyleText.guid, ConfigManager.orbStrikeRevolverChargedStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeElectricCannonStyleText.guid, ConfigManager.orbStrikeElectricCannonStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeMaliciousCannonStyleText.guid, ConfigManager.orbStrikeMaliciousCannonStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.maliciousChargebackStyleText.guid, ConfigManager.maliciousChargebackStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.sentryChargebackStyleText.guid, ConfigManager.sentryChargebackStyleText.formattedString); registered = true; Debug.Log("Registered all style ids"); } private static FieldInfo idNameDict = typeof(StyleHUD).GetField("idNameDict", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); public static void UpdateID(string id, string newName) { if (!registered || StyleHUD.Instance == null) return; (idNameDict.GetValue(StyleHUD.Instance) as Dictionary<string, string>)[id] = newName; } } public static Harmony harmonyTweaks; public static Harmony harmonyBase; private static MethodInfo GetMethod<T>(string name) { return typeof(T).GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } private static Dictionary<MethodInfo, HarmonyMethod> methodCache = new Dictionary<MethodInfo, HarmonyMethod>(); private static HarmonyMethod GetHarmonyMethod(MethodInfo method) { if (methodCache.TryGetValue(method, out HarmonyMethod harmonyMethod)) return harmonyMethod; else { harmonyMethod = new HarmonyMethod(method); methodCache.Add(method, harmonyMethod); return harmonyMethod; } } private static void PatchAllEnemies() { if (!ConfigManager.enemyTweakToggle.value) return; if (ConfigManager.friendlyFireDamageOverrideToggle.value) { harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<PhysicalShockwave>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<VirtueInsignia>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_FF>("Prefix"))); harmonyTweaks.Patch(GetMethod<Flammable>("Burn"), prefix: GetHarmonyMethod(GetMethod<Flammable_Burn_FF>("Prefix"))); harmonyTweaks.Patch(GetMethod<FireZone>("OnTriggerStay"), prefix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Postfix"))); } harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("UpdateModifiers"), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_UpdateModifiers>("Postfix"))); harmonyTweaks.Patch(GetMethod<StatueBoss>("Start"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Start_Patch>("Postfix"))); if (ConfigManager.cerberusDashToggle.value) harmonyTweaks.Patch(GetMethod<StatueBoss>("StopDash"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopDash_Patch>("Postfix"))); if(ConfigManager.cerberusParryable.value) { harmonyTweaks.Patch(GetMethod<StatueBoss>("StopTracking"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopTracking_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<StatueBoss>("Stomp"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Stomp_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Statue>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Statue_GetHurt_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Drone_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Drone>("Shoot"), prefix: GetHarmonyMethod(GetMethod<Drone_Shoot_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("PlaySound"), prefix: GetHarmonyMethod(GetMethod<Drone_PlaySound_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Update"), postfix: GetHarmonyMethod(GetMethod<Drone_Update>("Postfix"))); if(ConfigManager.droneHomeToggle.value) { harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Drone_Death_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Drone_GetHurt_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Ferryman>("Start"), postfix: GetHarmonyMethod(GetMethod<FerrymanStart>("Postfix"))); if(ConfigManager.ferrymanComboToggle.value) harmonyTweaks.Patch(GetMethod<Ferryman>("StopMoving"), postfix: GetHarmonyMethod(GetMethod<FerrymanStopMoving>("Postfix"))); if(ConfigManager.filthExplodeToggle.value) harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch2>("Prefix"))); if(ConfigManager.fleshPrisonSpinAttackToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<FleshPrisonShoot>("Postfix"))); if (ConfigManager.hideousMassInsigniaToggle.value) { harmonyTweaks.Patch(GetMethod<Projectile>("Explode"), postfix: GetHarmonyMethod(GetMethod<Projectile_Explode_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Mass>("ShootExplosive"), postfix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Postfix")), prefix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Prefix"))); } harmonyTweaks.Patch(GetMethod<SpiderBody>("Start"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<SpiderBody>("ChargeBeam"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ChargeBeam>("Postfix"))); harmonyTweaks.Patch(GetMethod<SpiderBody>("BeamChargeEnd"), prefix: GetHarmonyMethod(GetMethod<MaliciousFace_BeamChargeEnd>("Prefix"))); if (ConfigManager.maliciousFaceHomingProjectileToggle.value) { harmonyTweaks.Patch(GetMethod<SpiderBody>("ShootProj"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ShootProj_Patch>("Postfix"))); } if (ConfigManager.maliciousFaceRadianceOnEnrage.value) harmonyTweaks.Patch(GetMethod<SpiderBody>("Enrage"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Enrage_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Mindflayer>("Start"), postfix: GetHarmonyMethod(GetMethod<Mindflayer_Start_Patch>("Postfix"))); if (ConfigManager.mindflayerShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<Mindflayer>("ShootProjectiles"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_ShootProjectiles_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_MF>("Prefix"))); } if (ConfigManager.mindflayerTeleportComboToggle.value) { harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Mindflayer>("MeleeTeleport"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_MeleeTeleport_Patch>("Prefix"))); //harmonyTweaks.Patch(GetMethod<SwingCheck2>("DamageStop"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_DamageStop_Patch>("Postfix"))); } if (ConfigManager.minosPrimeRandomTeleportToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("Postfix"))); if (ConfigManager.minosPrimeTeleportTrail.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("Teleport"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("TeleportPostfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Start"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Dropkick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Dropkick>("Prefix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Combo"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Combo>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("StopAction"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_StopAction>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Ascend"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Ascend>("Prefix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Death"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Death>("Prefix"))); if (ConfigManager.minosPrimeCrushAttackToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("RiderKick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_RiderKick>("Prefix"))); if (ConfigManager.minosPrimeComboExplosiveEndToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_ProjectileCharge>("Prefix"))); if (ConfigManager.schismSpreadAttackToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ShootProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ShootProjectile_Patch>("Postfix"))); if (ConfigManager.soliderShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<Solider_Start_Patch>("Postfix"))); } if(ConfigManager.soliderCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_SpawnProjectile_Patch>("Postfix"))); if (ConfigManager.soliderShootGrenadeToggle.value || ConfigManager.soliderShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_ThrowProjectile_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Stalker>("SandExplode"), prefix: GetHarmonyMethod(GetMethod<Stalker_SandExplode_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SandificationZone>("Enter"), postfix: GetHarmonyMethod(GetMethod<SandificationZone_Enter_Patch>("Postfix"))); if (ConfigManager.strayCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Swing>("Postfix"))); if (ConfigManager.strayShootToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_Start_Patch1>("Postfix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ThrowProjectile_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<SwingEnd>("Prefix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("DamageEnd"), prefix: GetHarmonyMethod(GetMethod<DamageEnd>("Prefix"))); } if(ConfigManager.streetCleanerCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<Streetcleaner>("Start"), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Start_Patch>("Postfix"))); if(ConfigManager.streetCleanerPredictiveDodgeToggle.value) harmonyTweaks.Patch(GetMethod<BulletCheck>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<BulletCheck_OnTriggerEnter_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("Start"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Start>("Postfix"))); if (ConfigManager.swordsMachineNoLightKnockbackToggle.value || ConfigManager.swordsMachineSecondPhaseMode.value != ConfigManager.SwordsMachineSecondPhase.None) { harmonyTweaks.Patch(GetMethod<SwordsMachine>("Knockdown"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Knockdown_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("Down"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Prefix"))); //harmonyTweaks.Patch(GetMethod<SwordsMachine>("SetSpeed"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_SetSpeed_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("EndFirstPhase"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Prefix"))); } if (ConfigManager.swordsMachineExplosiveSwordToggle.value) { harmonyTweaks.Patch(GetMethod<ThrownSword>("Start"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<ThrownSword>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_OnTriggerEnter_Patch>("Postfix"))); } harmonyTweaks.Patch(GetMethod<Turret>("Start"), postfix: GetHarmonyMethod(GetMethod<TurretStart>("Postfix"))); if(ConfigManager.turretBurstFireToggle.value) { harmonyTweaks.Patch(GetMethod<Turret>("Shoot"), prefix: GetHarmonyMethod(GetMethod<TurretShoot>("Prefix"))); harmonyTweaks.Patch(GetMethod<Turret>("StartAiming"), postfix: GetHarmonyMethod(GetMethod<TurretAim>("Postfix"))); } harmonyTweaks.Patch(GetMethod<Explosion>("Start"), postfix: GetHarmonyMethod(GetMethod<V2CommonExplosion>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2FirstStart>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2FirstUpdate>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2FirstShootWeapon>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2SecondStart>("Postfix"))); //if(ConfigManager.v2SecondStartEnraged.value) // harmonyTweaks.Patch(GetMethod<BossHealthBar>("OnEnable"), postfix: GetHarmonyMethod(GetMethod<V2SecondEnrage>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2SecondUpdate>("Prefix"))); //harmonyTweaks.Patch(GetMethod<V2>("AltShootWeapon"), postfix: GetHarmonyMethod(GetMethod<V2AltShootWeapon>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("SwitchWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondSwitchWeapon>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Prefix")), postfix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Postfix"))); if(ConfigManager.v2SecondFastCoinToggle.value) harmonyTweaks.Patch(GetMethod<V2>("ThrowCoins"), prefix: GetHarmonyMethod(GetMethod<V2SecondFastCoin>("Prefix"))); harmonyTweaks.Patch(GetMethod<Cannonball>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<V2RocketLauncher>("CannonBallTriggerPrefix"))); if (ConfigManager.v2FirstSharpshooterToggle.value || ConfigManager.v2SecondSharpshooterToggle.value) { harmonyTweaks.Patch(GetMethod<EnemyRevolver>("PrepareAltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverPrepareAltFire>("Prefix"))); harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverBullet>("Prefix"))); harmonyTweaks.Patch(GetMethod<EnemyRevolver>("AltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverAltShoot>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Virtue_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Drone>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Virtue_SpawnInsignia_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Virtue_Death_Patch>("Prefix"))); if (ConfigManager.sisyInstJumpShockwave.value) { harmonyTweaks.Patch(GetMethod<Sisyphus>("Start"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Sisyphus>("Update"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Update>("Postfix"))); } if(ConfigManager.sisyInstBoulderShockwave.value) harmonyTweaks.Patch(GetMethod<Sisyphus>("SetupExplosion"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_SetupExplosion>("Postfix"))); if(ConfigManager.sisyInstStrongerExplosion.value) harmonyTweaks.Patch(GetMethod<Sisyphus>("StompExplosion"), prefix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_StompExplosion>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("Awake"), postfix: GetHarmonyMethod(GetMethod<LeviathanTail_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("BigSplash"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_BigSplash>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_SwingEnd>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("Start"), postfix: GetHarmonyMethod(GetMethod<Leviathan_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurst"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurstStart"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurstStart>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<Leviathan_FixedUpdate>("Prefix"))); if (ConfigManager.somethingWickedSpear.value) { harmonyTweaks.Patch(GetMethod<Wicked>("Start"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_GetHit>("Postfix"))); } if(ConfigManager.somethingWickedSpawnOn43.value) { harmonyTweaks.Patch(GetMethod<ObjectActivator>("Activate"), prefix: GetHarmonyMethod(GetMethod<ObjectActivator_Activate>("Prefix"))); harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<JokeWicked_GetHit>("Postfix"))); } if (ConfigManager.panopticonFullPhase.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Panopticon_Start>("Postfix"))); if (ConfigManager.panopticonAxisBeam.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnInsignia>("Prefix"))); if (ConfigManager.panopticonSpinAttackToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<Panopticon_HomingProjectileAttack>("Postfix"))); if (ConfigManager.panopticonBlackholeProj.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnBlackHole"), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnBlackHole>("Postfix"))); if (ConfigManager.panopticonBalanceEyes.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnFleshDrones"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Postfix"))); if (ConfigManager.panopticonBlueProjToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Update"), transpiler: GetHarmonyMethod(GetMethod<Panopticon_BlueProjectile>("Transpiler"))); if (ConfigManager.idolExplosionToggle.value) harmonyTweaks.Patch(GetMethod<Idol>("Death"), postfix: GetHarmonyMethod(GetMethod<Idol_Death_Patch>("Postfix"))); // ADDME /* harmonyTweaks.Patch(GetMethod<GabrielSecond>("Start"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("BasicCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_BasicCombo>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("FastCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_FastCombo>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("CombineSwords"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_CombineSwords>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("ThrowCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_ThrowCombo>("Postfix"))); */ } private static void PatchAllPlayers() { if (!ConfigManager.playerTweakToggle.value) return; harmonyTweaks.Patch(GetMethod<Punch>("CheckForProjectile"), prefix: GetHarmonyMethod(GetMethod<Punch_CheckForProjectile_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch1>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Collision"), prefix: GetHarmonyMethod(GetMethod<Grenade_Collision_Patch>("Prefix"))); if (ConfigManager.rocketBoostToggle.value) harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_Patch>("Prefix"))); if (ConfigManager.rocketGrabbingToggle.value) harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate_Patch>("Prefix"))); if (ConfigManager.orbStrikeToggle.value) { harmonyTweaks.Patch(GetMethod<Coin>("Start"), postfix: GetHarmonyMethod(GetMethod<Coin_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Punch>("BlastCheck"), prefix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Postfix"))); harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide>("Prefix"))); harmonyTweaks.Patch(GetMethod<Coin>("DelayedReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_DelayedReflectRevolver>("Postfix"))); harmonyTweaks.Patch(GetMethod<Coin>("ReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Postfix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Prefix")), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Postfix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("ExecuteHits"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Prefix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("HitSomething"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Prefix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("Start"), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_Start>("Prefix"))); harmonyTweaks.Patch(GetMethod<Cannonball>("Explode"), prefix: GetHarmonyMethod(GetMethod<Cannonball_Explode>("Prefix"))); harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_CollideOrbital>("Prefix"))); } if(ConfigManager.chargedRevRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<Revolver>("Update"), prefix: GetHarmonyMethod(GetMethod<Revolver_Update>("Prefix"))); if(ConfigManager.coinRegSpeedMulti.value != 1 || ConfigManager.sharpshooterRegSpeedMulti.value != 1 || ConfigManager.railcannonRegSpeedMulti.value != 1 || ConfigManager.rocketFreezeRegSpeedMulti.value != 1 || ConfigManager.rocketCannonballRegSpeedMulti.value != 1 || ConfigManager.nailgunAmmoRegSpeedMulti.value != 1 || ConfigManager.sawAmmoRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<WeaponCharges>("Charge"), prefix: GetHarmonyMethod(GetMethod<WeaponCharges_Charge>("Prefix"))); if(ConfigManager.nailgunHeatsinkRegSpeedMulti.value != 1 || ConfigManager.sawHeatsinkRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<Nailgun>("Update"), prefix: GetHarmonyMethod(GetMethod<NailGun_Update>("Prefix"))); if(ConfigManager.staminaRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<NewMovement>("Update"), prefix: GetHarmonyMethod(GetMethod<NewMovement_Update>("Prefix"))); if(ConfigManager.playerHpDeltaToggle.value || ConfigManager.maxPlayerHp.value != 100 || ConfigManager.playerHpSupercharge.value != 200 || ConfigManager.whiplashHardDamageCap.value != 50 || ConfigManager.whiplashHardDamageSpeed.value != 1) { harmonyTweaks.Patch(GetMethod<NewMovement>("GetHealth"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHealth>("Prefix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("SuperCharge"), prefix: GetHarmonyMethod(GetMethod<NewMovement_SuperCharge>("Prefix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("Respawn"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Respawn>("Postfix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("Start"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Transpiler"))); harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), transpiler: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate>("Transpiler"))); harmonyTweaks.Patch(GetMethod<NewMovement>("ForceAntiHP"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_ForceAntiHP>("Transpiler"))); } // ADDME harmonyTweaks.Patch(GetMethod<Revolver>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Revolver_Shoot>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Shotgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Transpiler")), prefix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Postfix"))); harmonyTweaks.Patch(GetMethod<Shotgun>("ShootSinks"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_ShootSinks>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Nailgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_Shoot>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Nailgun>("SuperSaw"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_SuperSaw>("Transpiler"))); if (ConfigManager.hardDamagePercent.normalizedValue != 1) harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Prefix")), postfix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Postfix"))); harmonyTweaks.Patch(GetMethod<HealthBar>("Start"), postfix: GetHarmonyMethod(GetMethod<HealthBar_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<HealthBar>("Update"), transpiler: GetHarmonyMethod(GetMethod<HealthBar_Update>("Transpiler"))); foreach (HealthBarTracker hb in HealthBarTracker.instances) { if (hb != null) hb.SetSliderRange(); } harmonyTweaks.Patch(GetMethod<Harpoon>("Start"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Start>("Postfix"))); if(ConfigManager.screwDriverHomeToggle.value) harmonyTweaks.Patch(GetMethod<Harpoon>("Punched"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Punched>("Postfix"))); if(ConfigManager.screwDriverSplitToggle.value) harmonyTweaks.Patch(GetMethod<Harpoon>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<Harpoon_OnTriggerEnter_Patch>("Prefix"))); } private static void PatchAllMemes() { if (ConfigManager.enrageSfxToggle.value) harmonyTweaks.Patch(GetMethod<EnrageEffect>("Start"), postfix: GetHarmonyMethod(GetMethod<EnrageEffect_Start>("Postfix"))); if(ConfigManager.funnyDruidKnightSFXToggle.value) { harmonyTweaks.Patch(GetMethod<Mandalore>("FullBurst"), postfix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Postfix")), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<Mandalore>("FullerBurst"), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullerBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Explode"), prefix: GetHarmonyMethod(GetMethod<Drone_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Drone_Explode>("Postfix"))); } if (ConfigManager.fleshObamiumToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Prefix"))); if (ConfigManager.obamapticonToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Prefix"))); } public static bool methodsPatched = false; public static void ScenePatchCheck() { if(methodsPatched && !ultrapainDifficulty) { harmonyTweaks.UnpatchSelf(); methodsPatched = false; } else if(!methodsPatched && ultrapainDifficulty) { PatchAll(); } } public static void PatchAll() { harmonyTweaks.UnpatchSelf(); methodsPatched = false; if (!ultrapainDifficulty) return; if(realUltrapainDifficulty && ConfigManager.discordRichPresenceToggle.value) harmonyTweaks.Patch(GetMethod<DiscordController>("SendActivity"), prefix: GetHarmonyMethod(GetMethod<DiscordController_SendActivity_Patch>("Prefix"))); if (realUltrapainDifficulty && ConfigManager.steamRichPresenceToggle.value) harmonyTweaks.Patch(GetMethod<SteamFriends>("SetRichPresence"), prefix: GetHarmonyMethod(GetMethod<SteamFriends_SetRichPresence_Patch>("Prefix"))); PatchAllEnemies(); PatchAllPlayers(); PatchAllMemes(); methodsPatched = true; } public static string workingPath; public static string workingDir; public static AssetBundle bundle; public static AudioClip druidKnightFullAutoAud; public static AudioClip druidKnightFullerAutoAud; public static AudioClip druidKnightDeathAud; public static AudioClip enrageAudioCustom; public static GameObject fleshObamium; public static GameObject obamapticon; public void Awake() { instance = this; workingPath = Assembly.GetExecutingAssembly().Location; workingDir = Path.GetDirectoryName(workingPath); Logger.LogInfo($"Working path: {workingPath}, Working dir: {workingDir}"); try { bundle = AssetBundle.LoadFromFile(Path.Combine(workingDir, "ultrapain")); druidKnightFullAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullauto.wav"); druidKnightFullerAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullerauto.wav"); druidKnightDeathAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/death.wav"); enrageAudioCustom = bundle.LoadAsset<AudioClip>("assets/ultrapain/sfx/enraged.wav"); fleshObamium = bundle.LoadAsset<GameObject>("assets/ultrapain/fleshprison/fleshobamium.prefab"); obamapticon = bundle.LoadAsset<GameObject>("assets/ultrapain/panopticon/obamapticon.prefab"); } catch (Exception e) { Logger.LogError($"Could not load the asset bundle:\n{e}"); } // DEBUG /*string logPath = Path.Combine(Environment.CurrentDirectory, "log.txt"); Logger.LogInfo($"Saving to {logPath}"); List<string> assetPaths = new List<string>() { "fonts.bundle", "videos.bundle", "shaders.bundle", "particles.bundle", "materials.bundle", "animations.bundle", "prefabs.bundle", "physicsmaterials.bundle", "models.bundle", "textures.bundle", }; //using (FileStream log = File.Open(logPath, FileMode.OpenOrCreate, FileAccess.Write)) //{ foreach(string assetPath in assetPaths) { Logger.LogInfo($"Attempting to load {assetPath}"); AssetBundle bundle = AssetBundle.LoadFromFile(Path.Combine(bundlePath, assetPath)); bundles.Add(bundle); //foreach (string name in bundle.GetAllAssetNames()) //{ // string line = $"[{bundle.name}][{name}]\n"; // log.Write(Encoding.ASCII.GetBytes(line), 0, line.Length); //} bundle.LoadAllAssets(); } //} */ // Plugin startup logic Logger.LogInfo($"Plugin {PluginInfo.PLUGIN_GUID} is loaded!"); harmonyTweaks = new Harmony(PLUGIN_GUID + "_tweaks"); harmonyBase = new Harmony(PLUGIN_GUID + "_base"); harmonyBase.Patch(GetMethod<DifficultySelectButton>("SetDifficulty"), postfix: GetHarmonyMethod(GetMethod<DifficultySelectPatch>("Postfix"))); harmonyBase.Patch(GetMethod<DifficultyTitle>("Check"), postfix: GetHarmonyMethod(GetMethod<DifficultyTitle_Check_Patch>("Postfix"))); harmonyBase.Patch(typeof(PrefsManager).GetConstructor(new Type[0]), postfix: GetHarmonyMethod(GetMethod<PrefsManager_Ctor>("Postfix"))); harmonyBase.Patch(GetMethod<PrefsManager>("EnsureValid"), prefix: GetHarmonyMethod(GetMethod<PrefsManager_EnsureValid>("Prefix"))); harmonyBase.Patch(GetMethod<Grenade>("Explode"), prefix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Prefix")), postfix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Postfix"))); LoadPrefabs(); ConfigManager.Initialize(); SceneManager.activeSceneChanged += OnSceneChange; } } public static class Tools { private static Transform _target; private static Transform target { get { if(_target == null) _target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); return _target; } } public static Vector3 PredictPlayerPosition(float speedMod, Collider enemyCol = null) { Vector3 projectedPlayerPos; if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f) { return target.position; } RaycastHit raycastHit; if (enemyCol != null && Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == enemyCol) { projectedPlayerPos = target.position; } else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide)) { projectedPlayerPos = raycastHit.point; } else { projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod; projectedPlayerPos = new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z); } return projectedPlayerPos; } } // Asset destroyer tracker /*[HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object) })] public class TempClass1 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object), typeof(float) })] public class TempClass2 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object) })] public class TempClass3 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object), typeof(bool) })] public class TempClass4 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } }*/ }
Ultrapain/Plugin.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static FloatField shotgunGreenExplosionSpeed;\n public static IntField shotgunGreenExplosionDamage;\n public static IntField shotgunGreenExplosionPlayerDamage;\n // NAILGUN/SAW LAUNCHER\n public static FloatField nailgunBlueDamage;\n public static FloatField nailgunGreenDamage;\n public static FloatField nailgunGreenBurningDamage;\n public static FloatField sawBlueDamage;\n public static FloatField sawBlueHitAmount;\n public static FloatField sawGreenDamage;", "score": 0.8398792147636414 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static ConfigPanel streetCleanerPanel;\n public static ConfigPanel swordsMachinePanel;\n public static ConfigPanel virtuePanel;\n public static ConfigPanel ferrymanPanel;\n public static ConfigPanel turretPanel;\n public static ConfigPanel fleshPrisonPanel;\n public static ConfigPanel minosPrimePanel;\n public static ConfigPanel v2FirstPanel;\n public static ConfigPanel v2SecondPanel;\n public static ConfigPanel sisyInstPanel;", "score": 0.8386452794075012 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static ConfigPanel leviathanPanel;\n public static ConfigPanel somethingWickedPanel;\n public static ConfigPanel panopticonPanel;\n public static ConfigPanel idolPanel;\n // GLOBAL ENEMY CONFIG\n public static BoolField friendlyFireDamageOverrideToggle;\n public static FloatSliderField friendlyFireDamageOverrideExplosion;\n public static FloatSliderField friendlyFireDamageOverrideProjectile;\n public static FloatSliderField friendlyFireDamageOverrideFire;\n public static FloatSliderField friendlyFireDamageOverrideMelee;", "score": 0.8362439274787903 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static ConfigPanel cerberusPanel;\n public static ConfigPanel dronePanel;\n public static ConfigPanel filthPanel;\n public static ConfigPanel hideousMassPanel;\n public static ConfigPanel maliciousFacePanel;\n public static ConfigPanel mindflayerPanel;\n public static ConfigPanel schismPanel;\n public static ConfigPanel soliderPanel;\n public static ConfigPanel stalkerPanel;\n public static ConfigPanel strayPanel;", "score": 0.8350788354873657 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static IntField cerberusTotalDashCount;\n public static BoolField cerberusParryable;\n public static FloatField cerberusParryableDuration;\n public static IntField cerberusParryDamage;\n // DRONE\n public static BoolField droneProjectileToggle;\n public static FloatField droneProjectileDelay;\n public static FloatSliderField droneProjectileChance;\n public static BoolField droneExplosionBeamToggle;\n public static FloatField droneExplosionBeamDelay;", "score": 0.8266670107841492 } ]
csharp
GameObject rocketLauncherAlt;
using NowPlaying.Utils; using System.Collections.Generic; using System.Threading; namespace NowPlaying.Models { public class GameCacheJob { public readonly GameCacheEntry entry; public readonly RoboStats stats; public readonly CancellationTokenSource tokenSource; public readonly CancellationToken token; public
PartialFileResumeOpts pfrOpts;
public long? partialFileResumeThresh; public int interPacketGap; public bool cancelledOnDiskFull; public bool cancelledOnMaxFill; public bool cancelledOnError; public List<string> errorLog; public GameCacheJob(GameCacheEntry entry, RoboStats stats=null, int interPacketGap = 0, PartialFileResumeOpts pfrOpts = null) { this.entry = entry; this.tokenSource = new CancellationTokenSource(); this.token = tokenSource.Token; this.stats = stats; this.pfrOpts = pfrOpts; this.interPacketGap = interPacketGap; this.cancelledOnDiskFull = false; this.cancelledOnMaxFill = false; this.cancelledOnError = false; this.errorLog = null; bool partialFileResume = pfrOpts?.Mode == EnDisThresh.Enabled || pfrOpts?.Mode == EnDisThresh.Threshold && pfrOpts?.FileSizeThreshold <= 0; stats?.Reset(entry.InstallFiles, entry.InstallSize, partialFileResume); } public override string ToString() { return $"{entry} {stats} Ipg:{interPacketGap} PfrOpts:[{pfrOpts}] OnDiskFull:{cancelledOnDiskFull} OnError:{cancelledOnError} ErrorLog:{errorLog}"; } } }
source/Models/GameCacheJob.cs
gittromney-Playnite-NowPlaying-23eec41
[ { "filename": "source/Models/RoboStats.cs", "retrieved_chunk": "using NowPlaying.Utils;\nusing System;\nnamespace NowPlaying.Models\n{\n public class RoboStats\n {\n // Overall Job stats\n public DateTime StartTime { get; private set; }\n public long FilesToCopy { get; private set; }\n public long BytesToCopy { get; private set; }", "score": 0.8919088244438171 }, { "filename": "source/NowPlayingGameEnabler.cs", "retrieved_chunk": "{\n public class NowPlayingGameEnabler\n {\n private readonly ILogger logger = NowPlaying.logger;\n private readonly NowPlaying plugin;\n private readonly IPlayniteAPI PlayniteApi;\n private readonly GameCacheManagerViewModel cacheManager;\n private readonly Game game;\n private readonly string cacheRootDir;\n public string Id => game.Id.ToString();", "score": 0.8814903497695923 }, { "filename": "source/ViewModels/GameCacheManagerViewModel.cs", "retrieved_chunk": "using static NowPlaying.Models.GameCacheManager;\nusing Playnite.SDK;\nnamespace NowPlaying.ViewModels\n{\n public class GameCacheManagerViewModel : ViewModelBase\n {\n public readonly NowPlaying plugin;\n public readonly ILogger logger;\n private readonly string pluginUserDataPath;\n private readonly string cacheRootsJsonPath;", "score": 0.8754842281341553 }, { "filename": "source/ViewModels/AddCacheRootViewModel.cs", "retrieved_chunk": "{\n public class AddCacheRootViewModel : ViewModelBase\n {\n private readonly NowPlaying plugin;\n private readonly GameCacheManagerViewModel cacheManager;\n private Dictionary<string, string> rootDevices;\n private List<string> existingRoots;\n public Window popup { get; set; }\n public bool DeviceIsValid { get; private set; }\n public bool RootIsValid { get; private set; }", "score": 0.8671437501907349 }, { "filename": "source/NowPlaying.cs", "retrieved_chunk": " {\n return false;\n }\n }\n public class SelectedGamesContext\n {\n private readonly NowPlaying plugin;\n public bool allEligible;\n public bool allEnabled;\n public bool allEnabledAndEmpty;", "score": 0.8637839555740356 } ]
csharp
PartialFileResumeOpts pfrOpts;
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Canvas.CLI.Models { public class Course { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public List<
Student> Roster {
get; set; } } }
Canvas.Library/Models/Course.cs
crmillsfsu-Canvas_Su2023-bcfeccd
[ { "filename": "Canvas.Library/Models/Student.cs", "retrieved_chunk": " public string Name { get; set; }\n public Student()\n {\n Name = string.Empty;\n }\n public override string ToString()\n {\n return $\"{Id}. {Name}\";\n }\n }", "score": 0.8815901279449463 }, { "filename": "Canvas.MAUI/App.xaml.cs", "retrieved_chunk": "namespace Canvas.MAUI\n{\n public partial class App : Application\n {\n public App()\n {\n InitializeComponent();\n MainPage = new AppShell();\n }\n }", "score": 0.8492717146873474 }, { "filename": "Canvas.MAUI/AppShell.xaml.cs", "retrieved_chunk": "namespace Canvas.MAUI\n{\n public partial class AppShell : Shell\n {\n public AppShell()\n {\n InitializeComponent();\n }\n }\n}", "score": 0.840695858001709 }, { "filename": "Canvas.MAUI/ViewModels/MainViewModel.cs", "retrieved_chunk": " }\n return new ObservableCollection<Student>(StudentService.Current.Search(Query));\n }\n }\n public string Query { get; set; }\n public void Search() {\n NotifyPropertyChanged(\"Students\");\n }\n public void Delete()\n {", "score": 0.822361409664154 }, { "filename": "Canvas.MAUI/Platforms/iOS/Program.cs", "retrieved_chunk": "using ObjCRuntime;\nusing UIKit;\nnamespace Canvas.MAUI\n{\n public class Program\n {\n // This is the main entry point of the application.\n static void Main(string[] args)\n {\n // if you want to use a different Application Delegate class from \"AppDelegate\"", "score": 0.8171728849411011 } ]
csharp
Student> Roster {
using System.Net; using LibreDteDotNet.Common; using LibreDteDotNet.RestRequest.Infraestructure; using LibreDteDotNet.RestRequest.Interfaces; using Microsoft.Extensions.Configuration; namespace LibreDteDotNet.RestRequest.Services { internal class ContribuyenteService : ComunEnum, IContribuyente { private readonly IRepositoryWeb repositoryWeb; public string Rut { get; } public ContribuyenteService(IRepositoryWeb repositoryWeb, IConfiguration configuration) { this.repositoryWeb = repositoryWeb; Rut = configuration.GetSection("Rut").Value!; } public async Task<string> GetInfo(string rutEmp, string dvEmp, string token) { if (HttpStatCode != HttpStatusCode.OK) { throw new Exception("Debe conectarse primero."); } using HttpResponseMessage? msg = await repositoryWeb.Send( new HttpRequestMessage(HttpMethod.Post, Properties.Resources.UrlConsultaRut) { Content = new FormUrlEncodedContent( new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("RUT_EMP", rutEmp), new KeyValuePair<string, string>("DV_EMP", dvEmp) } ) } )!; return await msg.Content.ReadAsStringAsync(); } public async Task<
IContribuyente> SetCookieCertificado() {
HttpStatCode = await repositoryWeb.Conectar(Properties.Resources.UrlConsultaRut); return this; } } }
LibreDteDotNet.RestRequest/Services/ContribuyenteService.cs
sergiokml-LibreDteDotNet.RestRequest-6843109
[ { "filename": "LibreDteDotNet.RestRequest/Services/BoletaService.cs", "retrieved_chunk": " new KeyValuePair<string, string>(\"AREA\", \"P\")\n }\n )\n }\n )!;\n return await msg.Content.ReadAsStringAsync();\n }\n public async Task<IBoleta> SetCookieCertificado()\n {\n HttpStatCode = await repositoryWeb.Conectar(Properties.Resources.UrlBasePalena);", "score": 0.9188231825828552 }, { "filename": "LibreDteDotNet.RestRequest/Services/FolioCafService.cs", "retrieved_chunk": " $\"{InputsText.GetValueOrDefault(\"FECHA\")!}\"\n )\n }\n )\n }\n )!;\n using StreamReader reader = new(await msg.Content.ReadAsStreamAsync());\n return XDocument.Load(reader);\n }\n public async Task<IFolioCaf> SetCookieCertificado()", "score": 0.892553448677063 }, { "filename": "LibreDteDotNet.RestRequest/Services/FolioCafService.cs", "retrieved_chunk": " \"COD_DOCTO\",\n ((int)tipodoc).ToString()\n ),\n }\n )\n }\n )!;\n return await msg.Content.ReadAsStringAsync();\n }\n public async Task<IFolioCaf> ReObtener(", "score": 0.8748793601989746 }, { "filename": "LibreDteDotNet.RestRequest/Services/DTEService.cs", "retrieved_chunk": " HttpMethod.Get,\n $\"{Properties.Resources.UrlEstadoDte}?{query}\"\n )\n )!;\n Dispose();\n return await msg.Content.ReadAsStringAsync();\n }\n public async Task<IDTE> SetCookieCertificado(string url)\n {\n HttpStatCode = await repositoryWeb.Conectar(url);", "score": 0.8733277320861816 }, { "filename": "LibreDteDotNet.RestRequest/Services/FolioCafService.cs", "retrieved_chunk": " )\n }\n )!;\n InputsText = await HtmlParse.GetValuesFromTag(input, msg, CancellationToken.None);\n return this;\n }\n public async Task<IFolioCaf> Obtener(\n string rut,\n string dv,\n string cant,", "score": 0.8336026668548584 } ]
csharp
IContribuyente> SetCookieCertificado() {
using Magic.IndexedDb.Models; using System; namespace IndexDb.Example.Pages { public partial class Index { private List<Person> allPeople { get; set; } = new List<Person>(); private IEnumerable<
Person> WhereExample {
get; set; } = Enumerable.Empty<Person>(); private double storageQuota { get; set; } private double storageUsage { get; set; } protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { try { var manager = await _MagicDb.GetDbManager(DbNames.Client); await manager.ClearTable<Person>(); var AllThePeeps = await manager.GetAll<Person>(); if (AllThePeeps.Count() < 1) { Person[] persons = new Person[] { new Person { Name = "Zack", TestInt = 9, _Age = 45, GUIY = Guid.NewGuid(), Secret = "I buried treasure behind my house"}, new Person { Name = "Luna", TestInt = 9, _Age = 35, GUIY = Guid.NewGuid(), Secret = "Jerry is my husband and I had an affair with Bob."}, new Person { Name = "Jerry", TestInt = 9, _Age = 35, GUIY = Guid.NewGuid(), Secret = "My wife is amazing"}, new Person { Name = "Jon", TestInt = 9, _Age = 37, GUIY = Guid.NewGuid(), Secret = "I black mail Luna for money because I know her secret"}, new Person { Name = "Jack", TestInt = 9, _Age = 37, GUIY = Guid.NewGuid(), Secret = "I have a drug problem"}, new Person { Name = "Cathy", TestInt = 9, _Age = 22, GUIY = Guid.NewGuid(), Secret = "I got away with reading Bobs diary."}, new Person { Name = "Bob", TestInt = 3 , _Age = 69, GUIY = Guid.NewGuid(), Secret = "I caught Cathy reading my diary, but I'm too shy to confront her." }, new Person { Name = "Alex", TestInt = 3 , _Age = 80, GUIY = Guid.NewGuid(), Secret = "I'm naked! But nobody can know!" } }; await manager.AddRange(persons); } //var StorageLimit = await manager.GetStorageEstimateAsync(); var storageInfo = await manager.GetStorageEstimateAsync(); storageQuota = storageInfo.quota; storageUsage = storageInfo.usage; var allPeopleDecrypted = await manager.GetAll<Person>(); foreach (Person person in allPeopleDecrypted) { person.SecretDecrypted = await manager.Decrypt(person.Secret); allPeople.Add(person); } WhereExample = await manager.Where<Person>(x => x.Name.StartsWith("c", StringComparison.OrdinalIgnoreCase) || x.Name.StartsWith("l", StringComparison.OrdinalIgnoreCase) || x.Name.StartsWith("j", StringComparison.OrdinalIgnoreCase) && x._Age > 35 ).OrderBy(x => x._Id).Skip(1).Execute(); /* * Still working on allowing nested */ //// Should return "Zack" //var NestedResult = await manager.Where<Person>(p => (p.Name == "Zack" || p.Name == "Luna") && (p._Age >= 35 && p._Age <= 45)).Execute(); //// should return "Luna", "Jerry" and "Jon" //var NonNestedResult = await manager.Where<Person>(p => p.TestInt == 9 && p._Age >= 35 && p._Age <= 45).Execute(); StateHasChanged(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } } }
IndexDb.Example/Pages/Index.razor.cs
magiccodingman-Magic.IndexedDb-a279d6d
[ { "filename": "IndexDb.Example/Models/Person.cs", "retrieved_chunk": "using Magic.IndexedDb;\nusing Magic.IndexedDb.SchemaAnnotations;\nnamespace IndexDb.Example\n{\n [MagicTable(\"Person\", DbNames.Client)]\n public class Person\n {\n [MagicPrimaryKey(\"id\")]\n public int _Id { get; set; }\n [MagicIndex]", "score": 0.8615589737892151 }, { "filename": "Magic.IndexedDb/Models/DbStore.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Magic.IndexedDb\n{\n public class DbStore\n {\n public string Name { get; set; }", "score": 0.8557486534118652 }, { "filename": "Magic.IndexedDb/Models/StoreSchema.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Magic.IndexedDb\n{\n public class StoreSchema\n {\n public string Name { get; set; }", "score": 0.8517844080924988 }, { "filename": "Magic.IndexedDb/Models/DbMigration.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Magic.IndexedDb\n{\n public class DbMigration\n {\n public string? FromVersion { get; set; }", "score": 0.8416687250137329 }, { "filename": "Magic.IndexedDb/Models/UpdateRecord.cs", "retrieved_chunk": "namespace Magic.IndexedDb\n{\n public class UpdateRecord<T> : StoreRecord<T>\n {\n public object Key { get; set; }\n }\n}", "score": 0.836846113204956 } ]
csharp
Person> WhereExample {
using HarmonyLib; using System.Reflection; using UnityEngine; namespace Ultrapain.Patches { class Mindflayer_Start_Patch { static void Postfix(Mindflayer __instance, ref EnemyIdentifier ___eid) { __instance.gameObject.AddComponent<MindflayerPatch>(); //___eid.SpeedBuff(); } } class Mindflayer_ShootProjectiles_Patch { public static float maxProjDistance = 5; public static float initialProjectileDistance = -1f; public static float distancePerProjShot = 0.2f; static bool Prefix(Mindflayer __instance, ref EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___enraged) { /*for(int i = 0; i < 20; i++) { Quaternion randomRotation = Quaternion.LookRotation(MonoSingleton<PlayerTracker>.Instance.GetTarget().position - __instance.transform.position); randomRotation.eulerAngles += new Vector3(UnityEngine.Random.Range(-15.0f, 15.0f), UnityEngine.Random.Range(-15.0f, 15.0f), UnityEngine.Random.Range(-15.0f, 15.0f)); Projectile componentInChildren = GameObject.Instantiate(Plugin.homingProjectile.gameObject, __instance.transform.position + __instance.transform.forward, randomRotation).GetComponentInChildren<Projectile>(); Vector3 randomPos = __instance.tentacles[UnityEngine.Random.RandomRangeInt(0, __instance.tentacles.Length)].position; if (!Physics.Raycast(__instance.transform.position, randomPos - __instance.transform.position, Vector3.Distance(randomPos, __instance.transform.position), ___environmentMask)) componentInChildren.transform.position = randomPos; componentInChildren.speed = 10f * ___eid.totalSpeedModifier * UnityEngine.Random.Range(0.5f, 1.5f); componentInChildren.turnSpeed *= UnityEngine.Random.Range(0.5f, 1.5f); componentInChildren.target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); componentInChildren.safeEnemyType = EnemyType.Mindflayer; componentInChildren.damage *= ___eid.totalDamageModifier; } __instance.chargeParticle.Stop(false, ParticleSystemStopBehavior.StopEmittingAndClear); __instance.cooldown = (float)UnityEngine.Random.Range(4, 5); return false;*/ MindflayerPatch counter = __instance.GetComponent<MindflayerPatch>(); if (counter == null) return true; if (counter.shotsLeft == 0) { counter.shotsLeft = ConfigManager.mindflayerShootAmount.value; __instance.chargeParticle.Stop(false, ParticleSystemStopBehavior.StopEmittingAndClear); __instance.cooldown = (float)UnityEngine.Random.Range(4, 5); return false; } Quaternion randomRotation = Quaternion.LookRotation(MonoSingleton<PlayerTracker>.Instance.GetTarget().position - __instance.transform.position); randomRotation.eulerAngles += new Vector3(UnityEngine.Random.Range(-10.0f, 10.0f), UnityEngine.Random.Range(-10.0f, 10.0f), UnityEngine.Random.Range(-10.0f, 10.0f)); Projectile componentInChildren = GameObject.Instantiate(Plugin.homingProjectile, __instance.transform.position + __instance.transform.forward, randomRotation).GetComponentInChildren<Projectile>(); Vector3 randomPos = __instance.tentacles[UnityEngine.Random.RandomRangeInt(0, __instance.tentacles.Length)].position; if (!Physics.Raycast(__instance.transform.position, randomPos - __instance.transform.position, Vector3.Distance(randomPos, __instance.transform.position), ___environmentMask)) componentInChildren.transform.position = randomPos; int shotCount = ConfigManager.mindflayerShootAmount.value - counter.shotsLeft; componentInChildren.transform.position += componentInChildren.transform.forward * Mathf.Clamp(initialProjectileDistance + shotCount * distancePerProjShot, 0, maxProjDistance); componentInChildren.speed = ConfigManager.mindflayerShootInitialSpeed.value * ___eid.totalSpeedModifier; componentInChildren.turningSpeedMultiplier = ConfigManager.mindflayerShootTurnSpeed.value; componentInChildren.target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); componentInChildren.safeEnemyType = EnemyType.Mindflayer; componentInChildren.damage *= ___eid.totalDamageModifier; componentInChildren.sourceWeapon = __instance.gameObject; counter.shotsLeft -= 1; __instance.Invoke("ShootProjectiles", ConfigManager.mindflayerShootDelay.value / ___eid.totalSpeedModifier); return false; } } class EnemyIdentifier_DeliverDamage_MF { static bool Prefix(EnemyIdentifier __instance, ref float __3, GameObject __6) { if (__instance.enemyType != EnemyType.Mindflayer) return true; if (__6 == null || __6.GetComponent<Mindflayer>() == null) return true; __3 *= ConfigManager.mindflayerProjectileSelfDamageMultiplier.value / 100f; return true; } } class SwingCheck2_CheckCollision_Patch { static FieldInfo goForward = typeof(Mindflayer).GetField("goForward", BindingFlags.NonPublic | BindingFlags.Instance); static MethodInfo meleeAttack = typeof(Mindflayer).GetMethod("MeleeAttack", BindingFlags.NonPublic | BindingFlags.Instance); static bool Prefix(Collider __0, out int __state) { __state = __0.gameObject.layer; return true; } static void Postfix(
SwingCheck2 __instance, Collider __0, int __state) {
if (__0.tag == "Player") Debug.Log($"Collision with {__0.name} with tag {__0.tag} and layer {__state}"); if (__0.gameObject.tag != "Player" || __state == 15) return; if (__instance.transform.parent == null) return; Debug.Log("Parent check"); Mindflayer mf = __instance.transform.parent.gameObject.GetComponent<Mindflayer>(); if (mf == null) return; //MindflayerPatch patch = mf.gameObject.GetComponent<MindflayerPatch>(); Debug.Log("Attempting melee combo"); __instance.DamageStop(); goForward.SetValue(mf, false); meleeAttack.Invoke(mf, new object[] { }); /*if (patch.swingComboLeft > 0) { patch.swingComboLeft -= 1; __instance.DamageStop(); goForward.SetValue(mf, false); meleeAttack.Invoke(mf, new object[] { }); } else patch.swingComboLeft = 2;*/ } } class Mindflayer_MeleeTeleport_Patch { public static Vector3 deltaPosition = new Vector3(0, -10, 0); static bool Prefix(Mindflayer __instance, ref EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___goingLeft, ref Animator ___anim, ref bool ___enraged) { if (___eid.drillers.Count > 0) return false; Vector3 targetPosition = MonoSingleton<PlayerTracker>.Instance.PredictPlayerPosition(0.9f) + deltaPosition; float distance = Vector3.Distance(__instance.transform.position, targetPosition); Ray targetRay = new Ray(__instance.transform.position, targetPosition - __instance.transform.position); RaycastHit hit; if (Physics.Raycast(targetRay, out hit, distance, ___environmentMask, QueryTriggerInteraction.Ignore)) { targetPosition = targetRay.GetPoint(Mathf.Max(0.0f, hit.distance - 1.0f)); } MonoSingleton<HookArm>.Instance.StopThrow(1f, true); __instance.transform.position = targetPosition; ___goingLeft = !___goingLeft; GameObject.Instantiate<GameObject>(__instance.teleportSound, __instance.transform.position, Quaternion.identity); GameObject gameObject = GameObject.Instantiate<GameObject>(__instance.decoy, __instance.transform.GetChild(0).position, __instance.transform.GetChild(0).rotation); Animator componentInChildren = gameObject.GetComponentInChildren<Animator>(); AnimatorStateInfo currentAnimatorStateInfo = ___anim.GetCurrentAnimatorStateInfo(0); componentInChildren.Play(currentAnimatorStateInfo.shortNameHash, 0, currentAnimatorStateInfo.normalizedTime); componentInChildren.speed = 0f; if (___enraged) { gameObject.GetComponent<MindflayerDecoy>().enraged = true; } ___anim.speed = 0f; __instance.CancelInvoke("ResetAnimSpeed"); __instance.Invoke("ResetAnimSpeed", 0.25f / ___eid.totalSpeedModifier); return false; } } class SwingCheck2_DamageStop_Patch { static void Postfix(SwingCheck2 __instance) { if (__instance.transform.parent == null) return; GameObject parent = __instance.transform.parent.gameObject; Mindflayer mf = parent.GetComponent<Mindflayer>(); if (mf == null) return; MindflayerPatch patch = parent.GetComponent<MindflayerPatch>(); patch.swingComboLeft = 2; } } class MindflayerPatch : MonoBehaviour { public int shotsLeft = ConfigManager.mindflayerShootAmount.value; public int swingComboLeft = 2; } }
Ultrapain/Patches/Mindflayer.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/V2Second.cs", "retrieved_chunk": " rb.velocity = rb.transform.forward * 150f;\n }\n }\n static MethodInfo bounce = typeof(Cannonball).GetMethod(\"Bounce\", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);\n public static bool CannonBallTriggerPrefix(Cannonball __instance, Collider __0)\n {\n if(__instance.sourceWeapon != null && __instance.sourceWeapon.GetComponent<V2RocketLauncher>() != null)\n {\n if (__0.gameObject.tag == \"Player\")\n {", "score": 0.8439661264419556 }, { "filename": "Ultrapain/Patches/Drone.cs", "retrieved_chunk": " static FieldInfo antennaFlashField = typeof(Turret).GetField(\"antennaFlash\", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);\n static ParticleSystem antennaFlash;\n public static Color defaultLineColor = new Color(1f, 0.44f, 0.74f);\n static bool Prefix(Drone __instance, EnemyIdentifier ___eid, AudioClip __0)\n {\n if (___eid.enemyType != EnemyType.Drone)\n return true;\n if(__0 == __instance.windUpSound)\n {\n DroneFlag flag = __instance.GetComponent<DroneFlag>();", "score": 0.8132708072662354 }, { "filename": "Ultrapain/Patches/Drone.cs", "retrieved_chunk": " public ParticleSystem particleSystem;\n public LineRenderer lr;\n public Firemode currentMode = Firemode.Projectile;\n private static Firemode[] allModes = Enum.GetValues(typeof(Firemode)) as Firemode[];\n static FieldInfo turretAimLine = typeof(Turret).GetField(\"aimLine\", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);\n static Material whiteMat;\n public void Awake()\n {\n lr = gameObject.AddComponent<LineRenderer>();\n lr.enabled = false;", "score": 0.8122164607048035 }, { "filename": "Ultrapain/Patches/V2First.cs", "retrieved_chunk": " }\n }\n class V2FirstShootWeapon\n {\n static MethodInfo RevolverBeamStart = typeof(RevolverBeam).GetMethod(\"Start\", BindingFlags.Instance | BindingFlags.NonPublic);\n static bool Prefix(V2 __instance, ref int ___currentWeapon)\n {\n if (__instance.secondEncounter)\n return true;\n V2FirstFlag flag = __instance.GetComponent<V2FirstFlag>();", "score": 0.8003283143043518 }, { "filename": "Ultrapain/Patches/Leviathan.cs", "retrieved_chunk": " public float beamChargeRate = 12f / 1f;\n public int beamRemaining = 0;\n public int projectilesRemaining = 0;\n public float projectileDelayRemaining = 0f;\n private static FieldInfo ___inAction = typeof(LeviathanHead).GetField(\"inAction\", BindingFlags.NonPublic | BindingFlags.Instance);\n private void Awake()\n {\n comp = GetComponent<LeviathanHead>();\n anim = GetComponent<Animator>();\n //col = GetComponent<Collider>();", "score": 0.7948393821716309 } ]
csharp
SwingCheck2 __instance, Collider __0, int __state) {
// <copyright file="Mod.cs" company="algernon (K. Algernon A. Sheppard)"> // Copyright (c) algernon (K. Algernon A. Sheppard). All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. // </copyright> namespace LineToolMod { using AlgernonCommons; using AlgernonCommons.Patching; using AlgernonCommons.Translation; using ColossalFramework.Plugins; using ICities; /// <summary> /// The base mod class for instantiation by the game. /// </summary> public sealed class Mod : PatcherMod<
OptionsPanel, Patcher>, IUserMod {
/// <summary> /// Gets the mod's base display name (name only). /// </summary> public override string BaseName => "Line Tool"; /// <summary> /// Gets the mod's unique Harmony identfier. /// </summary> public override string HarmonyID => "com.github.algernon-A.csl.linetool"; /// <summary> /// Gets the mod's description for display in the content manager. /// </summary> public string Description => Translations.Translate("MOD_DESCRIPTION"); /// <summary> /// Called by the game when the mod is enabled. /// </summary> public override void OnEnabled() { // Perform conflict detection. ConflictDetection conflictDetection = new ConflictDetection(); if (conflictDetection.CheckModConflicts()) { Logging.Error("aborting activation due to conflicting mods"); // Load mod settings to ensure that correct language is selected for notification display. LoadSettings(); // Disable mod. if (AssemblyUtils.ThisPlugin is PluginManager.PluginInfo plugin) { Logging.KeyMessage("disabling mod"); plugin.isEnabled = false; } // Don't do anything further. return; } base.OnEnabled(); } /// <summary> /// Saves settings file. /// </summary> public override void SaveSettings() => ModSettings.Save(); /// <summary> /// Loads settings file. /// </summary> public override void LoadSettings() { ModSettings.Load(); } } }
Code/Mod.cs
algernon-A-LineTool-f63b447
[ { "filename": "Code/ConflictDetection.cs", "retrieved_chunk": " using AlgernonCommons.Translation;\n using ColossalFramework.Plugins;\n using ColossalFramework.UI;\n /// <summary>\n /// Mod conflict detection.\n /// </summary>\n internal sealed class ConflictDetection\n {\n // List of conflicting mods.\n private List<string> _conflictingModNames;", "score": 0.8862190842628479 }, { "filename": "Code/Loading.cs", "retrieved_chunk": " /// Main loading class: the mod runs from here.\n /// </summary>\n public sealed class Loading : PatcherLoadingBase<OptionsPanel, Patcher>\n {\n /// <summary>\n /// Gets a list of permitted loading modes.\n /// </summary>\n protected override List<AppMode> PermittedModes => new List<AppMode> { AppMode.Game, AppMode.MapEditor, AppMode.AssetEditor, AppMode.ScenarioEditor };\n /// <summary>\n /// Performs any actions upon successful creation of the mod.", "score": 0.8828465342521667 }, { "filename": "Code/Patches/Patcher.cs", "retrieved_chunk": " using HarmonyLib;\n /// <summary>\n /// Class to manage the mod's Harmony patches.\n /// </summary>\n public sealed class Patcher : PatcherBase\n {\n /// <summary>\n /// Applies patches to Find It for prefab selection management.\n /// </summary>\n internal void PatchFindIt()", "score": 0.8816478848457336 }, { "filename": "Code/Tool/LineTool.cs", "retrieved_chunk": " using ColossalFramework;\n using ColossalFramework.Math;\n using ColossalFramework.UI;\n using HarmonyLib;\n using LineToolMod.Modes;\n using UnityEngine;\n using TreeInstance = global::TreeInstance;\n /// <summary>\n /// The line tool itslef.\n /// </summary>", "score": 0.8634103536605835 }, { "filename": "Code/Patches/PanelPatches.cs", "retrieved_chunk": " using HarmonyLib;\n /// <summary>\n /// Harmony patches for prefab selection panels to implement seamless prefab selection when line tool is active.\n /// </summary>\n [HarmonyPatch]\n [System.Diagnostics.CodeAnalysis.SuppressMessage(\"StyleCop.CSharp.NamingRules\", \"SA1313:Parameter names should begin with lower-case letter\", Justification = \"Harmony\")]\n internal static class PanelPatches\n {\n /// <summary>\n /// Determines list of target methods to patch.", "score": 0.8242559432983398 } ]
csharp
OptionsPanel, Patcher>, IUserMod {
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using SQLServerCoverage.Gateway; using SQLServerCoverage.Source; using SQLServerCoverage.Trace; namespace SQLServerCoverage { public class CodeCoverage { private const int MAX_DISPATCH_LATENCY = 1000; private readonly
DatabaseGateway _database;
private readonly string _databaseName; private readonly bool _debugger; private readonly TraceControllerType _traceType; private readonly List<string> _excludeFilter; private readonly bool _logging; private readonly SourceGateway _source; private CoverageResult _result; public const short TIMEOUT_EXPIRED = -2; //From TdsEnums public SQLServerCoverageException Exception { get; private set; } = null; public bool IsStarted { get; private set; } = false; private TraceController _trace; //This is to better support powershell and optional parameters public CodeCoverage(string connectionString, string databaseName) : this(connectionString, databaseName, null, false, false, TraceControllerType.Default) { } public CodeCoverage(string connectionString, string databaseName, string[] excludeFilter) : this(connectionString, databaseName, excludeFilter, false, false, TraceControllerType.Default) { } public CodeCoverage(string connectionString, string databaseName, string[] excludeFilter, bool logging) : this(connectionString, databaseName, excludeFilter, logging, false, TraceControllerType.Default) { } public CodeCoverage(string connectionString, string databaseName, string[] excludeFilter, bool logging, bool debugger) : this(connectionString, databaseName, excludeFilter, logging, debugger, TraceControllerType.Default) { } public CodeCoverage(string connectionString, string databaseName, string[] excludeFilter, bool logging, bool debugger, TraceControllerType traceType) { if (debugger) Debugger.Launch(); _databaseName = databaseName; if (excludeFilter == null) excludeFilter = new string[0]; _excludeFilter = excludeFilter.ToList(); _logging = logging; _debugger = debugger; _traceType = traceType; _database = new DatabaseGateway(connectionString, databaseName); _source = new DatabaseSourceGateway(_database); } public bool Start(int timeOut = 30) { Exception = null; try { _database.TimeOut = timeOut; _trace = new TraceControllerBuilder().GetTraceController(_database, _databaseName, _traceType); _trace.Start(); IsStarted = true; return true; } catch (Exception ex) { Debug("Error starting trace: {0}", ex); Exception = new SQLServerCoverageException("SQL Cover failed to start.", ex); IsStarted = false; return false; } } private List<string> StopInternal() { var events = _trace.ReadTrace(); _trace.Stop(); _trace.Drop(); return events; } public CoverageResult Stop() { if (!IsStarted) throw new SQLServerCoverageException("SQL Cover was not started, or did not start correctly."); IsStarted = false; WaitForTraceMaxLatency(); var results = StopInternal(); GenerateResults(_excludeFilter, results, new List<string>(), "SQLServerCoverage result of running external process"); return _result; } private void Debug(string message, params object[] args) { if (_logging) Console.WriteLine(message, args); } public CoverageResult Cover(string command, int timeOut = 30) { Debug("Starting Code Coverage"); _database.TimeOut = timeOut; if (!Start()) { throw new SQLServerCoverageException("Unable to start the trace - errors are recorded in the debug output"); } Debug("Executing Command: {0}", command); var sqlExceptions = new List<string>(); try { _database.Execute(command, timeOut, true); } catch (System.Data.SqlClient.SqlException e) { if (e.Number == -2) { throw; } sqlExceptions.Add(e.Message); } catch (Exception e) { Console.WriteLine("Exception running command: {0} - error: {1}", command, e.Message); } Debug("Executing Command: {0}...done", command); WaitForTraceMaxLatency(); Debug("Stopping Code Coverage"); try { var rawEvents = StopInternal(); Debug("Getting Code Coverage Result"); GenerateResults(_excludeFilter, rawEvents, sqlExceptions, $"SQLServerCoverage result of running '{command}'"); Debug("Result generated"); } catch (Exception e) { Console.Write(e.StackTrace); throw new SQLServerCoverageException("Exception gathering the results", e); } return _result; } private static void WaitForTraceMaxLatency() { Thread.Sleep(MAX_DISPATCH_LATENCY); } private void GenerateResults(List<string> filter, List<string> xml, List<string> sqlExceptions, string commandDetail) { var batches = _source.GetBatches(filter); _result = new CoverageResult(batches, xml, _databaseName, _database.DataSource, sqlExceptions, commandDetail); } public CoverageResult Results() { return _result; } } }
src/SQLServerCoverageLib/CodeCoverage.cs
sayantandey-SQLServerCoverage-aea57e3
[ { "filename": "src/SQLServerCoverageLib/Trace/TraceControllerBuilder.cs", "retrieved_chunk": "using System;\nusing SQLServerCoverage.Gateway;\nusing SQLServerCoverage.Objects;\nusing SQLServerCoverage.Source;\nnamespace SQLServerCoverage.Trace\n{\n class TraceControllerBuilder\n {\n public TraceController GetTraceController(DatabaseGateway gateway, string databaseName, TraceControllerType type)\n {", "score": 0.8846890330314636 }, { "filename": "src/SQLServerCoverageLib/Trace/TraceController.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing SQLServerCoverage.Gateway;\nnamespace SQLServerCoverage.Trace\n{\n abstract class TraceController\n {\n protected readonly string DatabaseId;\n protected readonly DatabaseGateway Gateway;\n protected string FileName;", "score": 0.8814260959625244 }, { "filename": "src/SQLServerCoverageLib/Trace/SqlTraceController.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Data;\nusing System.IO;\nusing SQLServerCoverage.Gateway;\nnamespace SQLServerCoverage.Trace\n{\n class SqlTraceController : TraceController\n {\n protected const string CreateTrace = @\"CREATE EVENT SESSION [{0}] ON SERVER ", "score": 0.8652874827384949 }, { "filename": "src/SQLServerCoverageLib/Trace/AzureTraceController.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Data;\nusing System.Threading;\nusing SQLServerCoverage.Gateway;\nnamespace SQLServerCoverage.Trace\n{\n internal class AzureTraceController : TraceController\n {\n private const string CreateTrace = @\"CREATE EVENT SESSION [{0}] ON DATABASE ", "score": 0.8631221055984497 }, { "filename": "src/SQLServerCoverageLib/CoverageResult.cs", "retrieved_chunk": "using Palmmedia.ReportGenerator.Core;\nusing ReportGenerator;\nnamespace SQLServerCoverage\n{\n public class CoverageResult : CoverageSummary\n {\n private readonly IEnumerable<Batch> _batches;\n private readonly List<string> _sqlExceptions;\n private readonly string _commandDetail;\n public string DatabaseName { get; }", "score": 0.8512758016586304 } ]
csharp
DatabaseGateway _database;
namespace DotNetDevBadgeWeb.Middleware { public class BadgeIdValidatorMiddleware { private readonly RequestDelegate _next; public BadgeIdValidatorMiddleware(RequestDelegate next) { _next = next; } public async
Task InvokeAsync(HttpContext context) {
if (context.Request.Query.ContainsKey("id")) { string id = context.Request.Query["id"].ToString(); if (id.Length > 20) { context.Response.StatusCode = StatusCodes.Status400BadRequest; await context.Response.WriteAsync("ID must be no longer than 20 characters."); return; } } await _next(context); } } }
src/dotnetdev-badge/dotnetdev-badge.web/Middleware/BadgeIdValidatorMiddleware.cs
chanos-dev-dotnetdev-badge-5740a40
[ { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Common/Palette.cs", "retrieved_chunk": " _ => \"CD7F32\",\n };\n }\n internal class ColorSet\n {\n internal string FontColor { get; private set; }\n internal string BackgroundColor { get; private set; }\n internal ColorSet(string fontColor, string backgroundColor)\n {\n FontColor = fontColor;", "score": 0.7921722531318665 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Interfaces/IBadge.cs", "retrieved_chunk": "using DotNetDevBadgeWeb.Common;\nnamespace DotNetDevBadgeWeb.Interfaces\n{\n public interface IBadge\n {\n Task<string> GetSmallBadge(string id, ETheme theme, CancellationToken token);\n Task<string> GetMediumBadge(string id, ETheme theme, CancellationToken token);\n }\n public interface IBadgeV1 : IBadge\n {", "score": 0.7770118713378906 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Core/Provider/ForumDataProvider.cs", "retrieved_chunk": " using HttpResponseMessage response = await client.GetAsync(uri, token);\n return await response.Content.ReadAsStringAsync(token);\n }\n private async Task<byte[]> GetResponseBytesAsync(Uri uri, CancellationToken token)\n {\n using HttpClient client = _httpClientFactory.CreateClient();\n using HttpResponseMessage response = await client.GetAsync(uri, token);\n return await response.Content.ReadAsByteArrayAsync(token);\n }\n public async Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token)", "score": 0.7625300884246826 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Model/User.cs", "retrieved_chunk": " public bool? Admin { get; set; }\n [JsonProperty(\"moderator\")]\n public bool? Moderator { get; set; }\n public ELevel Level => TrustLevel switch\n {\n 3 => ELevel.Silver,\n 4 => ELevel.Gold,\n _ => ELevel.Bronze,\n };\n public string AvatarEndPoint => AvatarTemplate?.Replace(\"{size}\", AVATAR_SIZE.ToString()) ?? string.Empty;", "score": 0.7466549277305603 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Common/Palette.cs", "retrieved_chunk": "namespace DotNetDevBadgeWeb.Common\n{\n internal static class Palette\n {\n private static readonly Dictionary<ETheme, ColorSet> _colorSets;\n static Palette()\n {\n _colorSets = new()\n {\n { ETheme.Light, new ColorSet(\"222222\", \"FFFFFF\") },", "score": 0.745194673538208 } ]
csharp
Task InvokeAsync(HttpContext context) {
// Licensed under the MIT License. See LICENSE in the project root for license information. using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; using UnityEngine; using UnityEngine.Scripting; using Utilities.WebRequestRest; namespace BlockadeLabs.Skyboxes { public sealed class SkyboxEndpoint : BlockadeLabsBaseEndpoint { [Preserve] private class SkyboxInfoRequest { [Preserve] [JsonConstructor] public SkyboxInfoRequest([JsonProperty("request")] SkyboxInfo skyboxInfo) { SkyboxInfo = skyboxInfo; } [Preserve] [JsonProperty("request")] public SkyboxInfo SkyboxInfo { get; } } [Preserve] private class SkyboxOperation { [Preserve] [JsonConstructor] public SkyboxOperation( [JsonProperty("success")] string success, [JsonProperty("error")] string error) { Success = success; Error = error; } [Preserve] [JsonProperty("success")] public string Success { get; } [Preserve] [JsonProperty("Error")] public string Error { get; } } public SkyboxEndpoint(BlockadeLabsClient client) : base(client) { } protected override string Root => string.Empty; /// <summary> /// Returns the list of predefined styles that can influence the overall aesthetic of your skybox generation. /// </summary> /// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param> /// <returns>A list of <see cref="SkyboxStyle"/>s.</returns> public async Task<IReadOnlyList<SkyboxStyle>> GetSkyboxStylesAsync(CancellationToken cancellationToken = default) { var response = await Rest.GetAsync(GetUrl("skybox/styles"), parameters: new RestParameters(client.DefaultRequestHeaders), cancellationToken); response.Validate(); return JsonConvert.DeserializeObject<IReadOnlyList<SkyboxStyle>>(response.Body, client.JsonSerializationOptions); } /// <summary> /// Generate a skybox image. /// </summary> /// <param name="skyboxRequest"><see cref="SkyboxRequest"/>.</param> /// <param name="pollingInterval">Optional, polling interval in seconds.</param> /// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param> /// <returns><see cref="SkyboxInfo"/>.</returns> public async Task<
SkyboxInfo> GenerateSkyboxAsync(SkyboxRequest skyboxRequest, int? pollingInterval = null, CancellationToken cancellationToken = default) {
var formData = new WWWForm(); formData.AddField("prompt", skyboxRequest.Prompt); if (!string.IsNullOrWhiteSpace(skyboxRequest.NegativeText)) { formData.AddField("negative_text", skyboxRequest.NegativeText); } if (skyboxRequest.Seed.HasValue) { formData.AddField("seed", skyboxRequest.Seed.Value); } if (skyboxRequest.SkyboxStyleId.HasValue) { formData.AddField("skybox_style_id", skyboxRequest.SkyboxStyleId.Value); } if (skyboxRequest.RemixImagineId.HasValue) { formData.AddField("remix_imagine_id", skyboxRequest.RemixImagineId.Value); } if (skyboxRequest.Depth) { formData.AddField("return_depth", skyboxRequest.Depth.ToString()); } if (skyboxRequest.ControlImage != null) { if (!string.IsNullOrWhiteSpace(skyboxRequest.ControlModel)) { formData.AddField("control_model", skyboxRequest.ControlModel); } using var imageData = new MemoryStream(); await skyboxRequest.ControlImage.CopyToAsync(imageData, cancellationToken); formData.AddBinaryData("control_image", imageData.ToArray(), skyboxRequest.ControlImageFileName); skyboxRequest.Dispose(); } var response = await Rest.PostAsync(GetUrl("skybox"), formData, parameters: new RestParameters(client.DefaultRequestHeaders), cancellationToken); response.Validate(); var skyboxInfo = JsonConvert.DeserializeObject<SkyboxInfo>(response.Body, client.JsonSerializationOptions); while (!cancellationToken.IsCancellationRequested) { await Task.Delay(pollingInterval ?? 3 * 1000, CancellationToken.None) .ConfigureAwait(true); // Configure await to make sure we're still in Unity context skyboxInfo = await GetSkyboxInfoAsync(skyboxInfo, CancellationToken.None); if (skyboxInfo.Status is Status.Pending or Status.Processing or Status.Dispatched) { continue; } break; } if (cancellationToken.IsCancellationRequested) { var cancelResult = await CancelSkyboxGenerationAsync(skyboxInfo, CancellationToken.None); if (!cancelResult) { throw new Exception($"Failed to cancel generation for {skyboxInfo.Id}"); } } cancellationToken.ThrowIfCancellationRequested(); if (skyboxInfo.Status != Status.Complete) { throw new Exception($"Failed to generate skybox! {skyboxInfo.Id} -> {skyboxInfo.Status}\nError: {skyboxInfo.ErrorMessage}\n{skyboxInfo}"); } await skyboxInfo.LoadTexturesAsync(cancellationToken); return skyboxInfo; } /// <summary> /// Returns the skybox metadata for the given skybox id. /// </summary> /// <param name="id">Skybox Id.</param> /// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param> /// <returns><see cref="SkyboxInfo"/>.</returns> public async Task<SkyboxInfo> GetSkyboxInfoAsync(int id, CancellationToken cancellationToken = default) { var response = await Rest.GetAsync(GetUrl($"imagine/requests/{id}"), parameters: new RestParameters(client.DefaultRequestHeaders), cancellationToken); response.Validate(); return JsonConvert.DeserializeObject<SkyboxInfoRequest>(response.Body, client.JsonSerializationOptions).SkyboxInfo; } /// <summary> /// Deletes a skybox by id. /// </summary> /// <param name="id">The id of the skybox.</param> /// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param> /// <returns>True, if skybox was successfully deleted.</returns> public async Task<bool> DeleteSkyboxAsync(int id, CancellationToken cancellationToken = default) { var response = await Rest.DeleteAsync(GetUrl($"imagine/deleteImagine/{id}"), new RestParameters(client.DefaultRequestHeaders), cancellationToken); response.Validate(); var skyboxOp = JsonConvert.DeserializeObject<SkyboxOperation>(response.Body, client.JsonSerializationOptions); const string successStatus = "Item deleted successfully"; if (skyboxOp is not { Success: successStatus }) { throw new Exception($"Failed to cancel generation for skybox {id}!\n{skyboxOp?.Error}"); } return skyboxOp.Success.Equals(successStatus); } /// <summary> /// Gets the previously generated skyboxes. /// </summary> /// <param name="parameters">Optional, <see cref="SkyboxHistoryParameters"/>.</param> /// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param> /// <returns><see cref="SkyboxHistory"/>.</returns> public async Task<SkyboxHistory> GetSkyboxHistoryAsync(SkyboxHistoryParameters parameters = null, CancellationToken cancellationToken = default) { var historyRequest = parameters ?? new SkyboxHistoryParameters(); var response = await Rest.GetAsync(GetUrl($"imagine/myRequests{historyRequest}"), parameters: new RestParameters(client.DefaultRequestHeaders), cancellationToken); response.Validate(); return JsonConvert.DeserializeObject<SkyboxHistory>(response.Body, client.JsonSerializationOptions); } /// <summary> /// Cancels a pending skybox generation request by id. /// </summary> /// <param name="id">The id of the skybox.</param> /// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param> /// <returns>True, if generation was cancelled.</returns> public async Task<bool> CancelSkyboxGenerationAsync(int id, CancellationToken cancellationToken = default) { var response = await Rest.DeleteAsync(GetUrl($"imagine/requests/{id}"), new RestParameters(client.DefaultRequestHeaders), cancellationToken); response.Validate(); var skyboxOp = JsonConvert.DeserializeObject<SkyboxOperation>(response.Body, client.JsonSerializationOptions); if (skyboxOp is not { Success: "true" }) { throw new Exception($"Failed to cancel generation for skybox {id}!\n{skyboxOp?.Error}"); } return skyboxOp.Success.Equals("true"); } /// <summary> /// Cancels ALL pending skybox generation requests. /// </summary> /// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param> public async Task<bool> CancelAllPendingSkyboxGenerationsAsync(CancellationToken cancellationToken = default) { var response = await Rest.DeleteAsync(GetUrl("imagine/requests/pending"), new RestParameters(client.DefaultRequestHeaders), cancellationToken); response.Validate(); var skyboxOp = JsonConvert.DeserializeObject<SkyboxOperation>(response.Body, client.JsonSerializationOptions); if (skyboxOp is not { Success: "true" }) { if (skyboxOp != null && skyboxOp.Error.Contains("You don't have any pending")) { return false; } throw new Exception($"Failed to cancel all pending skybox generations!\n{skyboxOp?.Error}"); } return skyboxOp.Success.Equals("true"); } } }
BlockadeLabs/Packages/com.rest.blockadelabs/Runtime/Skyboxes/SkyboxEndpoint.cs
RageAgainstThePixel-com.rest.blockadelabs-aa2142f
[ { "filename": "BlockadeLabs/Packages/com.rest.blockadelabs/Runtime/Skyboxes/SkyboxInfo.cs", "retrieved_chunk": " [JsonProperty(\"error_message\")]\n public string ErrorMessage { get; set; }\n public override string ToString() => JsonConvert.SerializeObject(this, Formatting.Indented);\n public static implicit operator int(SkyboxInfo skyboxInfo) => skyboxInfo.Id;\n /// <summary>\n /// Loads the textures for this skybox.\n /// </summary>\n /// <param name=\"cancellationToken\">Optional, <see cref=\"CancellationToken\"/>.</param>\n public async Task LoadTexturesAsync(CancellationToken cancellationToken = default)\n {", "score": 0.7756078243255615 }, { "filename": "BlockadeLabs/Packages/com.rest.blockadelabs/Runtime/BlockadeLabsAuthentication.cs", "retrieved_chunk": " /// </summary>\n /// <param name=\"apiKey\">The API key, required to access the API endpoint.</param>\n public BlockadeLabsAuthentication(string apiKey) => Info = new BlockadeLabsAuthInfo(apiKey);\n /// <summary>\n /// Instantiates a new Authentication object with the given <paramref name=\"authInfo\"/>, which may be <see langword=\"null\"/>.\n /// </summary>\n /// <param name=\"authInfo\"></param>\n public BlockadeLabsAuthentication(BlockadeLabsAuthInfo authInfo) => Info = authInfo;\n /// <inheritdoc />\n public override BlockadeLabsAuthInfo Info { get; }", "score": 0.7495303153991699 }, { "filename": "BlockadeLabs/Packages/com.rest.blockadelabs/Runtime/Skyboxes/SkyboxRequest.cs", "retrieved_chunk": " /// </param>\n /// <param name=\"controlImage\">\n /// <see cref=\"Stream\"/> data of control image for request.\n /// </param>\n /// <param name=\"controlImageFileName\">\n /// File name of <see cref=\"controlImage\"/>.\n /// </param>\n /// <param name=\"controlModel\">\n /// Model used for the <see cref=\"ControlImage\"/>.\n /// Currently the only option is: \"scribble\".", "score": 0.7319189310073853 }, { "filename": "BlockadeLabs/Packages/com.rest.blockadelabs/Runtime/Skyboxes/SkyboxRequest.cs", "retrieved_chunk": " /// </param>\n /// <param name=\"remixImagineId\">\n /// ID of a previously generated skybox.\n /// </param>\n /// <param name=\"depth\">\n /// Return depth map image.\n /// </param>\n public SkyboxRequest(\n string prompt,\n string negativeText = null,", "score": 0.7249588370323181 }, { "filename": "BlockadeLabs/Packages/com.rest.blockadelabs/Runtime/Skyboxes/SkyboxRequest.cs", "retrieved_chunk": " /// </param>\n /// <param name=\"remixImagineId\">\n /// ID of a previously generated skybox.\n /// </param>\n /// <param name=\"depth\">\n /// Return depth map image.\n /// </param>\n public SkyboxRequest(\n string prompt,\n Texture2D controlImage,", "score": 0.7144263386726379 } ]
csharp
SkyboxInfo> GenerateSkyboxAsync(SkyboxRequest skyboxRequest, int? pollingInterval = null, CancellationToken cancellationToken = default) {
using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Gum.InnerThoughts; using Gum.Utilities; namespace Gum { internal static partial class Tokens { public const string And = "and"; public const string And2 = "&&"; public const string Or = "or"; public const string Or2 = "||"; public const string Is = "is"; public const string Less = "<"; public const string LessEqual = "<="; public const string Equal = "=="; public const string Bigger = ">"; public const string BiggerEqual = ">="; public const string Different = "!="; public const string Else = "..."; } public partial class Parser { /// <summary> /// Read the next criterion. /// </summary> /// <param name="line"></param> /// <param name="node"> /// The resulting node. Only valid if it was able to read a non-empty valid /// requirement syntax. /// </param> /// <returns>Whether it read without any grammar errors.</returns> private bool ReadNextCriterion(ref ReadOnlySpan<char> line, int lineIndex, int currentColumn, out
CriterionNode? node) {
node = null; if (line.IsEmpty) { return true; } if (line.StartsWith(Tokens.Else)) { // This is actually a "else" block! line = line.Slice(Tokens.Else.Length); currentColumn += Tokens.Else.Length; } // Check if we started specifying the relationship from the previous requirement. ReadOnlySpan<char> token = PopNextWord(ref line, out int end); if (end == -1) { // No requirement specified. return true; } // Diagnostics... 🙏 currentColumn += token.Length; CriterionNodeKind? nodeKind = null; switch (token) { case Tokens.Or: case Tokens.Or2: nodeKind = CriterionNodeKind.Or; break; case Tokens.And: case Tokens.And2: nodeKind = CriterionNodeKind.And; break; // TODO: Check for '...' } ReadOnlySpan<char> variableToken = token; if (nodeKind is not null) { variableToken = PopNextWord(ref line, out end); if (end == -1) { // We saw something like a (and) condition. This is not really valid for us. OutputHelpers.WriteError($"Unexpected condition end after '{token}' on line {lineIndex}."); OutputHelpers.ProposeFixAtColumn( lineIndex, currentColumn, arrowLength: 1, content: _currentLine, issue: "Unexpected end of condition."); return false; } currentColumn += variableToken.Length; } else { // Assume 'AND' by default and move on. nodeKind = CriterionNodeKind.And; } // Check if this is actually a // (!SomethingBad) // ^ // variable. CriterionKind criterionKind = CriterionKind.Is; if (variableToken[0] == (char)TokenChar.Negative) { criterionKind = CriterionKind.Different; variableToken = variableToken.Slice(1); } // 'token' now corresponds to the variable name. Check if there is a blackboard specified. (string? blackboard, string variable) = ReadBlackboardVariableName(variableToken); // The following are *optional*, so let's not kick off any characters yet. ReadOnlySpan<char> @operator = GetNextWord(line, out end); bool readNextToken = [email protected]; if ([email protected]) { switch (@operator) { // is, == case Tokens.Is: case Tokens.Equal: break; // != case Tokens.Different: criterionKind = criterionKind == CriterionKind.Different ? CriterionKind.Is : CriterionKind.Different; break; // < case Tokens.Less: criterionKind = CriterionKind.Less; break; // <= case Tokens.LessEqual: criterionKind = CriterionKind.LessOrEqual; break; // >= case Tokens.BiggerEqual: criterionKind = CriterionKind.BiggerOrEqual; break; // > case Tokens.Bigger: criterionKind = CriterionKind.Bigger; break; default: // The next node will take care of this. readNextToken = false; break; } } FactKind? expectedFact; object? ruleValue; if (readNextToken) { line = line.Slice(end); currentColumn += end; // Check if we started specifying the relationship from the previous requirement. ReadOnlySpan<char> specifier = PopNextWord(ref line, out end); if (end == -1) { // We have something like a '==' or 'is' waiting for another condition. OutputHelpers.WriteError($"Unexpected condition end after '{@operator}' on line {lineIndex}."); OutputHelpers.ProposeFixAtColumn( lineIndex, currentColumn, arrowLength: 1, content: _currentLine, issue: "The matching value is missing."); return false; } if (!ReadFactValue(specifier, out expectedFact, out ruleValue)) { OutputInvalidRuleValueSpecifier(specifier, lineIndex, currentColumn); return false; } // currentColumn += end; } else { Debug.Assert(criterionKind == CriterionKind.Is || criterionKind == CriterionKind.Different, "Unexpected criterion kind for a condition without an explicit token value!"); // If there is no specifier, assume this is a boolean and the variable is enough. ruleValue = true; expectedFact = FactKind.Bool; } Fact fact = new(blackboard, variable, expectedFact.Value); Criterion criterion = new(fact, criterionKind, ruleValue); node = new(criterion, nodeKind.Value); return true; } private (string? Blackboard, string Variable) ReadBlackboardVariableName(ReadOnlySpan<char> value) { // 'token' now corresponds to the variable name. Check if there is a blackboard specified. string? blackboard; string variable; // First, check if there is a namespace specified. int blackboardIndex = value.IndexOf('.'); if (blackboardIndex != -1) { blackboard = value.Slice(0, blackboardIndex).ToString(); variable = value.Slice(blackboardIndex + 1).ToString(); } else { blackboard = null; variable = value.ToString(); } return (blackboard, variable); } private bool ReadFactValue(ReadOnlySpan<char> line, [NotNullWhen(true)] out FactKind? fact, [NotNullWhen(true)] out object? value) { fact = null; value = null; if (TryReadInteger(line) is int @int) { fact = FactKind.Int; value = @int; } else if (MemoryExtensions.Equals(line.Trim(), "true", StringComparison.OrdinalIgnoreCase)) { fact = FactKind.Bool; value = true; } else if (MemoryExtensions.Equals(line.Trim(), "false", StringComparison.OrdinalIgnoreCase)) { fact = FactKind.Bool; value = false; } else if ((line[0] == '\'' && line[line.Length - 1] == '\'') || (line[0] == '\"' && line[line.Length - 1] == '\"')) { fact = FactKind.String; value = line.Slice(1, line.Length - 2).ToString(); } else { return false; } return true; } private void OutputInvalidRuleValueSpecifier(ReadOnlySpan<char> specifier, int lineIndex, int column) { // Unrecognized token? OutputHelpers.WriteError($"Unexpected rule value '{specifier}' on line {lineIndex}."); if (OutputTryGuessAssignmentValue(specifier, lineIndex, column)) { return; } // We couldn't guess a fix. 😥 Sorry, just move on. OutputHelpers.ProposeFixAtColumn( lineIndex, column, arrowLength: specifier.Length, content: _currentLine, issue: "This rule could not be recognized."); } private bool OutputTryGuessAssignmentValue(ReadOnlySpan<char> specifier, int lineIndex, int column) { if (char.IsDigit(specifier[0])) { char[] clean = Array.FindAll(specifier.ToArray(), char.IsDigit); OutputHelpers.ProposeFix( lineIndex, before: _currentLine, after: _currentLine.Replace(specifier.ToString(), new string(clean))); return true; } string lowercaseSpecifier = specifier.ToString().ToLowerInvariant(); int commonLength = lowercaseSpecifier.Intersect("true").Count(); if (commonLength > 3) { OutputHelpers.ProposeFix( lineIndex, before: _currentLine, after: _currentLine.Replace(specifier.ToString(), "true")); return true; } commonLength = lowercaseSpecifier.Intersect("false").Count(); if (commonLength > 3) { OutputHelpers.ProposeFix( lineIndex, before: _currentLine, after: _currentLine.Replace(specifier.ToString(), "false")); return true; } return false; } } }
src/Gum/Parser_Requirements.cs
isadorasophia-gum-032cb2d
[ { "filename": "src/Gum/Parser.cs", "retrieved_chunk": " }\n }\n /// <summary>\n /// Fetches the immediate next word of a line.\n /// This disregards any indentation or white space prior to the word.\n /// </summary>\n /// <param name=\"end\">The end of the parameter. If -1, this is an empty word.</param>\n private static ReadOnlySpan<char> GetNextWord(ReadOnlySpan<char> line, out int end)\n {\n ReadOnlySpan<char> trimmed = line.TrimStart();", "score": 0.8861935138702393 }, { "filename": "src/Gum/Parser.cs", "retrieved_chunk": " /// <summary>\n /// Read the next line, without any comments.\n /// </summary>\n /// <returns>Whether it was successful and no error occurred.</returns>\n private bool ProcessLine(ReadOnlySpan<char> line, int index, int column, int depth = 0, int joinLevel = 0, bool hasCreatedBlock = false)\n {\n if (line.IsEmpty) return true;\n bool isNestedBlock = false;\n // If this is not a situation declaration ('=') but a situation has not been declared yet!\n if (line[0] != (char)TokenChar.Situation && _script.HasCurrentSituation is false)", "score": 0.8629956245422363 }, { "filename": "src/Gum/Parser.cs", "retrieved_chunk": " _ = Trim();\n return _script;\n }\n /// <summary>\n /// Check whether the first character of a line has a token defined.\n /// </summary>\n private bool Defines(ReadOnlySpan<char> line, TokenChar token, string? stringAfterToken = null)\n {\n ReadOnlySpan<char> word = GetNextWord(line, out int end).TrimStart();\n while (end != -1 && !word.IsEmpty)", "score": 0.8576308488845825 }, { "filename": "src/Gum/Parser.cs", "retrieved_chunk": " line = line.Slice(end);\n word = GetNextWord(line, out end).TrimStart();\n }\n return false;\n }\n /// <summary>\n /// Check whether the first character of a line has a token defined.\n /// </summary>\n private bool Defines(ReadOnlySpan<char> line, TokenChar[] tokens)\n {", "score": 0.854985773563385 }, { "filename": "src/Gum/Parser_Actions.cs", "retrieved_chunk": " /// </summary>\n /// <returns>Whether it succeeded parsing the action.</returns>\n private bool ParseAction(ReadOnlySpan<char> line, int lineIndex, int currentColumn)\n {\n if (line.IsEmpty)\n {\n // We saw something like a (and) condition. This is not really valid for us.\n OutputHelpers.WriteWarning($\"Empty action ('[]') found at line {lineIndex}. \" +\n \"Was this on purpose? Because it will be ignored.\");\n return true;", "score": 0.8506180644035339 } ]
csharp
CriterionNode? node) {
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Magic.IndexedDb.Extensions { public static class ServiceCollectionExtensions { public static IServiceCollection AddBlazorDB(this IServiceCollection services, Action<
DbStore> options) {
var dbStore = new DbStore(); options(dbStore); services.AddTransient<DbStore>((_) => dbStore); services.TryAddSingleton<IMagicDbFactory, MagicDbFactory>(); return services; } public static IServiceCollection AddEncryptionFactory(this IServiceCollection services) { services.TryAddSingleton<IEncryptionFactory, EncryptionFactory>(); return services; } } }
Magic.IndexedDb/Extensions/ServiceCollectionExtensions.cs
magiccodingman-Magic.IndexedDb-a279d6d
[ { "filename": "Magic.IndexedDb/Models/DbStore.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Magic.IndexedDb\n{\n public class DbStore\n {\n public string Name { get; set; }", "score": 0.8959238529205322 }, { "filename": "Magic.IndexedDb/Models/StoreSchema.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Magic.IndexedDb\n{\n public class StoreSchema\n {\n public string Name { get; set; }", "score": 0.8901236653327942 }, { "filename": "Magic.IndexedDb/Models/BlazorEvent.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Magic.IndexedDb\n{\n public class BlazorDbEvent\n {\n public Guid Transaction { get; set; }", "score": 0.8884304761886597 }, { "filename": "Magic.IndexedDb/Models/JsResponse.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Magic.IndexedDb.Models\n{\n public class JsResponse<T>\n {\n public JsResponse(T data, bool success, string message)", "score": 0.8878860473632812 }, { "filename": "Magic.IndexedDb/Models/DbMigrationInstruction.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Magic.IndexedDb\n{\n public class DbMigrationInstruction\n {\n public string Action { get; set; }", "score": 0.8876597285270691 } ]
csharp
DbStore> options) {
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ExpressionTree; using FindClosestString; using SyslogLogging; using Watson.ORM; using static Mysqlx.Expect.Open.Types.Condition.Types; namespace RosettaStone.Core.Services { public class CodecMetadataService { #region Public-Members #endregion #region Private-Members private LoggingModule _Logging = null; private WatsonORM _ORM = null; #endregion #region Constructors-and-Factories public CodecMetadataService(LoggingModule logging, WatsonORM orm) { _Logging = logging ?? throw new ArgumentNullException(nameof(logging)); _ORM = orm ?? throw new ArgumentNullException(nameof(orm)); } #endregion #region Public-Methods public List<CodecMetadata> All() { Expr expr = new Expr( _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.Id)), OperatorEnum.GreaterThan, 0); expr.PrependAnd( _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.IsAssigned)), OperatorEnum.Equals, 1); return _ORM.SelectMany<CodecMetadata>(expr); } public List<CodecMetadata> AllByVendor(string vendorGuid) { if (String.IsNullOrEmpty(vendorGuid)) throw new ArgumentNullException(nameof(vendorGuid)); vendorGuid = vendorGuid.ToUpper(); Expr expr = new Expr( _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.VendorGUID)), OperatorEnum.Equals, vendorGuid); expr.PrependAnd( _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.IsAssigned)), OperatorEnum.Equals, 1); return _ORM.SelectMany<CodecMetadata>(expr); } public
CodecMetadata GetByKey(string key) {
if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key)); key = key.ToUpper(); Expr expr = new Expr( _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.Key)), OperatorEnum.Equals, key); expr.PrependAnd( _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.IsAssigned)), OperatorEnum.Equals, 1); return _ORM.SelectFirst<CodecMetadata>(expr); } public bool ExistsByKey(string key) { if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key)); key = key.ToUpper(); Expr expr = new Expr( _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.Key)), OperatorEnum.Equals, key); expr.PrependAnd( _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.IsAssigned)), OperatorEnum.Equals, 1); return _ORM.Exists<CodecMetadata>(expr); } public CodecMetadata GetByGuid(string guid) { if (String.IsNullOrEmpty(guid)) throw new ArgumentNullException(nameof(guid)); guid = guid.ToUpper(); Expr expr = new Expr( _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.GUID)), OperatorEnum.Equals, guid); expr.PrependAnd( _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.IsAssigned)), OperatorEnum.Equals, 1); return _ORM.SelectFirst<CodecMetadata>(expr); } public bool ExistsByGuid(string guid) { if (String.IsNullOrEmpty(guid)) throw new ArgumentNullException(nameof(guid)); guid = guid.ToUpper(); Expr expr = new Expr( _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.GUID)), OperatorEnum.Equals, guid); expr.PrependAnd( _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.IsAssigned)), OperatorEnum.Equals, 1); return _ORM.Exists<CodecMetadata>(expr); } public List<CodecMetadata> Search(Expr expr, int startIndex, int maxResults) { if (expr == null) throw new ArgumentNullException(nameof(expr)); if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex)); if (maxResults > 1000) throw new ArgumentOutOfRangeException(nameof(maxResults)); return _ORM.SelectMany<CodecMetadata>(startIndex, maxResults, expr); } public CodecMetadata Add(CodecMetadata cm) { if (cm == null) throw new ArgumentNullException(nameof(cm)); cm.Key = cm.Key.ToUpper(); cm.GUID = cm.GUID.ToUpper(); cm.VendorGUID = cm.VendorGUID.ToUpper(); if (ExistsByGuid(cm.GUID)) throw new ArgumentException("Object with GUID '" + cm.GUID + "' already exists."); if (ExistsByKey(cm.Key)) throw new ArgumentException("Object with key '" + cm.Key + "' already exists."); return _ORM.Insert<CodecMetadata>(cm); } public CodecMetadata Update(CodecMetadata cm) { if (cm == null) throw new ArgumentNullException(nameof(cm)); cm.Key = cm.Key.ToUpper(); cm.GUID = cm.GUID.ToUpper(); cm.VendorGUID = cm.VendorGUID.ToUpper(); return _ORM.Update<CodecMetadata>(cm); } public void DeleteByGuid(string guid) { if (String.IsNullOrEmpty(guid)) throw new ArgumentNullException(nameof(guid)); guid = guid.ToUpper(); Expr expr = new Expr( _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.GUID)), OperatorEnum.Equals, guid ); _ORM.DeleteMany<CodecMetadata>(expr); } public void DeleteByKey(string key) { if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key)); key = key.ToUpper(); Expr expr = new Expr( _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.Key)), OperatorEnum.Equals, key ); _ORM.DeleteMany<CodecMetadata>(expr); } public void DeleteByVendorGuid(string vendorGuid) { if (String.IsNullOrEmpty(vendorGuid)) throw new ArgumentNullException(nameof(vendorGuid)); vendorGuid = vendorGuid.ToUpper(); Expr expr = new Expr( _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.VendorGUID)), OperatorEnum.Equals, vendorGuid ); _ORM.DeleteMany<CodecMetadata>(expr); } public CodecMetadata FindClosestMatch(string key) { if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key)); key = key.ToUpper(); List<CodecMetadata> all = All(); List<string> keys = all.Where(x => x.IsAssigned).Select(x => x.Key).ToList(); (string, int) result = ClosestString.UsingLevenshtein(key, keys); CodecMetadata codec = GetByKey(result.Item1); codec.EditDistance = result.Item2; return codec; } public List<CodecMetadata> FindClosestMatches(string key, int maxResults = 10) { if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key)); if (maxResults < 1 || maxResults > 10) throw new ArgumentOutOfRangeException(nameof(maxResults)); key = key.ToUpper(); List<CodecMetadata> all = All(); List<string> keys = all.Where(x => x.IsAssigned).Select(x => x.Key).ToList(); List<(string, int)> result = ClosestStrings.UsingLevenshtein(key, keys, maxResults); List<CodecMetadata> ret = new List<CodecMetadata>(); foreach ((string, int) item in result) { CodecMetadata codec = GetByKey(item.Item1); codec.EditDistance = item.Item2; ret.Add(codec); } return ret; } #endregion #region Private-Methods #endregion } }
src/RosettaStone.Core/Services/CodecMetadataService.cs
jchristn-RosettaStone-898982c
[ { "filename": "src/RosettaStone.Core/Services/VendorMetadataService.cs", "retrieved_chunk": " _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.Id)),\n OperatorEnum.GreaterThan,\n 0);\n expr.PrependAnd(\n _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.IsAssigned)),\n OperatorEnum.Equals,\n 1);\n return _ORM.SelectMany<VendorMetadata>(expr);\n }\n public VendorMetadata GetByKey(string key)", "score": 0.8731827735900879 }, { "filename": "src/RosettaStone.Core/Services/VendorMetadataService.cs", "retrieved_chunk": " key);\n expr.PrependAnd(\n _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.IsAssigned)),\n OperatorEnum.Equals,\n 1);\n return _ORM.Exists<VendorMetadata>(expr);\n }\n public VendorMetadata GetByGuid(string guid)\n {\n if (String.IsNullOrEmpty(guid)) throw new ArgumentNullException(nameof(guid));", "score": 0.8447692394256592 }, { "filename": "src/RosettaStone.Core/Services/VendorMetadataService.cs", "retrieved_chunk": " 1);\n return _ORM.SelectFirst<VendorMetadata>(expr);\n }\n public bool ExistsByKey(string key)\n {\n if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key));\n key = key.ToUpper();\n Expr expr = new Expr(\n _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.Key)),\n OperatorEnum.Equals,", "score": 0.8313125371932983 }, { "filename": "src/RosettaStone.Core/Services/VendorMetadataService.cs", "retrieved_chunk": " {\n if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key));\n key = key.ToUpper();\n Expr expr = new Expr(\n _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.Key)),\n OperatorEnum.Equals,\n key\n );\n _ORM.DeleteMany<VendorMetadata>(expr);\n }", "score": 0.8280951380729675 }, { "filename": "src/RosettaStone.Core/Services/VendorMetadataService.cs", "retrieved_chunk": " if (String.IsNullOrEmpty(guid)) throw new ArgumentNullException(nameof(guid));\n guid = guid.ToUpper();\n Expr expr = new Expr(\n _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.GUID)),\n OperatorEnum.Equals,\n guid\n );\n _ORM.DeleteMany<VendorMetadata>(expr);\n }\n public void DeleteByKey(string key)", "score": 0.8225555419921875 } ]
csharp
CodecMetadata GetByKey(string key) {
using System; namespace ClockSnowFlake { /// <summary> /// Id 生成器 /// </summary> public static class IdGener { /// <summary> ///基于时钟序列的 Long 生成器 /// </summary> public static
ILongGenerator ClockLongGenerator {
get; set; } = ClockSnowFlakeIdGenerator.Current; /// <summary> /// 用Guid创建标识 /// </summary> /// <returns></returns> public static string GetGuid() { return Guid.NewGuid().ToString("N"); } /// <summary> /// 创建 Long ID /// </summary> /// <returns></returns> public static long GetLong() { return ClockLongGenerator.Create(); } } }
src/ClockSnowFlake/IdGener.cs
Bryan-Cyf-ClockSnowFlake-7c4a524
[ { "filename": "src/ClockSnowFlake/Generator/ILongGenerator.cs", "retrieved_chunk": "namespace ClockSnowFlake\n{\n /// <summary>\n /// Long Id 生成器\n /// </summary>\n public interface ILongGenerator : IIdGenerator<long>\n {\n }\n}", "score": 0.8876029849052429 }, { "filename": "src/ClockSnowFlake/Generator/IIdGenerator.cs", "retrieved_chunk": "namespace ClockSnowFlake\n{\n /// <summary>\n /// ID 生成器\n /// </summary>\n /// <typeparam name=\"T\">数据类型</typeparam>\n public interface IIdGenerator<out T>\n {\n /// <summary>\n /// 创建 ID", "score": 0.8755163550376892 }, { "filename": "src/ClockSnowFlake/Ids/ClockSnowflakeId.cs", "retrieved_chunk": " private long _lastTimestamp = -1L;\n /// <summary>\n /// 机器ID\n /// </summary>\n public long WorkerId { get; protected set; }\n /// <summary>\n /// 序列号ID\n /// </summary>\n public long Sequence\n {", "score": 0.8690520524978638 }, { "filename": "src/ClockSnowFlake/Ids/ClockSnowflakeId.cs", "retrieved_chunk": " /// 获取当前时间戳\n /// </summary>\n /// <returns></returns>\n protected virtual long TimeGen()\n {\n return CurrentTimeMills();\n }\n /// <summary>\n /// 获取当前时间戳\n /// </summary>", "score": 0.8666542172431946 }, { "filename": "src/ClockSnowFlake/Options/SnowFakeOptionsConst.cs", "retrieved_chunk": "namespace ClockSnowFlake\n{\n public class SnowFakeOptionsConst\n {\n /// <summary>\n /// 工作节点ID,范围 0~128\n /// </summary>\n public static long? WorkId { get; set; }\n }\n}", "score": 0.8569024801254272 } ]
csharp
ILongGenerator ClockLongGenerator {
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ExpressionTree; using FindClosestString; using SyslogLogging; using Watson.ORM; namespace RosettaStone.Core.Services { public class VendorMetadataService { #region Public-Members #endregion #region Private-Members private LoggingModule _Logging = null; private WatsonORM _ORM = null; #endregion #region Constructors-and-Factories public VendorMetadataService(LoggingModule logging, WatsonORM orm) { _Logging = logging ?? throw new ArgumentNullException(nameof(logging)); _ORM = orm ?? throw new ArgumentNullException(nameof(orm)); } #endregion #region Public-Methods public List<VendorMetadata> All() { Expr expr = new Expr( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.Id)), OperatorEnum.GreaterThan, 0); expr.PrependAnd( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.IsAssigned)), OperatorEnum.Equals, 1); return _ORM.SelectMany<VendorMetadata>(expr); } public
VendorMetadata GetByKey(string key) {
if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key)); key = key.ToUpper(); Expr expr = new Expr( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.Key)), OperatorEnum.Equals, key); expr.PrependAnd( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.IsAssigned)), OperatorEnum.Equals, 1); return _ORM.SelectFirst<VendorMetadata>(expr); } public bool ExistsByKey(string key) { if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key)); key = key.ToUpper(); Expr expr = new Expr( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.Key)), OperatorEnum.Equals, key); expr.PrependAnd( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.IsAssigned)), OperatorEnum.Equals, 1); return _ORM.Exists<VendorMetadata>(expr); } public VendorMetadata GetByGuid(string guid) { if (String.IsNullOrEmpty(guid)) throw new ArgumentNullException(nameof(guid)); guid = guid.ToUpper(); Expr expr = new Expr( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.GUID)), OperatorEnum.Equals, guid); expr.PrependAnd( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.IsAssigned)), OperatorEnum.Equals, 1); return _ORM.SelectFirst<VendorMetadata>(expr); } public bool ExistsByGuid(string guid) { if (String.IsNullOrEmpty(guid)) throw new ArgumentNullException(nameof(guid)); guid = guid.ToUpper(); Expr expr = new Expr( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.GUID)), OperatorEnum.Equals, guid); expr.PrependAnd( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.IsAssigned)), OperatorEnum.Equals, 1); return _ORM.Exists<VendorMetadata>(expr); } public List<VendorMetadata> Search(Expr expr, int startIndex = 0, int maxResults = 1000) { if (expr == null) throw new ArgumentNullException(nameof(expr)); if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex)); if (maxResults > 1000) throw new ArgumentOutOfRangeException(nameof(maxResults)); return _ORM.SelectMany<VendorMetadata>(startIndex, maxResults, expr); } public VendorMetadata Add(VendorMetadata vm) { if (vm == null) throw new ArgumentNullException(nameof(vm)); if (ExistsByGuid(vm.GUID)) throw new ArgumentException("Object with GUID '" + vm.GUID + "' already exists."); if (ExistsByKey(vm.Key)) throw new ArgumentException("Object with key '" + vm.Key + "' already exists."); vm.Key = vm.Key.ToUpper(); vm.GUID = vm.GUID.ToUpper(); return _ORM.Insert<VendorMetadata>(vm); } public VendorMetadata Update(VendorMetadata vm) { if (vm == null) throw new ArgumentNullException(nameof(vm)); vm.Key = vm.Key.ToUpper(); vm.GUID = vm.GUID.ToUpper(); return _ORM.Update<VendorMetadata>(vm); } public void DeleteByGuid(string guid) { if (String.IsNullOrEmpty(guid)) throw new ArgumentNullException(nameof(guid)); guid = guid.ToUpper(); Expr expr = new Expr( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.GUID)), OperatorEnum.Equals, guid ); _ORM.DeleteMany<VendorMetadata>(expr); } public void DeleteByKey(string key) { if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key)); key = key.ToUpper(); Expr expr = new Expr( _ORM.GetColumnName<VendorMetadata>(nameof(VendorMetadata.Key)), OperatorEnum.Equals, key ); _ORM.DeleteMany<VendorMetadata>(expr); } public VendorMetadata FindClosestMatch(string key) { if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key)); key = key.ToUpper(); List<VendorMetadata> all = All(); List<string> keys = all.Where(x => x.IsAssigned).Select(x => x.Key).ToList(); (string, int) result = ClosestString.UsingLevenshtein(key, keys); VendorMetadata vendor = GetByKey(result.Item1); vendor.EditDistance = result.Item2; return vendor; } public List<VendorMetadata> FindClosestMatches(string key, int maxResults = 10) { if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key)); if (maxResults < 1 || maxResults > 10) throw new ArgumentOutOfRangeException(nameof(maxResults)); key = key.ToUpper(); List<VendorMetadata> all = All(); List<string> keys = all.Where(x => x.IsAssigned).Select(x => x.Key).ToList(); List<(string, int)> result = ClosestStrings.UsingLevenshtein(key, keys, maxResults); List<VendorMetadata> ret = new List<VendorMetadata>(); foreach ((string, int) item in result) { VendorMetadata vendor = GetByKey(item.Item1); vendor.EditDistance = item.Item2; ret.Add(vendor); } return ret; } #endregion #region Private-Methods #endregion } }
src/RosettaStone.Core/Services/VendorMetadataService.cs
jchristn-RosettaStone-898982c
[ { "filename": "src/RosettaStone.Core/Services/CodecMetadataService.cs", "retrieved_chunk": " OperatorEnum.Equals,\n key);\n expr.PrependAnd(\n _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.IsAssigned)),\n OperatorEnum.Equals,\n 1);\n return _ORM.SelectFirst<CodecMetadata>(expr);\n }\n public bool ExistsByKey(string key)\n {", "score": 0.8951444625854492 }, { "filename": "src/RosettaStone.Core/Services/CodecMetadataService.cs", "retrieved_chunk": " vendorGuid = vendorGuid.ToUpper();\n Expr expr = new Expr(\n _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.VendorGUID)),\n OperatorEnum.Equals,\n vendorGuid\n );\n _ORM.DeleteMany<CodecMetadata>(expr);\n }\n public CodecMetadata FindClosestMatch(string key)\n {", "score": 0.8822152018547058 }, { "filename": "src/RosettaStone.Core/Services/CodecMetadataService.cs", "retrieved_chunk": " Expr expr = new Expr(\n _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.Key)),\n OperatorEnum.Equals,\n key\n );\n _ORM.DeleteMany<CodecMetadata>(expr);\n }\n public void DeleteByVendorGuid(string vendorGuid)\n {\n if (String.IsNullOrEmpty(vendorGuid)) throw new ArgumentNullException(nameof(vendorGuid));", "score": 0.8742860555648804 }, { "filename": "src/RosettaStone.Core/Services/CodecMetadataService.cs", "retrieved_chunk": " Expr expr = new Expr(\n _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.Id)),\n OperatorEnum.GreaterThan,\n 0);\n expr.PrependAnd(\n _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.IsAssigned)),\n OperatorEnum.Equals,\n 1);\n return _ORM.SelectMany<CodecMetadata>(expr);\n }", "score": 0.8698115348815918 }, { "filename": "src/RosettaStone.Core/Services/CodecMetadataService.cs", "retrieved_chunk": " Expr expr = new Expr(\n _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.GUID)),\n OperatorEnum.Equals,\n guid);\n expr.PrependAnd(\n _ORM.GetColumnName<CodecMetadata>(nameof(CodecMetadata.IsAssigned)),\n OperatorEnum.Equals,\n 1);\n return _ORM.Exists<CodecMetadata>(expr);\n }", "score": 0.8567599058151245 } ]
csharp
VendorMetadata GetByKey(string key) {
using HarmonyLib; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.ConstrainedExecution; using UnityEngine; namespace Ultrapain.Patches { class Drone_Start_Patch { static void Postfix(Drone __instance, ref EnemyIdentifier ___eid) { if (___eid.enemyType != EnemyType.Drone) return; __instance.gameObject.AddComponent<DroneFlag>(); } } class Drone_PlaySound_Patch { static FieldInfo antennaFlashField = typeof(Turret).GetField("antennaFlash", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); static ParticleSystem antennaFlash; public static Color defaultLineColor = new Color(1f, 0.44f, 0.74f); static bool Prefix(Drone __instance, EnemyIdentifier ___eid, AudioClip __0) { if (___eid.enemyType != EnemyType.Drone) return true; if(__0 == __instance.windUpSound) { DroneFlag flag = __instance.GetComponent<DroneFlag>(); if (flag == null) return true; List<Tuple<DroneFlag.Firemode, float>> chances = new List<Tuple<DroneFlag.Firemode, float>>(); if (ConfigManager.droneProjectileToggle.value) chances.Add(new Tuple<DroneFlag.Firemode, float>(DroneFlag.Firemode.Projectile, ConfigManager.droneProjectileChance.value)); if (ConfigManager.droneExplosionBeamToggle.value) chances.Add(new Tuple<DroneFlag.Firemode, float>(DroneFlag.Firemode.Explosive, ConfigManager.droneExplosionBeamChance.value)); if (ConfigManager.droneSentryBeamToggle.value) chances.Add(new Tuple<DroneFlag.Firemode, float>(DroneFlag.Firemode.TurretBeam, ConfigManager.droneSentryBeamChance.value)); if (chances.Count == 0 || chances.Sum(item => item.Item2) <= 0) flag.currentMode = DroneFlag.Firemode.Projectile; else flag.currentMode = UnityUtils.GetRandomFloatWeightedItem(chances, item => item.Item2).Item1; if (flag.currentMode == DroneFlag.Firemode.Projectile) { flag.attackDelay = ConfigManager.droneProjectileDelay.value; return true; } else if (flag.currentMode == DroneFlag.Firemode.Explosive) { flag.attackDelay = ConfigManager.droneExplosionBeamDelay.value; GameObject chargeEffect = GameObject.Instantiate(Plugin.chargeEffect, __instance.transform); chargeEffect.transform.localPosition = new Vector3(0, 0, 0.8f); chargeEffect.transform.localScale = Vector3.zero; float duration = ConfigManager.droneExplosionBeamDelay.value / ___eid.totalSpeedModifier; RemoveOnTime remover = chargeEffect.AddComponent<RemoveOnTime>(); remover.time = duration; CommonLinearScaler scaler = chargeEffect.AddComponent<CommonLinearScaler>(); scaler.targetTransform = scaler.transform; scaler.scaleSpeed = 1f / duration; CommonAudioPitchScaler pitchScaler = chargeEffect.AddComponent<CommonAudioPitchScaler>(); pitchScaler.targetAud = chargeEffect.GetComponent<AudioSource>(); pitchScaler.scaleSpeed = 1f / duration; return false; } else if (flag.currentMode == DroneFlag.Firemode.TurretBeam) { flag.attackDelay = ConfigManager.droneSentryBeamDelay.value; if(ConfigManager.droneDrawSentryBeamLine.value) { flag.lr.enabled = true; flag.SetLineColor(ConfigManager.droneSentryBeamLineNormalColor.value); flag.Invoke("LineRendererColorToWarning", Mathf.Max(0.01f, (flag.attackDelay / ___eid.totalSpeedModifier) - ConfigManager.droneSentryBeamLineIndicatorDelay.value)); } if (flag.particleSystem == null) { if (antennaFlash == null) antennaFlash = (ParticleSystem)antennaFlashField.GetValue(Plugin.turret); flag.particleSystem = GameObject.Instantiate(antennaFlash, __instance.transform); flag.particleSystem.transform.localPosition = new Vector3(0, 0, 2); } flag.particleSystem.Play(); GameObject flash = GameObject.Instantiate(Plugin.turretFinalFlash, __instance.transform); GameObject.Destroy(flash.transform.Find("MuzzleFlash/muzzleflash").gameObject); return false; } } return true; } } class Drone_Shoot_Patch { static bool Prefix(Drone __instance, ref EnemyIdentifier ___eid) { DroneFlag flag = __instance.GetComponent<DroneFlag>(); if(flag == null || __instance.crashing) return true; DroneFlag.Firemode mode = flag.currentMode; if (mode == DroneFlag.Firemode.Projectile) return true; if (mode == DroneFlag.Firemode.Explosive) { GameObject beam = GameObject.Instantiate(Plugin.beam.gameObject, __instance.transform.position + __instance.transform.forward, __instance.transform.rotation); RevolverBeam revBeam = beam.GetComponent<RevolverBeam>(); revBeam.hitParticle = Plugin.shotgunGrenade.gameObject.GetComponent<Grenade>().explosion; revBeam.damage /= 2; revBeam.damage *= ___eid.totalDamageModifier; return false; } if(mode == DroneFlag.Firemode.TurretBeam) { GameObject turretBeam = GameObject.Instantiate(Plugin.turretBeam.gameObject, __instance.transform.position + __instance.transform.forward * 2f, __instance.transform.rotation); if (turretBeam.TryGetComponent<RevolverBeam>(out RevolverBeam revBeam)) { revBeam.damage = ConfigManager.droneSentryBeamDamage.value; revBeam.damage *= ___eid.totalDamageModifier; revBeam.alternateStartPoint = __instance.transform.position + __instance.transform.forward; revBeam.ignoreEnemyType = EnemyType.Drone; } flag.lr.enabled = false; return false; } Debug.LogError($"Drone fire mode in impossible state. Current value: {mode} : {(int)mode}"); return true; } } class Drone_Update { static void Postfix(Drone __instance, EnemyIdentifier ___eid, ref float ___attackCooldown, int ___difficulty) { if (___eid.enemyType != EnemyType.Drone) return; DroneFlag flag = __instance.GetComponent<DroneFlag>(); if (flag == null || flag.attackDelay < 0) return; float attackSpeedDecay = (float)(___difficulty / 2); if (___difficulty == 1) { attackSpeedDecay = 0.75f; } else if (___difficulty == 0) { attackSpeedDecay = 0.5f; } attackSpeedDecay *= ___eid.totalSpeedModifier; float delay = flag.attackDelay / ___eid.totalSpeedModifier; __instance.CancelInvoke("Shoot"); __instance.Invoke("Shoot", delay); ___attackCooldown = UnityEngine.Random.Range(2f, 4f) + (flag.attackDelay - 0.75f) * attackSpeedDecay; flag.attackDelay = -1; } } class DroneFlag : MonoBehaviour { public enum Firemode : int { Projectile = 0, Explosive, TurretBeam } public ParticleSystem particleSystem; public LineRenderer lr; public Firemode currentMode = Firemode.Projectile; private static Firemode[] allModes = Enum.GetValues(typeof(Firemode)) as Firemode[]; static FieldInfo turretAimLine = typeof(Turret).GetField("aimLine", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); static
Material whiteMat;
public void Awake() { lr = gameObject.AddComponent<LineRenderer>(); lr.enabled = false; lr.receiveShadows = false; lr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; lr.startWidth = lr.endWidth = lr.widthMultiplier = 0.025f; if (whiteMat == null) whiteMat = ((LineRenderer)turretAimLine.GetValue(Plugin.turret)).material; lr.material = whiteMat; } public void SetLineColor(Color c) { Gradient gradient = new Gradient(); GradientColorKey[] array = new GradientColorKey[1]; array[0].color = c; GradientAlphaKey[] array2 = new GradientAlphaKey[1]; array2[0].alpha = 1f; gradient.SetKeys(array, array2); lr.colorGradient = gradient; } public void LineRendererColorToWarning() { SetLineColor(ConfigManager.droneSentryBeamLineWarningColor.value); } public float attackDelay = -1; public bool homingTowardsPlayer = false; Transform target; Rigidbody rb; private void Update() { if(homingTowardsPlayer) { if(target == null) target = PlayerTracker.Instance.GetTarget(); if (rb == null) rb = GetComponent<Rigidbody>(); Quaternion to = Quaternion.LookRotation(target.position/* + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity()*/ - transform.position); transform.rotation = Quaternion.RotateTowards(transform.rotation, to, Time.deltaTime * ConfigManager.droneHomeTurnSpeed.value); rb.velocity = transform.forward * rb.velocity.magnitude; } if(lr.enabled) { lr.SetPosition(0, transform.position); lr.SetPosition(1, transform.position + transform.forward * 1000); } } } class Drone_Death_Patch { static bool Prefix(Drone __instance, EnemyIdentifier ___eid) { if (___eid.enemyType != EnemyType.Drone || __instance.crashing) return true; DroneFlag flag = __instance.GetComponent<DroneFlag>(); if (flag == null) return true; if (___eid.hitter == "heavypunch" || ___eid.hitter == "punch") return true; flag.homingTowardsPlayer = true; return true; } } class Drone_GetHurt_Patch { static bool Prefix(Drone __instance, EnemyIdentifier ___eid, bool ___parried) { if((___eid.hitter == "shotgunzone" || ___eid.hitter == "punch") && !___parried) { DroneFlag flag = __instance.GetComponent<DroneFlag>(); if (flag == null) return true; flag.homingTowardsPlayer = false; } return true; } } }
Ultrapain/Patches/Drone.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Leviathan.cs", "retrieved_chunk": " public float beamChargeRate = 12f / 1f;\n public int beamRemaining = 0;\n public int projectilesRemaining = 0;\n public float projectileDelayRemaining = 0f;\n private static FieldInfo ___inAction = typeof(LeviathanHead).GetField(\"inAction\", BindingFlags.NonPublic | BindingFlags.Instance);\n private void Awake()\n {\n comp = GetComponent<LeviathanHead>();\n anim = GetComponent<Animator>();\n //col = GetComponent<Collider>();", "score": 0.8114290237426758 }, { "filename": "Ultrapain/Patches/V2First.cs", "retrieved_chunk": " static MethodInfo ShootWeapon = typeof(V2).GetMethod(\"ShootWeapon\", BindingFlags.Instance | BindingFlags.NonPublic);\n static MethodInfo SwitchWeapon = typeof(V2).GetMethod(\"SwitchWeapon\", BindingFlags.Instance | BindingFlags.NonPublic);\n public static Transform targetGrenade;\n static bool Prefix(V2 __instance, ref int ___currentWeapon, ref Transform ___overrideTarget, ref Rigidbody ___overrideTargetRb, ref float ___shootCooldown,\n ref bool ___aboutToShoot, ref EnemyIdentifier ___eid, bool ___escaping)\n {\n if (__instance.secondEncounter)\n return true;\n if (!__instance.active || ___escaping || BlindEnemies.Blind)\n return true;", "score": 0.8007329702377319 }, { "filename": "Ultrapain/Patches/V2Second.cs", "retrieved_chunk": " //readonly static FieldInfo maliciousIgnorePlayer = typeof(RevolverBeam).GetField(\"maliciousIgnorePlayer\", BindingFlags.NonPublic | BindingFlags.Instance);\n Transform shootPoint;\n public Transform v2trans;\n public float cooldown = 0f;\n static readonly string debugTag = \"[V2][MalCannonShoot]\";\n void Awake()\n {\n shootPoint = UnityUtils.GetChildByNameRecursively(transform, \"Shootpoint\");\n }\n void PrepareFire()", "score": 0.7989198565483093 }, { "filename": "Ultrapain/Patches/Panopticon.cs", "retrieved_chunk": " comp.turningSpeedMultiplier *= ConfigManager.panopticonBlueProjTurnSpeed.value;\n comp.speed = ConfigManager.panopticonBlueProjInitialSpeed.value;\n }\n }\n static MethodInfo m_Panopticon_BlueProjectile_BlueProjectileSpawn = typeof(Panopticon_BlueProjectile).GetMethod(\"BlueProjectileSpawn\", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);\n static MethodInfo m_GameObject_GetComponent_Projectile = typeof(GameObject).GetMethod(\"GetComponent\", new Type[0]).MakeGenericMethod(new Type[1] { typeof(Projectile) });\n static IEnumerable Transpiler(IEnumerable<CodeInstruction> instructions)\n {\n List<CodeInstruction> code = new List<CodeInstruction>(instructions);\n for (int i = 0; i < code.Count; i++)", "score": 0.7701915502548218 }, { "filename": "Ultrapain/Patches/FleshPrison.cs", "retrieved_chunk": " currentNormal = Quaternion.Euler(0, anglePerProjectile, 0) * currentNormal;\n }\n }\n FieldInfo inAction;\n public float anglePerSecond = 1f;\n void Start()\n {\n SpawnInsignias();\n inAction = typeof(FleshPrison).GetField(\"inAction\", BindingFlags.Instance | BindingFlags.NonPublic);\n anglePerSecond = prison.altVersion ? ConfigManager.panopticonSpinAttackTurnSpeed.value : ConfigManager.fleshPrisonSpinAttackTurnSpeed.value;", "score": 0.7681994438171387 } ]
csharp
Material whiteMat;
using Gum.Utilities; using Newtonsoft.Json; using System.Diagnostics; namespace Gum.InnerThoughts { [DebuggerDisplay("{Name}")] public class Situation { [JsonProperty] public readonly int Id = 0; [JsonProperty] public readonly string Name = string.Empty; public int Root = 0; public readonly List<
Block> Blocks = new();
/// <summary> /// This points /// [ Node Id -> Edge ] /// </summary> public readonly Dictionary<int, Edge> Edges = new(); /// <summary> /// This points /// [ Node Id -> Parent ] /// If parent is empty, this is at the top. /// </summary> public readonly Dictionary<int, HashSet<int>> ParentOf = new(); private readonly Stack<int> _lastBlocks = new(); public Situation() { } public Situation(int id, string name) { Id = id; Name = name; // Add a root node. Block block = CreateBlock(playUntil: -1, track: true); Edge edge = CreateEdge(EdgeKind.Next); AssignOwnerToEdge(block.Id, edge); Root = block.Id; } public bool SwitchRelationshipTo(EdgeKind kind) { Edge lastEdge = LastEdge; if (lastEdge.Kind == kind) { // No operation, relationship is already set. return true; } int length = lastEdge.Blocks.Count; switch (kind) { case EdgeKind.Next: case EdgeKind.Random: lastEdge.Kind = kind; return true; case EdgeKind.Choice: case EdgeKind.HighestScore: if (length == 1) { lastEdge.Kind = kind; } else { Debug.Fail("I don't understand this scenario fully, please debug this."); // Remove the last block and create a new one? } return true; case EdgeKind.IfElse: return false; } return true; } internal EdgeKind PeekLastEdgeKind() => LastEdge.Kind; internal Block PeekLastBlock() => Blocks[_lastBlocks.Peek()]; internal Block PeekLastBlockParent() => Blocks[_lastBlocks.ElementAt(1)]; internal Block PeekBlockAt(int level) => Blocks[_lastBlocks.ElementAt(level)]; /// <summary> /// Creates a new block subjected to a <paramref name="kind"/> relationship. /// </summary> public Block? AddBlock(int playUntil, int joinLevel, bool isNested, EdgeKind kind = EdgeKind.Next) { Block lastBlock = PeekLastBlock(); if (joinLevel == 0 && playUntil == 1 && lastBlock.PlayUntil == 1 && !lastBlock.NonLinearNode) { // Consider this: // @1 -> Go // // @1 Some other dialog with the same indentation. // -> exit! // We need to "fake" another join level here to make up for our lack of indentation. joinLevel += 1; } // We need to know the "parent" node when nesting blocks (make the parent -> point to the new block). (int parentId, int[] blocksToBeJoined) = FetchParentOfJoinedBlock(joinLevel, kind); Edge lastEdge = Edges[parentId]; // Looks on whether we need to pop nodes on: // >> Dialog // > Choice // > Choice 2 <- pop here! bool shouldPopChoiceBlock = kind == EdgeKind.Choice && Blocks[parentId].IsChoice && lastEdge.Kind != kind && !isNested; if (shouldPopChoiceBlock || (!kind.IsSequential() && Blocks[parentId].NonLinearNode)) { // This is the only "HACKY" thing I will allow here. // Since I want to avoid a syntax such as: // (condition) // @score // - something // - something // and instead have something like // (condition) // - something // - something // I will do the following: _lastBlocks.Pop(); parentId = _lastBlocks.Peek(); blocksToBeJoined = new int[] { parentId }; } // Do not make a join on the leaves if this is an (...) or another choice (-/+) if (kind == EdgeKind.IfElse || (!lastEdge.Kind.IsSequential() && !kind.IsSequential()) || (kind == EdgeKind.Choice && lastEdge.Kind == EdgeKind.Choice)) { blocksToBeJoined = new int[] { parentId }; } Block block = CreateBlock(playUntil, track: true); block.NonLinearNode = !kind.IsSequential(); block.IsChoice = kind == EdgeKind.Choice; Edge? edge = CreateEdge(EdgeKind.Next); AssignOwnerToEdge(block.Id, edge); // If this was called right after a situation has been declared, it'll think that it is a nested block // (when it's not really). if (isNested) { Edge? parentEdge = Edges[parentId]; if (block.IsChoice) { parentEdge.Kind = EdgeKind.Next; // (Condition) // >> Nested title // > Option a // > Option b edge.Kind = kind; } else { parentEdge.Kind = kind; } AddNode(parentEdge, block.Id); return block; } foreach (int parent in blocksToBeJoined) { JoinBlock(block, edge, parent, kind); } return block; } private bool JoinBlock(Block block, Edge nextEdge, int parentId, EdgeKind kind) { Edge lastEdge = Edges[parentId]; switch (kind) { case EdgeKind.Choice: if (lastEdge.Kind != EdgeKind.Choice) { // before: // . // | D // A // // after: // . // | // A // | // D // {choice} lastEdge = Edges[parentId]; AddNode(lastEdge, block.Id); nextEdge.Kind = kind; return true; } AddNode(lastEdge, block.Id); return true; case EdgeKind.HighestScore: case EdgeKind.Random: // nextEdge.Kind = EdgeKind.HighestScore; break; case EdgeKind.IfElse: if (lastEdge.Kind == EdgeKind.IfElse || (lastEdge.Kind.IsSequential() && lastEdge.Blocks.Count == 1)) { lastEdge.Kind = EdgeKind.IfElse; AddNode(lastEdge, block.Id); return true; } if (lastEdge.Blocks.Count > 1) { CreateDummyNodeAt(lastEdge.Blocks.Last(), block.Id, kind); return true; } Debug.Fail("Empty edge?"); return false; } if (kind == EdgeKind.IfElse && lastEdge.Kind != kind) { if (lastEdge.Kind != EdgeKind.Next) { CreateDummyNodeAt(parentId, block.Id, kind); return true; } // This has been a bit of a headache, but if this is an "if else" and the current connection // is not the same, we'll convert this later. kind = EdgeKind.Next; } // If this is "intruding" an existing nested if-else. // (hasA) // (hasB) // (...) // (...) else if (kind == EdgeKind.IfElse && lastEdge.Kind == kind && parentId == lastEdge.Owner) { CreateDummyNodeAt(parentId, block.Id, kind); return true; } if (kind == EdgeKind.HighestScore && lastEdge.Kind == EdgeKind.Random) { // A "HighestScore" kind when is matched with a "random" relationship, it is considered one of them // automatically. kind = EdgeKind.Random; } if (lastEdge.Kind != kind && lastEdge.Blocks.Count == 0) { lastEdge.Kind = kind; } else if (lastEdge.Kind != kind && kind == EdgeKind.HighestScore) { // No-op? } else if (lastEdge.Kind != kind) { CreateDummyNodeAt(parentId, block.Id, kind); return true; } AddNode(lastEdge, block.Id); return true; } /// <summary> /// Given C and D: /// Before: /// A /// / \ /// B C <- parent D <- block /// / /// ... /// /// After: /// A /// / \ /// B E <- dummy /// / \ /// C D /// / ///... /// /// </summary> private void CreateDummyNodeAt(int parentId, int blockId, EdgeKind kind) { Block lastBlock = Blocks[parentId]; // Block the last block, this will be the block that we just added (blockId). _ = _lastBlocks.TryPop(out _); // If this block corresponds to the parent, remove it from the stack. if (_lastBlocks.TryPeek(out int peek) && peek == parentId) { _ = _lastBlocks.Pop(); } Block empty = CreateBlock(playUntil: lastBlock.PlayUntil, track: true); ReplaceEdgesToNodeWith(parentId, empty.Id); _lastBlocks.Push(blockId); Edge lastEdge = CreateEdge(kind); AddNode(lastEdge, parentId); AddNode(lastEdge, blockId); AssignOwnerToEdge(empty.Id, lastEdge); } /// <summary> /// Find all leaf nodes eligible to be joined. /// This will disregard nodes that are already dead (due to a goto!). /// </summary> private void GetAllLeaves(int block, bool createBlockForElse, ref HashSet<int> result) { Edge edge = Edges[block]; if (edge.Blocks.Count != 0) { foreach (int otherBlock in edge.Blocks) { GetAllLeaves(otherBlock, createBlockForElse, ref result); } if (createBlockForElse) { // @1 (Something) // Hello! // // (...Something2) // Hello once? // Bye. // // turns into: // @1 (Something) // Hello! // // (...Something2) // Hello once? // // (...) // // go down. // // Bye. // If this an else if, but may not enter any of the blocks, // do a last else to the next block. if (edge.Kind == EdgeKind.IfElse && Blocks[edge.Blocks.Last()].Requirements.Count != 0) { // Create else block and its edge. int elseBlockId = CreateBlock(-1, track: false).Id; Edge? elseBlockEdge = CreateEdge(EdgeKind.Next); AssignOwnerToEdge(elseBlockId, elseBlockEdge); // Assign the block as part of the .IfElse edge. AddNode(edge, elseBlockId); // Track the block as a leaf. result.Add(elseBlockId); } } } else { if (!_blocksWithGoto.Contains(block)) { // This doesn't point to any other blocks - so it's a leaf! result.Add(block); } } } private (int Parent, int[] blocksToBeJoined) FetchParentOfJoinedBlock(int joinLevel, EdgeKind edgeKind) { int topParent; if (joinLevel == 0) { topParent = _lastBlocks.Peek(); return (topParent, new int[] { topParent }); } while (_lastBlocks.Count > 1 && joinLevel-- > 0) { int blockId = _lastBlocks.Pop(); Block block = Blocks[blockId]; // When I said I would allow one (1) hacky code, I lied. // This is another one. // SO, the indentation gets really weird for conditionals, as we pretty // much disregard one indent? I found that the best approach to handle this is // manually cleaning up the stack when there is NOT a conditional block on join. // This is also true for @[0-9] blocks, since those add an extra indentation. if (block.NonLinearNode) { if (block.Conditional) { // Nevermind the last pop: this is actually not an indent at all, as the last // block was actually a condition (and we have a minus one indent). _lastBlocks.Push(blockId); } else if (Edges[ParentOf[blockId].First()].Kind != EdgeKind.HighestScore) { // Skip indentation for non linear nodes with the default setting. // TODO: Check how that breaks join with @order? Does it actually break? // no-op. } else { joinLevel++; } } else if (!block.Conditional) { // [parent] // @1 Conditional // Line // // And the other block. // but not here: // >> something // > a // >> b // > c // > d <- if (block.PlayUntil == -1 && (!block.IsChoice || edgeKind != EdgeKind.Choice)) { joinLevel++; } } } topParent = _lastBlocks.Peek(); int[] blocksToLookForLeaves = Edges[topParent].Blocks.ToArray(); HashSet<int> leafBlocks = new(); // Now, for each of those blocks, we'll collect all of its leaves and add edges to it. foreach (int blockToJoin in blocksToLookForLeaves) { GetAllLeaves(blockToJoin, createBlockForElse: edgeKind != EdgeKind.IfElse, ref leafBlocks); } leafBlocks.Add(topParent); if (leafBlocks.Count != 0) { HashSet<int> prunnedLeafBlocks = leafBlocks.ToHashSet(); foreach (int b in prunnedLeafBlocks) { if (b != topParent) { // Whether this block will always be played or is it tied to a condition. // If this is tied to the root directly, returns -1. int conditionalParent = GetConditionalBlock(b); if (conditionalParent == -1 || conditionalParent == topParent) { prunnedLeafBlocks.Remove(topParent); } } // If the last block doesn't have any condition *but* this is actually an // if else block. // I *think* this doesn't take into account child of child blocks, but it's not // the end of the world if we have an extra edge that will never be reached. switch (Edges[b].Kind) { case EdgeKind.IfElse: if (Edges[b].Blocks.LastOrDefault() is int lastBlockId) { if (Blocks[lastBlockId].Requirements.Count == 0 && prunnedLeafBlocks.Contains(lastBlockId)) { prunnedLeafBlocks.Remove(b); } } break; case EdgeKind.HighestScore: case EdgeKind.Choice: case EdgeKind.Random: prunnedLeafBlocks.Remove(b); break; } } leafBlocks = prunnedLeafBlocks; } return (topParent, leafBlocks.ToArray()); } private int GetConditionalBlock(int block) { if (Blocks[block].PlayUntil != -1) { return block; } if (Blocks[block].Requirements.Count != 0) { return block; } if (ParentOf[block].Contains(0)) { // This is tied to the root and the block can play forever. return -1; } int result = -1; foreach (int parent in ParentOf[block]) { result = GetConditionalBlock(parent); if (result == -1) { break; } } return result; } /// <summary> /// Creates a new block and assign an id to it. /// </summary> private Block CreateBlock(int playUntil, bool track) { int id = Blocks.Count; Block block = new(id, playUntil); Blocks.Add(block); if (track) { _lastBlocks.Push(id); } ParentOf[id] = new(); return block; } private Edge CreateEdge(EdgeKind kind) { Edge relationship = new(kind); return relationship; } private void AssignOwnerToEdge(int id, Edge edge) { Edges.Add(id, edge); edge.Owner = id; // Track parents. foreach (int block in edge.Blocks) { ParentOf[block].Add(id); } } private void AddNode(Edge edge, int id) { edge.Blocks.Add(id); if (edge.Owner != -1) { ParentOf[id].Add(edge.Owner); } } /// <summary> /// Given C and D: /// Before: /// A D /// / \ /// B C /// /// D /// After: /// A C /// / \ /// B D /// This assumes that <paramref name="other"/> is an orphan. /// <paramref name="id"/> will be orphan after this. /// </summary> private void ReplaceEdgesToNodeWith(int id, int other) { if (Root == id) { Root = other; } foreach (int parent in ParentOf[id]) { // Manually tell each parent that the child has stopped existing. int position = Edges[parent].Blocks.IndexOf(id); Edges[parent].Blocks[position] = other; ParentOf[other].Add(parent); } ParentOf[id].Clear(); } private bool IsParentOf(int parentNode, int childNode) { if (ParentOf[childNode].Count == 0) { return false; } if (ParentOf[childNode].Contains(parentNode)) { return true; } foreach (int otherParent in ParentOf[childNode]) { if (IsParentOf(parentNode, otherParent)) { return true; } } return false; } public void PopLastBlock() { if (_lastBlocks.Count > 1) { _ = _lastBlocks.Pop(); } } private Edge LastEdge => Edges[_lastBlocks.Peek()]; private readonly HashSet<int> _blocksWithGoto = new(); public void MarkGotoOnBlock(int block, bool isExit) { if (isExit) { Blocks[block].Exit(); } _ = _blocksWithGoto.Add(block); } } }
src/Gum/InnerThoughts/Situation.cs
isadorasophia-gum-032cb2d
[ { "filename": "src/Gum/InnerThoughts/Block.cs", "retrieved_chunk": " /// </summary>\n public int? GoTo = null;\n public bool NonLinearNode = false;\n public bool IsChoice = false;\n public bool Conditional = false;\n public Block() { }\n public Block(int id) { Id = id; }\n public Block(int id, int playUntil) { (Id, PlayUntil) = (id, playUntil); }\n public void AddLine(string? speaker, string? portrait, string text)\n {", "score": 0.8582929372787476 }, { "filename": "src/Gum/Attributes/TokenName.cs", "retrieved_chunk": "namespace Gum.Attributes\n{\n internal class TokenNameAttribute : Attribute\n {\n public string Name;\n public TokenNameAttribute(string name)\n {\n Name = name;\n }\n }", "score": 0.8495985269546509 }, { "filename": "src/Gum/InnerThoughts/DialogAction.cs", "retrieved_chunk": " public readonly BlackboardActionKind Kind = BlackboardActionKind.Set;\n public readonly string? StrValue = null;\n public readonly int? IntValue = null;\n public readonly bool? BoolValue = null;\n public readonly string? ComponentValue = null;\n public DialogAction() { }\n public DialogAction(Fact fact, BlackboardActionKind kind, object value)\n {\n bool? @bool = null;\n int? @int = null;", "score": 0.8424723148345947 }, { "filename": "src/Gum/InnerThoughts/Edge.cs", "retrieved_chunk": " public readonly List<int> Blocks = new();\n public Edge() { }\n public Edge(EdgeKind kind) => Kind = kind;\n public string DebuggerDisplay()\n {\n StringBuilder result = new();\n result = result.Append(\n $\"[{Kind}, Blocks = {{\");\n bool isFirst = true;\n foreach (int i in Blocks)", "score": 0.8367804288864136 }, { "filename": "src/Gum.Tests/Bungee.cs", "retrieved_chunk": " Assert.AreEqual(5, target.Owner);\n CollectionAssert.AreEqual(new int[] { 6 }, target.Blocks);\n }\n [TestMethod]\n public void TestNestedChoice()\n {\n const string situationText = @\"\n=Encounter\n >> No job...\n > All my paperwork is set, sir.", "score": 0.8324044346809387 } ]
csharp
Block> Blocks = new();
using VRC.SDK3.Data; using Koyashiro.GenericDataContainer.Internal; namespace Koyashiro.GenericDataContainer { public static class DataDictionaryExt { public static int Count<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary) { var dataDictionary = (DataDictionary)(object)(dictionary); return dataDictionary.Count; } public static void Add<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary, TKey key, TValue value) { var dataDictionary = (DataDictionary)(object)(dictionary); var keyToken = DataTokenUtil.NewDataToken(key); var valueToken = DataTokenUtil.NewDataToken(value); dataDictionary.Add(keyToken, valueToken); } public static void Clear<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary) { var dataDictionary = (DataDictionary)(object)(dictionary); dataDictionary.Clear(); } public static bool ContainsKey<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary, TKey key) { var dataDictionary = (DataDictionary)(object)(dictionary); var keyToken = DataTokenUtil.NewDataToken(key); return dataDictionary.ContainsKey(keyToken); } public static bool ContainsValue<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary, TValue value) { var dataDictionary = (DataDictionary)(object)(dictionary); var keyValue = DataTokenUtil.NewDataToken(value); return dataDictionary.ContainsValue(keyValue); } public static DataDictionary<TKey, TValue> DeepClohne<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary) { var dataDictionary = (DataDictionary)(object)(dictionary); return (DataDictionary<TKey, TValue>)(object)dataDictionary.DeepClone(); } public static DataList<TKey> GetKeys<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary) { var dataDictionary = (DataDictionary)(object)(dictionary); return (DataList<TKey>)(object)dataDictionary.GetKeys(); } public static DataList<TValue> GetValues<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary) { var dataDictionary = (DataDictionary)(object)(dictionary); return (DataList<TValue>)(object)dataDictionary.GetValues(); } public static bool Remove<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary, TKey key) { var dataDictionary = (DataDictionary)(object)(dictionary); var keyToken = DataTokenUtil.NewDataToken(key); return dataDictionary.Remove(keyToken); } public static bool Remove<TKey, TValue>(this
DataDictionary<TKey, TValue> dictionary, TKey key, out TValue value) {
var dataDictionary = (DataDictionary)(object)(dictionary); var keyToken = DataTokenUtil.NewDataToken(key); var result = dataDictionary.Remove(keyToken, out var valueToken); switch (valueToken.TokenType) { case TokenType.Reference: value = (TValue)valueToken.Reference; break; default: value = (TValue)(object)valueToken; break; } return result; } public static void SetValue<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary, TKey key, TValue value) { var dataDictionary = (DataDictionary)(object)(dictionary); var keyToken = DataTokenUtil.NewDataToken(key); var keyValue = DataTokenUtil.NewDataToken(value); dataDictionary.SetValue(keyToken, keyValue); } public static DataDictionary<TKey, TValue> ShallowClone<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary) { var dataDictionary = (DataDictionary)(object)(dictionary); return (DataDictionary<TKey, TValue>)(object)dataDictionary.ShallowClone(); } public static bool TryGetValue<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary, TKey key, out TValue value) { var dataDictionary = (DataDictionary)(object)(dictionary); var keyToken = DataTokenUtil.NewDataToken(key); if (!dataDictionary.TryGetValue(keyToken, out var valueToken)) { value = default; return false; } switch (valueToken.TokenType) { case TokenType.Reference: value = (TValue)valueToken.Reference; break; default: value = (TValue)(object)valueToken; break; } return true; } public static TValue GetValue<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary, TKey key) { var dataDictionary = (DataDictionary)(object)(dictionary); var keyToken = DataTokenUtil.NewDataToken(key); var valueToken = dataDictionary[keyToken]; switch (valueToken.TokenType) { case TokenType.Reference: return (TValue)valueToken.Reference; default: return (TValue)(object)valueToken; } } } }
Packages/net.koyashiro.genericdatacontainer/Runtime/DataDictionaryExt.cs
koyashiro-generic-data-container-1aef372
[ { "filename": "Packages/net.koyashiro.genericdatacontainer/Runtime/DataListExt.cs", "retrieved_chunk": " dataList.Clear();\n }\n public static bool Contains<T>(this DataList<T> list, T item)\n {\n var dataList = (DataList)(object)(list);\n var token = DataTokenUtil.NewDataToken(item);\n return dataList.Contains(token);\n }\n public static DataList<T> DeepClone<T>(this DataList<T> list)\n {", "score": 0.8543410301208496 }, { "filename": "Packages/net.koyashiro.genericdatacontainer/Runtime/DataListExt.cs", "retrieved_chunk": " }\n public static void BinarySearch<T>(this DataList<T> list, int index, int count, T item)\n {\n var dataList = (DataList)(object)(list);\n var token = DataTokenUtil.NewDataToken(item);\n dataList.BinarySearch(index, count, token);\n }\n public static void Clear<T>(this DataList<T> list)\n {\n var dataList = (DataList)(object)(list);", "score": 0.8371858596801758 }, { "filename": "Packages/net.koyashiro.genericdatacontainer/Runtime/DataListExt.cs", "retrieved_chunk": " var token = DataTokenUtil.NewDataToken(item);\n return dataList.LastIndexOf(token, index, count);\n }\n public static bool Remove<T>(this DataList<T> list, T item)\n {\n var dataList = (DataList)(object)(list);\n var token = DataTokenUtil.NewDataToken(item);\n return dataList.Remove(token);\n }\n public static bool RemoveAll<T>(this DataList<T> list, T item)", "score": 0.8357391953468323 }, { "filename": "Packages/net.koyashiro.genericdatacontainer/Runtime/DataListExt.cs", "retrieved_chunk": " }\n public static int LastIndexOf<T>(this DataList<T> list, T item, int index)\n {\n var dataList = (DataList)(object)(list);\n var token = DataTokenUtil.NewDataToken(item);\n return dataList.LastIndexOf(token, index);\n }\n public static int LastIndexOf<T>(this DataList<T> list, T item, int index, int count)\n {\n var dataList = (DataList)(object)(list);", "score": 0.8306873440742493 }, { "filename": "Packages/net.koyashiro.genericdatacontainer/Runtime/DataListExt.cs", "retrieved_chunk": " dataList.Add(token);\n }\n public static void AddRange<T>(this DataList<T> list, T[] collection)\n {\n foreach (var item in collection)\n {\n list.Add(item);\n }\n }\n public static void AddRange<T>(this DataList<T> list, DataList<T> collection)", "score": 0.8206758499145508 } ]
csharp
DataDictionary<TKey, TValue> dictionary, TKey key, out TValue value) {
using BepInEx; using UnityEngine; using UnityEngine.SceneManagement; using System; using HarmonyLib; using System.IO; using Ultrapain.Patches; using System.Linq; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Reflection; using Steamworks; using Unity.Audio; using System.Text; using System.Collections.Generic; using UnityEngine.AddressableAssets; using UnityEngine.AddressableAssets.ResourceLocators; using UnityEngine.ResourceManagement.ResourceLocations; using UnityEngine.UIElements; using PluginConfig.API; namespace Ultrapain { [BepInPlugin(PLUGIN_GUID, PLUGIN_NAME, PLUGIN_VERSION)] [BepInDependency("com.eternalUnion.pluginConfigurator", "1.6.0")] public class Plugin : BaseUnityPlugin { public const string PLUGIN_GUID = "com.eternalUnion.ultraPain"; public const string PLUGIN_NAME = "Ultra Pain"; public const string PLUGIN_VERSION = "1.1.0"; public static Plugin instance; private static bool addressableInit = false; public static T LoadObject<T>(string path) { if (!addressableInit) { Addressables.InitializeAsync().WaitForCompletion(); addressableInit = true; } return Addressables.LoadAssetAsync<T>(path).WaitForCompletion(); } public static Vector3 PredictPlayerPosition(Collider safeCollider, float speedMod) { Transform target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f) return target.position; RaycastHit raycastHit; if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == safeCollider) return target.position; else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide)) { return raycastHit.point; } else { Vector3 projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod; return new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z); } } public static GameObject projectileSpread; public static GameObject homingProjectile; public static GameObject hideousMassProjectile; public static GameObject decorativeProjectile2; public static GameObject shotgunGrenade; public static GameObject beam; public static GameObject turretBeam; public static GameObject lightningStrikeExplosiveSetup; public static GameObject lightningStrikeExplosive; public static GameObject lighningStrikeWindup; public static GameObject explosion; public static GameObject bigExplosion; public static GameObject sandExplosion; public static GameObject virtueInsignia; public static GameObject rocket; public static GameObject revolverBullet; public static GameObject maliciousCannonBeam; public static GameObject lightningBoltSFX; public static GameObject revolverBeam; public static GameObject blastwave; public static GameObject cannonBall; public static GameObject shockwave; public static GameObject sisyphiusExplosion; public static GameObject sisyphiusPrimeExplosion; public static GameObject explosionWaveKnuckleblaster; public static GameObject chargeEffect; public static GameObject maliciousFaceProjectile; public static GameObject hideousMassSpear; public static GameObject coin; public static GameObject sisyphusDestroyExplosion; //public static GameObject idol; public static GameObject ferryman; public static GameObject minosPrime; //public static GameObject maliciousFace; public static GameObject somethingWicked; public static Turret turret; public static GameObject turretFinalFlash; public static GameObject enrageEffect; public static GameObject v2flashUnparryable; public static GameObject ricochetSfx; public static GameObject parryableFlash; public static AudioClip cannonBallChargeAudio; public static Material gabrielFakeMat; public static Sprite blueRevolverSprite; public static Sprite greenRevolverSprite; public static Sprite redRevolverSprite; public static Sprite blueShotgunSprite; public static Sprite greenShotgunSprite; public static Sprite blueNailgunSprite; public static Sprite greenNailgunSprite; public static Sprite blueSawLauncherSprite; public static Sprite greenSawLauncherSprite; public static GameObject rocketLauncherAlt; public static GameObject maliciousRailcannon; // Variables public static float SoliderShootAnimationStart = 1.2f; public static float SoliderGrenadeForce = 10000f; public static float SwordsMachineKnockdownTimeNormalized = 0.8f; public static float SwordsMachineCoreSpeed = 80f; public static float MinGrenadeParryVelocity = 40f; public static GameObject _lighningBoltSFX; public static GameObject lighningBoltSFX { get { if (_lighningBoltSFX == null) _lighningBoltSFX = ferryman.gameObject.transform.Find("LightningBoltChimes").gameObject; return _lighningBoltSFX; } } private static bool loadedPrefabs = false; public void LoadPrefabs() { if (loadedPrefabs) return; loadedPrefabs = true; // Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab projectileSpread = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab homingProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab decorativeProjectile2 = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab"); // Assets/Prefabs/Attacks and Projectiles/Grenade.prefab shotgunGrenade = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Grenade.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab turretBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab beam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab lightningStrikeExplosiveSetup = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab"); // Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab lighningStrikeWindup = LoadObject<GameObject>("Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab"); //[bundle-0][assets/prefabs/enemies/idol.prefab] //idol = LoadObject<GameObject>("assets/prefabs/enemies/idol.prefab"); // Assets/Prefabs/Enemies/Ferryman.prefab ferryman = LoadObject<GameObject>("Assets/Prefabs/Enemies/Ferryman.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab explosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab bigExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab sandExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab"); // Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab virtueInsignia = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab hideousMassProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab"); // Assets/Particles/Enemies/RageEffect.prefab enrageEffect = LoadObject<GameObject>("Assets/Particles/Enemies/RageEffect.prefab"); // Assets/Particles/Flashes/V2FlashUnparriable.prefab v2flashUnparryable = LoadObject<GameObject>("Assets/Particles/Flashes/V2FlashUnparriable.prefab"); // Assets/Prefabs/Attacks and Projectiles/Rocket.prefab rocket = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Rocket.prefab"); // Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab revolverBullet = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab maliciousCannonBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab revolverBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab blastwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab"); // Assets/Prefabs/Enemies/MinosPrime.prefab minosPrime = LoadObject<GameObject>("Assets/Prefabs/Enemies/MinosPrime.prefab"); // Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab cannonBall = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab"); // get from Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab cannonBallChargeAudio = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab").transform.Find("RocketLauncher/Armature/Body_Bone/HologramDisplay").GetComponent<AudioSource>().clip; // Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab shockwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab sisyphiusExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab sisyphiusPrimeExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab explosionWaveKnuckleblaster = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab - [bundle-0][assets/prefabs/explosionlightning variant.prefab] lightningStrikeExplosive = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab"); // Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab rocketLauncherAlt = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab"); // Assets/Prefabs/Weapons/Railcannon Malicious.prefab maliciousRailcannon = LoadObject<GameObject>("Assets/Prefabs/Weapons/Railcannon Malicious.prefab"); //Assets/Particles/SoundBubbles/Ricochet.prefab ricochetSfx = LoadObject<GameObject>("Assets/Particles/SoundBubbles/Ricochet.prefab"); //Assets/Particles/Flashes/Flash.prefab parryableFlash = LoadObject<GameObject>("Assets/Particles/Flashes/Flash.prefab"); //Assets/Prefabs/Attacks and Projectiles/Spear.prefab hideousMassSpear = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Spear.prefab"); //Assets/Prefabs/Enemies/Wicked.prefab somethingWicked = LoadObject<GameObject>("Assets/Prefabs/Enemies/Wicked.prefab"); //Assets/Textures/UI/SingleRevolver.png blueRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/SingleRevolver.png"); //Assets/Textures/UI/RevolverSpecial.png greenRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSpecial.png"); //Assets/Textures/UI/RevolverSharp.png redRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSharp.png"); //Assets/Textures/UI/Shotgun.png blueShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun.png"); //Assets/Textures/UI/Shotgun1.png greenShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun1.png"); //Assets/Textures/UI/Nailgun2.png blueNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Nailgun2.png"); //Assets/Textures/UI/NailgunOverheat.png greenNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/NailgunOverheat.png"); //Assets/Textures/UI/SawbladeLauncher.png blueSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncher.png"); //Assets/Textures/UI/SawbladeLauncherOverheat.png greenSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncherOverheat.png"); //Assets/Prefabs/Attacks and Projectiles/Coin.prefab coin = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Coin.prefab"); //Assets/Materials/GabrielFake.mat gabrielFakeMat = LoadObject<Material>("Assets/Materials/GabrielFake.mat"); //Assets/Prefabs/Enemies/Turret.prefab turret = LoadObject<GameObject>("Assets/Prefabs/Enemies/Turret.prefab").GetComponent<Turret>(); //Assets/Particles/Flashes/GunFlashDistant.prefab turretFinalFlash = LoadObject<GameObject>("Assets/Particles/Flashes/GunFlashDistant.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab sisyphusDestroyExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab"); //Assets/Prefabs/Effects/Charge Effect.prefab chargeEffect = LoadObject<GameObject>("Assets/Prefabs/Effects/Charge Effect.prefab"); //Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab maliciousFaceProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab"); } public static bool ultrapainDifficulty = false; public static bool realUltrapainDifficulty = false; public static GameObject currentDifficultyButton; public static GameObject currentDifficultyPanel; public static Text currentDifficultyInfoText; public void OnSceneChange(Scene before, Scene after) { StyleIDs.RegisterIDs(); ScenePatchCheck(); string mainMenuSceneName = "b3e7f2f8052488a45b35549efb98d902"; string bootSequenceSceneName = "4f8ecffaa98c2614f89922daf31fa22d"; string currentSceneName = SceneManager.GetActiveScene().name; if (currentSceneName == mainMenuSceneName) { LoadPrefabs(); //Canvas/Difficulty Select (1)/Violent Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Difficulty Select (1)"); GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect); currentDifficultyButton = ultrapainButton; ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value; ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5; RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>(); ultrapainTrans.anchoredPosition = new Vector2(20f, -104f); //Canvas/Difficulty Select (1)/Violent Info GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect); currentDifficultyPanel = info; currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>(); currentDifficultyInfoText.text = ConfigManager.pluginInfo.value; Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>(); currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--"; currentDifficultyHeaderText.resizeTextForBestFit = true; currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap; currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate; info.SetActive(false); EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>(); evt.triggers.Clear(); /*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(false));*/ EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit }; trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false)); evt.triggers.Add(trigger1); evt.triggers.Add(trigger2); foreach(EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>()) { if (trigger.gameObject == ultrapainButton) continue; EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false)); trigger.triggers.Add(closeTrigger); } } else if(currentSceneName == bootSequenceSceneName) { LoadPrefabs(); //Canvas/Difficulty Select (1)/Violent Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Intro/Difficulty Select"); GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect); currentDifficultyButton = ultrapainButton; ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value; ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5; RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>(); ultrapainTrans.anchoredPosition = new Vector2(20f, -104f); //Canvas/Difficulty Select (1)/Violent Info GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect); currentDifficultyPanel = info; currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>(); currentDifficultyInfoText.text = ConfigManager.pluginInfo.value; Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>(); currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--"; currentDifficultyHeaderText.resizeTextForBestFit = true; currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap; currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate; info.SetActive(false); EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>(); evt.triggers.Clear(); /*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(false));*/ EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit }; trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false)); evt.triggers.Add(trigger1); evt.triggers.Add(trigger2); foreach (EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>()) { if (trigger.gameObject == ultrapainButton) continue; EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false)); trigger.triggers.Add(closeTrigger); } } // LOAD CUSTOM PREFABS HERE TO AVOID MID GAME LAG MinosPrimeCharge.CreateDecoy(); GameObject shockwaveSisyphus = SisyphusInstructionist_Start.shockwave; } public static class StyleIDs { private static bool registered = false; public static void RegisterIDs() { registered = false; if (MonoSingleton<StyleHUD>.Instance == null) return; MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.grenadeBoostStyleText.guid, ConfigManager.grenadeBoostStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.rocketBoostStyleText.guid, ConfigManager.rocketBoostStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverStyleText.guid, ConfigManager.orbStrikeRevolverStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverChargedStyleText.guid, ConfigManager.orbStrikeRevolverChargedStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeElectricCannonStyleText.guid, ConfigManager.orbStrikeElectricCannonStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeMaliciousCannonStyleText.guid, ConfigManager.orbStrikeMaliciousCannonStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.maliciousChargebackStyleText.guid, ConfigManager.maliciousChargebackStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.sentryChargebackStyleText.guid, ConfigManager.sentryChargebackStyleText.formattedString); registered = true; Debug.Log("Registered all style ids"); } private static FieldInfo idNameDict = typeof(StyleHUD).GetField("idNameDict", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); public static void UpdateID(string id, string newName) { if (!registered || StyleHUD.Instance == null) return; (idNameDict.GetValue(StyleHUD.Instance) as Dictionary<string, string>)[id] = newName; } } public static Harmony harmonyTweaks; public static
Harmony harmonyBase;
private static MethodInfo GetMethod<T>(string name) { return typeof(T).GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } private static Dictionary<MethodInfo, HarmonyMethod> methodCache = new Dictionary<MethodInfo, HarmonyMethod>(); private static HarmonyMethod GetHarmonyMethod(MethodInfo method) { if (methodCache.TryGetValue(method, out HarmonyMethod harmonyMethod)) return harmonyMethod; else { harmonyMethod = new HarmonyMethod(method); methodCache.Add(method, harmonyMethod); return harmonyMethod; } } private static void PatchAllEnemies() { if (!ConfigManager.enemyTweakToggle.value) return; if (ConfigManager.friendlyFireDamageOverrideToggle.value) { harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<PhysicalShockwave>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<VirtueInsignia>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_FF>("Prefix"))); harmonyTweaks.Patch(GetMethod<Flammable>("Burn"), prefix: GetHarmonyMethod(GetMethod<Flammable_Burn_FF>("Prefix"))); harmonyTweaks.Patch(GetMethod<FireZone>("OnTriggerStay"), prefix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Postfix"))); } harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("UpdateModifiers"), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_UpdateModifiers>("Postfix"))); harmonyTweaks.Patch(GetMethod<StatueBoss>("Start"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Start_Patch>("Postfix"))); if (ConfigManager.cerberusDashToggle.value) harmonyTweaks.Patch(GetMethod<StatueBoss>("StopDash"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopDash_Patch>("Postfix"))); if(ConfigManager.cerberusParryable.value) { harmonyTweaks.Patch(GetMethod<StatueBoss>("StopTracking"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopTracking_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<StatueBoss>("Stomp"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Stomp_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Statue>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Statue_GetHurt_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Drone_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Drone>("Shoot"), prefix: GetHarmonyMethod(GetMethod<Drone_Shoot_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("PlaySound"), prefix: GetHarmonyMethod(GetMethod<Drone_PlaySound_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Update"), postfix: GetHarmonyMethod(GetMethod<Drone_Update>("Postfix"))); if(ConfigManager.droneHomeToggle.value) { harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Drone_Death_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Drone_GetHurt_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Ferryman>("Start"), postfix: GetHarmonyMethod(GetMethod<FerrymanStart>("Postfix"))); if(ConfigManager.ferrymanComboToggle.value) harmonyTweaks.Patch(GetMethod<Ferryman>("StopMoving"), postfix: GetHarmonyMethod(GetMethod<FerrymanStopMoving>("Postfix"))); if(ConfigManager.filthExplodeToggle.value) harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch2>("Prefix"))); if(ConfigManager.fleshPrisonSpinAttackToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<FleshPrisonShoot>("Postfix"))); if (ConfigManager.hideousMassInsigniaToggle.value) { harmonyTweaks.Patch(GetMethod<Projectile>("Explode"), postfix: GetHarmonyMethod(GetMethod<Projectile_Explode_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Mass>("ShootExplosive"), postfix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Postfix")), prefix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Prefix"))); } harmonyTweaks.Patch(GetMethod<SpiderBody>("Start"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<SpiderBody>("ChargeBeam"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ChargeBeam>("Postfix"))); harmonyTweaks.Patch(GetMethod<SpiderBody>("BeamChargeEnd"), prefix: GetHarmonyMethod(GetMethod<MaliciousFace_BeamChargeEnd>("Prefix"))); if (ConfigManager.maliciousFaceHomingProjectileToggle.value) { harmonyTweaks.Patch(GetMethod<SpiderBody>("ShootProj"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ShootProj_Patch>("Postfix"))); } if (ConfigManager.maliciousFaceRadianceOnEnrage.value) harmonyTweaks.Patch(GetMethod<SpiderBody>("Enrage"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Enrage_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Mindflayer>("Start"), postfix: GetHarmonyMethod(GetMethod<Mindflayer_Start_Patch>("Postfix"))); if (ConfigManager.mindflayerShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<Mindflayer>("ShootProjectiles"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_ShootProjectiles_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_MF>("Prefix"))); } if (ConfigManager.mindflayerTeleportComboToggle.value) { harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Mindflayer>("MeleeTeleport"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_MeleeTeleport_Patch>("Prefix"))); //harmonyTweaks.Patch(GetMethod<SwingCheck2>("DamageStop"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_DamageStop_Patch>("Postfix"))); } if (ConfigManager.minosPrimeRandomTeleportToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("Postfix"))); if (ConfigManager.minosPrimeTeleportTrail.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("Teleport"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("TeleportPostfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Start"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Dropkick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Dropkick>("Prefix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Combo"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Combo>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("StopAction"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_StopAction>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Ascend"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Ascend>("Prefix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Death"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Death>("Prefix"))); if (ConfigManager.minosPrimeCrushAttackToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("RiderKick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_RiderKick>("Prefix"))); if (ConfigManager.minosPrimeComboExplosiveEndToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_ProjectileCharge>("Prefix"))); if (ConfigManager.schismSpreadAttackToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ShootProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ShootProjectile_Patch>("Postfix"))); if (ConfigManager.soliderShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<Solider_Start_Patch>("Postfix"))); } if(ConfigManager.soliderCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_SpawnProjectile_Patch>("Postfix"))); if (ConfigManager.soliderShootGrenadeToggle.value || ConfigManager.soliderShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_ThrowProjectile_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Stalker>("SandExplode"), prefix: GetHarmonyMethod(GetMethod<Stalker_SandExplode_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SandificationZone>("Enter"), postfix: GetHarmonyMethod(GetMethod<SandificationZone_Enter_Patch>("Postfix"))); if (ConfigManager.strayCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Swing>("Postfix"))); if (ConfigManager.strayShootToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_Start_Patch1>("Postfix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ThrowProjectile_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<SwingEnd>("Prefix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("DamageEnd"), prefix: GetHarmonyMethod(GetMethod<DamageEnd>("Prefix"))); } if(ConfigManager.streetCleanerCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<Streetcleaner>("Start"), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Start_Patch>("Postfix"))); if(ConfigManager.streetCleanerPredictiveDodgeToggle.value) harmonyTweaks.Patch(GetMethod<BulletCheck>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<BulletCheck_OnTriggerEnter_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("Start"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Start>("Postfix"))); if (ConfigManager.swordsMachineNoLightKnockbackToggle.value || ConfigManager.swordsMachineSecondPhaseMode.value != ConfigManager.SwordsMachineSecondPhase.None) { harmonyTweaks.Patch(GetMethod<SwordsMachine>("Knockdown"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Knockdown_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("Down"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Prefix"))); //harmonyTweaks.Patch(GetMethod<SwordsMachine>("SetSpeed"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_SetSpeed_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("EndFirstPhase"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Prefix"))); } if (ConfigManager.swordsMachineExplosiveSwordToggle.value) { harmonyTweaks.Patch(GetMethod<ThrownSword>("Start"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<ThrownSword>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_OnTriggerEnter_Patch>("Postfix"))); } harmonyTweaks.Patch(GetMethod<Turret>("Start"), postfix: GetHarmonyMethod(GetMethod<TurretStart>("Postfix"))); if(ConfigManager.turretBurstFireToggle.value) { harmonyTweaks.Patch(GetMethod<Turret>("Shoot"), prefix: GetHarmonyMethod(GetMethod<TurretShoot>("Prefix"))); harmonyTweaks.Patch(GetMethod<Turret>("StartAiming"), postfix: GetHarmonyMethod(GetMethod<TurretAim>("Postfix"))); } harmonyTweaks.Patch(GetMethod<Explosion>("Start"), postfix: GetHarmonyMethod(GetMethod<V2CommonExplosion>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2FirstStart>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2FirstUpdate>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2FirstShootWeapon>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2SecondStart>("Postfix"))); //if(ConfigManager.v2SecondStartEnraged.value) // harmonyTweaks.Patch(GetMethod<BossHealthBar>("OnEnable"), postfix: GetHarmonyMethod(GetMethod<V2SecondEnrage>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2SecondUpdate>("Prefix"))); //harmonyTweaks.Patch(GetMethod<V2>("AltShootWeapon"), postfix: GetHarmonyMethod(GetMethod<V2AltShootWeapon>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("SwitchWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondSwitchWeapon>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Prefix")), postfix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Postfix"))); if(ConfigManager.v2SecondFastCoinToggle.value) harmonyTweaks.Patch(GetMethod<V2>("ThrowCoins"), prefix: GetHarmonyMethod(GetMethod<V2SecondFastCoin>("Prefix"))); harmonyTweaks.Patch(GetMethod<Cannonball>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<V2RocketLauncher>("CannonBallTriggerPrefix"))); if (ConfigManager.v2FirstSharpshooterToggle.value || ConfigManager.v2SecondSharpshooterToggle.value) { harmonyTweaks.Patch(GetMethod<EnemyRevolver>("PrepareAltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverPrepareAltFire>("Prefix"))); harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverBullet>("Prefix"))); harmonyTweaks.Patch(GetMethod<EnemyRevolver>("AltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverAltShoot>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Virtue_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Drone>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Virtue_SpawnInsignia_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Virtue_Death_Patch>("Prefix"))); if (ConfigManager.sisyInstJumpShockwave.value) { harmonyTweaks.Patch(GetMethod<Sisyphus>("Start"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Sisyphus>("Update"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Update>("Postfix"))); } if(ConfigManager.sisyInstBoulderShockwave.value) harmonyTweaks.Patch(GetMethod<Sisyphus>("SetupExplosion"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_SetupExplosion>("Postfix"))); if(ConfigManager.sisyInstStrongerExplosion.value) harmonyTweaks.Patch(GetMethod<Sisyphus>("StompExplosion"), prefix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_StompExplosion>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("Awake"), postfix: GetHarmonyMethod(GetMethod<LeviathanTail_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("BigSplash"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_BigSplash>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_SwingEnd>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("Start"), postfix: GetHarmonyMethod(GetMethod<Leviathan_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurst"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurstStart"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurstStart>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<Leviathan_FixedUpdate>("Prefix"))); if (ConfigManager.somethingWickedSpear.value) { harmonyTweaks.Patch(GetMethod<Wicked>("Start"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_GetHit>("Postfix"))); } if(ConfigManager.somethingWickedSpawnOn43.value) { harmonyTweaks.Patch(GetMethod<ObjectActivator>("Activate"), prefix: GetHarmonyMethod(GetMethod<ObjectActivator_Activate>("Prefix"))); harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<JokeWicked_GetHit>("Postfix"))); } if (ConfigManager.panopticonFullPhase.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Panopticon_Start>("Postfix"))); if (ConfigManager.panopticonAxisBeam.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnInsignia>("Prefix"))); if (ConfigManager.panopticonSpinAttackToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<Panopticon_HomingProjectileAttack>("Postfix"))); if (ConfigManager.panopticonBlackholeProj.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnBlackHole"), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnBlackHole>("Postfix"))); if (ConfigManager.panopticonBalanceEyes.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnFleshDrones"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Postfix"))); if (ConfigManager.panopticonBlueProjToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Update"), transpiler: GetHarmonyMethod(GetMethod<Panopticon_BlueProjectile>("Transpiler"))); if (ConfigManager.idolExplosionToggle.value) harmonyTweaks.Patch(GetMethod<Idol>("Death"), postfix: GetHarmonyMethod(GetMethod<Idol_Death_Patch>("Postfix"))); // ADDME /* harmonyTweaks.Patch(GetMethod<GabrielSecond>("Start"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("BasicCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_BasicCombo>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("FastCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_FastCombo>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("CombineSwords"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_CombineSwords>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("ThrowCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_ThrowCombo>("Postfix"))); */ } private static void PatchAllPlayers() { if (!ConfigManager.playerTweakToggle.value) return; harmonyTweaks.Patch(GetMethod<Punch>("CheckForProjectile"), prefix: GetHarmonyMethod(GetMethod<Punch_CheckForProjectile_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch1>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Collision"), prefix: GetHarmonyMethod(GetMethod<Grenade_Collision_Patch>("Prefix"))); if (ConfigManager.rocketBoostToggle.value) harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_Patch>("Prefix"))); if (ConfigManager.rocketGrabbingToggle.value) harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate_Patch>("Prefix"))); if (ConfigManager.orbStrikeToggle.value) { harmonyTweaks.Patch(GetMethod<Coin>("Start"), postfix: GetHarmonyMethod(GetMethod<Coin_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Punch>("BlastCheck"), prefix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Postfix"))); harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide>("Prefix"))); harmonyTweaks.Patch(GetMethod<Coin>("DelayedReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_DelayedReflectRevolver>("Postfix"))); harmonyTweaks.Patch(GetMethod<Coin>("ReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Postfix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Prefix")), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Postfix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("ExecuteHits"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Prefix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("HitSomething"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Prefix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("Start"), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_Start>("Prefix"))); harmonyTweaks.Patch(GetMethod<Cannonball>("Explode"), prefix: GetHarmonyMethod(GetMethod<Cannonball_Explode>("Prefix"))); harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_CollideOrbital>("Prefix"))); } if(ConfigManager.chargedRevRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<Revolver>("Update"), prefix: GetHarmonyMethod(GetMethod<Revolver_Update>("Prefix"))); if(ConfigManager.coinRegSpeedMulti.value != 1 || ConfigManager.sharpshooterRegSpeedMulti.value != 1 || ConfigManager.railcannonRegSpeedMulti.value != 1 || ConfigManager.rocketFreezeRegSpeedMulti.value != 1 || ConfigManager.rocketCannonballRegSpeedMulti.value != 1 || ConfigManager.nailgunAmmoRegSpeedMulti.value != 1 || ConfigManager.sawAmmoRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<WeaponCharges>("Charge"), prefix: GetHarmonyMethod(GetMethod<WeaponCharges_Charge>("Prefix"))); if(ConfigManager.nailgunHeatsinkRegSpeedMulti.value != 1 || ConfigManager.sawHeatsinkRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<Nailgun>("Update"), prefix: GetHarmonyMethod(GetMethod<NailGun_Update>("Prefix"))); if(ConfigManager.staminaRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<NewMovement>("Update"), prefix: GetHarmonyMethod(GetMethod<NewMovement_Update>("Prefix"))); if(ConfigManager.playerHpDeltaToggle.value || ConfigManager.maxPlayerHp.value != 100 || ConfigManager.playerHpSupercharge.value != 200 || ConfigManager.whiplashHardDamageCap.value != 50 || ConfigManager.whiplashHardDamageSpeed.value != 1) { harmonyTweaks.Patch(GetMethod<NewMovement>("GetHealth"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHealth>("Prefix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("SuperCharge"), prefix: GetHarmonyMethod(GetMethod<NewMovement_SuperCharge>("Prefix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("Respawn"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Respawn>("Postfix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("Start"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Transpiler"))); harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), transpiler: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate>("Transpiler"))); harmonyTweaks.Patch(GetMethod<NewMovement>("ForceAntiHP"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_ForceAntiHP>("Transpiler"))); } // ADDME harmonyTweaks.Patch(GetMethod<Revolver>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Revolver_Shoot>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Shotgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Transpiler")), prefix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Postfix"))); harmonyTweaks.Patch(GetMethod<Shotgun>("ShootSinks"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_ShootSinks>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Nailgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_Shoot>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Nailgun>("SuperSaw"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_SuperSaw>("Transpiler"))); if (ConfigManager.hardDamagePercent.normalizedValue != 1) harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Prefix")), postfix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Postfix"))); harmonyTweaks.Patch(GetMethod<HealthBar>("Start"), postfix: GetHarmonyMethod(GetMethod<HealthBar_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<HealthBar>("Update"), transpiler: GetHarmonyMethod(GetMethod<HealthBar_Update>("Transpiler"))); foreach (HealthBarTracker hb in HealthBarTracker.instances) { if (hb != null) hb.SetSliderRange(); } harmonyTweaks.Patch(GetMethod<Harpoon>("Start"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Start>("Postfix"))); if(ConfigManager.screwDriverHomeToggle.value) harmonyTweaks.Patch(GetMethod<Harpoon>("Punched"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Punched>("Postfix"))); if(ConfigManager.screwDriverSplitToggle.value) harmonyTweaks.Patch(GetMethod<Harpoon>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<Harpoon_OnTriggerEnter_Patch>("Prefix"))); } private static void PatchAllMemes() { if (ConfigManager.enrageSfxToggle.value) harmonyTweaks.Patch(GetMethod<EnrageEffect>("Start"), postfix: GetHarmonyMethod(GetMethod<EnrageEffect_Start>("Postfix"))); if(ConfigManager.funnyDruidKnightSFXToggle.value) { harmonyTweaks.Patch(GetMethod<Mandalore>("FullBurst"), postfix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Postfix")), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<Mandalore>("FullerBurst"), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullerBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Explode"), prefix: GetHarmonyMethod(GetMethod<Drone_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Drone_Explode>("Postfix"))); } if (ConfigManager.fleshObamiumToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Prefix"))); if (ConfigManager.obamapticonToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Prefix"))); } public static bool methodsPatched = false; public static void ScenePatchCheck() { if(methodsPatched && !ultrapainDifficulty) { harmonyTweaks.UnpatchSelf(); methodsPatched = false; } else if(!methodsPatched && ultrapainDifficulty) { PatchAll(); } } public static void PatchAll() { harmonyTweaks.UnpatchSelf(); methodsPatched = false; if (!ultrapainDifficulty) return; if(realUltrapainDifficulty && ConfigManager.discordRichPresenceToggle.value) harmonyTweaks.Patch(GetMethod<DiscordController>("SendActivity"), prefix: GetHarmonyMethod(GetMethod<DiscordController_SendActivity_Patch>("Prefix"))); if (realUltrapainDifficulty && ConfigManager.steamRichPresenceToggle.value) harmonyTweaks.Patch(GetMethod<SteamFriends>("SetRichPresence"), prefix: GetHarmonyMethod(GetMethod<SteamFriends_SetRichPresence_Patch>("Prefix"))); PatchAllEnemies(); PatchAllPlayers(); PatchAllMemes(); methodsPatched = true; } public static string workingPath; public static string workingDir; public static AssetBundle bundle; public static AudioClip druidKnightFullAutoAud; public static AudioClip druidKnightFullerAutoAud; public static AudioClip druidKnightDeathAud; public static AudioClip enrageAudioCustom; public static GameObject fleshObamium; public static GameObject obamapticon; public void Awake() { instance = this; workingPath = Assembly.GetExecutingAssembly().Location; workingDir = Path.GetDirectoryName(workingPath); Logger.LogInfo($"Working path: {workingPath}, Working dir: {workingDir}"); try { bundle = AssetBundle.LoadFromFile(Path.Combine(workingDir, "ultrapain")); druidKnightFullAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullauto.wav"); druidKnightFullerAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullerauto.wav"); druidKnightDeathAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/death.wav"); enrageAudioCustom = bundle.LoadAsset<AudioClip>("assets/ultrapain/sfx/enraged.wav"); fleshObamium = bundle.LoadAsset<GameObject>("assets/ultrapain/fleshprison/fleshobamium.prefab"); obamapticon = bundle.LoadAsset<GameObject>("assets/ultrapain/panopticon/obamapticon.prefab"); } catch (Exception e) { Logger.LogError($"Could not load the asset bundle:\n{e}"); } // DEBUG /*string logPath = Path.Combine(Environment.CurrentDirectory, "log.txt"); Logger.LogInfo($"Saving to {logPath}"); List<string> assetPaths = new List<string>() { "fonts.bundle", "videos.bundle", "shaders.bundle", "particles.bundle", "materials.bundle", "animations.bundle", "prefabs.bundle", "physicsmaterials.bundle", "models.bundle", "textures.bundle", }; //using (FileStream log = File.Open(logPath, FileMode.OpenOrCreate, FileAccess.Write)) //{ foreach(string assetPath in assetPaths) { Logger.LogInfo($"Attempting to load {assetPath}"); AssetBundle bundle = AssetBundle.LoadFromFile(Path.Combine(bundlePath, assetPath)); bundles.Add(bundle); //foreach (string name in bundle.GetAllAssetNames()) //{ // string line = $"[{bundle.name}][{name}]\n"; // log.Write(Encoding.ASCII.GetBytes(line), 0, line.Length); //} bundle.LoadAllAssets(); } //} */ // Plugin startup logic Logger.LogInfo($"Plugin {PluginInfo.PLUGIN_GUID} is loaded!"); harmonyTweaks = new Harmony(PLUGIN_GUID + "_tweaks"); harmonyBase = new Harmony(PLUGIN_GUID + "_base"); harmonyBase.Patch(GetMethod<DifficultySelectButton>("SetDifficulty"), postfix: GetHarmonyMethod(GetMethod<DifficultySelectPatch>("Postfix"))); harmonyBase.Patch(GetMethod<DifficultyTitle>("Check"), postfix: GetHarmonyMethod(GetMethod<DifficultyTitle_Check_Patch>("Postfix"))); harmonyBase.Patch(typeof(PrefsManager).GetConstructor(new Type[0]), postfix: GetHarmonyMethod(GetMethod<PrefsManager_Ctor>("Postfix"))); harmonyBase.Patch(GetMethod<PrefsManager>("EnsureValid"), prefix: GetHarmonyMethod(GetMethod<PrefsManager_EnsureValid>("Prefix"))); harmonyBase.Patch(GetMethod<Grenade>("Explode"), prefix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Prefix")), postfix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Postfix"))); LoadPrefabs(); ConfigManager.Initialize(); SceneManager.activeSceneChanged += OnSceneChange; } } public static class Tools { private static Transform _target; private static Transform target { get { if(_target == null) _target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); return _target; } } public static Vector3 PredictPlayerPosition(float speedMod, Collider enemyCol = null) { Vector3 projectedPlayerPos; if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f) { return target.position; } RaycastHit raycastHit; if (enemyCol != null && Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == enemyCol) { projectedPlayerPos = target.position; } else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide)) { projectedPlayerPos = raycastHit.point; } else { projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod; projectedPlayerPos = new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z); } return projectedPlayerPos; } } // Asset destroyer tracker /*[HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object) })] public class TempClass1 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object), typeof(float) })] public class TempClass2 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object) })] public class TempClass3 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object), typeof(bool) })] public class TempClass4 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } }*/ }
Ultrapain/Plugin.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/SomethingWicked.cs", "retrieved_chunk": " public MassSpear spearComp;\n public EnemyIdentifier eid;\n public Transform spearOrigin;\n public Rigidbody spearRb;\n public static float SpearTriggerDistance = 80f;\n public static LayerMask envMask = new LayerMask() { value = (1 << 8) | (1 << 24) };\n void Awake()\n {\n if (eid == null)\n eid = GetComponent<EnemyIdentifier>();", "score": 0.7693430781364441 }, { "filename": "Ultrapain/Patches/PlayerStatTweaks.cs", "retrieved_chunk": " instances.RemoveAt(i);\n }\n }\n private void OnDestroy()\n {\n if (instances.Contains(this))\n instances.Remove(this);\n }\n public void SetSliderRange()\n {", "score": 0.7646486759185791 }, { "filename": "Ultrapain/Patches/CommonComponents.cs", "retrieved_chunk": " public Quaternion targetRotation;\n private void Awake()\n {\n transform.rotation = targetRotation;\n }\n }\n public class CommonActivator : MonoBehaviour\n {\n public int originalId;\n public Renderer rend;", "score": 0.7645328044891357 }, { "filename": "Ultrapain/Patches/Parry.cs", "retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class GrenadeParriedFlag : MonoBehaviour\n {\n public int parryCount = 1;\n public bool registeredStyle = false;\n public bool bigExplosionOverride = false;\n public GameObject temporaryExplosion;", "score": 0.7640262842178345 }, { "filename": "Ultrapain/Patches/Screwdriver.cs", "retrieved_chunk": " {\n public static float forwardForce = 10f;\n public static float upwardForce = 10f;\n static LayerMask envLayer = new LayerMask() { m_Mask = 16777472 };\n private static Harpoon lastHarpoon;\n static bool Prefix(Harpoon __instance, Collider __0)\n {\n if (!__instance.drill)\n return true;\n if(__0.TryGetComponent(out EnemyIdentifierIdentifier eii))", "score": 0.7627630233764648 } ]
csharp
Harmony harmonyBase;
using HarmonyLib; using System; using System.ComponentModel; using UnityEngine; namespace Ultrapain.Patches { class MaliciousFaceFlag : MonoBehaviour { public bool charging = false; } class MaliciousFace_Start_Patch { static void Postfix(SpiderBody __instance, ref GameObject ___proj, ref int ___maxBurst) { __instance.gameObject.AddComponent<MaliciousFaceFlag>(); if (ConfigManager.maliciousFaceHomingProjectileToggle.value) { ___proj = Plugin.homingProjectile; ___maxBurst = Math.Max(0, ConfigManager.maliciousFaceHomingProjectileCount.value - 1); } } } class MaliciousFace_ChargeBeam { static void Postfix(SpiderBody __instance) { if (__instance.TryGetComponent<MaliciousFaceFlag>(out MaliciousFaceFlag flag)) flag.charging = true; } } class MaliciousFace_BeamChargeEnd { static bool Prefix(
SpiderBody __instance, float ___maxHealth, ref int ___beamsAmount) {
if (__instance.TryGetComponent<MaliciousFaceFlag>(out MaliciousFaceFlag flag) && flag.charging) { if (__instance.health < ___maxHealth / 2) ___beamsAmount = ConfigManager.maliciousFaceBeamCountEnraged.value; else ___beamsAmount = ConfigManager.maliciousFaceBeamCountNormal.value; flag.charging = false; } return true; } } class MaliciousFace_ShootProj_Patch { /*static bool Prefix(SpiderBody __instance, ref GameObject ___proj, out bool __state) { __state = false; if (!Plugin.ultrapainDifficulty || !ConfigManager.enemyTweakToggle.value || !ConfigManager.maliciousFaceHomingProjectileToggle.value) return true; ___proj = Plugin.homingProjectile; __state = true; return true; }*/ static void Postfix(SpiderBody __instance, ref GameObject ___currentProj, EnemyIdentifier ___eid/*, bool __state*/) { /*if (!__state) return;*/ Projectile proj = ___currentProj.GetComponent<Projectile>(); proj.target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); proj.speed = ConfigManager.maliciousFaceHomingProjectileSpeed.value; proj.turningSpeedMultiplier = ConfigManager.maliciousFaceHomingProjectileTurnSpeed.value; proj.damage = ConfigManager.maliciousFaceHomingProjectileDamage.value; proj.safeEnemyType = EnemyType.MaliciousFace; proj.speed *= ___eid.totalSpeedModifier; proj.damage *= ___eid.totalDamageModifier; ___currentProj.SetActive(true); } } class MaliciousFace_Enrage_Patch { static void Postfix(SpiderBody __instance) { EnemyIdentifier comp = __instance.GetComponent<EnemyIdentifier>(); for(int i = 0; i < ConfigManager.maliciousFaceRadianceAmount.value; i++) comp.BuffAll(); comp.UpdateBuffs(false); //__instance.spark = new GameObject(); } } /*[HarmonyPatch(typeof(SpiderBody))] [HarmonyPatch("BeamChargeEnd")] class MaliciousFace_BeamChargeEnd_Patch { static void Postfix(SpiderBody __instance, ref bool ___parryable) { if (__instance.currentEnrageEffect == null) return; ___parryable = false; } }*/ /*[HarmonyPatch(typeof(HookArm))] [HarmonyPatch("FixedUpdate")] class HookArm_FixedUpdate_MaliciousFacePatch { static void Postfix(HookArm __instance, ref EnemyIdentifier ___caughtEid) { if (__instance.state == HookState.Caught && ___caughtEid.enemyType == EnemyType.MaliciousFace) { if (___caughtEid.GetComponent<SpiderBody>().currentEnrageEffect == null) return; //__instance.state = HookState.Pulling; ___caughtEid = null; __instance.StopThrow(); } } }*/ }
Ultrapain/Patches/MaliciousFace.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/MinosPrime.cs", "retrieved_chunk": " MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>();\n if (flag == null)\n return;\n flag.plannedAttack = \"Uppercut\";\n }\n }\n // aka DIE\n class MinosPrime_RiderKick\n {\n static bool Prefix(MinosPrime __instance, ref bool ___previouslyRiderKicked)", "score": 0.8583471179008484 }, { "filename": "Ultrapain/Patches/Cerberus.cs", "retrieved_chunk": " {\n CerberusFlag flag = __instance.GetComponent<CerberusFlag>();\n if (flag == null)\n return;\n flag.MakeParryable();\n }\n }\n class Statue_GetHurt_Patch\n {\n static bool Prefix(Statue __instance, EnemyIdentifier ___eid)", "score": 0.8483964204788208 }, { "filename": "Ultrapain/Patches/MinosPrime.cs", "retrieved_chunk": " flag.explosionAttack = false;\n flag.BigExplosion();\n __instance.Invoke(\"Uppercut\", 0.5f);\n return false;\n }\n }\n class MinosPrime_Death\n {\n static bool Prefix(MinosPrime __instance, Animator ___anim, ref bool ___vibrating)\n {", "score": 0.8467183709144592 }, { "filename": "Ultrapain/Patches/PlayerStatTweaks.cs", "retrieved_chunk": " }\n }\n return code.AsEnumerable();\n }\n }\n class NewMovement_GetHealth\n {\n static bool Prefix(NewMovement __instance, int __0, bool __1, ref AudioSource ___greenHpAud, Canvas ___fullHud)\n {\n if (__instance.dead || __instance.exploded)", "score": 0.8456717133522034 }, { "filename": "Ultrapain/Patches/Cerberus.cs", "retrieved_chunk": " ___eid.health -= ConfigManager.cerberusParryDamage.value;\n MonoSingleton<FistControl>.Instance.currentPunch.Parry(false, ___eid);\n return true;\n }\n }\n class StatueBoss_StopDash_Patch\n {\n public static void Postfix(StatueBoss __instance, ref int ___tackleChance)\n {\n CerberusFlag flag = __instance.GetComponent<CerberusFlag>();", "score": 0.8381125926971436 } ]
csharp
SpiderBody __instance, float ___maxHealth, ref int ___beamsAmount) {
using JWLSLMerge.Data.Attributes; namespace JWLSLMerge.Data.Models { public class TagMap { [
Ignore] public int TagMapId {
get; set; } public int? PlaylistItemId { get; set; } public int? LocationId { get; set; } public int? NoteId { get; set; } public int TagId { get; set; } public int Position { get; set; } } }
JWLSLMerge.Data/Models/TagMap.cs
pliniobrunelli-JWLSLMerge-7fe66dc
[ { "filename": "JWLSLMerge.Data/Attributes/Ignore.cs", "retrieved_chunk": "namespace JWLSLMerge.Data.Attributes\n{\n [AttributeUsage(AttributeTargets.Property)]\n public class IgnoreAttribute : Attribute { }\n}", "score": 0.8462638854980469 }, { "filename": "JWLSLMerge.Data/Models/Tag.cs", "retrieved_chunk": "using JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class Tag\n {\n [Ignore]\n public int TagId { get; set; }\n public int Type { get; set; }\n public string Name { get; set; } = null!;\n [Ignore]", "score": 0.8353756666183472 }, { "filename": "JWLSLMerge.Data/JWDal.cs", "retrieved_chunk": "using Dapper;\nusing JWLSLMerge.Data.Attributes;\nusing System.Data;\nusing System.Data.SQLite;\nnamespace JWLSLMerge.Data\n{\n public class JWDal\n {\n private string connectionString;\n public JWDal(string dbPath)", "score": 0.8072631359100342 }, { "filename": "JWLSLMerge.Data/Models/BlockRange.cs", "retrieved_chunk": "using JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class BlockRange\n {\n [Ignore]\n public int BlockRangeId { get; set; }\n public int BlockType { get; set; }\n public int Identifier { get; set; }\n public int? StartToken { get; set; }", "score": 0.8019012808799744 }, { "filename": "JWLSLMerge.Data/Models/UserMark.cs", "retrieved_chunk": "using JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class UserMark\n {\n [Ignore]\n public int UserMarkId { get; set; }\n public int ColorIndex { get; set; }\n public int LocationId { get; set; }\n public int StyleIndex { get; set; }", "score": 0.7950199246406555 } ]
csharp
Ignore] public int TagMapId {
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Resources; using System.Text; using System.Text.RegularExpressions; using Microsoft.Build.CPPTasks; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.Utilities; namespace Microsoft.Build.CPPTasks { public abstract class VCToolTask : ToolTask { public enum CommandLineFormat { ForBuildLog, ForTracking } [Flags] public enum EscapeFormat { Default = 0, EscapeTrailingSlash = 1 } protected class MessageStruct { public string Category { get; set; } = ""; public string SubCategory { get; set; } = ""; public string Code { get; set; } = ""; public string Filename { get; set; } = ""; public int Line { get; set; } public int Column { get; set; } public string Text { get; set; } = ""; public void Clear() { Category = ""; SubCategory = ""; Code = ""; Filename = ""; Line = 0; Column = 0; Text = ""; } public static void Swap(ref MessageStruct lhs, ref MessageStruct rhs) { MessageStruct messageStruct = lhs; lhs = rhs; rhs = messageStruct; } } private Dictionary<string, ToolSwitch> activeToolSwitchesValues = new Dictionary<string, ToolSwitch>(); #if __REMOVE private IntPtr cancelEvent; private string cancelEventName; #endif private bool fCancelled; private Dictionary<string, ToolSwitch> activeToolSwitches = new Dictionary<string, ToolSwitch>(StringComparer.OrdinalIgnoreCase); private Dictionary<string, Dictionary<string, string>> values = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase); private string additionalOptions = string.Empty; private char prefix = '/'; private TaskLoggingHelper logPrivate; protected List<Regex> errorListRegexList = new List<Regex>(); protected List<Regex> errorListRegexListExclusion = new List<Regex>(); protected MessageStruct lastMS = new MessageStruct(); protected MessageStruct currentMS = new MessageStruct(); protected Dictionary<string, ToolSwitch> ActiveToolSwitches => activeToolSwitches; protected static Regex FindBackSlashInPath { get; } = new Regex("(?<=[^\\\\])\\\\(?=[^\\\\\\\"\\s])|(\\\\(?=[^\\\"]))|((?<=[^\\\\][\\\\])\\\\(?=[\\\"]))", RegexOptions.Compiled); public string AdditionalOptions { get { return additionalOptions; } set { additionalOptions = TranslateAdditionalOptions(value); } } public bool UseMsbuildResourceManager { get; set; } #if __REMOVE protected override Encoding ResponseFileEncoding => Encoding.Unicode; #else // Linux下文件普遍采用没文件头的UTF8,否则容易引入兼容性问题。 private UTF8Encoding UTF8NoBom = new UTF8Encoding(false); protected override Encoding ResponseFileEncoding => UTF8NoBom; #endif protected virtual ArrayList SwitchOrderList => null; #if __REMOVE protected string CancelEventName => cancelEventName; #endif protected TaskLoggingHelper LogPrivate => logPrivate; protected override MessageImportance StandardOutputLoggingImportance => MessageImportance.High; protected override MessageImportance StandardErrorLoggingImportance => MessageImportance.High; protected virtual string AlwaysAppend { get { return string.Empty; } set { } } public ITaskItem[] ErrorListRegex { set { foreach (ITaskItem taskItem in value) { errorListRegexList.Add(new Regex(taskItem.ItemSpec, RegexOptions.IgnoreCase | RegexOptions.Compiled, TimeSpan.FromMilliseconds(100.0))); } } } public ITaskItem[] ErrorListListExclusion { set { foreach (ITaskItem taskItem in value) { errorListRegexListExclusion.Add(new Regex(taskItem.ItemSpec, RegexOptions.IgnoreCase | RegexOptions.Compiled, TimeSpan.FromMilliseconds(100.0))); } } } public bool EnableErrorListRegex { get; set; } = true; public bool ForceSinglelineErrorListRegex { get; set; } public virtual string[] AcceptableNonzeroExitCodes { get; set; } public Dictionary<string,
ToolSwitch> ActiveToolSwitchesValues {
get { return activeToolSwitchesValues; } set { activeToolSwitchesValues = value; } } public string EffectiveWorkingDirectory { get; set; } [Output] public string ResolvedPathToTool { get; protected set; } protected bool IgnoreUnknownSwitchValues { get; set; } protected VCToolTask(ResourceManager taskResources) : base(taskResources) { #if __REMOVE cancelEventName = "MSBuildConsole_CancelEvent" + Guid.NewGuid().ToString("N"); cancelEvent = VCTaskNativeMethods.CreateEventW(IntPtr.Zero, bManualReset: false, bInitialState: false, cancelEventName); #endif fCancelled = false; logPrivate = new TaskLoggingHelper(this); #if __REMOVE logPrivate.TaskResources = Microsoft.Build.Shared.AssemblyResources.PrimaryResources; #endif logPrivate.HelpKeywordPrefix = "MSBuild."; IgnoreUnknownSwitchValues = false; } protected virtual string TranslateAdditionalOptions(string options) { return options; } protected override string GetWorkingDirectory() { return EffectiveWorkingDirectory; } protected override string GenerateFullPathToTool() { return ToolName; } protected override bool ValidateParameters() { if (!logPrivate.HasLoggedErrors) { return !base.Log.HasLoggedErrors; } return false; } public string GenerateCommandLine(CommandLineFormat format = CommandLineFormat.ForBuildLog, EscapeFormat escapeFormat = EscapeFormat.Default) { string text = GenerateCommandLineCommands(format, escapeFormat); string text2 = GenerateResponseFileCommands(format, escapeFormat); if (!string.IsNullOrEmpty(text)) { return text + " " + text2; } return text2; } public string GenerateCommandLineExceptSwitches(string[] switchesToRemove, CommandLineFormat format = CommandLineFormat.ForBuildLog, EscapeFormat escapeFormat = EscapeFormat.Default) { string text = GenerateCommandLineCommandsExceptSwitches(switchesToRemove, format, escapeFormat); string text2 = GenerateResponseFileCommandsExceptSwitches(switchesToRemove, format, escapeFormat); if (!string.IsNullOrEmpty(text)) { return text + " " + text2; } return text2; } protected virtual string GenerateCommandLineCommandsExceptSwitches(string[] switchesToRemove, CommandLineFormat format = CommandLineFormat.ForBuildLog, EscapeFormat escapeFormat = EscapeFormat.Default) { return string.Empty; } protected override string GenerateResponseFileCommands() { return GenerateResponseFileCommands(CommandLineFormat.ForBuildLog, EscapeFormat.Default); } protected virtual string GenerateResponseFileCommands(CommandLineFormat format, EscapeFormat escapeFormat) { return GenerateResponseFileCommandsExceptSwitches(new string[0], format, escapeFormat); } protected override string GenerateCommandLineCommands() { return GenerateCommandLineCommands(CommandLineFormat.ForBuildLog, EscapeFormat.Default); } protected virtual string GenerateCommandLineCommands(CommandLineFormat format, EscapeFormat escapeFormat) { return GenerateCommandLineCommandsExceptSwitches(new string[0], format, escapeFormat); } protected virtual bool GenerateCostomCommandsAccordingToType(CommandLineBuilder builder, string switchName, bool dummyForBackwardCompatibility, CommandLineFormat format = CommandLineFormat.ForBuildLog, EscapeFormat escapeFormat = EscapeFormat.Default) { return false; } protected virtual string GenerateResponseFileCommandsExceptSwitches(string[] switchesToRemove, CommandLineFormat format = CommandLineFormat.ForBuildLog, EscapeFormat escapeFormat = EscapeFormat.Default) { bool flag = false; AddDefaultsToActiveSwitchList(); AddFallbacksToActiveSwitchList(); PostProcessSwitchList(); CommandLineBuilder commandLineBuilder = new CommandLineBuilder(quoteHyphensOnCommandLine: true); foreach (string switchOrder in SwitchOrderList) { if (GenerateCostomCommandsAccordingToType(commandLineBuilder, switchOrder, dummyForBackwardCompatibility: false, format, escapeFormat)) { // 已经处理 } else if(IsPropertySet(switchOrder)) { ToolSwitch toolSwitch = activeToolSwitches[switchOrder]; if (!VerifyDependenciesArePresent(toolSwitch) || !VerifyRequiredArgumentsArePresent(toolSwitch, throwOnError: false)) { continue; } bool flag2 = true; if (switchesToRemove != null) { foreach (string value in switchesToRemove) { if (switchOrder.Equals(value, StringComparison.OrdinalIgnoreCase)) { flag2 = false; break; } } } if (flag2 && !IsArgument(toolSwitch)) { GenerateCommandsAccordingToType(commandLineBuilder, toolSwitch, dummyForBackwardCompatibility: false, format, escapeFormat); } } else if (string.Equals(switchOrder, "additionaloptions", StringComparison.OrdinalIgnoreCase)) { BuildAdditionalArgs(commandLineBuilder); flag = true; } else if (string.Equals(switchOrder, "AlwaysAppend", StringComparison.OrdinalIgnoreCase)) { commandLineBuilder.AppendSwitch(AlwaysAppend); } } if (!flag) { BuildAdditionalArgs(commandLineBuilder); } return commandLineBuilder.ToString(); } protected override bool HandleTaskExecutionErrors() { if (IsAcceptableReturnValue()) { return true; } return base.HandleTaskExecutionErrors(); } public override bool Execute() { if (fCancelled) { return false; } bool result = base.Execute(); #if __REMOVE VCTaskNativeMethods.CloseHandle(cancelEvent); #endif PrintMessage(ParseLine(null), base.StandardOutputImportanceToUse); return result; } protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands) { #if __REMOVE #else // 由于创建响应文件速度需要额外IO,所以我们特别判断,如果命令行总长度小于2048(Linux支持2048长度问题不大)则不创建响应文件了。 if(responseFileCommands.Length != 0 && responseFileCommands.Length + commandLineCommands.Length + 1 < 2048) { if(commandLineCommands.Length != 0) { commandLineCommands += ' '; commandLineCommands += responseFileCommands; } else { commandLineCommands = responseFileCommands; } responseFileCommands = ""; } #endif ResolvedPathToTool = Environment.ExpandEnvironmentVariables(pathToTool); return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); } public override void Cancel() { fCancelled = true; #if __REMOVE VCTaskNativeMethods.SetEvent(cancelEvent); #endif base.Cancel(); } protected bool VerifyRequiredArgumentsArePresent(ToolSwitch property, bool throwOnError) { if (property.ArgumentRelationList != null) { foreach (ArgumentRelation argumentRelation in property.ArgumentRelationList) { if (argumentRelation.Required && (property.Value == argumentRelation.Value || argumentRelation.Value == string.Empty) && !HasSwitch(argumentRelation.Argument)) { string text = ""; text = ((!(string.Empty == argumentRelation.Value)) ? base.Log.FormatResourceString("MissingRequiredArgumentWithValue", argumentRelation.Argument, property.Name, argumentRelation.Value) : base.Log.FormatResourceString("MissingRequiredArgument", argumentRelation.Argument, property.Name)); base.Log.LogError(text); if (throwOnError) { throw new LoggerException(text); } return false; } } } return true; } protected bool IsAcceptableReturnValue() { return IsAcceptableReturnValue(base.ExitCode); } protected bool IsAcceptableReturnValue(int code) { if (AcceptableNonzeroExitCodes != null) { string[] acceptableNonzeroExitCodes = AcceptableNonzeroExitCodes; foreach (string value in acceptableNonzeroExitCodes) { if (code == Convert.ToInt32(value, CultureInfo.InvariantCulture)) { return true; } } } return code == 0; } protected void RemoveSwitchToolBasedOnValue(string switchValue) { if (ActiveToolSwitchesValues.Count > 0 && ActiveToolSwitchesValues.ContainsKey("/" + switchValue)) { ToolSwitch toolSwitch = ActiveToolSwitchesValues["/" + switchValue]; if (toolSwitch != null) { ActiveToolSwitches.Remove(toolSwitch.Name); } } } protected void AddActiveSwitchToolValue(ToolSwitch switchToAdd) { if (switchToAdd.Type != 0 || switchToAdd.BooleanValue) { if (switchToAdd.SwitchValue != string.Empty) { ActiveToolSwitchesValues.Add(switchToAdd.SwitchValue, switchToAdd); } } else if (switchToAdd.ReverseSwitchValue != string.Empty) { ActiveToolSwitchesValues.Add(switchToAdd.ReverseSwitchValue, switchToAdd); } } protected string GetEffectiveArgumentsValues(ToolSwitch property, CommandLineFormat format = CommandLineFormat.ForBuildLog) { StringBuilder stringBuilder = new StringBuilder(); bool flag = false; string text = string.Empty; if (property.ArgumentRelationList != null) { foreach (ArgumentRelation argumentRelation in property.ArgumentRelationList) { if (text != string.Empty && text != argumentRelation.Argument) { flag = true; } text = argumentRelation.Argument; if ((property.Value == argumentRelation.Value || argumentRelation.Value == string.Empty || (property.Type == ToolSwitchType.Boolean && property.BooleanValue)) && HasSwitch(argumentRelation.Argument)) { ToolSwitch toolSwitch = ActiveToolSwitches[argumentRelation.Argument]; stringBuilder.Append(argumentRelation.Separator); CommandLineBuilder commandLineBuilder = new CommandLineBuilder(); GenerateCommandsAccordingToType(commandLineBuilder, toolSwitch, dummyForBackwardCompatibility: true, format); stringBuilder.Append(commandLineBuilder.ToString()); } } } CommandLineBuilder commandLineBuilder2 = new CommandLineBuilder(); if (flag) { commandLineBuilder2.AppendSwitchIfNotNull("", stringBuilder.ToString()); } else { commandLineBuilder2.AppendSwitchUnquotedIfNotNull("", stringBuilder.ToString()); } return commandLineBuilder2.ToString(); } protected virtual void PostProcessSwitchList() { ValidateRelations(); ValidateOverrides(); } protected virtual void ValidateRelations() { } protected virtual void ValidateOverrides() { List<string> list = new List<string>(); foreach (KeyValuePair<string, ToolSwitch> activeToolSwitch in ActiveToolSwitches) { foreach (KeyValuePair<string, string> @override in activeToolSwitch.Value.Overrides) { if (!string.Equals(@override.Key, (activeToolSwitch.Value.Type == ToolSwitchType.Boolean && !activeToolSwitch.Value.BooleanValue) ? activeToolSwitch.Value.ReverseSwitchValue.TrimStart('/') : activeToolSwitch.Value.SwitchValue.TrimStart('/'), StringComparison.OrdinalIgnoreCase)) { continue; } foreach (KeyValuePair<string, ToolSwitch> activeToolSwitch2 in ActiveToolSwitches) { if (!string.Equals(activeToolSwitch2.Key, activeToolSwitch.Key, StringComparison.OrdinalIgnoreCase)) { if (string.Equals(activeToolSwitch2.Value.SwitchValue.TrimStart('/'), @override.Value, StringComparison.OrdinalIgnoreCase)) { list.Add(activeToolSwitch2.Key); break; } if (activeToolSwitch2.Value.Type == ToolSwitchType.Boolean && !activeToolSwitch2.Value.BooleanValue && string.Equals(activeToolSwitch2.Value.ReverseSwitchValue.TrimStart('/'), @override.Value, StringComparison.OrdinalIgnoreCase)) { list.Add(activeToolSwitch2.Key); break; } } } } } foreach (string item in list) { ActiveToolSwitches.Remove(item); } } protected bool IsSwitchValueSet(string switchValue) { if (!string.IsNullOrEmpty(switchValue)) { return ActiveToolSwitchesValues.ContainsKey("/" + switchValue); } return false; } protected virtual bool VerifyDependenciesArePresent(ToolSwitch value) { if (value.Parents.Count > 0) { bool flag = false; { foreach (string parent in value.Parents) { flag = flag || HasDirectSwitch(parent); } return flag; } } return true; } protected virtual void AddDefaultsToActiveSwitchList() { } protected virtual void AddFallbacksToActiveSwitchList() { } protected virtual void GenerateCommandsAccordingToType(CommandLineBuilder builder, ToolSwitch toolSwitch, bool dummyForBackwardCompatibility, CommandLineFormat format = CommandLineFormat.ForBuildLog, EscapeFormat escapeFormat = EscapeFormat.Default) { GenerateCommandsAccordingToType(builder, toolSwitch, format, escapeFormat); } protected virtual void GenerateCommandsAccordingToType(CommandLineBuilder builder, ToolSwitch toolSwitch, CommandLineFormat format = CommandLineFormat.ForBuildLog, EscapeFormat escapeFormat = EscapeFormat.Default) { try { switch (toolSwitch.Type) { case ToolSwitchType.Boolean: EmitBooleanSwitch(builder, toolSwitch, format); break; case ToolSwitchType.String: EmitStringSwitch(builder, toolSwitch); break; case ToolSwitchType.StringArray: EmitStringArraySwitch(builder, toolSwitch); break; case ToolSwitchType.StringPathArray: EmitStringArraySwitch(builder, toolSwitch, format, escapeFormat); break; case ToolSwitchType.Integer: EmitIntegerSwitch(builder, toolSwitch); break; case ToolSwitchType.File: EmitFileSwitch(builder, toolSwitch, format); break; case ToolSwitchType.Directory: EmitDirectorySwitch(builder, toolSwitch, format); break; case ToolSwitchType.ITaskItem: EmitTaskItemSwitch(builder, toolSwitch); break; case ToolSwitchType.ITaskItemArray: EmitTaskItemArraySwitch(builder, toolSwitch, format); break; case ToolSwitchType.AlwaysAppend: EmitAlwaysAppendSwitch(builder, toolSwitch); break; default: Microsoft.Build.Shared.ErrorUtilities.VerifyThrow(condition: false, "InternalError"); break; } } catch (Exception ex) { base.Log.LogErrorFromResources("GenerateCommandLineError", toolSwitch.Name, toolSwitch.ValueAsString, ex.Message); ex.RethrowIfCritical(); } } protected void BuildAdditionalArgs(CommandLineBuilder cmdLine) { if (cmdLine != null && !string.IsNullOrEmpty(additionalOptions)) { cmdLine.AppendSwitch(Environment.ExpandEnvironmentVariables(additionalOptions)); } } protected bool ValidateInteger(string switchName, int min, int max, int value) { if (value < min || value > max) { logPrivate.LogErrorFromResources("ArgumentOutOfRange", switchName, value); return false; } return true; } protected string ReadSwitchMap(string propertyName, string[][] switchMap, string value) { if (switchMap != null) { for (int i = 0; i < switchMap.Length; i++) { if (string.Equals(switchMap[i][0], value, StringComparison.CurrentCultureIgnoreCase)) { return switchMap[i][1]; } } if (!IgnoreUnknownSwitchValues) { logPrivate.LogErrorFromResources("ArgumentOutOfRange", propertyName, value); } } return string.Empty; } protected bool IsPropertySet(string propertyName) { return activeToolSwitches.ContainsKey(propertyName); } protected bool IsSetToTrue(string propertyName) { if (activeToolSwitches.ContainsKey(propertyName)) { return activeToolSwitches[propertyName].BooleanValue; } return false; } protected bool IsExplicitlySetToFalse(string propertyName) { if (activeToolSwitches.ContainsKey(propertyName)) { return !activeToolSwitches[propertyName].BooleanValue; } return false; } protected bool IsArgument(ToolSwitch property) { if (property != null && property.Parents.Count > 0) { if (string.IsNullOrEmpty(property.SwitchValue)) { return true; } foreach (string parent in property.Parents) { if (!activeToolSwitches.TryGetValue(parent, out var value)) { continue; } foreach (ArgumentRelation argumentRelation in value.ArgumentRelationList) { if (argumentRelation.Argument.Equals(property.Name, StringComparison.Ordinal)) { return true; } } } } return false; } protected bool HasSwitch(string propertyName) { if (IsPropertySet(propertyName)) { return !string.IsNullOrEmpty(activeToolSwitches[propertyName].Name); } return false; } protected bool HasDirectSwitch(string propertyName) { if (activeToolSwitches.TryGetValue(propertyName, out var value) && !string.IsNullOrEmpty(value.Name)) { if (value.Type == ToolSwitchType.Boolean) { return value.BooleanValue; } return true; } return false; } protected static string EnsureTrailingSlash(string directoryName) { Microsoft.Build.Shared.ErrorUtilities.VerifyThrow(directoryName != null, "InternalError"); if (directoryName != null && directoryName.Length > 0) { char c = directoryName[directoryName.Length - 1]; if (c != Path.DirectorySeparatorChar && c != Path.AltDirectorySeparatorChar) { directoryName += Path.DirectorySeparatorChar; } } return directoryName; } protected override void LogEventsFromTextOutput(string singleLine, MessageImportance messageImportance) { if (EnableErrorListRegex && errorListRegexList.Count > 0) { PrintMessage(ParseLine(singleLine), messageImportance); if (ForceSinglelineErrorListRegex) { PrintMessage(ParseLine(null), messageImportance); } } else { base.LogEventsFromTextOutput(singleLine, messageImportance); } } protected virtual void PrintMessage(MessageStruct message, MessageImportance messageImportance) { if (message != null && message.Text.Length > 0) { switch (message.Category) { case "fatal error": case "error": base.Log.LogError(message.SubCategory, message.Code, null, message.Filename, message.Line, message.Column, 0, 0, message.Text.TrimEnd()); break; case "warning": base.Log.LogWarning(message.SubCategory, message.Code, null, message.Filename, message.Line, message.Column, 0, 0, message.Text.TrimEnd()); break; case "note": base.Log.LogCriticalMessage(message.SubCategory, message.Code, null, message.Filename, message.Line, message.Column, 0, 0, message.Text.TrimEnd()); break; default: base.Log.LogMessage(messageImportance, message.Text.TrimEnd()); break; } message.Clear(); } } protected virtual MessageStruct ParseLine(string inputLine) { if (inputLine == null) { MessageStruct.Swap(ref lastMS, ref currentMS); currentMS.Clear(); return lastMS; } if (string.IsNullOrWhiteSpace(inputLine)) { return null; } bool flag = false; foreach (Regex item in errorListRegexListExclusion) { try { Match match = item.Match(inputLine); if (match.Success) { flag = true; break; } } catch (RegexMatchTimeoutException) { } catch (Exception e) { ReportRegexException(inputLine, item, e); } } if (!flag) { foreach (Regex errorListRegex in errorListRegexList) { try { Match match2 = errorListRegex.Match(inputLine); if (match2.Success) { int result = 0; int result2 = 0; if (!int.TryParse(match2.Groups["LINE"].Value, out result)) { result = 0; } if (!int.TryParse(match2.Groups["COLUMN"].Value, out result2)) { result2 = 0; } MessageStruct.Swap(ref lastMS, ref currentMS); currentMS.Clear(); currentMS.Category = match2.Groups["CATEGORY"].Value.ToLowerInvariant(); currentMS.SubCategory = match2.Groups["SUBCATEGORY"].Value.ToLowerInvariant(); currentMS.Filename = match2.Groups["FILENAME"].Value; currentMS.Code = match2.Groups["CODE"].Value; currentMS.Line = result; currentMS.Column = result2; MessageStruct messageStruct = currentMS; messageStruct.Text = messageStruct.Text + match2.Groups["TEXT"].Value.TrimEnd() + Environment.NewLine; flag = true; return lastMS; } } catch (RegexMatchTimeoutException) { } catch (Exception e2) { ReportRegexException(inputLine, errorListRegex, e2); } } } if (!flag && !string.IsNullOrEmpty(currentMS.Filename)) { MessageStruct messageStruct2 = currentMS; messageStruct2.Text = messageStruct2.Text + inputLine.TrimEnd() + Environment.NewLine; return null; } MessageStruct.Swap(ref lastMS, ref currentMS); currentMS.Clear(); currentMS.Text = inputLine; return lastMS; } protected void ReportRegexException(string inputLine, Regex regex, Exception e) { #if __REMOVE if (Microsoft.Build.Shared.ExceptionHandling.IsCriticalException(e)) { if (e is OutOfMemoryException) { int cacheSize = Regex.CacheSize; Regex.CacheSize = 0; Regex.CacheSize = cacheSize; } base.Log.LogErrorWithCodeFromResources("TrackedVCToolTask.CannotParseToolOutput", inputLine, regex.ToString(), e.Message); e.Rethrow(); } else #endif { base.Log.LogWarningWithCodeFromResources("TrackedVCToolTask.CannotParseToolOutput", inputLine, regex.ToString(), e.Message); } } private static void EmitAlwaysAppendSwitch(CommandLineBuilder builder, ToolSwitch toolSwitch) { builder.AppendSwitch(toolSwitch.Name); } private static void EmitTaskItemArraySwitch(CommandLineBuilder builder, ToolSwitch toolSwitch, CommandLineFormat format = CommandLineFormat.ForBuildLog) { if (string.IsNullOrEmpty(toolSwitch.Separator)) { ITaskItem[] taskItemArray = toolSwitch.TaskItemArray; foreach (ITaskItem taskItem in taskItemArray) { #if __REMOVE builder.AppendSwitchIfNotNull(toolSwitch.SwitchValue, Environment.ExpandEnvironmentVariables(taskItem.ItemSpec)); #else var ExpandItemSpec =Environment.ExpandEnvironmentVariables(toolSwitch.TaskItem.ItemSpec); if(toolSwitch.TaskItemFullPath) { ExpandItemSpec = FileUtilities.NormalizePath(ExpandItemSpec); } builder.AppendSwitchIfNotNull(toolSwitch.SwitchValue, ExpandItemSpec); #endif } return; } ITaskItem[] array = new ITaskItem[toolSwitch.TaskItemArray.Length]; for (int j = 0; j < toolSwitch.TaskItemArray.Length; j++) { #if __REMOVE array[j] = new TaskItem(Environment.ExpandEnvironmentVariables(toolSwitch.TaskItemArray[j].ItemSpec)); if (format == CommandLineFormat.ForTracking) { array[j].ItemSpec = array[j].ItemSpec.ToUpperInvariant(); } #else var ExpandItemSpec = Environment.ExpandEnvironmentVariables(toolSwitch.TaskItemArray[j].ItemSpec); if (toolSwitch.TaskItemFullPath) { ExpandItemSpec = FileUtilities.NormalizePath(ExpandItemSpec); } array[j] = new TaskItem(ExpandItemSpec); #endif } builder.AppendSwitchIfNotNull(toolSwitch.SwitchValue, array, toolSwitch.Separator); } private static void EmitTaskItemSwitch(CommandLineBuilder builder, ToolSwitch toolSwitch) { if (!string.IsNullOrEmpty(toolSwitch.TaskItem.ItemSpec)) { #if __REMOVE builder.AppendFileNameIfNotNull(Environment.ExpandEnvironmentVariables(toolSwitch.TaskItem.ItemSpec + toolSwitch.Separator)); #else var ExpandItemSpec = Environment.ExpandEnvironmentVariables(toolSwitch.TaskItem.ItemSpec); if(toolSwitch.TaskItemFullPath) { ExpandItemSpec = FileUtilities.NormalizePath(ExpandItemSpec); } builder.AppendFileNameIfNotNull(ExpandItemSpec + toolSwitch.Separator); #endif } } private static void EmitDirectorySwitch(CommandLineBuilder builder, ToolSwitch toolSwitch, CommandLineFormat format = CommandLineFormat.ForBuildLog) { if (!string.IsNullOrEmpty(toolSwitch.SwitchValue)) { if (format == CommandLineFormat.ForBuildLog) { builder.AppendSwitch(toolSwitch.SwitchValue + toolSwitch.Separator); } else { builder.AppendSwitch(toolSwitch.SwitchValue.ToUpperInvariant() + toolSwitch.Separator); } } } private static void EmitFileSwitch(CommandLineBuilder builder, ToolSwitch toolSwitch, CommandLineFormat format = CommandLineFormat.ForBuildLog) { if (!string.IsNullOrEmpty(toolSwitch.Value)) { string text = Environment.ExpandEnvironmentVariables(toolSwitch.Value); text = text.Trim(); //if (format == CommandLineFormat.ForTracking) //{ // text = text.ToUpperInvariant(); //} if (!text.StartsWith("\"", StringComparison.Ordinal)) { text = "\"" + text; text = ((!text.EndsWith("\\", StringComparison.Ordinal) || text.EndsWith("\\\\", StringComparison.Ordinal)) ? (text + "\"") : (text + "\\\"")); } builder.AppendSwitchUnquotedIfNotNull(toolSwitch.SwitchValue + toolSwitch.Separator, text); } } private void EmitIntegerSwitch(CommandLineBuilder builder, ToolSwitch toolSwitch) { if (toolSwitch.IsValid) { if (!string.IsNullOrEmpty(toolSwitch.Separator)) { builder.AppendSwitch(toolSwitch.SwitchValue + toolSwitch.Separator + toolSwitch.Number.ToString(CultureInfo.InvariantCulture) + GetEffectiveArgumentsValues(toolSwitch)); } else { builder.AppendSwitch(toolSwitch.SwitchValue + toolSwitch.Number.ToString(CultureInfo.InvariantCulture) + GetEffectiveArgumentsValues(toolSwitch)); } } } private static void EmitStringArraySwitch(CommandLineBuilder builder, ToolSwitch toolSwitch, CommandLineFormat format = CommandLineFormat.ForBuildLog, EscapeFormat escapeFormat = EscapeFormat.Default) { string[] array = new string[toolSwitch.StringList.Length]; char[] anyOf = new char[11] { ' ', '|', '<', '>', ',', ';', '-', '\r', '\n', '\t', '\f' }; for (int i = 0; i < toolSwitch.StringList.Length; i++) { string text = ((!toolSwitch.StringList[i].StartsWith("\"", StringComparison.Ordinal) || !toolSwitch.StringList[i].EndsWith("\"", StringComparison.Ordinal)) ? Environment.ExpandEnvironmentVariables(toolSwitch.StringList[i]) : Environment.ExpandEnvironmentVariables(toolSwitch.StringList[i].Substring(1, toolSwitch.StringList[i].Length - 2))); if (!string.IsNullOrEmpty(text)) { //if (format == CommandLineFormat.ForTracking) //{ // text = text.ToUpperInvariant(); //} if (escapeFormat.HasFlag(EscapeFormat.EscapeTrailingSlash) && text.IndexOfAny(anyOf) == -1 && text.EndsWith("\\", StringComparison.Ordinal) && !text.EndsWith("\\\\", StringComparison.Ordinal)) { text += "\\"; } array[i] = text; } } if (string.IsNullOrEmpty(toolSwitch.Separator)) { string[] array2 = array; foreach (string parameter in array2) { builder.AppendSwitchIfNotNull(toolSwitch.SwitchValue, parameter); } } else { builder.AppendSwitchIfNotNull(toolSwitch.SwitchValue, array, toolSwitch.Separator); } } private void EmitStringSwitch(CommandLineBuilder builder, ToolSwitch toolSwitch) { string empty = string.Empty; empty = empty + toolSwitch.SwitchValue + toolSwitch.Separator; StringBuilder stringBuilder = new StringBuilder(GetEffectiveArgumentsValues(toolSwitch)); string value = toolSwitch.Value; if (!toolSwitch.MultipleValues) { value = value.Trim(); if (!value.StartsWith("\"", StringComparison.Ordinal)) { value = "\"" + value; value = ((!value.EndsWith("\\", StringComparison.Ordinal) || value.EndsWith("\\\\", StringComparison.Ordinal)) ? (value + "\"") : (value + "\\\"")); } stringBuilder.Insert(0, value); } if (empty.Length != 0 || stringBuilder.ToString().Length != 0) { builder.AppendSwitchUnquotedIfNotNull(empty, stringBuilder.ToString()); } } private void EmitBooleanSwitch(CommandLineBuilder builder, ToolSwitch toolSwitch, CommandLineFormat format = CommandLineFormat.ForBuildLog) { if (toolSwitch.BooleanValue) { if (!string.IsNullOrEmpty(toolSwitch.SwitchValue)) { StringBuilder stringBuilder = new StringBuilder(GetEffectiveArgumentsValues(toolSwitch, format)); stringBuilder.Insert(0, toolSwitch.Separator); stringBuilder.Insert(0, toolSwitch.TrueSuffix); stringBuilder.Insert(0, toolSwitch.SwitchValue); builder.AppendSwitch(stringBuilder.ToString()); } } else { EmitReversibleBooleanSwitch(builder, toolSwitch); } } private void EmitReversibleBooleanSwitch(CommandLineBuilder builder, ToolSwitch toolSwitch) { if (!string.IsNullOrEmpty(toolSwitch.ReverseSwitchValue)) { string value = (toolSwitch.BooleanValue ? toolSwitch.TrueSuffix : toolSwitch.FalseSuffix); StringBuilder stringBuilder = new StringBuilder(GetEffectiveArgumentsValues(toolSwitch)); stringBuilder.Insert(0, value); stringBuilder.Insert(0, toolSwitch.Separator); stringBuilder.Insert(0, toolSwitch.TrueSuffix); stringBuilder.Insert(0, toolSwitch.ReverseSwitchValue); builder.AppendSwitch(stringBuilder.ToString()); } } private string Prefix(string toolSwitch) { if (!string.IsNullOrEmpty(toolSwitch) && toolSwitch[0] != prefix) { return prefix + toolSwitch; } return toolSwitch; } } }
Microsoft.Build.CPPTasks/VCToolTask.cs
Chuyu-Team-MSBuildCppCrossToolset-6c84a69
[ { "filename": "Microsoft.Build.CPPTasks/TrackedVCToolTask.cs", "retrieved_chunk": " set\n {\n trackCommandLines = value;\n }\n }\n public bool PostBuildTrackingCleanup { get; set; }\n public bool EnableExecuteTool { get; set; }\n public bool MinimalRebuildFromTracking\n {\n get", "score": 0.8689277768135071 }, { "filename": "Microsoft.Build.CPPTasks/TrackedVCToolTask.cs", "retrieved_chunk": " set\n {\n deleteOutputBeforeExecute = value;\n }\n }\n protected virtual bool MaintainCompositeRootingMarkers => false;\n protected virtual bool UseMinimalRebuildOptimization => false;\n public virtual string SourcesPropertyName => \"Sources\";\n // protected virtual ExecutableType? ToolType => null;\n public string ToolArchitecture { get; set; }", "score": 0.8670518398284912 }, { "filename": "Microsoft.Build.CPPTasks/TrackedVCToolTask.cs", "retrieved_chunk": " List<ITaskItem> list = new List<ITaskItem>(value);\n excludedInputPaths = list.ToArray();\n }\n }\n public string PathOverride\n {\n get\n {\n return pathOverride;\n }", "score": 0.8565627336502075 }, { "filename": "YY.Build.Cross.Tasks/Cross/Ar.cs", "retrieved_chunk": " toolSwitch.BooleanValue = value;\n base.ActiveToolSwitches.Add(\"SuppressStartupBanner\", toolSwitch);\n AddActiveSwitchToolValue(toolSwitch);\n }\n }\n public virtual bool Verbose\n {\n get\n {\n if (IsPropertySet(\"Verbose\"))", "score": 0.8545280694961548 }, { "filename": "Microsoft.Build.CPPTasks/ToolSwitch.cs", "retrieved_chunk": " result = number.ToString();\n break;\n }\n return result;\n }\n }\n public ToolSwitch()\n {\n }\n public ToolSwitch(ToolSwitchType toolType)", "score": 0.8492360711097717 } ]
csharp
ToolSwitch> ActiveToolSwitchesValues {
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace TreeifyTask { public class TaskNode : ITaskNode { private static Random rnd = new Random(); private readonly List<Task> taskObjects = new(); private readonly List<ITaskNode> childTasks = new(); private bool hasCustomAction; private Func<IProgressReporter, CancellationToken, Task> action = async (rep, tok) => await Task.Yield(); public event ProgressReportingEventHandler Reporting; private bool seriesRunnerIsBusy; private bool concurrentRunnerIsBusy; public TaskNode() { this.Id = rnd.Next() + string.Empty; this.Reporting += OnSelfReporting; } public TaskNode(string Id) : this() { this.Id = Id ?? rnd.Next() + string.Empty; } public TaskNode(string Id, Func<IProgressReporter, CancellationToken, Task> cancellableProgressReportingAsyncFunction) : this(Id) { this.SetAction(cancellableProgressReportingAsyncFunction); } #region Props public string Id { get; set; } public double ProgressValue { get; private set; } public object ProgressState { get; private set; } public TaskStatus TaskStatus { get; private set; } public ITaskNode Parent { get; set; } public IEnumerable<ITaskNode> ChildTasks => this.childTasks; #endregion Props public void AddChild(ITaskNode childTask) { childTask = childTask ?? throw new ArgumentNullException(nameof(childTask)); childTask.Parent = this; // Ensure this after setting its parent as this EnsureNoCycles(childTask); childTask.Reporting += OnChildReporting; childTasks.Add(childTask); } private class ActionReport { public ActionReport() { this.TaskStatus = TaskStatus.NotStarted; this.ProgressValue = 0; this.ProgressState = null; } public ActionReport(ITaskNode task) { this.Id = task.Id; this.TaskStatus = task.TaskStatus; this.ProgressState = task.ProgressState; this.ProgressValue = task.ProgressValue; } public string Id { get; set; } public TaskStatus TaskStatus { get; set; } public double ProgressValue { get; set; } public object ProgressState { get; set; } public override string ToString() { return $"Id={Id},({TaskStatus}, {ProgressValue}, {ProgressState})"; } } private ActionReport selfActionReport = new(); private void OnSelfReporting(object sender, ProgressReportingEventArgs eventArgs) { TaskStatus = selfActionReport.TaskStatus = eventArgs.TaskStatus; ProgressValue = selfActionReport.ProgressValue = eventArgs.ProgressValue; ProgressState = selfActionReport.ProgressState = eventArgs.ProgressState; } private void OnChildReporting(object sender, ProgressReportingEventArgs eventArgs) { // Child task that reports var cTask = sender as ITaskNode; var allReports = childTasks.Select(t => new ActionReport(t)); if (hasCustomAction) { allReports = allReports.Append(selfActionReport); } this.TaskStatus = allReports.Any(v => v.TaskStatus == TaskStatus.InDeterminate) ? TaskStatus.InDeterminate : TaskStatus.InProgress; this.TaskStatus = allReports.Any(v => v.TaskStatus == TaskStatus.Failed) ? TaskStatus.Failed : this.TaskStatus; if (this.TaskStatus == TaskStatus.Failed) { this.ProgressState = new AggregateException($"{Id}: One or more error occurred in child tasks.", childTasks.Where(v => v.TaskStatus == TaskStatus.Failed && v.ProgressState is Exception) .Select(c => c.ProgressState as Exception)); } this.ProgressValue = allReports.Select(t => t.ProgressValue).Average(); SafeRaiseReportingEvent(this, new ProgressReportingEventArgs { ProgressValue = this.ProgressValue, TaskStatus = this.TaskStatus, ChildTasksRunningInParallel = concurrentRunnerIsBusy, ProgressState = seriesRunnerIsBusy ? cTask.ProgressState : this.ProgressState }); } public async Task ExecuteConcurrently(CancellationToken cancellationToken, bool throwOnError) { if (concurrentRunnerIsBusy || seriesRunnerIsBusy) return; concurrentRunnerIsBusy = true; ResetChildrenProgressValues(); foreach (var child in childTasks) { taskObjects.Add(child.ExecuteConcurrently(cancellationToken, throwOnError)); } taskObjects.Add(ExceptionHandledAction(cancellationToken, throwOnError)); if (taskObjects.Any()) { await Task.WhenAll(taskObjects); } if (throwOnError && taskObjects.Any(t => t.IsFaulted)) { var exs = taskObjects.Where(t => t.IsFaulted).Select(t => t.Exception); throw new AggregateException($"Internal error occurred while executing task - {Id}.", exs); } concurrentRunnerIsBusy = false; if (TaskStatus != TaskStatus.Failed) { if (cancellationToken.IsCancellationRequested) Report(TaskStatus.Cancelled, 0); else Report(TaskStatus.Completed, 100); } } private async Task ExceptionHandledAction(CancellationToken cancellationToken, bool throwOnError) { try { await action(this, cancellationToken); } catch (OperationCanceledException) { // Don't throw this as an error as we have to come out of await. } catch (Exception ex) { this.Report(TaskStatus.Failed, this.ProgressValue, ex); if (throwOnError) { throw new AggregateException($"Internal error occurred while executing the action of task - {Id}.", ex); } } } public async Task ExecuteInSeries(CancellationToken cancellationToken, bool throwOnError) { if (seriesRunnerIsBusy || concurrentRunnerIsBusy) return; seriesRunnerIsBusy = true; ResetChildrenProgressValues(); try { foreach (var child in childTasks) { if (cancellationToken.IsCancellationRequested) break; await child.ExecuteInSeries(cancellationToken, throwOnError); } await ExceptionHandledAction(cancellationToken, throwOnError); } catch (Exception ex) { if (throwOnError) { throw new AggregateException($"Internal error occurred while executing task - {Id}.", ex); } } seriesRunnerIsBusy = false; if (TaskStatus != TaskStatus.Failed) { if (cancellationToken.IsCancellationRequested) Report(TaskStatus.Cancelled, 0); else Report(TaskStatus.Completed, 100); } } public IEnumerable<ITaskNode> ToFlatList() { return FlatList(this); } private void SafeRaiseReportingEvent(object sender, ProgressReportingEventArgs args) { this.Reporting?.Invoke(sender, args); } private void ResetChildrenProgressValues() { taskObjects.Clear(); foreach (var task in childTasks) { task.ResetStatus(); } } /// <summary> /// Throws <see cref="AsyncTasksCycleDetectedException"/> /// </summary> /// <param name="newTask"></param> private void EnsureNoCycles(ITaskNode newTask) { var thisNode = this as ITaskNode; HashSet<ITaskNode> hSet = new HashSet<ITaskNode>(); while (true) { if (thisNode.Parent is null) { break; } if (hSet.Contains(thisNode)) { throw new TaskNodeCycleDetectedException(thisNode, newTask); } hSet.Add(thisNode); thisNode = thisNode.Parent; } var existingTask = FlatList(thisNode).FirstOrDefault(t => t == newTask); if (existingTask != null) { throw new TaskNodeCycleDetectedException(newTask, existingTask.Parent); } } private IEnumerable<ITaskNode> FlatList(ITaskNode root) { yield return root; foreach (var ct in root.ChildTasks) { foreach (var item in FlatList(ct)) yield return item; } } public void RemoveChild(ITaskNode childTask) { childTask.Reporting -= OnChildReporting; childTasks.Remove(childTask); } public void Report(TaskStatus taskStatus, double progressValue, object progressState = null) { SafeRaiseReportingEvent(this, new ProgressReportingEventArgs { ChildTasksRunningInParallel = concurrentRunnerIsBusy, TaskStatus = taskStatus, ProgressValue = progressValue, ProgressState = progressState }); } public void SetAction(Func<
IProgressReporter, CancellationToken, Task> cancellableProgressReportingAction) {
cancellableProgressReportingAction = cancellableProgressReportingAction ?? throw new ArgumentNullException(nameof(cancellableProgressReportingAction)); hasCustomAction = true; action = cancellableProgressReportingAction; } public void ResetStatus() { this.TaskStatus = TaskStatus.NotStarted; this.ProgressState = null; this.ProgressValue = 0; } public override string ToString() { return $"Id={Id},({TaskStatus}, {ProgressValue}, {ProgressState})"; } } }
Source/TreeifyTask/TaskTree/TaskNode.cs
intuit-TreeifyTask-4b124d4
[ { "filename": "Source/TreeifyTask.WpfSample/MainWindow.xaml.cs", "retrieved_chunk": " e.Handled = true;\n }\n private async Task SimpleTimer(IProgressReporter progressReporter, CancellationToken token, CodeBehavior behaviors = null, string progressMessage = null)\n {\n behaviors ??= new CodeBehavior();\n progressMessage ??= \"In progress \";\n progressReporter.Report(TaskStatus.InProgress, 0, $\"{progressMessage}: 0%\");\n bool error = false;\n if (behaviors.ShouldThrowException)\n {", "score": 0.8591614961624146 }, { "filename": "Source/TreeifyTask.WpfSample/MainWindow.xaml.cs", "retrieved_chunk": " }\n if (!error && !token.IsCancellationRequested)\n {\n progressReporter.Report(TaskStatus.Completed, 100, $\"{progressMessage}: 100%\");\n }\n }\n CancellationTokenSource tokenSource;\n private async void StartClick(object sender, RoutedEventArgs e)\n {\n grpExecutionMethod.IsEnabled = false;", "score": 0.8547683358192444 }, { "filename": "Source/TreeifyTask/TaskTree/IProgressReporter.cs", "retrieved_chunk": "namespace TreeifyTask\n{\n public interface IProgressReporter\n {\n void Report(TaskStatus taskStatus, double progressValue, object progressState = default);\n event ProgressReportingEventHandler Reporting;\n }\n}", "score": 0.8417180776596069 }, { "filename": "Source/TreeifyTask/TaskTree/ITaskNode.cs", "retrieved_chunk": " object ProgressState { get; }\n ITaskNode Parent { get; set; }\n IEnumerable<ITaskNode> ChildTasks { get; }\n TaskStatus TaskStatus { get; }\n void SetAction(Func<IProgressReporter, CancellationToken, Task> cancellableProgressReportingAsyncFunction);\n Task ExecuteInSeries(CancellationToken cancellationToken, bool throwOnError);\n Task ExecuteConcurrently(CancellationToken cancellationToken, bool throwOnError);\n void AddChild(ITaskNode childTask);\n void RemoveChild(ITaskNode childTask);\n void ResetStatus();", "score": 0.8187044262886047 }, { "filename": "Source/TreeifyTask.WpfSample/TaskNodeViewModel.cs", "retrieved_chunk": " {\n this._childTasks.Add(new TaskNodeViewModel(ct));\n }\n }\n private void BaseTaskNode_Reporting(object sender, ProgressReportingEventArgs eventArgs)\n {\n this.TaskStatus = eventArgs.TaskStatus;\n }\n public ObservableCollection<TaskNodeViewModel> ChildTasks =>\n _childTasks;", "score": 0.8117020130157471 } ]
csharp
IProgressReporter, CancellationToken, Task> cancellableProgressReportingAction) {
using HarmonyLib; using System; using System.Collections.Generic; using System.Text; using UnityEngine; using static Ultrapain.ConfigManager; namespace Ultrapain.Patches { // EID class EnemyIdentifier_UpdateModifiers { static void Postfix(EnemyIdentifier __instance) { EidStatContainer container = ConfigManager.enemyStats[__instance.enemyType]; if(__instance.enemyType == EnemyType.V2) { V2 comp = __instance.GetComponent<V2>(); if(comp != null && comp.secondEncounter) { container = ConfigManager.enemyStats[EnemyType.V2Second]; } } __instance.totalHealthModifier *= container.health.value; __instance.totalDamageModifier *= container.damage.value; __instance.totalSpeedModifier *= container.speed.value; List<string> weakness = new List<string>(); List<float> weaknessMulti = new List<float>(); foreach(KeyValuePair<string, float> weaknessPair in container.resistanceDict) { weakness.Add(weaknessPair.Key); int index = Array.IndexOf(__instance.weaknesses, weaknessPair.Key); if(index >= 0) { float defaultResistance = 1f / __instance.weaknessMultipliers[index]; if (defaultResistance > weaknessPair.Value) weaknessMulti.Add(1f / defaultResistance); else weaknessMulti.Add(1f / weaknessPair.Value); } else weaknessMulti.Add(1f / weaknessPair.Value); } for(int i = 0; i < __instance.weaknessMultipliers.Length; i++) { if (container.resistanceDict.ContainsKey(__instance.weaknesses[i])) continue; weakness.Add(__instance.weaknesses[i]); weaknessMulti.Add(__instance.weaknessMultipliers[i]); } __instance.weaknesses = weakness.ToArray(); __instance.weaknessMultipliers = weaknessMulti.ToArray(); } } // DETECT DAMAGE TYPE class Explosion_Collide_FF { static bool Prefix(Explosion __instance) { EnemyIdentifier_DeliverDamage_FF.currentCause = EnemyIdentifier_DeliverDamage_FF.DamageCause.Explosion; if ((__instance.enemy || __instance.friendlyFire) && __instance.canHit != AffectedSubjects.PlayerOnly) EnemyIdentifier_DeliverDamage_FF.friendlyBurn = true; return true; } static void Postfix() { EnemyIdentifier_DeliverDamage_FF.currentCause = EnemyIdentifier_DeliverDamage_FF.DamageCause.Unknown; EnemyIdentifier_DeliverDamage_FF.friendlyBurn = false; } } class PhysicalShockwave_CheckCollision_FF { static bool Prefix() { EnemyIdentifier_DeliverDamage_FF.currentCause = EnemyIdentifier_DeliverDamage_FF.DamageCause.Explosion; return true; } static void Postfix() { EnemyIdentifier_DeliverDamage_FF.currentCause = EnemyIdentifier_DeliverDamage_FF.DamageCause.Unknown; } } class VirtueInsignia_OnTriggerEnter_FF { static bool Prefix(VirtueInsignia __instance) { if (__instance.gameObject.name == "PlayerSpawned") return true; EnemyIdentifier_DeliverDamage_FF.currentCause = EnemyIdentifier_DeliverDamage_FF.DamageCause.Fire; EnemyIdentifier_DeliverDamage_FF.friendlyBurn = true; return true; } static void Postfix() { EnemyIdentifier_DeliverDamage_FF.currentCause = EnemyIdentifier_DeliverDamage_FF.DamageCause.Unknown; EnemyIdentifier_DeliverDamage_FF.friendlyBurn = false; } } class SwingCheck2_CheckCollision_FF { static bool Prefix() { EnemyIdentifier_DeliverDamage_FF.currentCause = EnemyIdentifier_DeliverDamage_FF.DamageCause.Melee; return true; } static void Postfix() { EnemyIdentifier_DeliverDamage_FF.currentCause = EnemyIdentifier_DeliverDamage_FF.DamageCause.Unknown; } } class Projectile_Collided_FF { static bool Prefix() { EnemyIdentifier_DeliverDamage_FF.currentCause = EnemyIdentifier_DeliverDamage_FF.DamageCause.Projectile; return true; } static void Postfix() { EnemyIdentifier_DeliverDamage_FF.currentCause = EnemyIdentifier_DeliverDamage_FF.DamageCause.Unknown; } } class EnemyIdentifier_DeliverDamage_FF { public enum DamageCause { Explosion, Projectile, Fire, Melee, Unknown } public static DamageCause currentCause = DamageCause.Unknown; public static bool friendlyBurn = false; [HarmonyBefore] static bool Prefix(EnemyIdentifier __instance, ref float __3) { if (currentCause != DamageCause.Unknown && (__instance.hitter == "enemy" || __instance.hitter == "ffexplosion")) { switch(currentCause) { case DamageCause.Projectile: //if (ConfigManager.friendlyFireDamageOverrideProjectile.normalizedValue == 0) // return false; __3 *= ConfigManager.friendlyFireDamageOverrideProjectile.normalizedValue; break; case DamageCause.Explosion: //if (ConfigManager.friendlyFireDamageOverrideProjectile.normalizedValue == 0) // return false; __3 *= ConfigManager.friendlyFireDamageOverrideExplosion.normalizedValue; break; case DamageCause.Melee: //if (ConfigManager.friendlyFireDamageOverrideProjectile.normalizedValue == 0) // return false; __3 *= ConfigManager.friendlyFireDamageOverrideMelee.normalizedValue; break; } } return true; } } class Flammable_Burn_FF { static bool Prefix(Flammable __instance, ref float __0) { if (EnemyIdentifier_DeliverDamage_FF.friendlyBurn) { if (ConfigManager.friendlyFireDamageOverrideFire.normalizedValue == 0) return false; __0 *= ConfigManager.friendlyFireDamageOverrideFire.normalizedValue; } return true; } } class StreetCleaner_Fire_FF { static bool Prefix(
FireZone __instance) {
if (__instance.source != FlameSource.Streetcleaner) return true; EnemyIdentifier_DeliverDamage_FF.friendlyBurn = true; return true; } static void Postfix(FireZone __instance) { if (__instance.source == FlameSource.Streetcleaner) EnemyIdentifier_DeliverDamage_FF.friendlyBurn = false; } } }
Ultrapain/Patches/GlobalEnemyTweaks.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Screwdriver.cs", "retrieved_chunk": " {\n targetEids.Clear();\n }\n }\n }\n }\n class Harpoon_Start\n {\n static void Postfix(Harpoon __instance)\n {", "score": 0.8573668003082275 }, { "filename": "Ultrapain/Patches/MaliciousFace.cs", "retrieved_chunk": " flag.charging = false;\n }\n return true;\n }\n }\n class MaliciousFace_ShootProj_Patch\n {\n /*static bool Prefix(SpiderBody __instance, ref GameObject ___proj, out bool __state)\n {\n __state = false;", "score": 0.8504744172096252 }, { "filename": "Ultrapain/Patches/OrbitalStrike.cs", "retrieved_chunk": " return true;\n }\n static void Postfix(Coin __instance)\n {\n coinIsShooting = false;\n }\n }\n class RevolverBeam_Start\n {\n static bool Prefix(RevolverBeam __instance)", "score": 0.8501372933387756 }, { "filename": "Ultrapain/Patches/MinosPrime.cs", "retrieved_chunk": " }\n }\n // aka PREPARE THYSELF\n class MinosPrime_Combo\n {\n static float timing = 3f;\n static void Postfix(MinosPrime __instance, EnemyIdentifier ___eid)\n {\n if (!ConfigManager.minosPrimeComboToggle.value)\n return;", "score": 0.846390962600708 }, { "filename": "Ultrapain/Patches/CustomProgress.cs", "retrieved_chunk": " __1 = 100;\n return true;\n }\n }\n [HarmonyPatch(typeof(GameProgressSaver), \"GetPrime\")]\n class CustomProgress_GetPrime\n {\n static bool Prefix(ref int __1)\n {\n if (Plugin.ultrapainDifficulty)", "score": 0.8460562825202942 } ]
csharp
FireZone __instance) {
namespace Client.ClientBase { public static class ModuleManager { public static List<Module> modules = new List<Module>(); public static void AddModule(Module module) { modules.Add(module); } public static void RemoveModule(Module module) { modules.Remove(module); } public static void Init() { Console.WriteLine("Initializing modules..."); AddModule(new Modules.AimAssist()); AddModule(new Modules.Aura()); AddModule(new Modules.ArrayList()); Console.WriteLine("Modules initialized."); } public static Module GetModule(string name) { foreach (Module module in modules) { if (module.name == name) { return module; } } return null; } public static List<Module> GetModules() { return modules; } public static List<Module> GetModulesInCategory(string category) { List<Module> modulesInCategory = new List<Module>(); foreach (Module module in modules) { if (module.category == category) { modulesInCategory.Add(module); } } return modulesInCategory; } public static List<Module> GetEnabledModules() { List<Module> enabledModules = new List<Module>(); foreach (Module module in modules) { if (module.enabled) { enabledModules.Add(module); } } return enabledModules; } public static List<
Module> GetEnabledModulesInCategory(string category) {
List<Module> enabledModulesInCategory = new List<Module>(); foreach (Module module in modules) { if (module.enabled && module.category == category) { enabledModulesInCategory.Add(module); } } return enabledModulesInCategory; } public static void OnTick() { foreach (Module module in modules) { if (module.enabled && module.tickable) { module.OnTick(); } } } public static void OnKeyPress(char keyChar) { foreach (Module module in modules) { if (module.MatchesKey(keyChar)) { if (module.enabled) { module.OnDisable(); Console.WriteLine("Disabled " + module.name); } else { module.OnEnable(); Console.WriteLine("Enabled " + module.name); } } } } } }
ClientBase/ModuleManager.cs
R1ck404-External-Cheat-Base-65a7014
[ { "filename": "Program.cs", "retrieved_chunk": " try\n {\n ModuleManager.OnTick();\n Thread.Sleep(1);\n }\n catch (Exception)\n {\n // ignored\n }\n }", "score": 0.7732113003730774 }, { "filename": "ClientBase/Module.cs", "retrieved_chunk": " enabled = false;\n }\n public virtual void OnTick()\n {\n if (!tickable)\n return;\n Task.Delay(100);\n }\n public bool MatchesKey(char key)\n {", "score": 0.7703324556350708 }, { "filename": "ClientBase/Module.cs", "retrieved_chunk": " this.tickable = tickable;\n }\n public virtual void OnEnable()\n {\n Client.ClientBase.UI.Notification.NotificationManager.AddNotification(name + \" has been enabled\", Color.FromArgb(102, 255, 71));\n enabled = true;\n }\n public virtual void OnDisable()\n {\n Client.ClientBase.UI.Notification.NotificationManager.AddNotification(name + \" has been disabled\", Color.FromArgb(173, 28, 17));", "score": 0.7693063020706177 }, { "filename": "ClientBase/Modules/ArrayList.cs", "retrieved_chunk": " public class ArrayList : VisualModule\n {\n private Point uiPosition = new Point(0, 0);\n private readonly Font uiFont = new Font(FontRenderer.sigmaFamily, 16);\n private List<string> lastModuleNames = new List<string>();\n private readonly Dictionary<string, float> modulePositions = new Dictionary<string, float>();\n public ArrayList() : base(\"ArrayList\", (char)0x2D, \"UI\", \"Shows all enabled modules from longest name to shortest\", false) // 0x2D = INSERT\n {\n }\n public override void OnDraw(Graphics graphics)", "score": 0.7608684301376343 }, { "filename": "Program.cs", "retrieved_chunk": " // IntPtr hwnd = GetForegroundWindow();\n // GetWindowThreadProcessId(hwnd, out int pid);\n // Process process = Process.GetProcessById(pid);\n // return pid == 19688 || process.ProcessName == \"Shatterline\";\n // }\n private static void ListenForKeybinds(char key)\n {\n // if (!IsGameForeground() && key != 0x2D) return;\n ModuleManager.OnKeyPress(key);\n }", "score": 0.7427170276641846 } ]
csharp
Module> GetEnabledModulesInCategory(string category) {
using HarmonyLib; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.ConstrainedExecution; using UnityEngine; namespace Ultrapain.Patches { class Drone_Start_Patch { static void Postfix(Drone __instance, ref EnemyIdentifier ___eid) { if (___eid.enemyType != EnemyType.Drone) return; __instance.gameObject.AddComponent<DroneFlag>(); } } class Drone_PlaySound_Patch { static FieldInfo antennaFlashField = typeof(Turret).GetField("antennaFlash", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); static ParticleSystem antennaFlash; public static Color defaultLineColor = new Color(1f, 0.44f, 0.74f); static bool Prefix(Drone __instance, EnemyIdentifier ___eid, AudioClip __0) { if (___eid.enemyType != EnemyType.Drone) return true; if(__0 == __instance.windUpSound) { DroneFlag flag = __instance.GetComponent<DroneFlag>(); if (flag == null) return true; List<Tuple<DroneFlag.Firemode, float>> chances = new List<Tuple<DroneFlag.Firemode, float>>(); if (ConfigManager.droneProjectileToggle.value) chances.Add(new Tuple<DroneFlag.Firemode, float>(DroneFlag.Firemode.Projectile, ConfigManager.droneProjectileChance.value)); if (ConfigManager.droneExplosionBeamToggle.value) chances.Add(new Tuple<DroneFlag.Firemode, float>(DroneFlag.Firemode.Explosive, ConfigManager.droneExplosionBeamChance.value)); if (ConfigManager.droneSentryBeamToggle.value) chances.Add(new Tuple<DroneFlag.Firemode, float>(DroneFlag.Firemode.TurretBeam, ConfigManager.droneSentryBeamChance.value)); if (chances.Count == 0 || chances.Sum(item => item.Item2) <= 0) flag.currentMode = DroneFlag.Firemode.Projectile; else flag.currentMode = UnityUtils.GetRandomFloatWeightedItem(chances, item => item.Item2).Item1; if (flag.currentMode == DroneFlag.Firemode.Projectile) { flag.attackDelay = ConfigManager.droneProjectileDelay.value; return true; } else if (flag.currentMode == DroneFlag.Firemode.Explosive) { flag.attackDelay = ConfigManager.droneExplosionBeamDelay.value; GameObject chargeEffect = GameObject.Instantiate(Plugin.chargeEffect, __instance.transform); chargeEffect.transform.localPosition = new Vector3(0, 0, 0.8f); chargeEffect.transform.localScale = Vector3.zero; float duration = ConfigManager.droneExplosionBeamDelay.value / ___eid.totalSpeedModifier; RemoveOnTime remover = chargeEffect.AddComponent<RemoveOnTime>(); remover.time = duration; CommonLinearScaler scaler = chargeEffect.AddComponent<CommonLinearScaler>(); scaler.targetTransform = scaler.transform; scaler.scaleSpeed = 1f / duration; CommonAudioPitchScaler pitchScaler = chargeEffect.AddComponent<CommonAudioPitchScaler>(); pitchScaler.targetAud = chargeEffect.GetComponent<AudioSource>(); pitchScaler.scaleSpeed = 1f / duration; return false; } else if (flag.currentMode == DroneFlag.Firemode.TurretBeam) { flag.attackDelay = ConfigManager.droneSentryBeamDelay.value; if(ConfigManager.droneDrawSentryBeamLine.value) { flag.lr.enabled = true; flag.SetLineColor(ConfigManager.droneSentryBeamLineNormalColor.value); flag.Invoke("LineRendererColorToWarning", Mathf.Max(0.01f, (flag.attackDelay / ___eid.totalSpeedModifier) - ConfigManager.droneSentryBeamLineIndicatorDelay.value)); } if (flag.particleSystem == null) { if (antennaFlash == null) antennaFlash = (ParticleSystem)antennaFlashField.GetValue(Plugin.turret); flag.particleSystem = GameObject.Instantiate(antennaFlash, __instance.transform); flag.particleSystem.transform.localPosition = new Vector3(0, 0, 2); } flag.particleSystem.Play(); GameObject flash = GameObject.Instantiate(Plugin.turretFinalFlash, __instance.transform); GameObject.Destroy(flash.transform.Find("MuzzleFlash/muzzleflash").gameObject); return false; } } return true; } } class Drone_Shoot_Patch { static bool Prefix(Drone __instance, ref EnemyIdentifier ___eid) { DroneFlag flag = __instance.GetComponent<DroneFlag>(); if(flag == null || __instance.crashing) return true; DroneFlag.Firemode mode = flag.currentMode; if (mode == DroneFlag.Firemode.Projectile) return true; if (mode == DroneFlag.Firemode.Explosive) { GameObject beam = GameObject.Instantiate(Plugin.beam.gameObject, __instance.transform.position + __instance.transform.forward, __instance.transform.rotation); RevolverBeam revBeam = beam.GetComponent<RevolverBeam>(); revBeam.hitParticle = Plugin.shotgunGrenade.gameObject.GetComponent<Grenade>().explosion; revBeam.damage /= 2; revBeam.damage *= ___eid.totalDamageModifier; return false; } if(mode == DroneFlag.Firemode.TurretBeam) { GameObject turretBeam = GameObject.Instantiate(Plugin.turretBeam.gameObject, __instance.transform.position + __instance.transform.forward * 2f, __instance.transform.rotation); if (turretBeam.TryGetComponent<RevolverBeam>(out RevolverBeam revBeam)) { revBeam.damage = ConfigManager.droneSentryBeamDamage.value; revBeam.damage *= ___eid.totalDamageModifier; revBeam.alternateStartPoint = __instance.transform.position + __instance.transform.forward; revBeam.ignoreEnemyType = EnemyType.Drone; } flag.lr.enabled = false; return false; } Debug.LogError($"Drone fire mode in impossible state. Current value: {mode} : {(int)mode}"); return true; } } class Drone_Update { static void Postfix(Drone __instance, EnemyIdentifier ___eid, ref float ___attackCooldown, int ___difficulty) { if (___eid.enemyType != EnemyType.Drone) return; DroneFlag flag = __instance.GetComponent<DroneFlag>(); if (flag == null || flag.attackDelay < 0) return; float attackSpeedDecay = (float)(___difficulty / 2); if (___difficulty == 1) { attackSpeedDecay = 0.75f; } else if (___difficulty == 0) { attackSpeedDecay = 0.5f; } attackSpeedDecay *= ___eid.totalSpeedModifier; float delay = flag.attackDelay / ___eid.totalSpeedModifier; __instance.CancelInvoke("Shoot"); __instance.Invoke("Shoot", delay); ___attackCooldown = UnityEngine.Random.Range(2f, 4f) + (flag.attackDelay - 0.75f) * attackSpeedDecay; flag.attackDelay = -1; } } class DroneFlag : MonoBehaviour { public enum Firemode : int { Projectile = 0, Explosive, TurretBeam } public ParticleSystem particleSystem; public LineRenderer lr; public Firemode currentMode = Firemode.Projectile; private static Firemode[] allModes = Enum.GetValues(typeof(Firemode)) as Firemode[]; static FieldInfo turretAimLine = typeof(Turret).GetField("aimLine", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); static Material whiteMat; public void Awake() { lr = gameObject.AddComponent<LineRenderer>(); lr.enabled = false; lr.receiveShadows = false; lr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; lr.startWidth = lr.endWidth = lr.widthMultiplier = 0.025f; if (whiteMat == null) whiteMat = ((LineRenderer)turretAimLine.GetValue(Plugin.turret)).material; lr.material = whiteMat; } public void SetLineColor(Color c) { Gradient gradient = new Gradient(); GradientColorKey[] array = new GradientColorKey[1]; array[0].color = c; GradientAlphaKey[] array2 = new GradientAlphaKey[1]; array2[0].alpha = 1f; gradient.SetKeys(array, array2); lr.colorGradient = gradient; } public void LineRendererColorToWarning() { SetLineColor(ConfigManager.droneSentryBeamLineWarningColor.value); } public float attackDelay = -1; public bool homingTowardsPlayer = false; Transform target; Rigidbody rb; private void Update() { if(homingTowardsPlayer) { if(target == null) target = PlayerTracker.Instance.GetTarget(); if (rb == null) rb = GetComponent<Rigidbody>(); Quaternion to = Quaternion.LookRotation(target.position/* + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity()*/ - transform.position); transform.rotation = Quaternion.RotateTowards(transform.rotation, to, Time.deltaTime * ConfigManager.droneHomeTurnSpeed.value); rb.velocity = transform.forward * rb.velocity.magnitude; } if(lr.enabled) { lr.SetPosition(0, transform.position); lr.SetPosition(1, transform.position + transform.forward * 1000); } } } class Drone_Death_Patch { static bool Prefix(Drone __instance, EnemyIdentifier ___eid) { if (___eid.enemyType != EnemyType.Drone || __instance.crashing) return true; DroneFlag flag = __instance.GetComponent<DroneFlag>(); if (flag == null) return true; if (___eid.hitter == "heavypunch" || ___eid.hitter == "punch") return true; flag.homingTowardsPlayer = true; return true; } } class Drone_GetHurt_Patch { static bool Prefix(
Drone __instance, EnemyIdentifier ___eid, bool ___parried) {
if((___eid.hitter == "shotgunzone" || ___eid.hitter == "punch") && !___parried) { DroneFlag flag = __instance.GetComponent<DroneFlag>(); if (flag == null) return true; flag.homingTowardsPlayer = false; } return true; } } }
Ultrapain/Patches/Drone.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Cerberus.cs", "retrieved_chunk": " {\n CerberusFlag flag = __instance.GetComponent<CerberusFlag>();\n if (flag == null)\n return;\n flag.MakeParryable();\n }\n }\n class Statue_GetHurt_Patch\n {\n static bool Prefix(Statue __instance, EnemyIdentifier ___eid)", "score": 0.8857265114784241 }, { "filename": "Ultrapain/Patches/MaliciousFace.cs", "retrieved_chunk": " flag.charging = false;\n }\n return true;\n }\n }\n class MaliciousFace_ShootProj_Patch\n {\n /*static bool Prefix(SpiderBody __instance, ref GameObject ___proj, out bool __state)\n {\n __state = false;", "score": 0.8854522705078125 }, { "filename": "Ultrapain/Patches/DruidKnight.cs", "retrieved_chunk": " aud.time = offset;\n aud.Play();\n return true;\n }\n }\n class Drone_Explode\n {\n static bool Prefix(bool ___exploded, out bool __state)\n {\n __state = ___exploded;", "score": 0.8741232752799988 }, { "filename": "Ultrapain/Patches/Screwdriver.cs", "retrieved_chunk": " if (!__instance.drill)\n return;\n DrillFlag flag = __instance.gameObject.AddComponent<DrillFlag>();\n flag.drill = __instance;\n }\n }\n class Harpoon_Punched\n {\n static void Postfix(Harpoon __instance, EnemyIdentifierIdentifier ___target)\n {", "score": 0.8701804876327515 }, { "filename": "Ultrapain/Patches/PlayerStatTweaks.cs", "retrieved_chunk": " }\n }\n return code.AsEnumerable();\n }\n }\n class NewMovement_GetHealth\n {\n static bool Prefix(NewMovement __instance, int __0, bool __1, ref AudioSource ___greenHpAud, Canvas ___fullHud)\n {\n if (__instance.dead || __instance.exploded)", "score": 0.8652167320251465 } ]
csharp
Drone __instance, EnemyIdentifier ___eid, bool ___parried) {
using HarmonyLib; using UnityEngine; using UnityEngine.AI; namespace Ultrapain.Patches { public class StrayFlag : MonoBehaviour { //public int extraShotsRemaining = 6; private Animator anim; private EnemyIdentifier eid; public GameObject standardProjectile; public GameObject standardDecorativeProjectile; public int comboRemaining = ConfigManager.strayShootCount.value; public bool inCombo = false; public float lastSpeed = 1f; public enum AttackMode { ProjectileCombo, FastHoming } public AttackMode currentMode = AttackMode.ProjectileCombo; public void Awake() { anim = GetComponent<Animator>(); eid = GetComponent<EnemyIdentifier>(); } public void Update() { if(eid.dead) { Destroy(this); return; } if (inCombo) { anim.speed = ZombieProjectile_ThrowProjectile_Patch.animSpeed; anim.SetFloat("Speed", ZombieProjectile_ThrowProjectile_Patch.animSpeed); } } } public class ZombieProjectile_Start_Patch1 { static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid) { if (___eid.enemyType != EnemyType.Stray) return; StrayFlag flag = __instance.gameObject.AddComponent<StrayFlag>(); flag.standardProjectile = __instance.projectile; flag.standardDecorativeProjectile = __instance.decProjectile; flag.currentMode = StrayFlag.AttackMode.ProjectileCombo; /*__instance.projectile = Plugin.homingProjectile; __instance.decProjectile = Plugin.decorativeProjectile2;*/ } } public class ZombieProjectile_ThrowProjectile_Patch { public static float normalizedTime = 0f; public static float animSpeed = 20f; public static float projectileSpeed = 75; public static float turnSpeedMultiplier = 0.45f; public static int projectileDamage = 10; public static int explosionDamage = 20; public static float coreSpeed = 110f; static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid, ref Animator ___anim, ref GameObject ___currentProjectile , ref NavMeshAgent ___nma, ref
Zombie ___zmb) {
if (___eid.enemyType != EnemyType.Stray) return; StrayFlag flag = __instance.gameObject.GetComponent<StrayFlag>(); if (flag == null) return; if (flag.currentMode == StrayFlag.AttackMode.FastHoming) { Projectile proj = ___currentProjectile.GetComponent<Projectile>(); if (proj != null) { proj.target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); proj.speed = projectileSpeed * ___eid.totalSpeedModifier; proj.turningSpeedMultiplier = turnSpeedMultiplier; proj.safeEnemyType = EnemyType.Stray; proj.damage = projectileDamage * ___eid.totalDamageModifier; } flag.currentMode = StrayFlag.AttackMode.ProjectileCombo; __instance.projectile = flag.standardProjectile; __instance.decProjectile = flag.standardDecorativeProjectile; } else if(flag.currentMode == StrayFlag.AttackMode.ProjectileCombo) { flag.comboRemaining -= 1; if (flag.comboRemaining == 0) { flag.comboRemaining = ConfigManager.strayShootCount.value; //flag.currentMode = StrayFlag.AttackMode.FastHoming; flag.inCombo = false; ___anim.speed = flag.lastSpeed; ___anim.SetFloat("Speed", flag.lastSpeed); //__instance.projectile = Plugin.homingProjectile; //__instance.decProjectile = Plugin.decorativeProjectile2; } else { flag.inCombo = true; __instance.swinging = true; __instance.seekingPlayer = false; ___nma.updateRotation = false; __instance.transform.LookAt(new Vector3(___zmb.target.position.x, __instance.transform.position.y, ___zmb.target.position.z)); flag.lastSpeed = ___anim.speed; //___anim.Play("ThrowProjectile", 0, ZombieProjectile_ThrowProjectile_Patch.normalizedTime); ___anim.speed = ConfigManager.strayShootSpeed.value; ___anim.SetFloat("Speed", ConfigManager.strayShootSpeed.value); ___anim.SetTrigger("Swing"); //___anim.SetFloat("AttackType", 0f); //___anim.StopPlayback(); //flag.Invoke("LateCombo", 0.01f); //___anim.runtimeAnimatorController.animationClips.Where(clip => clip.name == "ThrowProjectile").First(). //___anim.fireEvents = true; } } } } class Swing { static void Postfix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid) { if (___eid.enemyType != EnemyType.Stray) return; ___eid.weakPoint = null; } } /*[HarmonyPatch(typeof(ZombieProjectiles), "Swing")] class Swing { static void Postfix() { Debug.Log("Swing()"); } }*/ class SwingEnd { static bool Prefix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid) { if (___eid.enemyType != EnemyType.Stray) return true; StrayFlag flag = __instance.gameObject.GetComponent<StrayFlag>(); if (flag == null) return true; if (flag.inCombo) return false; return true; } } /*[HarmonyPatch(typeof(ZombieProjectiles), "DamageStart")] class DamageStart { static void Postfix() { Debug.Log("DamageStart()"); } }*/ class DamageEnd { static bool Prefix(ZombieProjectiles __instance, ref EnemyIdentifier ___eid) { if (___eid.enemyType != EnemyType.Stray) return true; StrayFlag flag = __instance.gameObject.GetComponent<StrayFlag>(); if (flag == null) return true; if (flag.inCombo) return false; return true; } } }
Ultrapain/Patches/Stray.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Mindflayer.cs", "retrieved_chunk": " //___eid.SpeedBuff();\n }\n }\n class Mindflayer_ShootProjectiles_Patch\n {\n public static float maxProjDistance = 5;\n public static float initialProjectileDistance = -1f;\n public static float distancePerProjShot = 0.2f;\n static bool Prefix(Mindflayer __instance, ref EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___enraged)\n {", "score": 0.9025173783302307 }, { "filename": "Ultrapain/Patches/Leviathan.cs", "retrieved_chunk": " class Leviathan_FixedUpdate\n {\n public static float projectileForward = 10f;\n static bool Roll(float chancePercent)\n {\n return UnityEngine.Random.Range(0, 99.9f) <= chancePercent;\n }\n static bool Prefix(LeviathanHead __instance, LeviathanController ___lcon, ref bool ___projectileBursting, float ___projectileBurstCooldown,\n Transform ___shootPoint, ref bool ___trackerIgnoreLimits, Animator ___anim, ref int ___previousAttack)\n {", "score": 0.8895494937896729 }, { "filename": "Ultrapain/Plugin.cs", "retrieved_chunk": " public static GameObject maliciousRailcannon;\n // Variables\n public static float SoliderShootAnimationStart = 1.2f;\n public static float SoliderGrenadeForce = 10000f;\n public static float SwordsMachineKnockdownTimeNormalized = 0.8f;\n public static float SwordsMachineCoreSpeed = 80f;\n public static float MinGrenadeParryVelocity = 40f;\n public static GameObject _lighningBoltSFX;\n public static GameObject lighningBoltSFX\n {", "score": 0.8868683576583862 }, { "filename": "Ultrapain/Patches/CommonComponents.cs", "retrieved_chunk": " public float superSize = 1f;\n public float superSpeed = 1f;\n public float superDamage = 1f;\n public int superPlayerDamageOverride = -1;\n struct StateInfo\n {\n public GameObject tempHarmless;\n public GameObject tempNormal;\n public GameObject tempSuper;\n public StateInfo()", "score": 0.8648834228515625 }, { "filename": "Ultrapain/Patches/V2Common.cs", "retrieved_chunk": " return true;\n }\n }\n class V2CommonRevolverBulletSharp : MonoBehaviour\n {\n public int reflectionCount = 2;\n public float autoAimAngle = 30f;\n public Projectile proj;\n public float speed = 350f;\n public bool hasTargetPoint = false;", "score": 0.860183596611023 } ]
csharp
Zombie ___zmb) {
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Moadian.Dto { public class InvoiceDto : PrimitiveDto { public
InvoiceHeaderDto header {
get; set; } public List<InvoiceBodyDto> body { get; set; } public List<InvoicePaymentDto> payments { get; set; } } }
Dto/InvoiceDto.cs
Torabi-srh-Moadian-482c806
[ { "filename": "Dto/InvoiceBodyDto.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Moadian.Dto\n{\n public class InvoiceBodyDto : PrimitiveDto\n {\n // service stuff ID", "score": 0.9621332883834839 }, { "filename": "Dto/InvoicePaymentDto.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Moadian.Dto\n{\n public class InvoicePaymentDto : PrimitiveDto\n {\n private string? iinn;", "score": 0.9587174654006958 }, { "filename": "Dto/InquiryByReferenceNumberDto.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Moadian.Dto\n{\n public class InquiryByReferenceNumberDto : PrimitiveDto\n {\n private string[] referenceNumber;", "score": 0.9363775849342346 }, { "filename": "Dto/GetTokenDto.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Moadian.Dto\n{\n public class GetTokenDto : PrimitiveDto\n {\n public string username { get; set; }", "score": 0.9239293336868286 }, { "filename": "Dto/TokenModel.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Moadian.Dto\n{\n public class TokenModel\n {\n public TokenModel(string token, int expiresAt)", "score": 0.913796067237854 } ]
csharp
InvoiceHeaderDto header {
using DotNetDevBadgeWeb.Interfaces; using DotNetDevBadgeWeb.Model; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace DotNetDevBadgeWeb.Core.Provider { internal class ForumDataProvider : IProvider { private const string UNKOWN_IMG_PATH = "Assets/unknown.png"; private const string BASE_URL = "https://forum.dotnetdev.kr"; private const string BADGE_URL = "https://forum.dotnetdev.kr/user-badges/{0}.json?grouped=true"; private const string SUMMARY_URL = "https://forum.dotnetdev.kr/u/{0}/summary.json"; private readonly IHttpClientFactory _httpClientFactory; public ForumDataProvider(IHttpClientFactory httpClientFactory) { _httpClientFactory = httpClientFactory; } private async Task<string> GetResponseStringAsync(Uri uri, CancellationToken token) { using HttpClient client = _httpClientFactory.CreateClient(); using HttpResponseMessage response = await client.GetAsync(uri, token); return await response.Content.ReadAsStringAsync(token); } private async Task<byte[]> GetResponseBytesAsync(Uri uri, CancellationToken token) { using HttpClient client = _httpClientFactory.CreateClient(); using HttpResponseMessage response = await client.GetAsync(uri, token); return await response.Content.ReadAsByteArrayAsync(token); } public async
Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token) {
Uri summaryUri = new(string.Format(SUMMARY_URL, id)); string summaryData = await GetResponseStringAsync(summaryUri, token); JObject summaryJson = JObject.Parse(summaryData); UserSummary userSummary = JsonConvert.DeserializeObject<UserSummary>(summaryJson["user_summary"]?.ToString() ?? string.Empty) ?? new(); List<User>? users = JsonConvert.DeserializeObject<List<User>>(summaryJson["users"]?.ToString() ?? string.Empty); User user = users?.Where(user => user.Id != -1).FirstOrDefault() ?? new(); return (userSummary, user); } public async Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token) { (UserSummary summary, User user) = await GetUserInfoAsync(id, token); if (string.IsNullOrEmpty(user.AvatarEndPoint)) return (await File.ReadAllBytesAsync(UNKOWN_IMG_PATH, token), summary, user); Uri avatarUri = new(string.Concat(BASE_URL, user.AvatarEndPoint)); return (await GetResponseBytesAsync(avatarUri, token), summary, user); } public async Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token) { Uri badgeUri = new(string.Format(BADGE_URL, id)); string badgeData = await GetResponseStringAsync(badgeUri, token); JObject badgeJson = JObject.Parse(badgeData); var badges = badgeJson["badges"]?.GroupBy(badge => badge["badge_type_id"]?.ToString() ?? string.Empty).Select(g => new { Type = g.Key, Count = g.Count(), }).ToDictionary(kv => kv.Type, kv => kv.Count); int gold = default; int silver = default; int bronze = default; if (badges is not null) { gold = badges.ContainsKey("1") ? badges["1"] : 0; silver = badges.ContainsKey("2") ? badges["2"] : 0; bronze = badges.ContainsKey("3") ? badges["3"] : 0; } return (gold, silver, bronze); } } }
src/dotnetdev-badge/dotnetdev-badge.web/Core/Provider/ForumDataProvider.cs
chanos-dev-dotnetdev-badge-5740a40
[ { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Interfaces/IProvider.cs", "retrieved_chunk": "using DotNetDevBadgeWeb.Model;\nnamespace DotNetDevBadgeWeb.Interfaces\n{\n public interface IProvider\n {\n Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n }\n}", "score": 0.8026026487350464 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Middleware/BadgeIdValidatorMiddleware.cs", "retrieved_chunk": "namespace DotNetDevBadgeWeb.Middleware\n{\n public class BadgeIdValidatorMiddleware\n {\n private readonly RequestDelegate _next;\n public BadgeIdValidatorMiddleware(RequestDelegate next)\n {\n _next = next;\n }\n public async Task InvokeAsync(HttpContext context)", "score": 0.7528550028800964 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Interfaces/IBadge.cs", "retrieved_chunk": "using DotNetDevBadgeWeb.Common;\nnamespace DotNetDevBadgeWeb.Interfaces\n{\n public interface IBadge\n {\n Task<string> GetSmallBadge(string id, ETheme theme, CancellationToken token);\n Task<string> GetMediumBadge(string id, ETheme theme, CancellationToken token);\n }\n public interface IBadgeV1 : IBadge\n {", "score": 0.75242018699646 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Core/Badge/BadgeCreatorV1.cs", "retrieved_chunk": " private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n private readonly IProvider _forumProvider;\n private readonly IMeasureTextV1 _measureTextV1;\n public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n {\n _forumProvider = forumProvider;\n _measureTextV1 = measureTextV1;\n }\n public async Task<string> GetSmallBadge(string id, ETheme theme, CancellationToken token)\n {", "score": 0.7495548725128174 }, { "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Endpoints/Badge/BadgeEndpoints.cs", "retrieved_chunk": " {\n app.UseMiddleware<BadgeIdValidatorMiddleware>();\n app.MapBadgeEndpointsV1();\n return app;\n }\n internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n {\n app.MapGet(\"/api/v1/badge/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n {\n string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);", "score": 0.7091333270072937 } ]
csharp
Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token) {
namespace Parser.SymbolTableUtil { /// <summary> /// Represents a symbol table for TSLang. /// </summary> internal class SymbolTable { /// <summary> /// Gets the symbol table of the upper scope. /// </summary> public SymbolTable? UpperScope { get; } /// <summary> /// Includes symbols of the symbol table. /// </summary> private readonly Dictionary<string,
ISymbol> symbols;
/// <summary> /// Initializes a new instance of the <see cref="SymbolTable"/> class. /// </summary> public SymbolTable() { symbols = new(); } /// <summary> /// Initializes a new instance of the <see cref="SymbolTable"/> class. /// </summary> /// <param name="upperScope">The symbol table for the upper scope.</param> public SymbolTable(SymbolTable? upperScope) { symbols = new(); UpperScope = upperScope; } /// <summary> /// Checks whether a symbol with provided identifier (name) exists in the symbol table. /// </summary> /// <param name="identifier">Identifier to check for.</param> /// <returns> /// True if a symbol with the specified identifier exists in the symbol table. /// False otherwise. /// </returns> public bool Exists(string identifier) { bool e; SymbolTable? st = this; do { e = st.symbols.ContainsKey(identifier); st = st.UpperScope; } while (!e && st is not null); return e; } /// <summary> /// Adds new symbol to the symbol table. /// </summary> /// <param name="symbol">The symbol to be added to the symbol table.</param> /// <exception cref="ArgumentException"></exception> public void Add(ISymbol symbol) { if (Exists(symbol.Identifier)) throw new ArgumentException("A symbol with the same identifier already exists in the symbol table."); symbols.Add(symbol.Identifier, symbol); } /// <summary> /// Gets the symbol with specified identifier (name) from the symbol table. /// </summary> /// <param name="identifier">Identifier (name) of the symbol.</param> /// <returns>The symbol with the specified identifier.</returns> /// <exception cref="ArgumentException"></exception> public ISymbol Get(string identifier) { SymbolTable? st = this; do { if (st.symbols.ContainsKey(identifier)) return st.symbols[identifier]; st = st.UpperScope; } while (st is not null); throw new ArgumentException("Identifier does not exist in the symbol table."); } } }
Parser/SymbolTableUtil/SymbolTable.cs
amirsina-mashayekh-TSLang-Compiler-3a68caf
[ { "filename": "Parser/TSLangParser.cs", "retrieved_chunk": " private Token lastToken;\n /// <summary>\n /// Gets current token.\n /// </summary>\n private Token CurrentToken => lastToken;\n /// <summary>\n /// Root symbol table of the code.\n /// </summary>\n private readonly SymbolTable rootSymTab;\n /// <summary>", "score": 0.923865020275116 }, { "filename": "Parser/TSLangParser.cs", "retrieved_chunk": " /// Symbol table for current scope.\n /// </summary>\n private SymbolTable currentSymTab;\n /// <summary>\n /// Gets whether an error occured while parsing the code.\n /// </summary>\n public bool HasError { get; private set; }\n /// <summary>\n /// Last token which caused syntax error.\n /// </summary>", "score": 0.923227846622467 }, { "filename": "Parser/SymbolTableUtil/ISymbol.cs", "retrieved_chunk": "namespace Parser.SymbolTableUtil\n{\n /// <summary>\n /// Represents a symbol which has a name and type.\n /// </summary>\n internal interface ISymbol\n {\n /// <summary>\n /// Gets name of the symbol.\n /// </summary>", "score": 0.9225186109542847 }, { "filename": "Parser/SymbolTableUtil/Function.cs", "retrieved_chunk": " /// </summary>\n public string Identifier { get; }\n /// <summary>\n /// Gets return type of the function.\n /// </summary>\n public SymbolType Type { get; }\n /// <summary>\n /// Gets list of the function parameters.\n /// </summary>\n public ReadOnlyCollection<Variable> Parameters { get; }", "score": 0.9190041422843933 }, { "filename": "Parser/SymbolTableUtil/ISymbol.cs", "retrieved_chunk": " public string Identifier { get; }\n /// <summary>\n /// Gets type of the symbol.\n /// </summary>\n public SymbolType Type { get; }\n }\n}", "score": 0.906810998916626 } ]
csharp
ISymbol> symbols;
using ExampleWebApplication.WebSocketHubKeys; using Microsoft.AspNetCore.Mvc; using TraTech.WebSocketHub; namespace ExampleWebApplication.Controllers { [ApiController] [Route("[controller]")] public class WebSocket2Controller : ControllerBase { private readonly WebSocketHub<
SocketUser> _webSocketHub;
public WebSocket2Controller(WebSocketHub<SocketUser> webSocketHub) { _webSocketHub = webSocketHub; } [HttpGet("GetSocketListWithSelector")] public IActionResult GetSocketListWithSelector(int id) { var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id); return Ok(socketListOfUser); } [HttpGet("RemoveAsyncWithSelector")] public async Task<IActionResult> RemoveWithSelector(int id) { var firstSocketOfUser = _webSocketHub.GetSocketList((key) => key.Id == id).First(); await _webSocketHub.RemoveAsync( (key) => key.Id == id, firstSocketOfUser ); return Ok(firstSocketOfUser); } [HttpGet("RemoveFirstAsync")] public async Task<IActionResult> RemoveFirstAsync(int id) { await _webSocketHub.RemoveFirstAsync( (key) => key.Id > id ); return Ok(); } [HttpGet("RemoveWhereAsync")] public async Task<IActionResult> RemoveWhereAsync(int id) { await _webSocketHub.RemoveWhereAsync( (key) => key.Id > id ); return Ok(); } [HttpGet("RemoveAllAsync")] public async Task<IActionResult> RemoveAllAsync() { await _webSocketHub.RemoveAllAsync(); return Ok(); } [HttpGet("SendAsyncWithSocketList")] public async Task<IActionResult> SendAsyncWithSocketList(int id) { var message = new Message() { Type = "SendAsyncWithSocketList", Payload = new { Data = "SendAsyncWithSocketList" } }; var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id); await _webSocketHub.SendAsync(message, socketListOfUser.ToArray()); return Ok(); } [HttpGet("SendAsyncWithSelector")] public async Task<IActionResult> SendAsyncWithSelector(int id) { var message = new Message() { Type = "SendAsyncWithSelector", Payload = new { Data = "SendAsyncWithSelector" } }; await _webSocketHub.SendAsync(message, (key) => key.Id == id); return Ok(); } [HttpGet("SendWhereAsync")] public async Task<IActionResult> SendWhereAsync(int id) { var message = new Message() { Type = "SendWhereAsync", Payload = new { Data = "SendWhereAsync" } }; await _webSocketHub.SendWhereAsync(message, (key) => key.Id > id); return Ok(); } [HttpGet("SendAllAsync")] public async Task<IActionResult> SendAllAsync() { var message = new Message() { Type = "SendAllAsync", Payload = new { Data = "SendAllAsync" } }; await _webSocketHub.SendAllAsync(message); return Ok(); } } }
src/ExampleWebApplication/Controllers/WebSocket2Controller.cs
TRA-Tech-dotnet-websocket-9049854
[ { "filename": "src/ExampleWebApplication/Controllers/WebSocket1Controller.cs", "retrieved_chunk": "using Microsoft.AspNetCore.Mvc;\nusing TraTech.WebSocketHub;\nnamespace ExampleWebApplication.Controllers\n{\n [ApiController]\n [Route(\"[controller]\")]\n public class WebSocket1Controller : ControllerBase\n {\n private readonly WebSocketHub<int> _webSocketHub;\n public WebSocket1Controller(WebSocketHub<int> webSocketHub)", "score": 0.9785761833190918 }, { "filename": "src/WebSocketHub/Core/src/WebSocketHubMiddleware.cs", "retrieved_chunk": "using System.Net.WebSockets;\nusing System.Text;\nusing Microsoft.AspNetCore.Http;\nusing Newtonsoft.Json;\nnamespace TraTech.WebSocketHub\n{\n public class WebSocketHubMiddleware<TKey>\n where TKey : notnull\n {\n private readonly IServiceProvider _serviceProvider;", "score": 0.832648515701294 }, { "filename": "src/ExampleWebApplication/WebSocketRequestHandlers/WebSocketRequestHandler2.cs", "retrieved_chunk": "using TraTech.WebSocketHub;\nnamespace ExampleWebApplication.WebSocketRequestHandlers\n{\n public class WebSocketRequestHandler2 : IWebSocketRequestHandler\n {\n public Task HandleRequestAsync(string key, string data)\n {\n Console.WriteLine(\"------- HandleRequestAsync started -------\");\n Console.WriteLine(\"key\");\n Console.WriteLine(key);", "score": 0.7906262278556824 }, { "filename": "src/ExampleWebApplication/WebSocketRequestHandlers/WebSocketRequestHandler1.cs", "retrieved_chunk": "using TraTech.WebSocketHub;\nnamespace ExampleWebApplication.WebSocketRequestHandlers\n{\n public class WebSocketRequestHandler1 : IWebSocketRequestHandler\n {\n public Task HandleRequestAsync(string key, string data)\n {\n Console.WriteLine(\"------- HandleRequestAsync started -------\");\n Console.WriteLine(\"key\");\n Console.WriteLine(key);", "score": 0.7902464866638184 }, { "filename": "src/WebSocketHub/Core/src/WebSocketHubAppBuilderExtensions.cs", "retrieved_chunk": "using Microsoft.AspNetCore.Builder;\nusing Microsoft.AspNetCore.Http;\nusing Microsoft.AspNetCore.WebSockets;\nnamespace TraTech.WebSocketHub\n{\n public static class WebSocketHubAppBuilderExtensions\n {\n /// <summary>\n /// Adds the WebSocketHubMiddleware to the pipeline with the specified acceptIf and keyGenerator functions.\n /// </summary>", "score": 0.7394169569015503 } ]
csharp
SocketUser> _webSocketHub;
using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Linq.Expressions; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text.Json; using System.Threading.Tasks; using Magic.IndexedDb.Helpers; using Magic.IndexedDb.Models; using Magic.IndexedDb.SchemaAnnotations; using Microsoft.JSInterop; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; using static System.Collections.Specialized.BitVector32; using static System.Runtime.InteropServices.JavaScript.JSType; namespace Magic.IndexedDb { /// <summary> /// Provides functionality for accessing IndexedDB from Blazor application /// </summary> public class IndexedDbManager { readonly DbStore _dbStore; readonly IJSRuntime _jsRuntime; const string InteropPrefix = "window.magicBlazorDB"; DotNetObjectReference<IndexedDbManager> _objReference; IDictionary<Guid, WeakReference<Action<BlazorDbEvent>>> _transactions = new Dictionary<Guid, WeakReference<Action<BlazorDbEvent>>>(); IDictionary<Guid, TaskCompletionSource<BlazorDbEvent>> _taskTransactions = new Dictionary<Guid, TaskCompletionSource<BlazorDbEvent>>(); private IJSObjectReference? _module { get; set; } /// <summary> /// A notification event that is raised when an action is completed /// </summary> public event EventHandler<BlazorDbEvent> ActionCompleted; /// <summary> /// Ctor /// </summary> /// <param name="dbStore"></param> /// <param name="jsRuntime"></param> #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. internal IndexedDbManager(DbStore dbStore, IJSRuntime jsRuntime) #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. { _objReference = DotNetObjectReference.Create(this); _dbStore = dbStore; _jsRuntime = jsRuntime; } public async Task<IJSObjectReference> GetModule(IJSRuntime jsRuntime) { if (_module == null) { _module = await jsRuntime.InvokeAsync<IJSObjectReference>("import", "./_content/Magic.IndexedDb/magicDB.js"); } return _module; } public List<StoreSchema> Stores => _dbStore.StoreSchemas; public string CurrentVersion => _dbStore.Version; public string DbName => _dbStore.Name; /// <summary> /// Opens the IndexedDB defined in the DbStore. Under the covers will create the database if it does not exist /// and create the stores defined in DbStore. /// </summary> /// <returns></returns> public async Task<Guid> OpenDb(Action<BlazorDbEvent>? action = null) { var trans = GenerateTransaction(action); await CallJavascriptVoid(IndexedDbFunctions.CREATE_DB, trans, _dbStore); return trans; } /// <summary> /// Deletes the database corresponding to the dbName passed in /// </summary> /// <param name="dbName">The name of database to delete</param> /// <returns></returns> public async Task<Guid> DeleteDb(string dbName, Action<BlazorDbEvent>? action = null) { if (string.IsNullOrEmpty(dbName)) { throw new ArgumentException("dbName cannot be null or empty", nameof(dbName)); } var trans = GenerateTransaction(action); await CallJavascriptVoid(IndexedDbFunctions.DELETE_DB, trans, dbName); return trans; } /// <summary> /// Deletes the database corresponding to the dbName passed in /// Waits for response /// </summary> /// <param name="dbName">The name of database to delete</param> /// <returns></returns> public async Task<BlazorDbEvent> DeleteDbAsync(string dbName) { if (string.IsNullOrEmpty(dbName)) { throw new ArgumentException("dbName cannot be null or empty", nameof(dbName)); } var trans = GenerateTransaction(); await CallJavascriptVoid(IndexedDbFunctions.DELETE_DB, trans.trans, dbName); return await trans.task; } /// <summary> /// Adds a new record/object to the specified store /// </summary> /// <typeparam name="T"></typeparam> /// <param name="recordToAdd">An instance of StoreRecord that provides the store name and the data to add</param> /// <returns></returns> private async Task<Guid> AddRecord<T>(
StoreRecord<T> recordToAdd, Action<BlazorDbEvent>? action = null) {
var trans = GenerateTransaction(action); try { recordToAdd.DbName = DbName; await CallJavascriptVoid(IndexedDbFunctions.ADD_ITEM, trans, recordToAdd); } catch (JSException e) { RaiseEvent(trans, true, e.Message); } return trans; } public async Task<Guid> Add<T>(T record, Action<BlazorDbEvent>? action = null) where T : class { string schemaName = SchemaHelper.GetSchemaName<T>(); T? myClass = null; object? processedRecord = await ProcessRecord(record); if (processedRecord is ExpandoObject) myClass = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(processedRecord)); else myClass = (T?)processedRecord; var trans = GenerateTransaction(action); try { Dictionary<string, object?>? convertedRecord = null; if (processedRecord is ExpandoObject) { var result = ((ExpandoObject)processedRecord)?.ToDictionary(kv => kv.Key, kv => (object?)kv.Value); if (result != null) { convertedRecord = result; } } else { convertedRecord = ManagerHelper.ConvertRecordToDictionary(myClass); } var propertyMappings = ManagerHelper.GeneratePropertyMapping<T>(); // Convert the property names in the convertedRecord dictionary if (convertedRecord != null) { var updatedRecord = ManagerHelper.ConvertPropertyNamesUsingMappings(convertedRecord, propertyMappings); if (updatedRecord != null) { StoreRecord<Dictionary<string, object?>> RecordToSend = new StoreRecord<Dictionary<string, object?>>() { DbName = this.DbName, StoreName = schemaName, Record = updatedRecord }; await CallJavascriptVoid(IndexedDbFunctions.ADD_ITEM, trans, RecordToSend); } } } catch (JSException e) { RaiseEvent(trans, true, e.Message); } return trans; } public async Task<string> Decrypt(string EncryptedValue) { EncryptionFactory encryptionFactory = new EncryptionFactory(_jsRuntime, this); string decryptedValue = await encryptionFactory.Decrypt(EncryptedValue, _dbStore.EncryptionKey); return decryptedValue; } private async Task<object?> ProcessRecord<T>(T record) where T : class { string schemaName = SchemaHelper.GetSchemaName<T>(); StoreSchema? storeSchema = Stores.FirstOrDefault(s => s.Name == schemaName); if (storeSchema == null) { throw new InvalidOperationException($"StoreSchema not found for '{schemaName}'"); } // Encrypt properties with EncryptDb attribute var propertiesToEncrypt = typeof(T).GetProperties() .Where(p => p.GetCustomAttributes(typeof(MagicEncryptAttribute), false).Length > 0); EncryptionFactory encryptionFactory = new EncryptionFactory(_jsRuntime, this); foreach (var property in propertiesToEncrypt) { if (property.PropertyType != typeof(string)) { throw new InvalidOperationException("EncryptDb attribute can only be used on string properties."); } string? originalValue = property.GetValue(record) as string; if (!string.IsNullOrWhiteSpace(originalValue)) { string encryptedValue = await encryptionFactory.Encrypt(originalValue, _dbStore.EncryptionKey); property.SetValue(record, encryptedValue); } else { property.SetValue(record, originalValue); } } // Proceed with adding the record if (storeSchema.PrimaryKeyAuto) { var primaryKeyProperty = typeof(T) .GetProperties() .FirstOrDefault(p => p.GetCustomAttributes(typeof(MagicPrimaryKeyAttribute), false).Length > 0); if (primaryKeyProperty != null) { Dictionary<string, object?> recordAsDict; var primaryKeyValue = primaryKeyProperty.GetValue(record); if (primaryKeyValue == null || primaryKeyValue.Equals(GetDefaultValue(primaryKeyValue.GetType()))) { recordAsDict = typeof(T).GetProperties() .Where(p => p.Name != primaryKeyProperty.Name && p.GetCustomAttributes(typeof(MagicNotMappedAttribute), false).Length == 0) .ToDictionary(p => p.Name, p => p.GetValue(record)); } else { recordAsDict = typeof(T).GetProperties() .Where(p => p.GetCustomAttributes(typeof(MagicNotMappedAttribute), false).Length == 0) .ToDictionary(p => p.Name, p => p.GetValue(record)); } // Create a new ExpandoObject and copy the key-value pairs from the dictionary var expandoRecord = new ExpandoObject() as IDictionary<string, object?>; foreach (var kvp in recordAsDict) { expandoRecord.Add(kvp); } return expandoRecord as ExpandoObject; } } return record; } // Returns the default value for the given type private static object? GetDefaultValue(Type type) { return type.IsValueType ? Activator.CreateInstance(type) : null; } /// <summary> /// Adds records/objects to the specified store in bulk /// </summary> /// <typeparam name="T"></typeparam> /// <param name="recordsToBulkAdd">The data to add</param> /// <returns></returns> private async Task<Guid> BulkAddRecord<T>(string storeName, IEnumerable<T> recordsToBulkAdd, Action<BlazorDbEvent>? action = null) { var trans = GenerateTransaction(action); try { await CallJavascriptVoid(IndexedDbFunctions.BULKADD_ITEM, trans, DbName, storeName, recordsToBulkAdd); } catch (JSException e) { RaiseEvent(trans, true, e.Message); } return trans; } //public async Task<Guid> AddRange<T>(IEnumerable<T> records, Action<BlazorDbEvent> action = null) where T : class //{ // string schemaName = SchemaHelper.GetSchemaName<T>(); // var propertyMappings = ManagerHelper.GeneratePropertyMapping<T>(); // List<object> processedRecords = new List<object>(); // foreach (var record in records) // { // object processedRecord = await ProcessRecord(record); // if (processedRecord is ExpandoObject) // { // var convertedRecord = ((ExpandoObject)processedRecord).ToDictionary(kv => kv.Key, kv => (object)kv.Value); // processedRecords.Add(ManagerHelper.ConvertPropertyNamesUsingMappings(convertedRecord, propertyMappings)); // } // else // { // var convertedRecord = ManagerHelper.ConvertRecordToDictionary((T)processedRecord); // processedRecords.Add(ManagerHelper.ConvertPropertyNamesUsingMappings(convertedRecord, propertyMappings)); // } // } // return await BulkAddRecord(schemaName, processedRecords, action); //} /// <summary> /// Adds records/objects to the specified store in bulk /// Waits for response /// </summary> /// <typeparam name="T"></typeparam> /// <param name="recordsToBulkAdd">An instance of StoreRecord that provides the store name and the data to add</param> /// <returns></returns> private async Task<BlazorDbEvent> BulkAddRecordAsync<T>(string storeName, IEnumerable<T> recordsToBulkAdd) { var trans = GenerateTransaction(); try { await CallJavascriptVoid(IndexedDbFunctions.BULKADD_ITEM, trans.trans, DbName, storeName, recordsToBulkAdd); } catch (JSException e) { RaiseEvent(trans.trans, true, e.Message); } return await trans.task; } public async Task AddRange<T>(IEnumerable<T> records) where T : class { string schemaName = SchemaHelper.GetSchemaName<T>(); //var trans = GenerateTransaction(null); //var TableCount = await CallJavascript<int>(IndexedDbFunctions.COUNT_TABLE, trans, DbName, schemaName); List<Dictionary<string, object?>> processedRecords = new List<Dictionary<string, object?>>(); foreach (var record in records) { bool IsExpando = false; T? myClass = null; object? processedRecord = await ProcessRecord(record); if (processedRecord is ExpandoObject) { myClass = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(processedRecord)); IsExpando = true; } else myClass = (T?)processedRecord; Dictionary<string, object?>? convertedRecord = null; if (processedRecord is ExpandoObject) { var result = ((ExpandoObject)processedRecord)?.ToDictionary(kv => kv.Key, kv => (object?)kv.Value); if (result != null) convertedRecord = result; } else { convertedRecord = ManagerHelper.ConvertRecordToDictionary(myClass); } var propertyMappings = ManagerHelper.GeneratePropertyMapping<T>(); // Convert the property names in the convertedRecord dictionary if (convertedRecord != null) { var updatedRecord = ManagerHelper.ConvertPropertyNamesUsingMappings(convertedRecord, propertyMappings); if (updatedRecord != null) { if (IsExpando) { //var test = updatedRecord.Cast<Dictionary<string, object>(); var dictionary = updatedRecord as Dictionary<string, object?>; processedRecords.Add(dictionary); } else { processedRecords.Add(updatedRecord); } } } } await BulkAddRecordAsync(schemaName, processedRecords); } public async Task<Guid> Update<T>(T item, Action<BlazorDbEvent>? action = null) where T : class { var trans = GenerateTransaction(action); try { string schemaName = SchemaHelper.GetSchemaName<T>(); PropertyInfo? primaryKeyProperty = typeof(T).GetProperties().FirstOrDefault(prop => Attribute.IsDefined(prop, typeof(MagicPrimaryKeyAttribute))); if (primaryKeyProperty != null) { object? primaryKeyValue = primaryKeyProperty.GetValue(item); var convertedRecord = ManagerHelper.ConvertRecordToDictionary(item); if (primaryKeyValue != null) { UpdateRecord<Dictionary<string, object?>> record = new UpdateRecord<Dictionary<string, object?>>() { Key = primaryKeyValue, DbName = this.DbName, StoreName = schemaName, Record = convertedRecord }; // Get the primary key value of the item await CallJavascriptVoid(IndexedDbFunctions.UPDATE_ITEM, trans, record); } else { throw new ArgumentException("Item being updated must have a key."); } } } catch (JSException jse) { RaiseEvent(trans, true, jse.Message); } return trans; } public async Task<Guid> UpdateRange<T>(IEnumerable<T> items, Action<BlazorDbEvent>? action = null) where T : class { var trans = GenerateTransaction(action); try { string schemaName = SchemaHelper.GetSchemaName<T>(); PropertyInfo? primaryKeyProperty = typeof(T).GetProperties().FirstOrDefault(prop => Attribute.IsDefined(prop, typeof(MagicPrimaryKeyAttribute))); if (primaryKeyProperty != null) { List<UpdateRecord<Dictionary<string, object?>>> recordsToUpdate = new List<UpdateRecord<Dictionary<string, object?>>>(); foreach (var item in items) { object? primaryKeyValue = primaryKeyProperty.GetValue(item); var convertedRecord = ManagerHelper.ConvertRecordToDictionary(item); if (primaryKeyValue != null) { recordsToUpdate.Add(new UpdateRecord<Dictionary<string, object?>>() { Key = primaryKeyValue, DbName = this.DbName, StoreName = schemaName, Record = convertedRecord }); } await CallJavascriptVoid(IndexedDbFunctions.BULKADD_UPDATE, trans, recordsToUpdate); } } else { throw new ArgumentException("Item being update range item must have a key."); } } catch (JSException jse) { RaiseEvent(trans, true, jse.Message); } return trans; } public async Task<TResult?> GetById<TResult>(object key) where TResult : class { string schemaName = SchemaHelper.GetSchemaName<TResult>(); // Find the primary key property var primaryKeyProperty = typeof(TResult) .GetProperties() .FirstOrDefault(p => p.GetCustomAttributes(typeof(MagicPrimaryKeyAttribute), false).Length > 0); if (primaryKeyProperty == null) { throw new InvalidOperationException("No primary key property found with PrimaryKeyDbAttribute."); } // Check if the key is of the correct type if (!primaryKeyProperty.PropertyType.IsInstanceOfType(key)) { throw new ArgumentException($"Invalid key type. Expected: {primaryKeyProperty.PropertyType}, received: {key.GetType()}"); } var trans = GenerateTransaction(null); string columnName = primaryKeyProperty.GetPropertyColumnName<MagicPrimaryKeyAttribute>(); var data = new { DbName = DbName, StoreName = schemaName, Key = columnName, KeyValue = key }; try { var propertyMappings = ManagerHelper.GeneratePropertyMapping<TResult>(); var RecordToConvert = await CallJavascript<Dictionary<string, object>>(IndexedDbFunctions.FIND_ITEMV2, trans, data.DbName, data.StoreName, data.KeyValue); if (RecordToConvert != null) { var ConvertedResult = ConvertIndexedDbRecordToCRecord<TResult>(RecordToConvert, propertyMappings); return ConvertedResult; } else { return default(TResult); } } catch (JSException jse) { RaiseEvent(trans, true, jse.Message); } return default(TResult); } public MagicQuery<T> Where<T>(Expression<Func<T, bool>> predicate) where T : class { string schemaName = SchemaHelper.GetSchemaName<T>(); MagicQuery<T> query = new MagicQuery<T>(schemaName, this); // Preprocess the predicate to break down Any and All expressions var preprocessedPredicate = PreprocessPredicate(predicate); var asdf = preprocessedPredicate.ToString(); CollectBinaryExpressions(preprocessedPredicate.Body, preprocessedPredicate, query.JsonQueries); return query; } private Expression<Func<T, bool>> PreprocessPredicate<T>(Expression<Func<T, bool>> predicate) { var visitor = new PredicateVisitor<T>(); var newExpression = visitor.Visit(predicate.Body); return Expression.Lambda<Func<T, bool>>(newExpression, predicate.Parameters); } internal async Task<IList<T>?> WhereV2<T>(string storeName, List<string> jsonQuery, MagicQuery<T> query) where T : class { var trans = GenerateTransaction(null); try { string? jsonQueryAdditions = null; if (query != null && query.storedMagicQueries != null && query.storedMagicQueries.Count > 0) { jsonQueryAdditions = Newtonsoft.Json.JsonConvert.SerializeObject(query.storedMagicQueries.ToArray()); } var propertyMappings = ManagerHelper.GeneratePropertyMapping<T>(); IList<Dictionary<string, object>>? ListToConvert = await CallJavascript<IList<Dictionary<string, object>>> (IndexedDbFunctions.WHEREV2, trans, DbName, storeName, jsonQuery.ToArray(), jsonQueryAdditions!, query?.ResultsUnique!); var resultList = ConvertListToRecords<T>(ListToConvert, propertyMappings); return resultList; } catch (Exception jse) { RaiseEvent(trans, true, jse.Message); } return default; } private void CollectBinaryExpressions<T>(Expression expression, Expression<Func<T, bool>> predicate, List<string> jsonQueries) where T : class { var binaryExpr = expression as BinaryExpression; if (binaryExpr != null && binaryExpr.NodeType == ExpressionType.OrElse) { // Split the OR condition into separate expressions var left = binaryExpr.Left; var right = binaryExpr.Right; // Process left and right expressions recursively CollectBinaryExpressions(left, predicate, jsonQueries); CollectBinaryExpressions(right, predicate, jsonQueries); } else { // If the expression is a single condition, create a query for it var test = expression.ToString(); var tes2t = predicate.ToString(); string jsonQuery = GetJsonQueryFromExpression(Expression.Lambda<Func<T, bool>>(expression, predicate.Parameters)); jsonQueries.Add(jsonQuery); } } private object ConvertValueToType(object value, Type targetType) { if (targetType == typeof(Guid) && value is string stringValue) { return Guid.Parse(stringValue); } return Convert.ChangeType(value, targetType); } private IList<TRecord> ConvertListToRecords<TRecord>(IList<Dictionary<string, object>> listToConvert, Dictionary<string, string> propertyMappings) { var records = new List<TRecord>(); var recordType = typeof(TRecord); foreach (var item in listToConvert) { var record = Activator.CreateInstance<TRecord>(); foreach (var kvp in item) { if (propertyMappings.TryGetValue(kvp.Key, out var propertyName)) { var property = recordType.GetProperty(propertyName); var value = ManagerHelper.GetValueFromValueKind(kvp.Value); if (property != null) { property.SetValue(record, ConvertValueToType(value!, property.PropertyType)); } } } records.Add(record); } return records; } private TRecord ConvertIndexedDbRecordToCRecord<TRecord>(Dictionary<string, object> item, Dictionary<string, string> propertyMappings) { var recordType = typeof(TRecord); var record = Activator.CreateInstance<TRecord>(); foreach (var kvp in item) { if (propertyMappings.TryGetValue(kvp.Key, out var propertyName)) { var property = recordType.GetProperty(propertyName); var value = ManagerHelper.GetValueFromValueKind(kvp.Value); if (property != null) { property.SetValue(record, ConvertValueToType(value!, property.PropertyType)); } } } return record; } private string GetJsonQueryFromExpression<T>(Expression<Func<T, bool>> predicate) where T : class { var serializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var conditions = new List<JObject>(); var orConditions = new List<List<JObject>>(); void TraverseExpression(Expression expression, bool inOrBranch = false) { if (expression is BinaryExpression binaryExpression) { if (binaryExpression.NodeType == ExpressionType.AndAlso) { TraverseExpression(binaryExpression.Left, inOrBranch); TraverseExpression(binaryExpression.Right, inOrBranch); } else if (binaryExpression.NodeType == ExpressionType.OrElse) { if (inOrBranch) { throw new InvalidOperationException("Nested OR conditions are not supported."); } TraverseExpression(binaryExpression.Left, !inOrBranch); TraverseExpression(binaryExpression.Right, !inOrBranch); } else { AddCondition(binaryExpression, inOrBranch); } } else if (expression is MethodCallExpression methodCallExpression) { AddCondition(methodCallExpression, inOrBranch); } } void AddCondition(Expression expression, bool inOrBranch) { if (expression is BinaryExpression binaryExpression) { var leftMember = binaryExpression.Left as MemberExpression; var rightMember = binaryExpression.Right as MemberExpression; var leftConstant = binaryExpression.Left as ConstantExpression; var rightConstant = binaryExpression.Right as ConstantExpression; var operation = binaryExpression.NodeType.ToString(); if (leftMember != null && rightConstant != null) { AddConditionInternal(leftMember, rightConstant, operation, inOrBranch); } else if (leftConstant != null && rightMember != null) { // Swap the order of the left and right expressions and the operation if (operation == "GreaterThan") { operation = "LessThan"; } else if (operation == "LessThan") { operation = "GreaterThan"; } else if (operation == "GreaterThanOrEqual") { operation = "LessThanOrEqual"; } else if (operation == "LessThanOrEqual") { operation = "GreaterThanOrEqual"; } AddConditionInternal(rightMember, leftConstant, operation, inOrBranch); } } else if (expression is MethodCallExpression methodCallExpression) { if (methodCallExpression.Method.DeclaringType == typeof(string) && (methodCallExpression.Method.Name == "Equals" || methodCallExpression.Method.Name == "Contains" || methodCallExpression.Method.Name == "StartsWith")) { var left = methodCallExpression.Object as MemberExpression; var right = methodCallExpression.Arguments[0] as ConstantExpression; var operation = methodCallExpression.Method.Name; var caseSensitive = true; if (methodCallExpression.Arguments.Count > 1) { var stringComparison = methodCallExpression.Arguments[1] as ConstantExpression; if (stringComparison != null && stringComparison.Value is StringComparison comparisonValue) { caseSensitive = comparisonValue == StringComparison.Ordinal || comparisonValue == StringComparison.CurrentCulture; } } AddConditionInternal(left, right, operation == "Equals" ? "StringEquals" : operation, inOrBranch, caseSensitive); } } } void AddConditionInternal(MemberExpression? left, ConstantExpression? right, string operation, bool inOrBranch, bool caseSensitive = false) { if (left != null && right != null) { var propertyInfo = typeof(T).GetProperty(left.Member.Name); if (propertyInfo != null) { bool index = propertyInfo.GetCustomAttributes(typeof(MagicIndexAttribute), false).Length == 0; bool unique = propertyInfo.GetCustomAttributes(typeof(MagicUniqueIndexAttribute), false).Length == 0; bool primary = propertyInfo.GetCustomAttributes(typeof(MagicPrimaryKeyAttribute), false).Length == 0; if (index == true && unique == true && primary == true) { throw new InvalidOperationException($"Property '{propertyInfo.Name}' does not have the IndexDbAttribute."); } string? columnName = null; if (index == false) columnName = propertyInfo.GetPropertyColumnName<MagicIndexAttribute>(); else if (unique == false) columnName = propertyInfo.GetPropertyColumnName<MagicUniqueIndexAttribute>(); else if (primary == false) columnName = propertyInfo.GetPropertyColumnName<MagicPrimaryKeyAttribute>(); bool _isString = false; JToken? valSend = null; if (right != null && right.Value != null) { valSend = JToken.FromObject(right.Value); _isString = right.Value is string; } var jsonCondition = new JObject { { "property", columnName }, { "operation", operation }, { "value", valSend }, { "isString", _isString }, { "caseSensitive", caseSensitive } }; if (inOrBranch) { var currentOrConditions = orConditions.LastOrDefault(); if (currentOrConditions == null) { currentOrConditions = new List<JObject>(); orConditions.Add(currentOrConditions); } currentOrConditions.Add(jsonCondition); } else { conditions.Add(jsonCondition); } } } } TraverseExpression(predicate.Body); if (conditions.Any()) { orConditions.Add(conditions); } return JsonConvert.SerializeObject(orConditions, serializerSettings); } public class QuotaUsage { public long quota { get; set; } public long usage { get; set; } } /// <summary> /// Returns Mb /// </summary> /// <returns></returns> public async Task<(double quota, double usage)> GetStorageEstimateAsync() { var storageInfo = await CallJavascriptNoTransaction<QuotaUsage>(IndexedDbFunctions.GET_STORAGE_ESTIMATE); double quotaInMB = ConvertBytesToMegabytes(storageInfo.quota); double usageInMB = ConvertBytesToMegabytes(storageInfo.usage); return (quotaInMB, usageInMB); } private static double ConvertBytesToMegabytes(long bytes) { return (double)bytes / (1024 * 1024); } public async Task<IEnumerable<T>> GetAll<T>() where T : class { var trans = GenerateTransaction(null); try { string schemaName = SchemaHelper.GetSchemaName<T>(); var propertyMappings = ManagerHelper.GeneratePropertyMapping<T>(); IList<Dictionary<string, object>>? ListToConvert = await CallJavascript<IList<Dictionary<string, object>>>(IndexedDbFunctions.TOARRAY, trans, DbName, schemaName); var resultList = ConvertListToRecords<T>(ListToConvert, propertyMappings); return resultList; } catch (JSException jse) { RaiseEvent(trans, true, jse.Message); } return Enumerable.Empty<T>(); } public async Task<Guid> Delete<T>(T item, Action<BlazorDbEvent>? action = null) where T : class { var trans = GenerateTransaction(action); try { string schemaName = SchemaHelper.GetSchemaName<T>(); PropertyInfo? primaryKeyProperty = typeof(T).GetProperties().FirstOrDefault(prop => Attribute.IsDefined(prop, typeof(MagicPrimaryKeyAttribute))); if (primaryKeyProperty != null) { object? primaryKeyValue = primaryKeyProperty.GetValue(item); var convertedRecord = ManagerHelper.ConvertRecordToDictionary(item); if (primaryKeyValue != null) { UpdateRecord<Dictionary<string, object?>> record = new UpdateRecord<Dictionary<string, object?>>() { Key = primaryKeyValue, DbName = this.DbName, StoreName = schemaName, Record = convertedRecord }; // Get the primary key value of the item await CallJavascriptVoid(IndexedDbFunctions.DELETE_ITEM, trans, record); } else { throw new ArgumentException("Item being Deleted must have a key."); } } } catch (JSException jse) { RaiseEvent(trans, true, jse.Message); } return trans; } public async Task<int> DeleteRange<TResult>(IEnumerable<TResult> items) where TResult : class { List<object> keys = new List<object>(); foreach (var item in items) { PropertyInfo? primaryKeyProperty = typeof(TResult).GetProperties().FirstOrDefault(prop => Attribute.IsDefined(prop, typeof(MagicPrimaryKeyAttribute))); if (primaryKeyProperty == null) { throw new InvalidOperationException("No primary key property found with PrimaryKeyDbAttribute."); } object? primaryKeyValue = primaryKeyProperty.GetValue(item); if (primaryKeyValue != null) keys.Add(primaryKeyValue); } string schemaName = SchemaHelper.GetSchemaName<TResult>(); var trans = GenerateTransaction(null); var data = new { DbName = DbName, StoreName = schemaName, Keys = keys }; try { var deletedCount = await CallJavascript<int>(IndexedDbFunctions.BULK_DELETE, trans, data.DbName, data.StoreName, data.Keys); return deletedCount; } catch (JSException jse) { RaiseEvent(trans, true, jse.Message); } return 0; } /// <summary> /// Clears all data from a Table but keeps the table /// </summary> /// <param name="storeName"></param> /// <param name="action"></param> /// <returns></returns> public async Task<Guid> ClearTable(string storeName, Action<BlazorDbEvent>? action = null) { var trans = GenerateTransaction(action); try { await CallJavascriptVoid(IndexedDbFunctions.CLEAR_TABLE, trans, DbName, storeName); } catch (JSException jse) { RaiseEvent(trans, true, jse.Message); } return trans; } public async Task<Guid> ClearTable<T>(Action<BlazorDbEvent>? action = null) where T : class { var trans = GenerateTransaction(action); try { string schemaName = SchemaHelper.GetSchemaName<T>(); await CallJavascriptVoid(IndexedDbFunctions.CLEAR_TABLE, trans, DbName, schemaName); } catch (JSException jse) { RaiseEvent(trans, true, jse.Message); } return trans; } /// <summary> /// Clears all data from a Table but keeps the table /// Wait for response /// </summary> /// <param name="storeName"></param> /// <returns></returns> public async Task<BlazorDbEvent> ClearTableAsync(string storeName) { var trans = GenerateTransaction(); try { await CallJavascriptVoid(IndexedDbFunctions.CLEAR_TABLE, trans.trans, DbName, storeName); } catch (JSException jse) { RaiseEvent(trans.trans, true, jse.Message); } return await trans.task; } [JSInvokable("BlazorDBCallback")] public void CalledFromJS(Guid transaction, bool failed, string message) { if (transaction != Guid.Empty) { WeakReference<Action<BlazorDbEvent>>? r = null; _transactions.TryGetValue(transaction, out r); TaskCompletionSource<BlazorDbEvent>? t = null; _taskTransactions.TryGetValue(transaction, out t); if (r != null && r.TryGetTarget(out Action<BlazorDbEvent>? action)) { action?.Invoke(new BlazorDbEvent() { Transaction = transaction, Message = message, Failed = failed }); _transactions.Remove(transaction); } else if (t != null) { t.TrySetResult(new BlazorDbEvent() { Transaction = transaction, Message = message, Failed = failed }); _taskTransactions.Remove(transaction); } else RaiseEvent(transaction, failed, message); } } //async Task<TResult> CallJavascriptNoTransaction<TResult>(string functionName, params object[] args) //{ // return await _jsRuntime.InvokeAsync<TResult>($"{InteropPrefix}.{functionName}", args); //} async Task<TResult> CallJavascriptNoTransaction<TResult>(string functionName, params object[] args) { var mod = await GetModule(_jsRuntime); return await mod.InvokeAsync<TResult>($"{functionName}", args); } private const string dynamicJsCaller = "DynamicJsCaller"; /// <summary> /// /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="functionName"></param> /// <param name="transaction"></param> /// <param name="timeout">in ms</param> /// <param name="args"></param> /// <returns></returns> /// <exception cref="ArgumentException"></exception> public async Task<TResult> CallJS<TResult>(string functionName, double Timeout, params object[] args) { List<object> modifiedArgs = new List<object>(args); modifiedArgs.Insert(0, $"{InteropPrefix}.{functionName}"); Task<JsResponse<TResult>> task = _jsRuntime.InvokeAsync<JsResponse<TResult>>(dynamicJsCaller, modifiedArgs.ToArray()).AsTask(); Task delay = Task.Delay(TimeSpan.FromMilliseconds(Timeout)); if (await Task.WhenAny(task, delay) == task) { JsResponse<TResult> response = await task; if (response.Success) return response.Data; else throw new ArgumentException(response.Message); } else { throw new ArgumentException("Timed out after 1 minute"); } } //public async Task<TResult> CallJS<TResult>(string functionName, JsSettings Settings, params object[] args) //{ // var newArgs = GetNewArgs(Settings.Transaction, args); // Task<JsResponse<TResult>> task = _jsRuntime.InvokeAsync<JsResponse<TResult>>($"{InteropPrefix}.{functionName}", newArgs).AsTask(); // Task delay = Task.Delay(TimeSpan.FromMilliseconds(Settings.Timeout)); // if (await Task.WhenAny(task, delay) == task) // { // JsResponse<TResult> response = await task; // if (response.Success) // return response.Data; // else // throw new ArgumentException(response.Message); // } // else // { // throw new ArgumentException("Timed out after 1 minute"); // } //} //async Task<TResult> CallJavascript<TResult>(string functionName, Guid transaction, params object[] args) //{ // var newArgs = GetNewArgs(transaction, args); // return await _jsRuntime.InvokeAsync<TResult>($"{InteropPrefix}.{functionName}", newArgs); //} //async Task CallJavascriptVoid(string functionName, Guid transaction, params object[] args) //{ // var newArgs = GetNewArgs(transaction, args); // await _jsRuntime.InvokeVoidAsync($"{InteropPrefix}.{functionName}", newArgs); //} async Task<TResult> CallJavascript<TResult>(string functionName, Guid transaction, params object[] args) { var mod = await GetModule(_jsRuntime); var newArgs = GetNewArgs(transaction, args); return await mod.InvokeAsync<TResult>($"{functionName}", newArgs); } async Task CallJavascriptVoid(string functionName, Guid transaction, params object[] args) { var mod = await GetModule(_jsRuntime); var newArgs = GetNewArgs(transaction, args); await mod.InvokeVoidAsync($"{functionName}", newArgs); } object[] GetNewArgs(Guid transaction, params object[] args) { var newArgs = new object[args.Length + 2]; newArgs[0] = _objReference; newArgs[1] = transaction; for (var i = 0; i < args.Length; i++) newArgs[i + 2] = args[i]; return newArgs; } (Guid trans, Task<BlazorDbEvent> task) GenerateTransaction() { bool generated = false; var transaction = Guid.Empty; TaskCompletionSource<BlazorDbEvent> tcs = new TaskCompletionSource<BlazorDbEvent>(); do { transaction = Guid.NewGuid(); if (!_taskTransactions.ContainsKey(transaction)) { generated = true; _taskTransactions.Add(transaction, tcs); } } while (!generated); return (transaction, tcs.Task); } Guid GenerateTransaction(Action<BlazorDbEvent>? action) { bool generated = false; Guid transaction = Guid.Empty; do { transaction = Guid.NewGuid(); if (!_transactions.ContainsKey(transaction)) { generated = true; _transactions.Add(transaction, new WeakReference<Action<BlazorDbEvent>>(action!)); } } while (!generated); return transaction; } void RaiseEvent(Guid transaction, bool failed, string message) => ActionCompleted?.Invoke(this, new BlazorDbEvent { Transaction = transaction, Failed = failed, Message = message }); } }
Magic.IndexedDb/IndexDbManager.cs
magiccodingman-Magic.IndexedDb-a279d6d
[ { "filename": "Magic.IndexedDb/Models/JsResponse.cs", "retrieved_chunk": " {\n Data = data;\n Success = success;\n Message = message;\n }\n /// <summary>\n /// Dynamic typed response data\n /// </summary>\n public T Data { get; set; }\n /// <summary>", "score": 0.7884857654571533 }, { "filename": "Magic.IndexedDb/Models/MagicQuery.cs", "retrieved_chunk": " JsonQueries = new List<string>();\n }\n public List<StoredMagicQuery> storedMagicQueries { get; set; } = new List<StoredMagicQuery>();\n public bool ResultsUnique { get; set; } = true;\n /// <summary>\n /// Return a list of items in which the items do not have to be unique. Therefore, you can get \n /// duplicate instances of an object depending on how you write your query.\n /// </summary>\n /// <param name=\"amount\"></param>\n /// <returns></returns>", "score": 0.785547137260437 }, { "filename": "Magic.IndexedDb/Helpers/SchemaHelper.cs", "retrieved_chunk": " }\n }\n }\n }\n return schemas;\n }\n public static StoreSchema GetStoreSchema<T>(string name = null, bool PrimaryKeyAuto = true) where T : class\n {\n Type type = typeof(T);\n return GetStoreSchema(type, name, PrimaryKeyAuto);", "score": 0.771162748336792 }, { "filename": "Magic.IndexedDb/Factories/MagicDbFactory.cs", "retrieved_chunk": " return _dbs[dbName];\n#pragma warning disable CS8603 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.\n return null;\n#pragma warning restore CS8603 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.\n }\n public Task<IndexedDbManager> GetDbManager(DbStore dbStore)\n => GetDbManager(dbStore.Name);\n async Task BuildFromServices()\n {\n var dbStores = _serviceProvider.GetServices<DbStore>();", "score": 0.769420325756073 }, { "filename": "Magic.IndexedDb/Models/JsResponse.cs", "retrieved_chunk": " /// Boolean indicator for successful API call\n /// </summary>\n public bool Success { get; set; }\n /// <summary>\n /// Human readable message to describe success / error conditions\n /// </summary>\n public string Message { get; set; }\n }\n}", "score": 0.7632859945297241 } ]
csharp
StoreRecord<T> recordToAdd, Action<BlazorDbEvent>? action = null) {
#nullable enable using System.Collections.Generic; namespace Mochineko.KoeiromapAPI { internal static class StyleResolver { private static readonly IReadOnlyDictionary<
Style, string> Dictionary = new Dictionary<Style, string> {
[Style.Talk] = "talk", [Style.Happy] = "happy", [Style.Sad] = "sad", [Style.Angry] = "angry", [Style.Fear] = "fear", [Style.Surprised] = "surprised", }; public static Style ToStyle(this string style) => Dictionary.Inverse(style); public static string ToText(this Style style) => Dictionary[style]; } }
Assets/Mochineko/KoeiromapAPI/StyleResolver.cs
mochi-neko-llm-agent-sandbox-unity-6521c0b
[ { "filename": "Assets/Mochineko/KoeiromapAPI/InverseDictionaryExtension.cs", "retrieved_chunk": "#nullable enable\nusing System;\nusing System.Collections.Generic;\nnamespace Mochineko.KoeiromapAPI\n{\n internal static class InverseDictionaryExtension\n {\n public static T Inverse<T>(this IReadOnlyDictionary<T, string> dictionary, string key)\n where T : Enum\n {", "score": 0.9026174545288086 }, { "filename": "Assets/Mochineko/LLMAgent/Memory/TokenizerExtensions.cs", "retrieved_chunk": "#nullable enable\nusing System.Collections.Generic;\nusing Mochineko.ChatGPT_API;\nusing TiktokenSharp;\nnamespace Mochineko.LLMAgent.Memory\n{\n public static class TokenizerExtensions\n {\n public static int TokenLength(\n this IEnumerable<Message> messages,", "score": 0.8421143293380737 }, { "filename": "Assets/Mochineko/KoeiromapAPI/ResponseBody.cs", "retrieved_chunk": "#nullable enable\nusing System;\nusing Newtonsoft.Json;\nnamespace Mochineko.KoeiromapAPI\n{\n [JsonObject]\n internal sealed class ResponseBody\n {\n /// <summary>\n /// Required.", "score": 0.8348283171653748 }, { "filename": "Assets/Mochineko/LLMAgent/Operation/EmotionConverter.cs", "retrieved_chunk": "#nullable enable\nusing Mochineko.KoeiromapAPI;\nnamespace Mochineko.LLMAgent.Operation\n{\n internal static class EmotionConverter\n {\n public static Style ExcludeHighestEmotionStyle(\n Emotion.Emotion emotion,\n float threshold = 0.5f)\n {", "score": 0.832658052444458 }, { "filename": "Assets/Mochineko/KoeiromapAPI/RequestBody.cs", "retrieved_chunk": "#nullable enable\nusing Newtonsoft.Json;\nnamespace Mochineko.KoeiromapAPI\n{\n [JsonObject]\n internal sealed class RequestBody\n {\n /// <summary>\n /// Required.\n /// </summary>", "score": 0.8147218227386475 } ]
csharp
Style, string> Dictionary = new Dictionary<Style, string> {
using NowPlaying.Models; using NowPlaying.Views; using Playnite.SDK; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Windows; using System.Windows.Input; using System.Windows.Threading; namespace NowPlaying.ViewModels { public class AddGameCachesViewModel : ViewModelBase { private readonly NowPlaying plugin; private readonly Window popup; private readonly List<CacheRootViewModel> cacheRoots; private readonly List<
GameViewModel> allEligibleGames;
private string searchText; public string SearchText { get => searchText; set { if (searchText != value) { searchText = value; OnPropertyChanged(); if (string.IsNullOrWhiteSpace(searchText)) { EligibleGames = allEligibleGames; OnPropertyChanged(nameof(EligibleGames)); SelectNoGames(); } else { EligibleGames = allEligibleGames.Where(g => g.Title.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0).ToList(); OnPropertyChanged(nameof(EligibleGames)); SelectNoGames(); } } } } public class CustomInstallSizeSorter : IComparer { public int Compare(object x, object y) { long sizeX = ((GameViewModel)x).InstallSizeBytes; long sizeY = ((GameViewModel)y).InstallSizeBytes; return sizeX.CompareTo(sizeY); } } public CustomInstallSizeSorter CustomInstallSizeSort { get; private set; } public ICommand ClearSearchTextCommand { get; private set; } public ICommand SelectAllCommand { get; private set; } public ICommand SelectNoneCommand { get; private set; } public ICommand CloseCommand { get; private set; } public ICommand EnableSelectedGamesCommand { get; private set; } public List<string> CacheRoots => cacheRoots.Select(r => r.Directory).ToList(); public List<GameViewModel> EligibleGames { get; private set; } private List<GameViewModel> selectedGames; public List<GameViewModel> SelectedGames { get => selectedGames; set { selectedGames = value; OnPropertyChanged(); } } public string SelectedCacheRoot { get; set; } public string EligibleGamesVisibility => allEligibleGames.Count > 0 ? "Visible" : "Collapsed"; public string NoEligibleGamesVisibility => allEligibleGames.Count > 0 ? "Collapsed" : "Visible"; public AddGameCachesViewModel(NowPlaying plugin, Window popup) { this.plugin = plugin; this.popup = popup; this.CustomInstallSizeSort = new CustomInstallSizeSorter(); this.cacheRoots = plugin.cacheManager.CacheRoots.ToList(); this.SelectedGames = new List<GameViewModel>(); var eligibles = plugin.PlayniteApi.Database.Games.Where(g => plugin.IsGameNowPlayingEligible(g) != GameCachePlatform.InEligible); this.allEligibleGames = eligibles.Select(g => new GameViewModel(g)).ToList(); ClearSearchTextCommand = new RelayCommand(() => SearchText = string.Empty); SelectAllCommand = new RelayCommand(() => SelectAllGames()); SelectNoneCommand = new RelayCommand(() => SelectNoGames()); CloseCommand = new RelayCommand(() => CloseWindow()); EnableSelectedGamesCommand = new RelayCommand(() => EnableSelectedGamesAsync(), () => SelectedGames.Count > 0); SelectedCacheRoot = cacheRoots.First()?.Directory; OnPropertyChanged(nameof(SelectedCacheRoot)); EligibleGames = allEligibleGames; OnPropertyChanged(nameof(EligibleGames)); OnPropertyChanged(nameof(EligibleGamesVisibility)); OnPropertyChanged(nameof(NoEligibleGamesVisibility)); } public void SelectNoGames() { var view = popup.Content as AddGameCachesView; view?.EligibleGames_ClearSelected(); } public void SelectAllGames() { var view = popup.Content as AddGameCachesView; view?.EligibleGames_SelectAll(); } private async void EnableSelectedGamesAsync() { CloseWindow(); if (SelectedGames != null) { var cacheRoot = plugin.cacheManager.FindCacheRoot(SelectedCacheRoot); if (cacheRoot != null) { foreach (var game in SelectedGames) { if (!plugin.IsGameNowPlayingEnabled(game.game)) { if (await plugin.CheckIfGameInstallDirIsAccessibleAsync(game.Title, game.InstallDir)) { if (plugin.CheckAndConfirmOrAdjustInstallDirDepth(game.game)) { (new NowPlayingGameEnabler(plugin, game.game, cacheRoot.Directory)).Activate(); } } } } } } } public void CloseWindow() { if (popup.Dispatcher.CheckAccess()) { popup.Close(); } else { popup.Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadStart(popup.Close)); } } } }
source/ViewModels/AddGameCachesViewModel.cs
gittromney-Playnite-NowPlaying-23eec41
[ { "filename": "source/ViewModels/GameCacheManagerViewModel.cs", "retrieved_chunk": "using static NowPlaying.Models.GameCacheManager;\nusing Playnite.SDK;\nnamespace NowPlaying.ViewModels\n{\n public class GameCacheManagerViewModel : ViewModelBase\n {\n public readonly NowPlaying plugin;\n public readonly ILogger logger;\n private readonly string pluginUserDataPath;\n private readonly string cacheRootsJsonPath;", "score": 0.9332249164581299 }, { "filename": "source/ViewModels/AddCacheRootViewModel.cs", "retrieved_chunk": "{\n public class AddCacheRootViewModel : ViewModelBase\n {\n private readonly NowPlaying plugin;\n private readonly GameCacheManagerViewModel cacheManager;\n private Dictionary<string, string> rootDevices;\n private List<string> existingRoots;\n public Window popup { get; set; }\n public bool DeviceIsValid { get; private set; }\n public bool RootIsValid { get; private set; }", "score": 0.8896821737289429 }, { "filename": "source/NowPlayingGameEnabler.cs", "retrieved_chunk": "{\n public class NowPlayingGameEnabler\n {\n private readonly ILogger logger = NowPlaying.logger;\n private readonly NowPlaying plugin;\n private readonly IPlayniteAPI PlayniteApi;\n private readonly GameCacheManagerViewModel cacheManager;\n private readonly Game game;\n private readonly string cacheRootDir;\n public string Id => game.Id.ToString();", "score": 0.8808067440986633 }, { "filename": "source/Views/AddGameCachesView.xaml.cs", "retrieved_chunk": " /// </summary>\n public partial class AddGameCachesView : UserControl\n {\n private readonly AddGameCachesViewModel viewModel;\n public AddGameCachesView(AddGameCachesViewModel viewModel)\n {\n InitializeComponent();\n DataContext = viewModel;\n this.viewModel = viewModel;\n }", "score": 0.8806847929954529 }, { "filename": "source/ViewModels/GameCacheManagerViewModel.cs", "retrieved_chunk": " private readonly string gameCacheEntriesJsonPath;\n private readonly string installAverageBpsJsonPath;\n public readonly GameCacheManager gameCacheManager;\n public ObservableCollection<CacheRootViewModel> CacheRoots { get; private set; }\n public ObservableCollection<GameCacheViewModel> GameCaches { get; private set; }\n public SortedDictionary<string, long> InstallAverageBps { get; private set; }\n public GameCacheManagerViewModel(NowPlaying plugin, ILogger logger)\n {\n this.plugin = plugin;\n this.logger = logger;", "score": 0.8803848028182983 } ]
csharp
GameViewModel> allEligibleGames;
using HarmonyLib; using Sandbox; using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.AI; namespace Ultrapain.Patches { class MinosPrimeCharge { static GameObject decoy; public static void CreateDecoy() { if (decoy != null || Plugin.minosPrime == null) return; decoy = GameObject.Instantiate(Plugin.minosPrime, Vector3.zero, Quaternion.identity); decoy.SetActive(false); GameObject.Destroy(decoy.GetComponent<MinosPrime>()); GameObject.Destroy(decoy.GetComponent<Machine>()); GameObject.Destroy(decoy.GetComponent<BossHealthBar>()); GameObject.Destroy(decoy.GetComponent<EventOnDestroy>()); GameObject.Destroy(decoy.GetComponent<BossIdentifier>()); GameObject.Destroy(decoy.GetComponent<EnemyIdentifier>()); GameObject.Destroy(decoy.GetComponent<BasicEnemyDataRelay>()); GameObject.Destroy(decoy.GetComponent<Rigidbody>()); GameObject.Destroy(decoy.GetComponent<CapsuleCollider>()); GameObject.Destroy(decoy.GetComponent<AudioSource>()); GameObject.Destroy(decoy.GetComponent<NavMeshAgent>()); foreach (SkinnedMeshRenderer renderer in UnityUtils.GetComponentsInChildrenRecursively<SkinnedMeshRenderer>(decoy.transform)) { renderer.material = new Material(Plugin.gabrielFakeMat); } SandboxEnemy sbe = decoy.GetComponent<SandboxEnemy>(); if (sbe != null) GameObject.Destroy(sbe); MindflayerDecoy comp = decoy.AddComponent<MindflayerDecoy>(); comp.fadeSpeed = 1f; //decoy.GetComponent<Animator>().StopPlayback(); //decoy.GetComponent<Animator>().Update(100f); GameObject.Destroy(decoy.transform.Find("SwingCheck").gameObject); GameObject.Destroy(decoy.transform.Find("Capsule").gameObject); GameObject.Destroy(decoy.transform.Find("Point Light").gameObject); foreach (EnemyIdentifierIdentifier eii in UnityUtils.GetComponentsInChildrenRecursively<EnemyIdentifierIdentifier>(decoy.transform)) GameObject.Destroy(eii); } static void DrawTrail(MinosPrime instance, Animator anim, Vector3 startPosition, Vector3 targetPosition) { if(decoy == null) { CreateDecoy(); return; } targetPosition = Vector3.MoveTowards(targetPosition, startPosition, 5f); Vector3 currentPosition = startPosition; float distance = Vector3.Distance(startPosition, targetPosition); if (distance < 2.5f) return; float deltaDistance = 2.5f; float fadeSpeed = 1f / ConfigManager.minosPrimeTeleportTrailDuration.value; AnimatorStateInfo currentAnimatorStateInfo = anim.GetCurrentAnimatorStateInfo(0); int maxIterations = Mathf.CeilToInt(distance / deltaDistance); float currentTransparency = 0.1f; float deltaTransparencyPerIteration = 1f / maxIterations; while (currentPosition != targetPosition) { GameObject gameObject = GameObject.Instantiate(decoy, currentPosition, instance.transform.rotation); gameObject.SetActive(true); Animator componentInChildren = gameObject.GetComponentInChildren<Animator>(); componentInChildren.Play(currentAnimatorStateInfo.shortNameHash, 0, currentAnimatorStateInfo.normalizedTime); componentInChildren.speed = 0f; MindflayerDecoy comp = gameObject.GetComponent<MindflayerDecoy>(); comp.fadeSpeed = fadeSpeed; currentTransparency += deltaTransparencyPerIteration; comp.fadeOverride = Mathf.Min(1f, currentTransparency); currentPosition = Vector3.MoveTowards(currentPosition, targetPosition, deltaDistance); } } static void Postfix(MinosPrime __instance, Animator ___anim) { string stateName = ___anim.GetCurrentAnimatorClipInfo(0)[0].clip.name; MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (stateName == "Combo" || (flag != null && flag.throwingProjectile)) return; Transform player = MonoSingleton<PlayerTracker>.Instance.GetPlayer(); float min = ConfigManager.minosPrimeRandomTeleportMinDistance.value; float max = ConfigManager.minosPrimeRandomTeleportMaxDistance.value; Vector3 unitSphere = UnityEngine.Random.onUnitSphere; unitSphere.y = Mathf.Abs(unitSphere.y); float distance = UnityEngine.Random.Range(min, max); Ray ray = new Ray(player.position, unitSphere); LayerMask mask = new LayerMask(); mask.value |= 256 | 16777216; if (Physics.Raycast(ray, out RaycastHit hit, max, mask, QueryTriggerInteraction.Ignore)) { if (hit.distance < min) return; Vector3 point = ray.GetPoint(hit.distance - 5); __instance.Teleport(point, __instance.transform.position); } else { Vector3 point = ray.GetPoint(distance); __instance.Teleport(point, __instance.transform.position); } } static void TeleportPostfix(MinosPrime __instance, Animator ___anim, Vector3 __0, Vector3 __1) { DrawTrail(__instance, ___anim, __1, __0); } } class MinosPrimeFlag : MonoBehaviour { void Start() { } public void ComboExplosion() { GameObject explosion = Instantiate(Plugin.lightningStrikeExplosive, transform.position, Quaternion.identity); foreach(Explosion e in explosion.GetComponentsInChildren<Explosion>()) { e.toIgnore.Add(EnemyType.MinosPrime); e.maxSize *= ConfigManager.minosPrimeComboExplosionSize.value; e.speed *= ConfigManager.minosPrimeComboExplosionSize.value; e.damage = (int)(e.damage * ConfigManager.minosPrimeComboExplosionDamage.value); } } public void BigExplosion() { GameObject explosion = Instantiate(Plugin.lightningStrikeExplosive, transform.position, Quaternion.identity); foreach (Explosion e in explosion.GetComponentsInChildren<Explosion>()) { e.toIgnore.Add(EnemyType.MinosPrime); e.maxSize *= ConfigManager.minosPrimeExplosionSize.value; e.speed *= ConfigManager.minosPrimeExplosionSize.value; e.damage = (int)(e.damage * ConfigManager.minosPrimeExplosionDamage.value); } } public bool throwingProjectile = false; public string plannedAttack = ""; public bool explosionAttack = false; } class MinosPrime_Start { static void Postfix(MinosPrime __instance, Animator ___anim, ref bool ___enraged) { if (ConfigManager.minosPrimeEarlyPhaseToggle.value) ___enraged = true; __instance.gameObject.AddComponent<MinosPrimeFlag>(); if (ConfigManager.minosPrimeComboExplosionToggle.value) { AnimationClip boxing = ___anim.runtimeAnimatorController.animationClips.Where(item => item.name == "Boxing").First(); List<UnityEngine.AnimationEvent> boxingEvents = boxing.events.ToList(); boxingEvents.Insert(15, new UnityEngine.AnimationEvent() { time = 2.4f, functionName = "ComboExplosion", messageOptions = SendMessageOptions.RequireReceiver }); boxing.events = boxingEvents.ToArray(); } } } class MinosPrime_StopAction { static void Postfix(MinosPrime __instance, EnemyIdentifier ___eid) { MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (flag == null) return; if (flag.plannedAttack != "") { __instance.SendMessage(flag.plannedAttack); flag.plannedAttack = ""; } } } // aka JUDGEMENT class MinosPrime_Dropkick { static bool Prefix(MinosPrime __instance, EnemyIdentifier ___eid, ref bool ___inAction, Animator ___anim) { MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (flag == null) return true; if (!flag.throwingProjectile) { if (ConfigManager.minosPrimeExplosionToggle.value && UnityEngine.Random.Range(0, 99.9f) < ConfigManager.minosPrimeExplosionChance.value) { __instance.TeleportAnywhere(); ___inAction = true; flag.explosionAttack = true; ___anim.speed = ___eid.totalSpeedModifier * ConfigManager.minosPrimeExplosionWindupSpeed.value; ___anim.Play("Outro", 0, 0.5f); __instance.PlayVoice(new AudioClip[] { __instance.phaseChangeVoice }); return false; } if (ConfigManager.minosPrimeComboToggle.value) { flag.throwingProjectile = true; flag.plannedAttack = "Dropkick"; __instance.SendMessage("ProjectilePunch"); } return false; } else { if (ConfigManager.minosPrimeComboToggle.value) { flag.plannedAttack = "ProjectilePunch"; flag.throwingProjectile = false; } } return true; } } // aka PREPARE THYSELF class MinosPrime_Combo { static float timing = 3f; static void Postfix(MinosPrime __instance, EnemyIdentifier ___eid) { if (!ConfigManager.minosPrimeComboToggle.value) return; MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (flag == null) return; flag.plannedAttack = "Uppercut"; } } // aka DIE class MinosPrime_RiderKick { static bool Prefix(MinosPrime __instance, ref bool ___previouslyRiderKicked) { if (UnityEngine.Random.Range(0, 99.9f) > ConfigManager.minosPrimeCrushAttackChance.value) return true; ___previouslyRiderKicked = true; Vector3 vector = MonoSingleton<PlayerTracker>.Instance.PredictPlayerPosition(0.5f); Transform target = MonoSingleton<PlayerTracker>.Instance.GetPlayer(); if (vector.y < target.position.y) { vector.y = target.position.y; } __instance.Teleport(vector + Vector3.up * 25f, __instance.transform.position); __instance.SendMessage("DropAttack"); return false; } } // End of PREPARE THYSELF class MinosPrime_ProjectileCharge { static bool Prefix(MinosPrime __instance, Animator ___anim) { string clipname = ___anim.GetCurrentAnimatorClipInfo(0)[0].clip.name; if (clipname != "Combo" || UnityEngine.Random.Range(0, 99.9f) > ConfigManager.minosPrimeComboExplosiveEndChance.value) return true; ___anim.Play("Dropkick", 0, (1.0815f - 0.4279f) / 2.65f); return false; } } class MinosPrime_Ascend { static bool Prefix(MinosPrime __instance, EnemyIdentifier ___eid, Animator ___anim, ref bool ___vibrating) { if (___eid.health <= 0) return true; MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (flag == null) return true; if (!flag.explosionAttack) return true; ___anim.speed = ___eid.totalSpeedModifier; ___vibrating = false; flag.explosionAttack = false; flag.BigExplosion(); __instance.Invoke("Uppercut", 0.5f); return false; } } class MinosPrime_Death { static bool Prefix(MinosPrime __instance,
Animator ___anim, ref bool ___vibrating) {
MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (flag == null) return true; if (!flag.explosionAttack) return true; flag.explosionAttack = false; ___vibrating = false; ___anim.speed = 1f; ___anim.Play("Walk", 0, 0f); return true; } } }
Ultrapain/Patches/MinosPrime.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/PlayerStatTweaks.cs", "retrieved_chunk": " }\n }\n return code.AsEnumerable();\n }\n }\n class NewMovement_GetHealth\n {\n static bool Prefix(NewMovement __instance, int __0, bool __1, ref AudioSource ___greenHpAud, Canvas ___fullHud)\n {\n if (__instance.dead || __instance.exploded)", "score": 0.869421124458313 }, { "filename": "Ultrapain/Patches/Leviathan.cs", "retrieved_chunk": " }\n return false;\n }\n }\n class Leviathan_ProjectileBurst\n {\n static bool Prefix(LeviathanHead __instance, Animator ___anim,\n ref int ___projectilesLeftInBurst, ref float ___projectileBurstCooldown, ref bool ___inAction)\n {\n if (!__instance.active)", "score": 0.8678959608078003 }, { "filename": "Ultrapain/Patches/DruidKnight.cs", "retrieved_chunk": " aud.time = offset;\n aud.Play();\n return true;\n }\n }\n class Drone_Explode\n {\n static bool Prefix(bool ___exploded, out bool __state)\n {\n __state = ___exploded;", "score": 0.8646405935287476 }, { "filename": "Ultrapain/Patches/MaliciousFace.cs", "retrieved_chunk": " flag.charging = false;\n }\n return true;\n }\n }\n class MaliciousFace_ShootProj_Patch\n {\n /*static bool Prefix(SpiderBody __instance, ref GameObject ___proj, out bool __state)\n {\n __state = false;", "score": 0.8473946452140808 }, { "filename": "Ultrapain/Patches/Drone.cs", "retrieved_chunk": " return false;\n }\n Debug.LogError($\"Drone fire mode in impossible state. Current value: {mode} : {(int)mode}\");\n return true;\n }\n }\n class Drone_Update\n {\n static void Postfix(Drone __instance, EnemyIdentifier ___eid, ref float ___attackCooldown, int ___difficulty)\n {", "score": 0.8382798433303833 } ]
csharp
Animator ___anim, ref bool ___vibrating) {
using VRC.SDK3.Data; using Koyashiro.GenericDataContainer.Internal; namespace Koyashiro.GenericDataContainer { public static class DataListExt { public static int Capacity<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); return dataList.Capacity; } public static int Count<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); return dataList.Count; } public static void Add<T>(this DataList<T> list, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); dataList.Add(token); } public static void AddRange<T>(this DataList<T> list, T[] collection) { foreach (var item in collection) { list.Add(item); } } public static void AddRange<T>(this DataList<T> list, DataList<T> collection) { var dataList = (DataList)(object)(list); var tokens = (DataList)(object)collection; dataList.AddRange(tokens); } public static void BinarySearch<T>(this DataList<T> list, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); dataList.BinarySearch(token); } public static void BinarySearch<T>(this DataList<T> list, int index, int count, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); dataList.BinarySearch(index, count, token); } public static void Clear<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); dataList.Clear(); } public static bool Contains<T>(this DataList<T> list, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.Contains(token); } public static DataList<T> DeepClone<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); return (DataList<T>)(object)dataList.DeepClone(); } public static DataList<T> GetRange<T>(this DataList<T> list, int index, int count) { var dataList = (DataList)(object)(list); return (DataList<T>)(object)dataList.GetRange(index, count); } public static int IndexOf<T>(this DataList<T> list, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.IndexOf(token); } public static int IndexOf<T>(this DataList<T> list, T item, int index) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.IndexOf(token, index); } public static int IndexOf<T>(this DataList<T> list, T item, int index, int count) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.IndexOf(token, index, count); } public static void Insert<T>(this DataList<T> list, int index, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); dataList.Insert(index, token); } public static void InsertRange<T>(this DataList<T> list, int index, T[] collection) { for (var i = index; i < collection.Length; i++) { list.Insert(i, collection[i]); } } public static void InsertRange<T>(this DataList<T> list, int index, DataList<T> collection) { var dataList = (DataList)(object)(list); var tokens = (DataList)(object)collection; dataList.InsertRange(index, tokens); } public static int LastIndexOf<T>(this DataList<T> list, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.LastIndexOf(token); } public static int LastIndexOf<T>(this DataList<T> list, T item, int index) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.LastIndexOf(token, index); } public static int LastIndexOf<T>(this DataList<T> list, T item, int index, int count) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.LastIndexOf(token, index, count); } public static bool Remove<T>(this DataList<T> list, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.Remove(token); } public static bool RemoveAll<T>(this DataList<T> list, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); return dataList.RemoveAll(token); } public static void RemoveAt<T>(this DataList<T> list, int index) { var dataList = (DataList)(object)(list); dataList.RemoveAt(index); } public static void RemoveRange<T>(this DataList<T> list, int index, int count) { var dataList = (DataList)(object)(list); dataList.RemoveRange(index, count); } public static void Reverse<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); dataList.Reverse(); } public static void Reverse<T>(this DataList<T> list, int index, int count) { var dataList = (DataList)(object)(list); dataList.Reverse(index, count); } public static void SetValue<T>(this DataList<T> list, int index, T item) { var dataList = (DataList)(object)(list); var token = DataTokenUtil.NewDataToken(item); dataList.SetValue(index, token); } public static
DataList<T> ShallowClone<T>(this DataList<T> list) {
var dataList = (DataList)(object)(list); return (DataList<T>)(object)dataList.ShallowClone(); } public static void Sort<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); dataList.Sort(); } public static void Sort<T>(this DataList<T> list, int index, int count) { var dataList = (DataList)(object)(list); dataList.Sort(index, count); } public static T[] ToArray<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); var length = dataList.Count; var array = new T[length]; for (var i = 0; i < length; i++) { var token = dataList[i]; switch (token.TokenType) { case TokenType.Reference: array[i] = (T)token.Reference; break; default: array[i] = (T)(object)token; break; } } return array; } public static object[] ToObjectArray<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); var length = dataList.Count; var array = new object[length]; for (var i = 0; i < length; i++) { var token = dataList[i]; switch (token.TokenType) { case TokenType.Reference: array[i] = (T)token.Reference; break; default: array[i] = (T)(object)token; break; } } return array; } public static void TrimExcess<T>(this DataList<T> list) { var dataList = (DataList)(object)(list); dataList.TrimExcess(); } public static bool TryGetValue<T>(this DataList<T> list, int index, out T value) { var dataList = (DataList)(object)(list); if (!dataList.TryGetValue(index, out var token)) { value = default; return false; } switch (token.TokenType) { case TokenType.Reference: value = (T)token.Reference; break; default: value = (T)(object)token; break; } return true; } public static T GetValue<T>(this DataList<T> list, int index) { var dataList = (DataList)(object)(list); var token = dataList[index]; switch (token.TokenType) { case TokenType.Reference: return (T)token.Reference; default: return (T)(object)token; } } } }
Packages/net.koyashiro.genericdatacontainer/Runtime/DataListExt.cs
koyashiro-generic-data-container-1aef372
[ { "filename": "Packages/net.koyashiro.genericdatacontainer/Runtime/DataDictionaryExt.cs", "retrieved_chunk": " return result;\n }\n public static void SetValue<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary, TKey key, TValue value)\n {\n var dataDictionary = (DataDictionary)(object)(dictionary);\n var keyToken = DataTokenUtil.NewDataToken(key);\n var keyValue = DataTokenUtil.NewDataToken(value);\n dataDictionary.SetValue(keyToken, keyValue);\n }\n public static DataDictionary<TKey, TValue> ShallowClone<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary)", "score": 0.8722127676010132 }, { "filename": "Packages/net.koyashiro.genericdatacontainer/Runtime/DataDictionaryExt.cs", "retrieved_chunk": " }\n public static void Add<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary, TKey key, TValue value)\n {\n var dataDictionary = (DataDictionary)(object)(dictionary);\n var keyToken = DataTokenUtil.NewDataToken(key);\n var valueToken = DataTokenUtil.NewDataToken(value);\n dataDictionary.Add(keyToken, valueToken);\n }\n public static void Clear<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary)\n {", "score": 0.8633701801300049 }, { "filename": "Packages/net.koyashiro.genericdatacontainer/Runtime/DataList.cs", "retrieved_chunk": " {\n return (DataList<T>)(object)new DataList();\n }\n public static DataList<T> New(params T[] array)\n {\n var tokens = DataTokenUtil.NewDataTokens(array);\n return (DataList<T>)(object)new DataList(tokens);\n }\n }\n}", "score": 0.8595669865608215 }, { "filename": "Packages/net.koyashiro.genericdatacontainer/Runtime/DataDictionaryExt.cs", "retrieved_chunk": " var dataDictionary = (DataDictionary)(object)(dictionary);\n dataDictionary.Clear();\n }\n public static bool ContainsKey<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary, TKey key)\n {\n var dataDictionary = (DataDictionary)(object)(dictionary);\n var keyToken = DataTokenUtil.NewDataToken(key);\n return dataDictionary.ContainsKey(keyToken);\n }\n public static bool ContainsValue<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary, TValue value)", "score": 0.8370541930198669 }, { "filename": "Packages/net.koyashiro.genericdatacontainer/Runtime/DataDictionaryExt.cs", "retrieved_chunk": " {\n var dataDictionary = (DataDictionary)(object)(dictionary);\n return (DataDictionary<TKey, TValue>)(object)dataDictionary.ShallowClone();\n }\n public static bool TryGetValue<TKey, TValue>(this DataDictionary<TKey, TValue> dictionary, TKey key, out TValue value)\n {\n var dataDictionary = (DataDictionary)(object)(dictionary);\n var keyToken = DataTokenUtil.NewDataToken(key);\n if (!dataDictionary.TryGetValue(keyToken, out var valueToken))\n {", "score": 0.8356088399887085 } ]
csharp
DataList<T> ShallowClone<T>(this DataList<T> list) {
using Microsoft.Extensions.Logging; using System; namespace ServiceSelf { /// <summary> /// 命名管道日志提供者 /// </summary> sealed class NamedPipeLoggerProvider : ILoggerProvider { private static readonly
NamedPipeClient pipeClient = CreateNamedPipeClient();
/// <summary> /// 创建与当前processId对应的NamedPipeClient /// </summary> /// <returns></returns> private static NamedPipeClient CreateNamedPipeClient() { #if NET6_0_OR_GREATER var processId = Environment.ProcessId; #else var processId = System.Diagnostics.Process.GetCurrentProcess().Id; #endif var pipeName = $"{nameof(ServiceSelf)}_{processId}"; return new NamedPipeClient(pipeName); } /// <summary> /// 创建日志 /// </summary> /// <param name="categoryName"></param> /// <returns></returns> public ILogger CreateLogger(string categoryName) { return new NamedPipeLogger(categoryName, pipeClient); } public void Dispose() { } } }
ServiceSelf/NamedPipeLoggerProvider.cs
xljiulang-ServiceSelf-7f8604b
[ { "filename": "ServiceSelf/NamedPipeLogger.cs", "retrieved_chunk": "using Microsoft.Extensions.Logging;\nusing System;\nnamespace ServiceSelf\n{\n /// <summary>\n /// 命名管道日志\n /// </summary>\n sealed class NamedPipeLogger : ILogger\n {\n private readonly string categoryName;", "score": 0.9202771186828613 }, { "filename": "ServiceSelf/NamedPipeLoggerServer.cs", "retrieved_chunk": "using Google.Protobuf;\nusing System;\nusing System.IO;\nusing System.IO.Pipes;\nnamespace ServiceSelf\n{\n /// <summary>\n /// 命名管道日志服务端\n /// </summary>\n static class NamedPipeLoggerServer", "score": 0.8700960278511047 }, { "filename": "ServiceSelf/WindowsServiceOptions.cs", "retrieved_chunk": "namespace ServiceSelf\n{\n /// <summary>\n /// windows独有的服务选项\n /// </summary>\n public sealed class WindowsServiceOptions\n {\n /// <summary>\n /// 在服务控制管理器中显示的服务名称\n /// </summary>", "score": 0.8653833866119385 }, { "filename": "ServiceSelf/LinuxServiceOptions.cs", "retrieved_chunk": "using System.IO;\nnamespace ServiceSelf\n{\n /// <summary>\n /// linux独有的服务选项\n /// </summary>\n public sealed class LinuxServiceOptions\n {\n /// <summary>\n /// 获取Unit章节", "score": 0.8590383529663086 }, { "filename": "ServiceSelf/ServiceOptions.cs", "retrieved_chunk": "using System.Collections.Generic;\nnamespace ServiceSelf\n{\n /// <summary>\n /// 服务选项\n /// </summary>\n public sealed class ServiceOptions\n {\n /// <summary>\n /// 启动参数", "score": 0.8539143204689026 } ]
csharp
NamedPipeClient pipeClient = CreateNamedPipeClient();
#nullable enable using System.Collections.Generic; namespace Mochineko.FacialExpressions.LipSync { /// <summary> /// Composition of some <see cref="Mochineko.FacialExpressions.LipSync.ILipMorpher"/>s. /// </summary> public sealed class CompositeLipMorpher : ILipMorpher { private readonly IReadOnlyList<ILipMorpher> morphers; /// <summary> /// Creates a new instance of <see cref="Mochineko.FacialExpressions.LipSync.CompositeLipMorpher"/>. /// </summary> /// <param name="morphers">Composited morphers.</param> public CompositeLipMorpher(IReadOnlyList<ILipMorpher> morphers) { this.morphers = morphers; } void ILipMorpher.MorphInto(LipSample sample) { foreach (var morpher in morphers) { morpher.MorphInto(sample); } } float
ILipMorpher.GetWeightOf(Viseme viseme) {
return morphers[0].GetWeightOf(viseme); } void ILipMorpher.Reset() { foreach (var morpher in morphers) { morpher.Reset(); } } } }
Assets/Mochineko/FacialExpressions/LipSync/CompositeLipMorpher.cs
mochi-neko-facial-expressions-unity-ab0d020
[ { "filename": "Assets/Mochineko/FacialExpressions/Emotion/CompositeEmotionMorpher.cs", "retrieved_chunk": " this.morphers = morphers;\n }\n void IEmotionMorpher<TEmotion>.MorphInto(EmotionSample<TEmotion> sample)\n {\n foreach (var morpher in morphers)\n {\n morpher.MorphInto(sample);\n }\n }\n float IEmotionMorpher<TEmotion>.GetWeightOf(TEmotion emotion)", "score": 0.8708013892173767 }, { "filename": "Assets/Mochineko/FacialExpressions/Blink/CompositeEyelidMorpher.cs", "retrieved_chunk": " foreach (var morpher in morphers)\n {\n morpher.MorphInto(sample);\n }\n }\n float IEyelidMorpher.GetWeightOf(Eyelid eyelid)\n {\n return morphers[0].GetWeightOf(eyelid);\n }\n void IEyelidMorpher.Reset()", "score": 0.8449199199676514 }, { "filename": "Assets/Mochineko/FacialExpressions/Emotion/CompositeEmotionMorpher.cs", "retrieved_chunk": " {\n return morphers[0].GetWeightOf(emotion);\n }\n void IEmotionMorpher<TEmotion>.Reset()\n {\n foreach (var morpher in morphers)\n {\n morpher.Reset();\n }\n }", "score": 0.8249684572219849 }, { "filename": "Assets/Mochineko/FacialExpressions.Extensions/VRM/VRMLipMorpher.cs", "retrieved_chunk": " public void MorphInto(LipSample sample)\n {\n if (KeyMap.TryGetValue(sample.viseme, out var key))\n {\n expression.SetWeight(key, sample.weight);\n }\n }\n public float GetWeightOf(Viseme viseme)\n {\n if (KeyMap.TryGetValue(viseme, out var key))", "score": 0.8010425567626953 }, { "filename": "Assets/Mochineko/FacialExpressions.Extensions/uLipSync/ULipSyncAnimator.cs", "retrieved_chunk": " private void SetDefault()\n {\n foreach (var viseme in phonomeMap.Values)\n {\n followingLipAnimator.SetTarget(new LipSample(viseme, weight: 0f));\n }\n }\n }\n}", "score": 0.7887901067733765 } ]
csharp
ILipMorpher.GetWeightOf(Viseme viseme) {
using Beeching.Commands.Interfaces; using Beeching.Helpers; using Beeching.Models; using Newtonsoft.Json; using Polly; using Spectre.Console; using System.Net.Http.Headers; using System.Text; namespace Beeching.Commands { internal class Axe : IAxe { private readonly HttpClient _client; public Axe(IHttpClientFactory httpClientFactory) { _client = httpClientFactory.CreateClient("ArmApi"); } public async Task<int> AxeResources(AxeSettings settings) { // Get the access token and add it to the request header for the http client _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Bearer", await AuthHelper.GetAccessToken(settings.Debug) ); AnsiConsole.Markup($"[green]=> Determining running user details[/]\n"); (string, string) userInformation = AzCliHelper.GetSignedInUser(); settings.UserId = userInformation.Item1; AnsiConsole.Markup($"[green]=> Running as user [white]{userInformation.Item2}[/] // [white]{userInformation.Item1}[/][/]\n"); AnsiConsole.Markup($"[green]=> Determining subscription details[/]\n"); settings.Subscription = AzCliHelper.GetSubscriptionId(settings); if (settings.Subscription == Guid.Empty) { return -1; } string name = AzCliHelper.GetSubscriptionName(settings.Subscription.ToString()); AnsiConsole.Markup($"[green]=> Using subscription [white]{name}[/] // [white]{settings.Subscription}[/][/]\n"); List<EffectiveRole> subscriptionRoles = await DetermineSubscriptionRoles(settings); if (subscriptionRoles.Count > 0) { string primaryRole = subscriptionRoles.OrderBy(r => r.Priority).First().Name; settings.SubscriptionRole = primaryRole; settings.IsSubscriptionRolePrivileged = primaryRole == "Owner" || primaryRole == "Contributor"; AnsiConsole.Markup( $"[green]=> Role [white]{settings.SubscriptionRole}[/] assigned on subscription which will be inherited by all resources[/]\n" ); if (settings.IsSubscriptionRolePrivileged == false) { AnsiConsole.Markup( $"[green]=> No privileged subscription role assigned so axe may fail if resource specific role not assigned[/]\n" ); } } else { settings.SubscriptionRole = "None"; AnsiConsole.Markup($"[green]=> No subscription roles assigned[/]\n"); } // Get the list of resources to axe based on the supplied options List<Resource> resourcesToAxe = await GetAxeResourceList(settings); // If we are in what-if mode then just output the details of the resources to axe if (settings.WhatIf) { AnsiConsole.Markup($"[cyan]=> +++ RUNNING WHAT-IF +++[/]\n"); } bool showedNoResources = false; int unlockedAxeCount = resourcesToAxe.Where(r => r.IsLocked == false).Count(); if ((unlockedAxeCount == 0 && settings.Force == false) || resourcesToAxe.Count == 0) { AnsiConsole.Markup($"[cyan]=> No resources to axe[/]\n\n"); showedNoResources = true; } else { foreach (var resource in resourcesToAxe) { // Determine our primary role for the resource string primaryResourceRole = string.Empty; if (resource.Roles.Any()) { primaryResourceRole = resource.Roles.OrderBy(r => r.Priority).First().Name; AnsiConsole.Markup( $"[green]=> Role [white]{primaryResourceRole}[/] assigned on resource [white]{resource.OutputMessage}[/][/]\n" ); } else { AnsiConsole.Markup($"[green]=> No roles assigned on resource [white]{resource.OutputMessage}[/][/]\n"); } // Determine if we're skipping this resource because it's locked resource.Skip = resource.IsLocked == true && Axe.ShouldSkipIfLocked(settings, resource); string skipMessage = resource.Skip == true ? " so will not be able to remove any locks - [white]SKIPPING[/]" : string.Empty; string lockedState = resource.IsLocked == true ? "[red]LOCKED[/] " : string.Empty; // Are we skipping this resource because it's locked? if (resource.Skip == true) { AnsiConsole.Markup( $"[green]=> Found [red]LOCKED[/] resource [white]{resource.OutputMessage}[/] but you do not have permission to remove locks - [white]SKIPPING[/][/]\n" ); } else if (resource.IsLocked == true && settings.Force == false) { resource.Skip = true; AnsiConsole.Markup( $"[green]=> Found [red]LOCKED[/] resource [white]{resource.OutputMessage}[/] which cannot be axed - [white]SKIPPING[/][/]\n" ); } else { bool axeFailWarning = settings.IsSubscriptionRolePrivileged == false && resource.Roles.Any() == false; string locked = resource.IsLocked == true ? "LOCKED " : string.Empty; string group = settings.ResourceGroups == true ? " and [red]ALL[/] resources within it" : string.Empty; string axeFail = axeFailWarning == true ? " [red](may fail due to role)[/]" : string.Empty; string axeAttemptMessage = axeFailWarning == true ? "ATTEMPT TO " : string.Empty; AnsiConsole.Markup( $"[green]=> [red]WILL {axeAttemptMessage}AXE {locked}[/]resource [white]{resource.OutputMessage}[/]{group}{axeFail}[/]\n" ); } } } // If we're running what-if then just drop out here if (settings.WhatIf) { AnsiConsole.Markup($"[cyan]=> +++ WHAT-IF COMPLETE +++[/]\n"); return 0; } // If we had some resources, but now we don't because they're locked then drop out here if ( (unlockedAxeCount == 0 && settings.Force == false) || resourcesToAxe.Count == 0 || resourcesToAxe.Where(r => r.Skip == false).Any() == false ) { if (showedNoResources == false) { AnsiConsole.Markup($"[cyan]=> No resources to axe[/]\n\n"); } return 0; } // If you want to skip confirmation then go ahead - make my day, punk. if (settings.SkipConfirmation == false) { string title = $"\nAre you sure you want to axe these {resourcesToAxe.Where(r => r.Skip == false).Count()} resources? [red](This cannot be undone)[/]"; if (resourcesToAxe.Count == 1) { title = "\nAre you sure you want to axe this resource? [red](This cannot be undone)[/]"; } var confirm = AnsiConsole.Prompt(new SelectionPrompt<string>().Title(title).AddChoices(new[] { "Yes", "No" })); if (confirm == "No") { AnsiConsole.Markup($"[green]=> Resource axing abandoned[/]\n\n"); return 0; } } else { AnsiConsole.Markup($"[green]=> Detected --yes. Skipping confirmation[/]\n\n"); } int retryCount = 1; AxeStatus axeStatus = new(); while (retryCount < (settings.MaxRetries + 1)) { // Iterate through the list of resources to axe and make the delete requests axeStatus = await SwingTheAxe(settings, resourcesToAxe); if (axeStatus.AxeList.Count == 0) { break; } AnsiConsole.Markup( $"[green]=>[/] [red]Possibly a dependency issue. Pausing for {settings.RetryPause} seconds and will retry. Attempt {retryCount} of {settings.MaxRetries}[/]\n" ); await Task.Delay(settings.RetryPause * 1000); resourcesToAxe = axeStatus.AxeList; retryCount++; } if (retryCount < (settings.MaxRetries + 1) && axeStatus.Status == true) { AnsiConsole.Markup($"[green]=> All resources axed successfully[/]\n\n"); } else if (retryCount < (settings.MaxRetries + 1) && axeStatus.Status == false) { AnsiConsole.Markup($"[green]=> Axe failed on some resources[/]\n\n"); } else { AnsiConsole.Markup( $"[green]=>[/] [red]Axe failed after {settings.MaxRetries} attempts. Try running the command again with --debug flag for more information[/]\n\n" ); } return 0; } private async Task<AxeStatus> SwingTheAxe(AxeSettings settings, List<Resource> axeUriList) { AxeStatus axeStatus = new(); foreach (var resource in axeUriList) { bool skipAxe = false; if (resource.IsLocked && settings.Force) { foreach (var resourceLock in resource.ResourceLocks) { int retryCount = 1; bool lockRemoved = false; while (retryCount < (settings.MaxRetries + 1)) { AnsiConsole.Markup( $"[green]=> Attempting to remove {resourceLock.Scope} lock [white]{resourceLock.Name}[/] for [white]{resource.OutputMessage}[/][/]\n" ); var lockResponse = await _client.DeleteAsync( new Uri($"{resourceLock.Id}?api-version=2016-09-01", UriKind.Relative) ); if (lockResponse.IsSuccessStatusCode == true) { lockRemoved = true; break; } AnsiConsole.Markup( $"[green]=>[/] [red]Failed to remove lock for {resource.OutputMessage}[/]. Pausing for {settings.RetryPause} seconds and will retry. Attempt {retryCount} of {settings.MaxRetries}[/]\n" ); await Task.Delay(settings.RetryPause * 1000); retryCount++; } if (retryCount < (settings.MaxRetries + 1) && lockRemoved == true) { AnsiConsole.Markup($"[green]=> Lock removed successfully[/]\n"); } else { AnsiConsole.Markup($"[green]=>[/] [red]Failed to remove lock for {resource.OutputMessage}[/] - SKIPPING\n"); skipAxe = true; axeStatus.Status = false; break; } } } // If we can't remove the lock then skip the axe if (skipAxe == true) { continue; } string group = settings.ResourceGroups == true ? " and [red]ALL[/] resources within it" : string.Empty; // Output the details of the delete request AnsiConsole.Markup($"[green]=> [red]AXING[/] [white]{resource.OutputMessage}[/]{group}[/]\n"); // Make the delete request var response = await _client.DeleteAsync(new Uri($"{resource.Id}?api-version={resource.ApiVersion}", UriKind.Relative)); if (settings.Debug) { AnsiConsole.Markup($"[green]=> Response status code is {response.StatusCode}[/]"); AnsiConsole.Markup($"[green]=> Response content: {await response.Content.ReadAsStringAsync()}[/]"); } if (!response.IsSuccessStatusCode) { string responseContent = await response.Content.ReadAsStringAsync(); if (responseContent.Contains("Please remove the lock and try again")) { AnsiConsole.Markup( $"[green]=>[/] [red]Axe failed because the resource is [red]LOCKED[/]. Remove the lock and try again[/]\n" ); axeStatus.Status = false; continue; } else if (response.StatusCode.ToString() == "Forbidden") { AnsiConsole.Markup($"[green]=>[/] [red]Axe failed: Permission denied - [white]SKIPPING[/][/]\n"); axeStatus.Status = false; continue; } else if (response.StatusCode.ToString() == "NotFound") { AnsiConsole.Markup($"[green]=>[/] [red]Axe failed: Resouce already axed - [white]SKIPPING[/][/]\n"); axeStatus.Status = false; continue; } else { AnsiConsole.Markup($"[green]=>[/] [red]Axe failed: {response.StatusCode}[/]\n"); axeStatus.AxeList.Add(resource); axeStatus.Status = false; } } else { AnsiConsole.Markup($"[green]=> Resource axed successfully[/]\n"); if (resource.IsLocked && settings.Force) { foreach (var resourceLock in resource.ResourceLocks) { if ( (resourceLock.Scope == "resource group" && settings.ResourceGroups == false) || resourceLock.Scope == "subscription" ) { AnsiConsole.Markup( $"[green]=> Reapplying {resourceLock.Scope} lock [white]{resourceLock.Name}[/] for [white]{resource.OutputMessage}[/][/]\n" ); var createLockResponse = await _client.PutAsync( new Uri($"{resourceLock.Id}?api-version=2016-09-01", UriKind.Relative), new StringContent(JsonConvert.SerializeObject(resourceLock), Encoding.UTF8, "application/json") ); if (!createLockResponse.IsSuccessStatusCode) { AnsiConsole.Markup($"[green]=>[/] [red]Failed to reapply lock for {resource.OutputMessage}[/]\n"); skipAxe = true; } } } } } } return axeStatus; } private async Task<string?> GetLatestApiVersion(
AxeSettings settings, string provider, string type) {
var apiVersion = await _client.GetAsync( $"subscriptions/{settings.Subscription}/providers/{provider}/resourceTypes?api-version=2021-04-01" ); string apiJson = await apiVersion.Content.ReadAsStringAsync(); List<ApiVersion> allApiVersions = new(); if (apiJson.Contains("Microsoft.Resources' does not contain sufficient information to enforce access control policy")) { AnsiConsole.Markup( $"[green]=>[/] [red]You do not have sufficient permissions determine latest API version. Please check your subscription permissions and try again[/]\n" ); return null; } allApiVersions = JsonConvert.DeserializeObject<Dictionary<string, List<ApiVersion>>>(apiJson)!["value"]; if (allApiVersions == null) { return null; } ApiVersion apiTypeVersion = allApiVersions.Where(x => x.ResourceType == type).First(); return apiTypeVersion.DefaultApiVersion ?? apiTypeVersion.ApiVersions.First(); } private async Task<List<Resource>> GetAxeResourceList(AxeSettings settings) { bool useNameFilter = !string.IsNullOrEmpty(settings.Name); List<Resource> resourcesFound = new(); if (settings.ResourceGroups) { if (useNameFilter) { List<string> names = new(); if (settings.Name.Contains(':')) { names = settings.Name.Split(':').ToList(); } else { names.Add(settings.Name); } foreach (string name in names) { AnsiConsole.Markup($"[green]=> Searching for resource groups where name contains [white]{name}[/][/]\n"); HttpResponseMessage response = await _client.GetAsync( $"subscriptions/{settings.Subscription}/resourcegroups?api-version=2021-04-01" ); string jsonResponse = await response.Content.ReadAsStringAsync(); if (jsonResponse != null) { List<Resource> resources = JsonConvert.DeserializeObject<Dictionary<string, List<Resource>>>(jsonResponse)![ "value" ]; resourcesFound.AddRange(resources.Where(x => x.Name.Contains(name, StringComparison.OrdinalIgnoreCase))); } } } else { List<string> tag = settings.Tag.Split(':').ToList(); AnsiConsole.Markup( $"[green]=> Searching for resource groups where tag [white]{tag[0]}[/] equals [white]{tag[1]}[/][/]\n" ); HttpResponseMessage response = await _client.GetAsync( $"subscriptions/{settings.Subscription}/resourcegroups?$filter=tagName eq '{tag[0]}' and tagValue eq '{tag[1]}'&api-version=2021-04-01" ); string jsonResponse = await response.Content.ReadAsStringAsync(); if (jsonResponse != null) { resourcesFound.AddRange(JsonConvert.DeserializeObject<Dictionary<string, List<Resource>>>(jsonResponse)!["value"]); } } } else { if (useNameFilter) { List<string> names = new(); if (settings.Name.Contains(':')) { names = settings.Name.Split(':').ToList(); } else { names.Add(settings.Name); } foreach (string name in names) { AnsiConsole.Markup($"[green]=> Searching for resources where name contains [white]{name}[/][/]\n"); HttpResponseMessage response = await _client.GetAsync( $"subscriptions/{settings.Subscription}/resources?$filter=substringof('{name}',name)&api-version=2021-04-01" ); string jsonResponse = await response.Content.ReadAsStringAsync(); if (jsonResponse != null) { List<Resource> resources = JsonConvert.DeserializeObject<Dictionary<string, List<Resource>>>(jsonResponse)![ "value" ]; foreach (var resource in resources) { string[] sections = resource.Id.Split('/'); resource.ResourceGroup = $"/subscriptions/{settings.Subscription}/resourceGroups/{sections[4]}"; resourcesFound.Add(resource); } } } } else { // Split the tag into a key and value List<string> tag = settings.Tag.Split(':').ToList(); AnsiConsole.Markup($"[green]=> Searching for resources where tag [white]{tag[0]}[/] equals [white]{tag[1]}[/][/]\n"); HttpResponseMessage response = await _client.GetAsync( $"subscriptions/{settings.Subscription}/resources?$filter=tagName eq '{tag[0]}' and tagValue eq '{tag[1]}'&api-version=2021-04-01" ); string jsonResponse = await response.Content.ReadAsStringAsync(); if (jsonResponse != null) { List<Resource> resources = JsonConvert.DeserializeObject<Dictionary<string, List<Resource>>>(jsonResponse)![ "value" ]; foreach (var resource in resources) { string[] sections = resource.Id.Split('/'); resource.ResourceGroup = $"/subscriptions/{settings.Subscription}/resourceGroups/{sections[4]}"; resourcesFound.Add(resource); } } } // Do we need to filter the resource types? if (!string.IsNullOrEmpty(settings.ResourceTypes)) { List<string> allowedTypes = settings.ResourceTypes.Split(':').ToList(); AnsiConsole.Markup($"[green]=> Restricting resource types to:[/]\n"); foreach (string type in allowedTypes) { AnsiConsole.Markup($"\t- [white]{type}[/]\n"); } resourcesFound = resourcesFound.Where(r => allowedTypes.Contains(r.Type)).ToList(); } } // Do we need to filter exclusions? if (!string.IsNullOrEmpty(settings.Exclude)) { List<string> exclusions = settings.Exclude.Split(':').ToList(); List<Resource> filteredResources = resourcesFound.Where(r => !exclusions.Contains(r.Name)).ToList(); foreach (var resource in resourcesFound.Except(filteredResources)) { AnsiConsole.Markup($"[green]=> Excluding [white]{resource.Name}[/][/]\n"); } resourcesFound = filteredResources; } // Now we have our actual list of resources to axe, let's get the latest API version for each resource type foreach (var resource in resourcesFound) { string[] sections = resource.Id.Split('/'); string resourceGroup = sections[4]; string provider; string resourceType; if (!settings.ResourceGroups) { provider = sections[6]; resourceType = sections[7]; resource.OutputMessage = $"[white]{resource.Type} {resource.Name}[/] [green]in resource group[/] [white]{resourceGroup}[/]"; } else { provider = "Microsoft.Resources"; resourceType = "resourceGroups"; resource.OutputMessage = $"[green]group[/] [white]{resource.Name}[/]"; } string? apiVersion = await GetLatestApiVersion(settings, provider, resourceType); if (apiVersion == null) { AnsiConsole.Markup($"[green]=> Unable to get latest API version for {resource.OutputMessage} so will exclude[/]\n"); } resource.ApiVersion = apiVersion; } // Remove any resources that we couldn't get an API version for resourcesFound = resourcesFound.Except(resourcesFound.Where(r => string.IsNullOrEmpty(r.ApiVersion)).ToList()).ToList(); await DetermineLocks(settings, resourcesFound); await DetermineRoles(settings, resourcesFound); // Return whatever is left return resourcesFound; } private async Task<List<EffectiveRole>> DetermineSubscriptionRoles(AxeSettings settings) { List<EffectiveRole> subscriptionRoles = new(); string roleId = $"subscriptions/{settings.Subscription}/providers/Microsoft.Authorization/roleAssignments?$filter=principalId eq '{settings.UserId}'&api-version=2022-04-01"; HttpResponseMessage response = await _client.GetAsync(roleId); if (response.IsSuccessStatusCode) { string jsonResponse = await response.Content.ReadAsStringAsync(); if (jsonResponse != null) { List<dynamic> roles = JsonConvert.DeserializeObject<Dictionary<string, List<dynamic>>>(jsonResponse)!["value"]; foreach (var role in roles) { RoleDefinition roleDefinition = await GetRoleDefinition(role.properties.roleDefinitionId.ToString()); if (role.properties.scope != $"/subscriptions/{settings.Subscription}") { continue; } EffectiveRole effectiveRole = new() { RoleDefinitionId = roleDefinition.Name, Scope = role.properties.scope, ScopeType = "subscription", Name = roleDefinition.Properties.RoleName, Type = roleDefinition.Properties.Type }; if (effectiveRole.Name == "Owner") { effectiveRole.Priority = 0; } else if (effectiveRole.Name == "Contributor") { effectiveRole.Priority = 1; } else { effectiveRole.Priority = 2; } bool hasFullPermission = roleDefinition.Properties.Permissions.Where(r => r.Actions.Contains("*")).Any(); bool hasFullAuthPermission = roleDefinition.Properties.Permissions .Where(r => r.Actions.Contains("Microsoft.Authorization/*")) .Any(); bool allAuthPermissionBlocked = roleDefinition.Properties.Permissions .Where(r => r.NotActions.Contains("Microsoft.Authorization/*")) .Any(); bool deleteAuthPermissionBlocked = roleDefinition.Properties.Permissions .Where(r => r.NotActions.Contains("Microsoft.Authorization/*/Delete")) .Any(); bool writeAuthPermissionBlocked = roleDefinition.Properties.Permissions .Where(r => r.NotActions.Contains("Microsoft.Authorization/*/Write")) .Any(); if ( (hasFullPermission || hasFullAuthPermission) && (!allAuthPermissionBlocked && !deleteAuthPermissionBlocked && !writeAuthPermissionBlocked) ) { effectiveRole.CanManageLocks = true; } subscriptionRoles.Add(effectiveRole); } } } return subscriptionRoles; } private async Task DetermineRoles(AxeSettings settings, List<Resource> resources) { AnsiConsole.Markup($"[green]=> Checking resources for role assignments[/]\n"); foreach (Resource resource in resources) { string roleId = $"{resource.Id}/providers/Microsoft.Authorization/roleAssignments?$filter=principalId eq '{settings.UserId}'&api-version=2022-04-01"; HttpResponseMessage response = await _client.GetAsync(roleId); if (response.IsSuccessStatusCode) { string jsonResponse = await response.Content.ReadAsStringAsync(); if (jsonResponse != null) { List<dynamic> roles = JsonConvert.DeserializeObject<Dictionary<string, List<dynamic>>>(jsonResponse)!["value"]; foreach (var role in roles) { RoleDefinition roleDefinition = await GetRoleDefinition(role.properties.roleDefinitionId.ToString()); if (role.properties.scope == $"/subscriptions/{settings.Subscription}") { continue; } string[] scopeSections = role.properties.scope.ToString().Split('/'); EffectiveRole effectiveRole = new() { RoleDefinitionId = roleDefinition.Name, Scope = role.properties.scope, ScopeType = scopeSections.Length > 5 ? "resource" : "resource group", Name = roleDefinition.Properties.RoleName, Type = roleDefinition.Properties.Type }; if (effectiveRole.Name == "Owner") { effectiveRole.Priority = 0; } else if (effectiveRole.Name == "Contributor") { effectiveRole.Priority = 1; } else { effectiveRole.Priority = 2; } bool hasFullPermission = roleDefinition.Properties.Permissions.Where(r => r.Actions.Contains("*")).Any(); bool hasFullAuthPermission = roleDefinition.Properties.Permissions .Where(r => r.Actions.Contains("Microsoft.Authorization/*")) .Any(); bool allAuthPermissionBlocked = roleDefinition.Properties.Permissions .Where(r => r.NotActions.Contains("Microsoft.Authorization/*")) .Any(); bool deleteAuthPermissionBlocked = roleDefinition.Properties.Permissions .Where(r => r.NotActions.Contains("Microsoft.Authorization/*/Delete")) .Any(); bool writeAuthPermissionBlocked = roleDefinition.Properties.Permissions .Where(r => r.NotActions.Contains("Microsoft.Authorization/*/Write")) .Any(); if ( (hasFullPermission || hasFullAuthPermission) && (!allAuthPermissionBlocked && !deleteAuthPermissionBlocked && !writeAuthPermissionBlocked) ) { effectiveRole.CanManageLocks = true; } resource.Roles.Add(effectiveRole); } } } } } private async Task<RoleDefinition> GetRoleDefinition(string roleDefinitionId) { string[] sections = roleDefinitionId.Split('/'); string roleId = sections[^1]; string roleDefinition = $"providers/Microsoft.Authorization/roleDefinitions/{roleId}?api-version=2022-04-01"; HttpResponseMessage response = await _client.GetAsync(roleDefinition); if (response.IsSuccessStatusCode) { string jsonResponse = await response.Content.ReadAsStringAsync(); if (jsonResponse != null) { return JsonConvert.DeserializeObject<RoleDefinition>(jsonResponse)!; } } return new RoleDefinition(); } private async Task DetermineLocks(AxeSettings settings, List<Resource> resources) { AnsiConsole.Markup($"[green]=> Checking resources for locks[/]\n"); List<ResourceLock> resourceLocks = new(); if (settings.Force == true) { AnsiConsole.Markup($"[green]=> Detected --force. Resource locks will be removed and reapplied where possible[/]\n"); } string locks = $"/subscriptions/{settings.Subscription}/providers/Microsoft.Authorization/locks?api-version=2016-09-01"; var response = await _client.GetAsync(locks); if (response.IsSuccessStatusCode) { string responseContent = await response.Content.ReadAsStringAsync(); if (responseContent != null) { resourceLocks.AddRange( JsonConvert.DeserializeObject<Dictionary<string, List<ResourceLock>>>(responseContent)!["value"] ); foreach (var resource in resources) { string[] sections = resource.Id.Split('/'); foreach (var resourceLock in resourceLocks) { string lockId = resourceLock.Id.ToLower(); string resourceGroupId = $"/subscriptions/{settings.Subscription}/resourceGroups/{sections[4]}/providers/{resourceLock.Type}/{resourceLock.Name}".ToLower(); string subscriptionId = $"/subscriptions/{settings.Subscription}/providers/{resourceLock.Type}/{resourceLock.Name}".ToLower(); if (lockId.StartsWith(resource.Id.ToLower())) { resourceLock.Scope = resource.Type.ToLower() == "microsoft.resources/resourcegroups" ? "resource group" : "resource"; resource.ResourceLocks.Add(resourceLock); resource.IsLocked = true; } else if (lockId == resourceGroupId) { resourceLock.Scope = "resource group"; resource.ResourceLocks.Add(resourceLock); resource.IsLocked = true; } else if (lockId == subscriptionId) { resourceLock.Scope = "subscription"; resource.ResourceLocks.Add(resourceLock); resource.IsLocked = true; } } if (settings.Force == false && resource.IsLocked == true) { AnsiConsole.Markup( $"[green]=> Found [red]LOCKED[/] resource {resource.OutputMessage} which cannot be deleted[/] - [white]SKIPPING[/]\n" ); } } } } } private static bool ShouldSkipIfLocked(AxeSettings settings, Resource resource) { // Find out what kind of powers we have bool hasSubscriptionLockPowers = settings.SubscriptionRole == "Owner"; bool hasResourceLockPowers = resource.Roles.Where(r => r.CanManageLocks == true).Any(); // If we don't have subscription lock powers and we don't have resource lock powers then we're not good if (hasSubscriptionLockPowers == false && hasResourceLockPowers == false) { return true; } // If we have subscription lock powers, we can remove any lock so we're good if (hasSubscriptionLockPowers == true) { return false; } // Find out if we have subscription level locks bool hasSubscriptionLocks = resource.ResourceLocks.Where(r => r.Scope == "subscription").Any(); // We don't have subscription lock powers so if the locks are at the subscription level then we're not good if (hasSubscriptionLocks == true) { return true; } // We do have resource lock powers and we're dealing with resource groups so we're good if (settings.ResourceGroups == true) { return false; } // Find out what kind of locks we have at the group and resource level bool hasGroupLocks = resource.ResourceLocks.Where(r => r.Scope == "resource group").Any(); bool hasResourceLocks = resource.ResourceLocks.Where(r => r.Scope == "resource").Any(); // We have resource lock powers and the resource is locked at the resource level so we're good if (hasGroupLocks == false) { return false; } // Find out if the role scope is for the resource group bool hasOwnerOnGroup = resource.Roles.Where(r => r.ScopeType == "resource group" && r.Name == "Owner").Any(); // We have resource lock powers and the resource is locked at the group level if (hasGroupLocks == true && hasOwnerOnGroup == true) { return false; } // Has owner on resource but lock is on group lands here so we're not good return true; } public static IAsyncPolicy<HttpResponseMessage> GetRetryAfterPolicy() { return Policy .HandleResult<HttpResponseMessage>(msg => msg.Headers.TryGetValues("RetryAfter", out var _)) .WaitAndRetryAsync( retryCount: 3, sleepDurationProvider: (_, response, _) => response.Result.Headers.TryGetValues("RetryAfter", out var seconds) ? TimeSpan.FromSeconds(int.Parse(seconds.First())) : TimeSpan.FromSeconds(5), onRetryAsync: (msg, time, retries, context) => Task.CompletedTask ); } } }
src/Commands/Axe.cs
irarainey-beeching-e846af0
[ { "filename": "src/Commands/AxeCommand.cs", "retrieved_chunk": " return ValidationResult.Error(\"Retry pause must be set between 5 and 60 seconds.\");\n }\n return ValidationResult.Success();\n }\n public override async Task<int> ExecuteAsync(CommandContext context, AxeSettings settings)\n {\n return await _axe.AxeResources(settings);\n }\n }\n}", "score": 0.8862783908843994 }, { "filename": "src/Helpers/AzCliHelper.cs", "retrieved_chunk": " AnsiConsole.WriteException(\n new ArgumentException(\"Missing subscription ID. Please specify a subscription ID or login to Azure CLI.\", ex)\n );\n }\n }\n return subscriptionId;\n }\n public static string GetCurrentAzureSubscription()\n {\n string azCliExecutable = DetermineAzCliPath();", "score": 0.857515811920166 }, { "filename": "src/Helpers/AzCliHelper.cs", "retrieved_chunk": " return displayNameElement.GetString() ?? string.Empty;\n }\n else\n {\n return \"[Error Determining Name]\";\n }\n }\n public static string CallAzCliRest(string uri)\n {\n string azCliExecutable = DetermineAzCliPath();", "score": 0.8444658517837524 }, { "filename": "src/Helpers/AzCliHelper.cs", "retrieved_chunk": " throw new Exception($\"Error executing '{Constants.AzCliExecutable} ad signed-in-user show': {error}\");\n }\n }\n private static Process CreateProcess(string filename, string arguments)\n {\n return new Process\n {\n StartInfo = new ProcessStartInfo\n {\n FileName = filename,", "score": 0.8164981603622437 }, { "filename": "src/Helpers/AzCliHelper.cs", "retrieved_chunk": " return idElement.GetString() ?? string.Empty;\n }\n else\n {\n throw new Exception(\"Unable to find the 'id' property in the JSON output.\");\n }\n }\n else\n {\n string error = process.StandardError.ReadToEnd();", "score": 0.7953712940216064 } ]
csharp
AxeSettings settings, string provider, string type) {
using Grasshopper.Kernel; using Rhino; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab; namespace Brain.Templates { public abstract class GH_Component_HTTPAsync : GH_Component { protected string _response = ""; protected bool _shouldExpire = false; protected
RequestState _currentState = RequestState.Off;
public GH_Component_HTTPAsync(string name, string nickname, string description, string category, string subcategory) : base(name, nickname, description, category, subcategory) { } protected override void ExpireDownStreamObjects() { if (_shouldExpire) { base.ExpireDownStreamObjects(); } } protected void POSTAsync( string url, string body, string contentType, string authorization, int timeout) { Task.Run(() => { try { // Compose the request byte[] data = Encoding.ASCII.GetBytes(body); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = contentType; request.ContentLength = data.Length; request.Timeout = timeout; // Handle authorization if (authorization != null && authorization.Length > 0) { System.Net.ServicePointManager.Expect100Continue = true; System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; //the auth type request.PreAuthenticate = true; request.Headers.Add("Authorization", authorization); } else { request.Credentials = CredentialCache.DefaultCredentials; } using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } var res = request.GetResponse(); _response = new StreamReader(res.GetResponseStream()).ReadToEnd(); _currentState = RequestState.Done; _shouldExpire = true; RhinoApp.InvokeOnUiThread((Action)delegate { ExpireSolution(true); }); } catch (Exception ex) { _response = ex.Message; _currentState = RequestState.Error; _shouldExpire = true; RhinoApp.InvokeOnUiThread((Action)delegate { ExpireSolution(true); }); return; } }); } protected void GETAsync( string url, string authorization, int timeout) { Task.Run(() => { try { // Compose the request HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.Timeout = timeout; // Handle authorization if (authorization != null && authorization.Length > 0) { System.Net.ServicePointManager.Expect100Continue = true; System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; //the auth type request.PreAuthenticate = true; request.Headers.Add("Authorization", authorization); } else { request.Credentials = CredentialCache.DefaultCredentials; } var res = request.GetResponse(); _response = new StreamReader(res.GetResponseStream()).ReadToEnd(); _currentState = RequestState.Done; _shouldExpire = true; RhinoApp.InvokeOnUiThread((Action)delegate { ExpireSolution(true); }); } catch (Exception ex) { _response = ex.Message; _currentState = RequestState.Error; _shouldExpire = true; RhinoApp.InvokeOnUiThread((Action)delegate { ExpireSolution(true); }); return; } }); } } }
src/Templates/GH_Component_HTTPAsync.cs
ParametricCamp-brain-plugin-grasshopper-9240b81
[ { "filename": "src/UtilComps/HTTPPostRequestAsyncComponent.cs", "retrieved_chunk": "using Rhino.Geometry;\nusing static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab;\nnamespace Brain.UtilComps\n{\n public class HTTPPostRequestAsyncComponent : GH_Component_HTTPAsync\n {\n /// <summary>\n /// Initializes a new instance of the HTTPPostRequestAsyncComponent class.\n /// </summary>\n public HTTPPostRequestAsyncComponent()", "score": 0.8870534896850586 }, { "filename": "src/UtilComps/HTTPGetRequestComponent.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing Grasshopper.Kernel;\nusing Rhino.Geometry;\nusing Brain.Templates;\nusing static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab;\nnamespace Brain.UtilComps\n{\n public class HTTPGetRequestComponent : GH_Component_HTTPSync\n {", "score": 0.8061482310295105 }, { "filename": "src/Templates/GH_Component_HTTPSync.cs", "retrieved_chunk": "namespace Brain.Templates\n{\n public abstract class GH_Component_HTTPSync : GH_Component\n {\n public GH_Component_HTTPSync(string name, string nickname, string description, string category, string subcategory)\n : base(name, nickname, description, category, subcategory)\n {\n }\n protected string POST(\n string url,", "score": 0.7930216789245605 }, { "filename": "src/UtilComps/EnvironmentVariableComponent.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing Grasshopper.Kernel;\nusing Rhino.Geometry;\nnamespace Brain.UtilComps\n{\n public class EnvironmentVariableComponent : GH_Component\n {\n /// <summary>\n /// Initializes a new instance of the EnvironmentVariableComponent class.", "score": 0.7878931164741516 }, { "filename": "src/UtilComps/HTTPGetRequestAsyncComponent.cs", "retrieved_chunk": "namespace Brain.UtilComps\n{\n public class HTTPGetRequestAsyncComponent : GH_Component_HTTPAsync\n {\n /// <summary>\n /// Initializes a new instance of the HTTPGetRequestAsyncComponent class.\n /// </summary>\n public HTTPGetRequestAsyncComponent()\n : base(\"HTTP GET (Async)\", \"GET Async\",\n \"Creates a generic HTTP GET request (asynchronous)\",", "score": 0.7869305610656738 } ]
csharp
RequestState _currentState = RequestState.Off;
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; namespace DrakiaXYZ.Waypoints { public class CustomWaypointLoader { // Singleton because I'm lazy private static CustomWaypointLoader instance = new CustomWaypointLoader(); public static CustomWaypointLoader Instance { get { return instance; } } // The dictionary is [map][zone][patrol] public Dictionary<string, Dictionary<string, Dictionary<string, CustomPatrol>>> mapZoneWaypoints = new Dictionary<string, Dictionary<string, Dictionary<string, CustomPatrol>>>(); public void loadData() { // If the "custom" folder doesn't exist, don't try to load from it if (!Directory.Exists(WaypointsPlugin.CustomFolder)) { return; } // Loop through all subfolders, and load data, assuming the filename is the map name foreach (string directory in Directory.GetDirectories(WaypointsPlugin.CustomFolder)) { foreach (string file in Directory.GetFiles(directory, "*.json")) { string mapName = getMapFromFilename(file); //Console.WriteLine($"Loading waypoints for {mapName}"); loadMapData(mapName, file); } } // This is meant for creation purposes only, we'll loop through all files in the "custom" folder, and // strip anything after an underscore. This allows us to create "[mapname]_[date].json" files automatically foreach (string file in Directory.GetFiles(WaypointsPlugin.CustomFolder, "*.json")) { string mapName = getMapFromFilename(file); //Console.WriteLine($"Loading development waypoints for {mapName}"); loadMapData(mapName, file); } } private void loadMapData(string mapName, string file) { if (!mapZoneWaypoints.ContainsKey(mapName)) { mapZoneWaypoints[mapName] = new Dictionary<string, Dictionary<string, CustomPatrol>>(); } // We have to manually merge in our data, so multiple people can add waypoints to the same patrols Dictionary<string, Dictionary<string, CustomPatrol>> zoneWaypoints = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, CustomPatrol>>>(File.ReadAllText(file)); foreach (string zoneName in zoneWaypoints.Keys) { // If the map already has this zone, merge in the patrols if (mapZoneWaypoints[mapName].ContainsKey(zoneName)) { foreach (string patrolName in zoneWaypoints[zoneName].Keys) { // If the patrol already exists, merge in the waypoints if (mapZoneWaypoints[mapName][zoneName].ContainsKey(patrolName)) { CustomPatrol existingPatrol = mapZoneWaypoints[mapName][zoneName][patrolName]; CustomPatrol newPatrol = zoneWaypoints[zoneName][patrolName]; // TODO: What do we do about mis-matched patrol data? Should we allow overrriding it? Who wins in the event of a conflict? // For now, we'll go with "Last to load wins" existingPatrol.waypoints.AddRange(newPatrol.waypoints); existingPatrol.blockRoles = newPatrol.blockRoles ?? existingPatrol.blockRoles; existingPatrol.maxPersons = newPatrol.maxPersons ?? existingPatrol.maxPersons; existingPatrol.patrolType = newPatrol.patrolType ?? existingPatrol.patrolType; } // If the patrol doesn't exist, copy the whole thing over else { mapZoneWaypoints[mapName][zoneName][patrolName] = zoneWaypoints[zoneName][patrolName]; } } } // If the zoneName key doesn't exist yet, we can just throw the whole thing in else { mapZoneWaypoints[mapName][zoneName] = zoneWaypoints[zoneName]; } } } public Dictionary<string,
CustomPatrol> getMapZonePatrols(string map, string zone) {
if (!mapZoneWaypoints.ContainsKey(map)) { return null; } if (!mapZoneWaypoints[map].ContainsKey(zone)) { return null; } return mapZoneWaypoints[map][zone]; } private string getMapFromFilename(string file) { string fileWithoutExt = file.Substring(0, file.LastIndexOf('.')); string mapName = fileWithoutExt.Substring(fileWithoutExt.LastIndexOf('\\') + 1); int nUnderscoreOffset = mapName.IndexOf('_'); if (nUnderscoreOffset > -1) { // If this is factory, we have to check for the SECOND underscore, stupid factory if (mapName.StartsWith("factory4")) { nUnderscoreOffset = mapName.IndexOf('_', nUnderscoreOffset + 1); } if (nUnderscoreOffset > -1) { mapName = mapName.Substring(0, nUnderscoreOffset); } } return mapName; } } }
CustomWaypointLoader.cs
DrakiaXYZ-SPT-Waypoints-051d99b
[ { "filename": "Components/EditorComponent.cs", "retrieved_chunk": " currentZoneIndex = botZones.Count - 1;\n }\n }\n }\n private bool DeleteNearestAddedWaypoint(Vector3 position)\n {\n string zoneName = getCurrentZone().NameZone;\n string patrolName = getCurrentPatrolName();\n // If there are no custom waypoints, just return false\n if (!zoneWaypoints[zoneName].ContainsKey(patrolName) || zoneWaypoints[zoneName][patrolName].waypoints.Count == 0)", "score": 0.8392582535743713 }, { "filename": "Patches/WaypointPatch.cs", "retrieved_chunk": " doorLink.CheckAfterCreatedCarver();\n }\n }\n else\n {\n Logger.LogError($\"Error finding doorLinkList\");\n }\n }\n private static void InjectWaypoints(GameWorld gameWorld, BotZone[] botZones)\n {", "score": 0.8134970664978027 }, { "filename": "Components/EditorComponent.cs", "retrieved_chunk": " BotZone currentZone = getCurrentZone();\n if (currentZoneIndex < 0)\n {\n return $\"Nearest ({currentZone.NameZone})\";\n }\n return currentZone.NameZone;\n }\n public string getCurrentPatrolName()\n {\n return Settings.CustomPatrolName.Value;", "score": 0.807162880897522 }, { "filename": "Components/EditorComponent.cs", "retrieved_chunk": " private Dictionary<string, Dictionary<string, CustomPatrol>> zoneWaypoints = new Dictionary<string, Dictionary<string, CustomPatrol>>();\n private string filename;\n private EditorComponent()\n {\n // Empty\n }\n public void Dispose()\n {\n gameObjects.ForEach(Destroy);\n gameObjects.Clear();", "score": 0.8018437027931213 }, { "filename": "Patches/WaypointPatch.cs", "retrieved_chunk": " {\n InjectWaypoints(gameWorld, botZones);\n }\n if (Settings.EnableCustomNavmesh.Value)\n {\n InjectNavmesh(gameWorld);\n }\n }\n /// <summary>\n /// Re-calculate the doorlink navmesh carvers, since these are baked into the map, but we've", "score": 0.7934859991073608 } ]
csharp
CustomPatrol> getMapZonePatrols(string map, string zone) {
using Aas = AasCore.Aas3_0; // renamed // ReSharper disable RedundantUsingDirective using System.CommandLine; // can't alias using System.Diagnostics.CodeAnalysis; // can't alias using System.Linq; // can't alias namespace SplitEnvironmentForStaticHosting { public static class Program { static readonly char[] Base64Padding = { '=' }; private static string? OutputRegistry( string outputDir, Registering.
TypedRegistry<Aas.IIdentifiable> registry ) {
System.IO.Directory.CreateDirectory(outputDir); var indexArray = new System.Text.Json.Nodes.JsonArray( registry.Items.Select( identifiable => { var value = System.Text.Json.Nodes.JsonValue .Create(identifiable.Id); if (value == null) { throw new System.InvalidOperationException( "Unexpected null value" ); } return value; }) .ToArray<System.Text.Json.Nodes.JsonNode?>() ); if (indexArray == null) { throw new System.InvalidOperationException( "Unexpected null indexArray" ); } var writerOptions = new System.Text.Json.JsonWriterOptions { Indented = true }; var indexArrayPath = System.IO.Path.Join(outputDir, "index.json"); try { using var outputStream = System.IO.File.OpenWrite(indexArrayPath); using var writer = new System.Text.Json.Utf8JsonWriter( outputStream, writerOptions ); indexArray.WriteTo(writer); } catch (System.Exception exception) { return $"Failed to write to {indexArrayPath}: {exception.Message}"; } foreach (var identifiable in registry.Items) { var idBytes = System.Text.Encoding.UTF8.GetBytes(identifiable.Id); var idBase64 = System.Convert.ToBase64String(idBytes); // NOTE (mristin, 2023-04-05): // We use here the URL-safe Base64 encoding. // // See: https://stackoverflow.com/questions/26353710/how-to-achieve-base64-url-safe-encoding-in-c idBase64 = idBase64 .TrimEnd(Base64Padding) .Replace('+', '-') .Replace('/', '_'); var pth = System.IO.Path.Join(outputDir, idBase64); System.Text.Json.Nodes.JsonObject? jsonable; try { jsonable = Aas.Jsonization.Serialize.ToJsonObject(identifiable); } catch (System.Exception exception) { return $"Failed to serialize {identifiable.GetType().Name} " + $"with ID {identifiable.Id} to JSON: {exception.Message}"; } if (jsonable == null) { throw new System.InvalidOperationException( "Unexpected null jsonable" ); } try { using var outputStream = System.IO.File.OpenWrite(pth); using var writer = new System.Text.Json.Utf8JsonWriter( outputStream, writerOptions ); jsonable.WriteTo(writer); } catch (System.Exception exception) { return $"Failed to write to {indexArrayPath}: {exception.Message}"; } } return null; } public static int Execute( string environmentPath, string outputDir, System.IO.TextWriter stderr ) { var shellRegistry = new Registering.TypedRegistry<Aas.IIdentifiable>(); var submodelRegistry = new Registering.TypedRegistry<Aas.IIdentifiable>(); var conceptDescriptionRegistry = new Registering.TypedRegistry<Aas.IIdentifiable>(); var fileInfo = new System.IO.FileInfo(environmentPath); if (!fileInfo.Exists) { stderr.WriteLine($"{fileInfo.FullName}: File does not exist"); return 1; } System.Text.Json.Nodes.JsonNode? node; try { using var file = fileInfo.OpenRead(); node = System.Text.Json.Nodes.JsonNode.Parse( System.IO.File.ReadAllBytes(environmentPath) ); } catch (System.Text.Json.JsonException exception) { stderr.WriteLine( $"{fileInfo.FullName}: " + $"JSON parsing failed: {exception.Message}" ); return 1; } if (node == null) { throw new System.InvalidOperationException( "Unexpected null node" ); } Aas.IEnvironment? env; try { env = Aas.Jsonization.Deserialize.EnvironmentFrom(node); } catch (Aas.Jsonization.Exception exception) { stderr.WriteLine( $"{fileInfo.FullName}: " + $"JSON parsing failed: {exception.Cause} at {exception.Path}" ); return 1; } if (env == null) { throw new System.InvalidOperationException( "Unexpected null instance" ); } foreach (var shell in env.OverAssetAdministrationShellsOrEmpty()) { var otherShell = shellRegistry.TryGet(shell.Id); if (otherShell != null) { stderr.WriteLine( $"{fileInfo.FullName}: " + "Conflict in IDs of asset administration shells; " + $"the shell with the ID {shell.Id} is defined " + "more than once" ); return 1; } shellRegistry.Add(shell); } foreach (var submodel in env.OverSubmodelsOrEmpty()) { var otherSubmodel = submodelRegistry.TryGet(submodel.Id); if (otherSubmodel != null) { stderr.WriteLine( $"{fileInfo.FullName}: " + "Conflict in IDs of submodels; " + $"the submodel with the ID {submodel.Id} " + "is defined more than once." ); return 1; } submodelRegistry.Add(submodel); } foreach (var conceptDescription in env.OverConceptDescriptionsOrEmpty()) { var otherConceptDescription = conceptDescriptionRegistry.TryGet(conceptDescription.Id); if (otherConceptDescription != null) { stderr.WriteLine( $"{fileInfo.FullName}: " + "Conflict in IDs of concept descriptions; " + "the concept description " + $"with the ID {conceptDescription.Id} " + "is defined more than once." ); return 1; } conceptDescriptionRegistry.Add(conceptDescription); } var targetDir = System.IO.Path.Join(outputDir, "shells"); var error = OutputRegistry( targetDir, shellRegistry ); if (error != null) { stderr.WriteLine( $"Error when outputting asset administration shells to {targetDir}: " + $"{error}" ); return 1; } targetDir = System.IO.Path.Join(outputDir, "submodels"); error = OutputRegistry( targetDir, submodelRegistry ); if (error != null) { stderr.WriteLine( $"Error when outputting submodels to {targetDir}: " + $"{error}" ); return 1; } targetDir = System.IO.Path.Join(outputDir, "conceptDescriptions"); error = OutputRegistry( targetDir, conceptDescriptionRegistry ); if (error != null) { stderr.WriteLine( $"Error when outputting concept descriptions to {targetDir}: " + $"{error}" ); return 1; } return 0; } [SuppressMessage("ReSharper", "RedundantNameQualifier")] static async System.Threading.Tasks.Task<int> Main(string[] args) { var rootCommand = new System.CommandLine.RootCommand( "Split an AAS environment into multiple files " + "so that they can be readily served as static files." ); var environmentOption = new System.CommandLine.Option< string >( name: "--environments", description: "Path to the AAS environment serialized as a JSON file " + "to be split into different files for static hosting" ) { IsRequired = true }; rootCommand.AddOption(environmentOption); var outputDirOption = new System.CommandLine.Option< string >( name: "--output-dir", description: "Path to the output directory" ) { IsRequired = true }; rootCommand.AddOption(outputDirOption); rootCommand.SetHandler( ( environmentPaths, outputDir ) => System.Threading.Tasks.Task.FromResult( Execute( environmentPaths, outputDir, System.Console.Error ) ), environmentOption, outputDirOption ); return await rootCommand.InvokeAsync(args); } } }
src/SplitEnvironmentForStaticHosting/Program.cs
aas-core-works-aas-core3.0-cli-swiss-knife-eb9a3ef
[ { "filename": "src/ListDanglingModelReferences/Program.cs", "retrieved_chunk": " }\n return anotherKey.Type == Type && anotherKey.Value == Value;\n }\n public HashableKey(Aas.KeyTypes type, string value) : base(type, value)\n {\n // Intentionally empty.\n }\n }\n static class Referencing\n {", "score": 0.8467084169387817 }, { "filename": "src/MergeEnvironments/Program.cs", "retrieved_chunk": " internal readonly string Path;\n public Enhancement(string path)\n {\n Path = path;\n }\n }\n public static class Program\n {\n public static int Execute(\n List<string> environmentPaths,", "score": 0.8443288803100586 }, { "filename": "src/ListDanglingModelReferences/Program.cs", "retrieved_chunk": " {\n yield return error;\n }\n }\n }\n public static class Program\n {\n public static int Execute(\n string environmentPath,\n System.IO.TextWriter stdout,", "score": 0.841832160949707 }, { "filename": "src/Verify/Program.cs", "retrieved_chunk": "using Aas = AasCore.Aas3_0; // renamed\nusing System.CommandLine; // can't alias\nusing System.Diagnostics.CodeAnalysis; // can't alias\nnamespace Verify\n{\n public static class Program\n {\n public static int Execute(\n string environmentPath,\n System.IO.TextWriter stderr", "score": 0.8322641849517822 }, { "filename": "src/CommonOutputting/Jsonization.cs", "retrieved_chunk": "using Aas = AasCore.Aas3_0; // renamed\nnamespace CommonOutputting\n{\n public static class Jsonization\n {\n /**\n * <summary>Output the environment either to a file or to STDOUT.</summary>\n * <returns>Error message, if any</returns>\n */\n public static string? Serialize(", "score": 0.8304696679115295 } ]
csharp
TypedRegistry<Aas.IIdentifiable> registry ) {
using Discord; using HarmonyLib; using System.Text.RegularExpressions; namespace Ultrapain.Patches { class DiscordController_SendActivity_Patch { static bool Prefix(DiscordController __instance, ref
Activity ___cachedActivity) {
if (___cachedActivity.State != null && ___cachedActivity.State == "DIFFICULTY: UKMD") { Regex rich = new Regex(@"<[^>]*>"); string text = $"DIFFICULTY: {ConfigManager.pluginName.value}"; if (rich.IsMatch(text)) { ___cachedActivity.State = rich.Replace(text, string.Empty); } else { ___cachedActivity.State = text; } } return true; } } }
Ultrapain/Patches/DiscordController.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/SteamFriends.cs", "retrieved_chunk": "using HarmonyLib;\nusing Steamworks;\nusing System.Text.RegularExpressions;\nnamespace Ultrapain.Patches\n{\n class SteamFriends_SetRichPresence_Patch\n {\n static bool Prefix(string __0, ref string __1)\n {\n if (__1.ToLower() != \"ukmd\")", "score": 0.8647420406341553 }, { "filename": "Ultrapain/Patches/Idol.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class Idol_Death_Patch\n {\n static void Postfix(Idol __instance)\n {", "score": 0.8582490682601929 }, { "filename": "Ultrapain/Patches/FleshPrison.cs", "retrieved_chunk": "using HarmonyLib;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing UnityEngine;\nusing UnityEngine.UI;\nnamespace Ultrapain.Patches\n{\n class FleshObamium_Start\n {\n static bool Prefix(FleshPrison __instance)", "score": 0.8553147315979004 }, { "filename": "Ultrapain/Patches/StreetCleaner.cs", "retrieved_chunk": "using HarmonyLib;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class StreetCleaner_Start_Patch\n {\n static void Postfix(Streetcleaner __instance, ref EnemyIdentifier ___eid)\n {\n ___eid.weakPoint = null;\n }", "score": 0.8365306854248047 }, { "filename": "Ultrapain/Patches/EnrageEffect.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing UnityEngine;\nnamespace Ultrapain.Patches\n{\n class EnrageEffect_Start\n {\n static void Postfix(EnrageEffect __instance)", "score": 0.8309102058410645 } ]
csharp
Activity ___cachedActivity) {
// Copyright (c) 2023, João Matos // Check the end of the file for extended copyright notice. using System; namespace ProtoIP { class Node { protected
ProtoServer _server;
protected ProtoClient _client; // Constructors public Node() { } } } // MIT License // // Copyright (c) 2023 João Matos // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE.
src/p2p.cs
JoaoAJMatos-ProtoIP-84f8797
[ { "filename": "src/common.cs", "retrieved_chunk": "// Copyright (c) 2023, João Matos\n// Check the end of the file for extended copyright notice.\nusing System.Net.Sockets;\nusing System.Net;\nnamespace ProtoIP\n{\n namespace Common \n {\n // Error definitions\n public class Error {", "score": 0.957857608795166 }, { "filename": "src/packet.cs", "retrieved_chunk": "// Copyright (c) 2023, João Matos\n// Check the end of the file for extended copyright notice.\nusing System.Text;\nusing System;\nusing ProtoIP.Common;\nnamespace ProtoIP\n{\n public class Packet\n {\n // Default packet types for the ProtoIP library", "score": 0.9498720169067383 }, { "filename": "src/client.cs", "retrieved_chunk": "// Copyright (c) 2023, João Matos\n// Check the end of the file for extended copyright notice.\nusing System.Text;\nusing System;\nusing ProtoIP;\nusing ProtoIP.Common;\nnamespace ProtoIP\n{\n public class ProtoClient\n {", "score": 0.9391246438026428 }, { "filename": "examples/netpods.cs", "retrieved_chunk": "// Copyright (c) 2023, João Matos\n// Check the end of the file for extended copyright notice.\nusing System;\nusing System.Threading;\nusing ProtoIP;\nclass Program \n{\n static void Main() \n {\n Ethernet ethernet = new Ethernet();", "score": 0.9325697422027588 }, { "filename": "src/ip.cs", "retrieved_chunk": "// Copyright (c) 2023, João Matos\n// Check the end of the file for extended copyright notice.\nusing System;\nusing System.Net;\nnamespace ProtoIP\n{ \n // Provides an interface for creating and manipulating IP packets\n // to be used with the NetPods.\n public class IP\n {", "score": 0.9308153390884399 } ]
csharp
ProtoServer _server;
using HarmonyLib; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using UnityEngine; namespace Ultrapain.Patches { public class OrbitalStrikeFlag : MonoBehaviour { public CoinChainList chainList; public bool isOrbitalRay = false; public bool exploded = false; public float activasionDistance; } public class Coin_Start { static void Postfix(Coin __instance) { __instance.gameObject.AddComponent<OrbitalStrikeFlag>(); } } public class CoinChainList : MonoBehaviour { public List<Coin> chainList = new List<Coin>(); public bool isOrbitalStrike = false; public float activasionDistance; } class Punch_BlastCheck { [HarmonyBefore(new string[] { "tempy.fastpunch" })] static bool Prefix(Punch __instance) { __instance.blastWave = GameObject.Instantiate(Plugin.explosionWaveKnuckleblaster, new Vector3(1000000, 1000000, 1000000), Quaternion.identity); __instance.blastWave.AddComponent<OrbitalStrikeFlag>(); return true; } [HarmonyBefore(new string[] { "tempy.fastpunch" })] static void Postfix(Punch __instance) { GameObject.Destroy(__instance.blastWave); __instance.blastWave = Plugin.explosionWaveKnuckleblaster; } } class Explosion_Collide { static bool Prefix(Explosion __instance, Collider __0, List<Collider> ___hitColliders) { if (___hitColliders.Contains(__0)/* || __instance.transform.parent.GetComponent<OrbitalStrikeFlag>() == null*/) return true; Coin coin = __0.GetComponent<Coin>(); if (coin != null) { OrbitalStrikeFlag flag = coin.GetComponent<OrbitalStrikeFlag>(); if(flag == null) { coin.gameObject.AddComponent<OrbitalStrikeFlag>(); Debug.Log("Added orbital strike flag"); } } return true; } } class Coin_DelayedReflectRevolver { static void Postfix(Coin __instance, GameObject ___altBeam) { CoinChainList flag = null; OrbitalStrikeFlag orbitalBeamFlag = null; if (___altBeam != null) { orbitalBeamFlag = ___altBeam.GetComponent<OrbitalStrikeFlag>(); if (orbitalBeamFlag == null) { orbitalBeamFlag = ___altBeam.AddComponent<OrbitalStrikeFlag>(); GameObject obj = new GameObject(); obj.AddComponent<RemoveOnTime>().time = 5f; flag = obj.AddComponent<CoinChainList>(); orbitalBeamFlag.chainList = flag; } else flag = orbitalBeamFlag.chainList; } else { if (__instance.ccc == null) { GameObject obj = new GameObject(); __instance.ccc = obj.AddComponent<CoinChainCache>(); obj.AddComponent<RemoveOnTime>().time = 5f; } flag = __instance.ccc.gameObject.GetComponent<CoinChainList>(); if(flag == null) flag = __instance.ccc.gameObject.AddComponent<CoinChainList>(); } if (flag == null) return; if (!flag.isOrbitalStrike && flag.chainList.Count != 0 && __instance.GetComponent<OrbitalStrikeFlag>() != null) { Coin lastCoin = flag.chainList.LastOrDefault(); float distance = Vector3.Distance(__instance.transform.position, lastCoin.transform.position); if (distance >= ConfigManager.orbStrikeMinDistance.value) { flag.isOrbitalStrike = true; flag.activasionDistance = distance; if (orbitalBeamFlag != null) { orbitalBeamFlag.isOrbitalRay = true; orbitalBeamFlag.activasionDistance = distance; } Debug.Log("Coin valid for orbital strike"); } } if (flag.chainList.Count == 0 || flag.chainList.LastOrDefault() != __instance) flag.chainList.Add(__instance); } } class Coin_ReflectRevolver { public static bool coinIsShooting = false; public static
Coin shootingCoin = null;
public static GameObject shootingAltBeam; public static float lastCoinTime = 0; static bool Prefix(Coin __instance, GameObject ___altBeam) { coinIsShooting = true; shootingCoin = __instance; lastCoinTime = Time.time; shootingAltBeam = ___altBeam; return true; } static void Postfix(Coin __instance) { coinIsShooting = false; } } class RevolverBeam_Start { static bool Prefix(RevolverBeam __instance) { OrbitalStrikeFlag flag = __instance.GetComponent<OrbitalStrikeFlag>(); if (flag != null && flag.isOrbitalRay) { RevolverBeam_ExecuteHits.orbitalBeam = __instance; RevolverBeam_ExecuteHits.orbitalBeamFlag = flag; } return true; } } class RevolverBeam_ExecuteHits { public static bool isOrbitalRay = false; public static RevolverBeam orbitalBeam = null; public static OrbitalStrikeFlag orbitalBeamFlag = null; static bool Prefix(RevolverBeam __instance) { OrbitalStrikeFlag flag = __instance.GetComponent<OrbitalStrikeFlag>(); if (flag != null && flag.isOrbitalRay) { isOrbitalRay = true; orbitalBeam = __instance; orbitalBeamFlag = flag; } return true; } static void Postfix() { isOrbitalRay = false; } } class OrbitalExplosionInfo : MonoBehaviour { public bool active = true; public string id; public int points; } class Grenade_Explode { class StateInfo { public bool state = false; public string id; public int points; public GameObject templateExplosion; } static bool Prefix(Grenade __instance, ref float __3, out StateInfo __state, bool __1, bool __2) { __state = new StateInfo(); if((Coin_ReflectRevolver.coinIsShooting && Coin_ReflectRevolver.shootingCoin != null) || (Time.time - Coin_ReflectRevolver.lastCoinTime <= 0.1f)) { CoinChainList list = null; if (Coin_ReflectRevolver.shootingAltBeam != null) { OrbitalStrikeFlag orbitalFlag = Coin_ReflectRevolver.shootingAltBeam.GetComponent<OrbitalStrikeFlag>(); if (orbitalFlag != null) list = orbitalFlag.chainList; } else if (Coin_ReflectRevolver.shootingCoin != null && Coin_ReflectRevolver.shootingCoin.ccc != null) list = Coin_ReflectRevolver.shootingCoin.ccc.GetComponent<CoinChainList>(); if (list != null && list.isOrbitalStrike) { if (__1) { __state.templateExplosion = GameObject.Instantiate(__instance.harmlessExplosion, new Vector3(1000000, 1000000, 1000000), Quaternion.identity); __instance.harmlessExplosion = __state.templateExplosion; } else if (__2) { __state.templateExplosion = GameObject.Instantiate(__instance.superExplosion, new Vector3(1000000, 1000000, 1000000), Quaternion.identity); __instance.superExplosion = __state.templateExplosion; } else { __state.templateExplosion = GameObject.Instantiate(__instance.explosion, new Vector3(1000000, 1000000, 1000000), Quaternion.identity); __instance.explosion = __state.templateExplosion; } OrbitalExplosionInfo info = __state.templateExplosion.AddComponent<OrbitalExplosionInfo>(); info.id = ""; __state.state = true; float damageMulti = 1f; float sizeMulti = 1f; // REVOLVER NORMAL if (Coin_ReflectRevolver.shootingAltBeam == null) { if (ConfigManager.orbStrikeRevolverGrenade.value) { damageMulti += ConfigManager.orbStrikeRevolverGrenadeExtraDamage.value; sizeMulti += ConfigManager.orbStrikeRevolverGrenadeExtraSize.value; info.id = ConfigManager.orbStrikeRevolverStyleText.guid; info.points = ConfigManager.orbStrikeRevolverStylePoint.value; } } else if (Coin_ReflectRevolver.shootingAltBeam.TryGetComponent(out RevolverBeam beam)) { if (beam.beamType == BeamType.Revolver) { // REVOLVER CHARGED (NORMAL + ALT. IF DISTINCTION IS NEEDED, USE beam.strongAlt FOR ALT) if (beam.ultraRicocheter) { if (ConfigManager.orbStrikeRevolverChargedGrenade.value) { damageMulti += ConfigManager.orbStrikeRevolverChargedGrenadeExtraDamage.value; sizeMulti += ConfigManager.orbStrikeRevolverChargedGrenadeExtraSize.value; info.id = ConfigManager.orbStrikeRevolverChargedStyleText.guid; info.points = ConfigManager.orbStrikeRevolverChargedStylePoint.value; } } // REVOLVER ALT else { if (ConfigManager.orbStrikeRevolverGrenade.value) { damageMulti += ConfigManager.orbStrikeRevolverGrenadeExtraDamage.value; sizeMulti += ConfigManager.orbStrikeRevolverGrenadeExtraSize.value; info.id = ConfigManager.orbStrikeRevolverStyleText.guid; info.points = ConfigManager.orbStrikeRevolverStylePoint.value; } } } // ELECTRIC RAILCANNON else if (beam.beamType == BeamType.Railgun && beam.hitAmount > 500) { if (ConfigManager.orbStrikeElectricCannonGrenade.value) { damageMulti += ConfigManager.orbStrikeElectricCannonExplosionDamage.value; sizeMulti += ConfigManager.orbStrikeElectricCannonExplosionSize.value; info.id = ConfigManager.orbStrikeElectricCannonStyleText.guid; info.points = ConfigManager.orbStrikeElectricCannonStylePoint.value; } } // MALICIOUS RAILCANNON else if (beam.beamType == BeamType.Railgun) { if (ConfigManager.orbStrikeMaliciousCannonGrenade.value) { damageMulti += ConfigManager.orbStrikeMaliciousCannonGrenadeExtraDamage.value; sizeMulti += ConfigManager.orbStrikeMaliciousCannonGrenadeExtraSize.value; info.id = ConfigManager.orbStrikeMaliciousCannonStyleText.guid; info.points = ConfigManager.orbStrikeMaliciousCannonStylePoint.value; } } else __state.state = false; } else __state.state = false; if(sizeMulti != 1 || damageMulti != 1) foreach(Explosion exp in __state.templateExplosion.GetComponentsInChildren<Explosion>()) { exp.maxSize *= sizeMulti; exp.speed *= sizeMulti; exp.damage = (int)(exp.damage * damageMulti); } Debug.Log("Applied orbital strike bonus"); } } return true; } static void Postfix(Grenade __instance, StateInfo __state) { if (__state.templateExplosion != null) GameObject.Destroy(__state.templateExplosion); if (!__state.state) return; } } class Cannonball_Explode { static bool Prefix(Cannonball __instance, GameObject ___interruptionExplosion, ref GameObject ___breakEffect) { if ((Coin_ReflectRevolver.coinIsShooting && Coin_ReflectRevolver.shootingCoin != null) || (Time.time - Coin_ReflectRevolver.lastCoinTime <= 0.1f)) { CoinChainList list = null; if (Coin_ReflectRevolver.shootingAltBeam != null) { OrbitalStrikeFlag orbitalFlag = Coin_ReflectRevolver.shootingAltBeam.GetComponent<OrbitalStrikeFlag>(); if (orbitalFlag != null) list = orbitalFlag.chainList; } else if (Coin_ReflectRevolver.shootingCoin != null && Coin_ReflectRevolver.shootingCoin.ccc != null) list = Coin_ReflectRevolver.shootingCoin.ccc.GetComponent<CoinChainList>(); if (list != null && list.isOrbitalStrike && ___interruptionExplosion != null) { float damageMulti = 1f; float sizeMulti = 1f; GameObject explosion = GameObject.Instantiate<GameObject>(___interruptionExplosion, __instance.transform.position, Quaternion.identity); OrbitalExplosionInfo info = explosion.AddComponent<OrbitalExplosionInfo>(); info.id = ""; // REVOLVER NORMAL if (Coin_ReflectRevolver.shootingAltBeam == null) { if (ConfigManager.orbStrikeRevolverGrenade.value) { damageMulti += ConfigManager.orbStrikeRevolverGrenadeExtraDamage.value; sizeMulti += ConfigManager.orbStrikeRevolverGrenadeExtraSize.value; info.id = ConfigManager.orbStrikeRevolverStyleText.guid; info.points = ConfigManager.orbStrikeRevolverStylePoint.value; } } else if (Coin_ReflectRevolver.shootingAltBeam.TryGetComponent(out RevolverBeam beam)) { if (beam.beamType == BeamType.Revolver) { // REVOLVER CHARGED (NORMAL + ALT. IF DISTINCTION IS NEEDED, USE beam.strongAlt FOR ALT) if (beam.ultraRicocheter) { if (ConfigManager.orbStrikeRevolverChargedGrenade.value) { damageMulti += ConfigManager.orbStrikeRevolverChargedGrenadeExtraDamage.value; sizeMulti += ConfigManager.orbStrikeRevolverChargedGrenadeExtraSize.value; info.id = ConfigManager.orbStrikeRevolverChargedStyleText.guid; info.points = ConfigManager.orbStrikeRevolverChargedStylePoint.value; } } // REVOLVER ALT else { if (ConfigManager.orbStrikeRevolverGrenade.value) { damageMulti += ConfigManager.orbStrikeRevolverGrenadeExtraDamage.value; sizeMulti += ConfigManager.orbStrikeRevolverGrenadeExtraSize.value; info.id = ConfigManager.orbStrikeRevolverStyleText.guid; info.points = ConfigManager.orbStrikeRevolverStylePoint.value; } } } // ELECTRIC RAILCANNON else if (beam.beamType == BeamType.Railgun && beam.hitAmount > 500) { if (ConfigManager.orbStrikeElectricCannonGrenade.value) { damageMulti += ConfigManager.orbStrikeElectricCannonExplosionDamage.value; sizeMulti += ConfigManager.orbStrikeElectricCannonExplosionSize.value; info.id = ConfigManager.orbStrikeElectricCannonStyleText.guid; info.points = ConfigManager.orbStrikeElectricCannonStylePoint.value; } } // MALICIOUS RAILCANNON else if (beam.beamType == BeamType.Railgun) { if (ConfigManager.orbStrikeMaliciousCannonGrenade.value) { damageMulti += ConfigManager.orbStrikeMaliciousCannonGrenadeExtraDamage.value; sizeMulti += ConfigManager.orbStrikeMaliciousCannonGrenadeExtraSize.value; info.id = ConfigManager.orbStrikeMaliciousCannonStyleText.guid; info.points = ConfigManager.orbStrikeMaliciousCannonStylePoint.value; } } } if (sizeMulti != 1 || damageMulti != 1) foreach (Explosion exp in explosion.GetComponentsInChildren<Explosion>()) { exp.maxSize *= sizeMulti; exp.speed *= sizeMulti; exp.damage = (int)(exp.damage * damageMulti); } if (MonoSingleton<PrefsManager>.Instance.GetBoolLocal("simpleExplosions", false)) { ___breakEffect = null; } __instance.Break(); return false; } } return true; } } class Explosion_CollideOrbital { static bool Prefix(Explosion __instance, Collider __0) { OrbitalExplosionInfo flag = __instance.transform.parent.GetComponent<OrbitalExplosionInfo>(); if (flag == null || !flag.active) return true; if ( __0.gameObject.tag != "Player" && (__0.gameObject.layer == 10 || __0.gameObject.layer == 11) && __instance.canHit != AffectedSubjects.PlayerOnly) { EnemyIdentifierIdentifier componentInParent = __0.GetComponentInParent<EnemyIdentifierIdentifier>(); if (componentInParent != null && componentInParent.eid != null && !componentInParent.eid.blessed/* && !componentInParent.eid.dead*/) { flag.active = false; if(flag.id != "") StyleHUD.Instance.AddPoints(flag.points, flag.id); } } return true; } } class EnemyIdentifier_DeliverDamage { static Coin lastExplosiveCoin = null; class StateInfo { public bool canPostStyle = false; public OrbitalExplosionInfo info = null; } static bool Prefix(EnemyIdentifier __instance, out StateInfo __state, Vector3 __2, ref float __3) { //if (Coin_ReflectRevolver.shootingCoin == lastExplosiveCoin) // return true; __state = new StateInfo(); bool causeExplosion = false; if (__instance.dead) return true; if ((Coin_ReflectRevolver.coinIsShooting && Coin_ReflectRevolver.shootingCoin != null)/* || (Time.time - Coin_ReflectRevolver.lastCoinTime <= 0.1f)*/) { CoinChainList list = null; if (Coin_ReflectRevolver.shootingAltBeam != null) { OrbitalStrikeFlag orbitalFlag = Coin_ReflectRevolver.shootingAltBeam.GetComponent<OrbitalStrikeFlag>(); if (orbitalFlag != null) list = orbitalFlag.chainList; } else if (Coin_ReflectRevolver.shootingCoin != null && Coin_ReflectRevolver.shootingCoin.ccc != null) list = Coin_ReflectRevolver.shootingCoin.ccc.GetComponent<CoinChainList>(); if (list != null && list.isOrbitalStrike) { causeExplosion = true; } } else if (RevolverBeam_ExecuteHits.isOrbitalRay && RevolverBeam_ExecuteHits.orbitalBeam != null) { if (RevolverBeam_ExecuteHits.orbitalBeamFlag != null && !RevolverBeam_ExecuteHits.orbitalBeamFlag.exploded) { causeExplosion = true; } } if(causeExplosion) { __state.canPostStyle = true; // REVOLVER NORMAL if (Coin_ReflectRevolver.shootingAltBeam == null) { if(ConfigManager.orbStrikeRevolverExplosion.value) { GameObject explosion = GameObject.Instantiate(Plugin.explosion, /*__instance.gameObject.transform.position*/__2, Quaternion.identity); foreach (Explosion exp in explosion.GetComponentsInChildren<Explosion>()) { exp.enemy = false; exp.hitterWeapon = ""; exp.maxSize *= ConfigManager.orbStrikeRevolverExplosionSize.value; exp.speed *= ConfigManager.orbStrikeRevolverExplosionSize.value; exp.damage = (int)(exp.damage * ConfigManager.orbStrikeRevolverExplosionDamage.value); } OrbitalExplosionInfo info = explosion.AddComponent<OrbitalExplosionInfo>(); info.id = ConfigManager.orbStrikeRevolverStyleText.guid; info.points = ConfigManager.orbStrikeRevolverStylePoint.value; __state.info = info; } } else if (Coin_ReflectRevolver.shootingAltBeam.TryGetComponent(out RevolverBeam beam)) { if (beam.beamType == BeamType.Revolver) { // REVOLVER CHARGED (NORMAL + ALT. IF DISTINCTION IS NEEDED, USE beam.strongAlt FOR ALT) if (beam.ultraRicocheter) { if(ConfigManager.orbStrikeRevolverChargedInsignia.value) { GameObject insignia = GameObject.Instantiate(Plugin.virtueInsignia, /*__instance.transform.position*/__2, Quaternion.identity); // This is required for ff override to detect this insignia as non ff attack insignia.gameObject.name = "PlayerSpawned"; float horizontalSize = ConfigManager.orbStrikeRevolverChargedInsigniaSize.value; insignia.transform.localScale = new Vector3(horizontalSize, insignia.transform.localScale.y, horizontalSize); VirtueInsignia comp = insignia.GetComponent<VirtueInsignia>(); comp.windUpSpeedMultiplier = ConfigManager.orbStrikeRevolverChargedInsigniaDelayBoost.value; comp.damage = ConfigManager.orbStrikeRevolverChargedInsigniaDamage.value; comp.predictive = false; comp.hadParent = false; comp.noTracking = true; StyleHUD.Instance.AddPoints(ConfigManager.orbStrikeRevolverChargedStylePoint.value, ConfigManager.orbStrikeRevolverChargedStyleText.guid); __state.canPostStyle = false; } } // REVOLVER ALT else { if (ConfigManager.orbStrikeRevolverExplosion.value) { GameObject explosion = GameObject.Instantiate(Plugin.explosion, /*__instance.gameObject.transform.position*/__2, Quaternion.identity); foreach (Explosion exp in explosion.GetComponentsInChildren<Explosion>()) { exp.enemy = false; exp.hitterWeapon = ""; exp.maxSize *= ConfigManager.orbStrikeRevolverExplosionSize.value; exp.speed *= ConfigManager.orbStrikeRevolverExplosionSize.value; exp.damage = (int)(exp.damage * ConfigManager.orbStrikeRevolverExplosionDamage.value); } OrbitalExplosionInfo info = explosion.AddComponent<OrbitalExplosionInfo>(); info.id = ConfigManager.orbStrikeRevolverStyleText.guid; info.points = ConfigManager.orbStrikeRevolverStylePoint.value; __state.info = info; } } } // ELECTRIC RAILCANNON else if (beam.beamType == BeamType.Railgun && beam.hitAmount > 500) { if(ConfigManager.orbStrikeElectricCannonExplosion.value) { GameObject lighning = GameObject.Instantiate(Plugin.lightningStrikeExplosive, /*__instance.gameObject.transform.position*/ __2, Quaternion.identity); foreach (Explosion exp in lighning.GetComponentsInChildren<Explosion>()) { exp.enemy = false; exp.hitterWeapon = ""; if (exp.damage == 0) exp.maxSize /= 2; exp.maxSize *= ConfigManager.orbStrikeElectricCannonExplosionSize.value; exp.speed *= ConfigManager.orbStrikeElectricCannonExplosionSize.value; exp.damage = (int)(exp.damage * ConfigManager.orbStrikeElectricCannonExplosionDamage.value); exp.canHit = AffectedSubjects.All; } OrbitalExplosionInfo info = lighning.AddComponent<OrbitalExplosionInfo>(); info.id = ConfigManager.orbStrikeElectricCannonStyleText.guid; info.points = ConfigManager.orbStrikeElectricCannonStylePoint.value; __state.info = info; } } // MALICIOUS RAILCANNON else if (beam.beamType == BeamType.Railgun) { // UNUSED causeExplosion = false; } // MALICIOUS BEAM else if (beam.beamType == BeamType.MaliciousFace) { GameObject explosion = GameObject.Instantiate(Plugin.sisyphiusPrimeExplosion, /*__instance.gameObject.transform.position*/__2, Quaternion.identity); foreach (Explosion exp in explosion.GetComponentsInChildren<Explosion>()) { exp.enemy = false; exp.hitterWeapon = ""; exp.maxSize *= ConfigManager.maliciousChargebackExplosionSizeMultiplier.value; exp.speed *= ConfigManager.maliciousChargebackExplosionSizeMultiplier.value; exp.damage = (int)(exp.damage * ConfigManager.maliciousChargebackExplosionDamageMultiplier.value); } OrbitalExplosionInfo info = explosion.AddComponent<OrbitalExplosionInfo>(); info.id = ConfigManager.maliciousChargebackStyleText.guid; info.points = ConfigManager.maliciousChargebackStylePoint.value; __state.info = info; } // SENTRY BEAM else if (beam.beamType == BeamType.Enemy) { StyleHUD.Instance.AddPoints(ConfigManager.sentryChargebackStylePoint.value, ConfigManager.sentryChargebackStyleText.formattedString); if (ConfigManager.sentryChargebackExtraBeamCount.value > 0) { List<Tuple<EnemyIdentifier, float>> enemies = UnityUtils.GetClosestEnemies(__2, ConfigManager.sentryChargebackExtraBeamCount.value, UnityUtils.doNotCollideWithPlayerValidator); foreach (Tuple<EnemyIdentifier, float> enemy in enemies) { RevolverBeam newBeam = GameObject.Instantiate(beam, beam.transform.position, Quaternion.identity); newBeam.hitEids.Add(__instance); newBeam.transform.LookAt(enemy.Item1.transform); GameObject.Destroy(newBeam.GetComponent<OrbitalStrikeFlag>()); } } RevolverBeam_ExecuteHits.isOrbitalRay = false; } } if (causeExplosion && RevolverBeam_ExecuteHits.orbitalBeamFlag != null) RevolverBeam_ExecuteHits.orbitalBeamFlag.exploded = true; Debug.Log("Applied orbital strike explosion"); } return true; } static void Postfix(EnemyIdentifier __instance, StateInfo __state) { if(__state.canPostStyle && __instance.dead && __state.info != null) { __state.info.active = false; if (__state.info.id != "") StyleHUD.Instance.AddPoints(__state.info.points, __state.info.id); } } } class RevolverBeam_HitSomething { static bool Prefix(RevolverBeam __instance, out GameObject __state) { __state = null; if (RevolverBeam_ExecuteHits.orbitalBeam == null) return true; if (__instance.beamType != BeamType.Railgun) return true; if (__instance.hitAmount != 1) return true; if (RevolverBeam_ExecuteHits.orbitalBeam.GetInstanceID() == __instance.GetInstanceID()) { if (!RevolverBeam_ExecuteHits.orbitalBeamFlag.exploded && ConfigManager.orbStrikeMaliciousCannonExplosion.value) { Debug.Log("MALICIOUS EXPLOSION EXTRA SIZE"); GameObject tempExp = GameObject.Instantiate(__instance.hitParticle, new Vector3(1000000, 1000000, 1000000), Quaternion.identity); foreach (Explosion exp in tempExp.GetComponentsInChildren<Explosion>()) { exp.maxSize *= ConfigManager.orbStrikeMaliciousCannonExplosionSizeMultiplier.value; exp.speed *= ConfigManager.orbStrikeMaliciousCannonExplosionSizeMultiplier.value; exp.damage = (int)(exp.damage * ConfigManager.orbStrikeMaliciousCannonExplosionDamageMultiplier.value); } __instance.hitParticle = tempExp; OrbitalExplosionInfo info = tempExp.AddComponent<OrbitalExplosionInfo>(); info.id = ConfigManager.orbStrikeMaliciousCannonStyleText.guid; info.points = ConfigManager.orbStrikeMaliciousCannonStylePoint.value; RevolverBeam_ExecuteHits.orbitalBeamFlag.exploded = true; } Debug.Log("Already exploded"); } else Debug.Log("Not the same instance"); return true; } static void Postfix(RevolverBeam __instance, GameObject __state) { if (__state != null) GameObject.Destroy(__state); } } }
Ultrapain/Patches/OrbitalStrike.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/V2Second.cs", "retrieved_chunk": " if (___currentWeapon == 4)\n {\n V2SecondSwitchWeapon.SwitchWeapon.Invoke(__instance, new object[] { 0 });\n }\n }\n }\n class V2SecondSwitchWeapon\n {\n public static MethodInfo SwitchWeapon = typeof(V2).GetMethod(\"SwitchWeapon\", BindingFlags.Instance | BindingFlags.NonPublic);\n static bool Prefix(V2 __instance, ref int __0)", "score": 0.7977926731109619 }, { "filename": "Ultrapain/Patches/MinosPrime.cs", "retrieved_chunk": " MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>();\n if (flag == null)\n return;\n flag.plannedAttack = \"Uppercut\";\n }\n }\n // aka DIE\n class MinosPrime_RiderKick\n {\n static bool Prefix(MinosPrime __instance, ref bool ___previouslyRiderKicked)", "score": 0.7965443134307861 }, { "filename": "Ultrapain/Patches/V2Second.cs", "retrieved_chunk": " }\n class V2SecondFastCoin\n {\n static MethodInfo switchWeapon = typeof(V2).GetMethod(\"SwitchWeapon\", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);\n static bool Prefix(V2 __instance, ref int ___coinsToThrow, ref bool ___aboutToShoot, ref Transform ___overrideTarget, ref Rigidbody ___overrideTargetRb,\n ref Transform ___target, Animator ___anim, ref bool ___shootingForCoin, ref int ___currentWeapon, ref float ___shootCooldown, ref bool ___aiming)\n {\n if (___coinsToThrow == 0)\n {\n return false;", "score": 0.7952256798744202 }, { "filename": "Ultrapain/Patches/Turret.cs", "retrieved_chunk": " else\n flag.shootCountRemaining = ConfigManager.turretBurstFireCount.value;\n return true;\n }\n }\n class TurretAim\n {\n static void Postfix(Turret __instance)\n {\n TurretFlag flag = __instance.GetComponent<TurretFlag>();", "score": 0.7841048836708069 }, { "filename": "Ultrapain/Patches/MaliciousFace.cs", "retrieved_chunk": " flag.charging = false;\n }\n return true;\n }\n }\n class MaliciousFace_ShootProj_Patch\n {\n /*static bool Prefix(SpiderBody __instance, ref GameObject ___proj, out bool __state)\n {\n __state = false;", "score": 0.7782546281814575 } ]
csharp
Coin shootingCoin = null;
using System.Net.WebSockets; using System.Text; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; namespace TraTech.WebSocketHub { public class WebSocketHubMiddleware<TKey> where TKey : notnull { private readonly IServiceProvider _serviceProvider; private readonly RequestDelegate _next; private readonly Func<HttpContext, bool> _acceptIf; private readonly
WebSocketHub<TKey> _webSocketHub;
private readonly Func<HttpContext, TKey> _keyGenerator; private readonly byte[] _receiveBuffer; public WebSocketHubMiddleware(IServiceProvider serviceProvider, RequestDelegate next, WebSocketHub<TKey> webSocketHub, Func<HttpContext, bool> acceptIf, Func<HttpContext, TKey> keyGenerator) { _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); _next = next ?? throw new ArgumentNullException(nameof(next)); _acceptIf = acceptIf ?? throw new ArgumentNullException(nameof(acceptIf)); _webSocketHub = webSocketHub ?? throw new ArgumentNullException(nameof(webSocketHub)); _keyGenerator = keyGenerator ?? throw new ArgumentNullException(nameof(keyGenerator)); _receiveBuffer = new byte[_webSocketHub.Options.ReceiveBufferSize]; } public async Task Invoke(HttpContext httpContext) { if (httpContext.WebSockets.IsWebSocketRequest && _acceptIf(httpContext)) { try { WebSocket webSocket = await httpContext.WebSockets.AcceptWebSocketAsync(); var key = _keyGenerator(httpContext); _webSocketHub.Add(key, webSocket); while (webSocket.State == WebSocketState.Open || webSocket.State == WebSocketState.CloseSent) { try { WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(_receiveBuffer), CancellationToken.None); string request = Encoding.UTF8.GetString(_receiveBuffer, 0, result.Count); if (result.MessageType == WebSocketMessageType.Close) { break; } Message? serializedRequest = _webSocketHub.DeserializeMessage(request); if (serializedRequest == null) { throw new NullReferenceException(nameof(serializedRequest)); } Type? handlerType = await _webSocketHub.Options.WebSocketRequestHandler.GetHandlerAsync(serializedRequest.Type); if (handlerType == null) { throw new NullReferenceException(nameof(handlerType)); } if (_serviceProvider.GetService(handlerType) is not IWebSocketRequestHandler service) { throw new NullReferenceException(nameof(service)); } await service.HandleRequestAsync( JsonConvert.SerializeObject(key, _webSocketHub.Options.JsonSerializerSettings), JsonConvert.SerializeObject(serializedRequest.Payload, _webSocketHub.Options.JsonSerializerSettings) ); } catch (Exception exp) { Console.WriteLine(exp.ToString()); continue; } } await _webSocketHub.RemoveAsync(key, webSocket); } catch (Exception exp) { Console.WriteLine(exp.ToString()); } } else { await _next(httpContext); } } } }
src/WebSocketHub/Core/src/WebSocketHubMiddleware.cs
TRA-Tech-dotnet-websocket-9049854
[ { "filename": "src/ExampleWebApplication/WebSocketRequestHandlers/WebSocketRequestHandler2.cs", "retrieved_chunk": "using TraTech.WebSocketHub;\nnamespace ExampleWebApplication.WebSocketRequestHandlers\n{\n public class WebSocketRequestHandler2 : IWebSocketRequestHandler\n {\n public Task HandleRequestAsync(string key, string data)\n {\n Console.WriteLine(\"------- HandleRequestAsync started -------\");\n Console.WriteLine(\"key\");\n Console.WriteLine(key);", "score": 0.8412150144577026 }, { "filename": "src/ExampleWebApplication/WebSocketRequestHandlers/WebSocketRequestHandler1.cs", "retrieved_chunk": "using TraTech.WebSocketHub;\nnamespace ExampleWebApplication.WebSocketRequestHandlers\n{\n public class WebSocketRequestHandler1 : IWebSocketRequestHandler\n {\n public Task HandleRequestAsync(string key, string data)\n {\n Console.WriteLine(\"------- HandleRequestAsync started -------\");\n Console.WriteLine(\"key\");\n Console.WriteLine(key);", "score": 0.8411123752593994 }, { "filename": "src/ExampleWebApplication/WebSocketHubKeys/SocketUser.cs", "retrieved_chunk": "namespace ExampleWebApplication.WebSocketHubKeys\n{\n public class SocketUser\n {\n public int Id { get; private set; }\n public DateTime OpenDate { get; private set; }\n public SocketUser(int id)\n {\n Id = id;\n OpenDate = DateTime.UtcNow;", "score": 0.8357444405555725 }, { "filename": "src/WebSocketHub/Core/src/WebSocketHubBuilder.cs", "retrieved_chunk": " /// This method adds a WebSocket request handler of type THandler for the specified message type to the WebSocketHubOptions. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. The THandler type is also registered as a transient service in the application services.\n /// </remarks>\n public WebSocketHubBuilder AddRequestHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)\n where THandler : class, IWebSocketRequestHandler\n {\n Services.Configure<WebSocketHubOptions>(o =>\n {\n o.WebSocketRequestHandler.TryAddHandler<THandler>(messageType);\n });\n Services.TryAddTransient<THandler>();", "score": 0.8205922245979309 }, { "filename": "src/WebSocketHub/Core/src/WebSocketHubAppBuilderExtensions.cs", "retrieved_chunk": "using Microsoft.AspNetCore.Builder;\nusing Microsoft.AspNetCore.Http;\nusing Microsoft.AspNetCore.WebSockets;\nnamespace TraTech.WebSocketHub\n{\n public static class WebSocketHubAppBuilderExtensions\n {\n /// <summary>\n /// Adds the WebSocketHubMiddleware to the pipeline with the specified acceptIf and keyGenerator functions.\n /// </summary>", "score": 0.8183086514472961 } ]
csharp
WebSocketHub<TKey> _webSocketHub;
using HarmonyLib; using Sandbox; using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.AI; namespace Ultrapain.Patches { class MinosPrimeCharge { static GameObject decoy; public static void CreateDecoy() { if (decoy != null || Plugin.minosPrime == null) return; decoy = GameObject.Instantiate(Plugin.minosPrime, Vector3.zero, Quaternion.identity); decoy.SetActive(false); GameObject.Destroy(decoy.GetComponent<MinosPrime>()); GameObject.Destroy(decoy.GetComponent<Machine>()); GameObject.Destroy(decoy.GetComponent<BossHealthBar>()); GameObject.Destroy(decoy.GetComponent<EventOnDestroy>()); GameObject.Destroy(decoy.GetComponent<BossIdentifier>()); GameObject.Destroy(decoy.GetComponent<EnemyIdentifier>()); GameObject.Destroy(decoy.GetComponent<BasicEnemyDataRelay>()); GameObject.Destroy(decoy.GetComponent<Rigidbody>()); GameObject.Destroy(decoy.GetComponent<CapsuleCollider>()); GameObject.Destroy(decoy.GetComponent<AudioSource>()); GameObject.Destroy(decoy.GetComponent<NavMeshAgent>()); foreach (SkinnedMeshRenderer renderer in UnityUtils.GetComponentsInChildrenRecursively<SkinnedMeshRenderer>(decoy.transform)) { renderer.material = new Material(Plugin.gabrielFakeMat); } SandboxEnemy sbe = decoy.GetComponent<SandboxEnemy>(); if (sbe != null) GameObject.Destroy(sbe); MindflayerDecoy comp = decoy.AddComponent<MindflayerDecoy>(); comp.fadeSpeed = 1f; //decoy.GetComponent<Animator>().StopPlayback(); //decoy.GetComponent<Animator>().Update(100f); GameObject.Destroy(decoy.transform.Find("SwingCheck").gameObject); GameObject.Destroy(decoy.transform.Find("Capsule").gameObject); GameObject.Destroy(decoy.transform.Find("Point Light").gameObject); foreach (EnemyIdentifierIdentifier eii in UnityUtils.GetComponentsInChildrenRecursively<EnemyIdentifierIdentifier>(decoy.transform)) GameObject.Destroy(eii); } static void DrawTrail(MinosPrime instance, Animator anim, Vector3 startPosition, Vector3 targetPosition) { if(decoy == null) { CreateDecoy(); return; } targetPosition = Vector3.MoveTowards(targetPosition, startPosition, 5f); Vector3 currentPosition = startPosition; float distance = Vector3.Distance(startPosition, targetPosition); if (distance < 2.5f) return; float deltaDistance = 2.5f; float fadeSpeed = 1f / ConfigManager.minosPrimeTeleportTrailDuration.value; AnimatorStateInfo currentAnimatorStateInfo = anim.GetCurrentAnimatorStateInfo(0); int maxIterations = Mathf.CeilToInt(distance / deltaDistance); float currentTransparency = 0.1f; float deltaTransparencyPerIteration = 1f / maxIterations; while (currentPosition != targetPosition) { GameObject gameObject = GameObject.Instantiate(decoy, currentPosition, instance.transform.rotation); gameObject.SetActive(true); Animator componentInChildren = gameObject.GetComponentInChildren<Animator>(); componentInChildren.Play(currentAnimatorStateInfo.shortNameHash, 0, currentAnimatorStateInfo.normalizedTime); componentInChildren.speed = 0f; MindflayerDecoy comp = gameObject.GetComponent<MindflayerDecoy>(); comp.fadeSpeed = fadeSpeed; currentTransparency += deltaTransparencyPerIteration; comp.fadeOverride = Mathf.Min(1f, currentTransparency); currentPosition = Vector3.MoveTowards(currentPosition, targetPosition, deltaDistance); } } static void Postfix(MinosPrime __instance, Animator ___anim) { string stateName = ___anim.GetCurrentAnimatorClipInfo(0)[0].clip.name; MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (stateName == "Combo" || (flag != null && flag.throwingProjectile)) return; Transform player = MonoSingleton<PlayerTracker>.Instance.GetPlayer(); float min = ConfigManager.minosPrimeRandomTeleportMinDistance.value; float max = ConfigManager.minosPrimeRandomTeleportMaxDistance.value; Vector3 unitSphere = UnityEngine.Random.onUnitSphere; unitSphere.y = Mathf.Abs(unitSphere.y); float distance = UnityEngine.Random.Range(min, max); Ray ray = new Ray(player.position, unitSphere); LayerMask mask = new LayerMask(); mask.value |= 256 | 16777216; if (Physics.Raycast(ray, out RaycastHit hit, max, mask, QueryTriggerInteraction.Ignore)) { if (hit.distance < min) return; Vector3 point = ray.GetPoint(hit.distance - 5); __instance.Teleport(point, __instance.transform.position); } else { Vector3 point = ray.GetPoint(distance); __instance.Teleport(point, __instance.transform.position); } } static void TeleportPostfix(MinosPrime __instance, Animator ___anim, Vector3 __0, Vector3 __1) { DrawTrail(__instance, ___anim, __1, __0); } } class MinosPrimeFlag : MonoBehaviour { void Start() { } public void ComboExplosion() { GameObject explosion = Instantiate(Plugin.lightningStrikeExplosive, transform.position, Quaternion.identity); foreach(Explosion e in explosion.GetComponentsInChildren<Explosion>()) { e.toIgnore.Add(EnemyType.MinosPrime); e.maxSize *= ConfigManager.minosPrimeComboExplosionSize.value; e.speed *= ConfigManager.minosPrimeComboExplosionSize.value; e.damage = (int)(e.damage * ConfigManager.minosPrimeComboExplosionDamage.value); } } public void BigExplosion() { GameObject explosion = Instantiate(Plugin.lightningStrikeExplosive, transform.position, Quaternion.identity); foreach (Explosion e in explosion.GetComponentsInChildren<Explosion>()) { e.toIgnore.Add(EnemyType.MinosPrime); e.maxSize *= ConfigManager.minosPrimeExplosionSize.value; e.speed *= ConfigManager.minosPrimeExplosionSize.value; e.damage = (int)(e.damage * ConfigManager.minosPrimeExplosionDamage.value); } } public bool throwingProjectile = false; public string plannedAttack = ""; public bool explosionAttack = false; } class MinosPrime_Start { static void Postfix(MinosPrime __instance, Animator ___anim, ref bool ___enraged) { if (ConfigManager.minosPrimeEarlyPhaseToggle.value) ___enraged = true; __instance.gameObject.AddComponent<MinosPrimeFlag>(); if (ConfigManager.minosPrimeComboExplosionToggle.value) { AnimationClip boxing = ___anim.runtimeAnimatorController.animationClips.Where(item => item.name == "Boxing").First(); List<UnityEngine.AnimationEvent> boxingEvents = boxing.events.ToList(); boxingEvents.Insert(15, new UnityEngine.AnimationEvent() { time = 2.4f, functionName = "ComboExplosion", messageOptions = SendMessageOptions.RequireReceiver }); boxing.events = boxingEvents.ToArray(); } } } class MinosPrime_StopAction { static void Postfix(MinosPrime __instance, EnemyIdentifier ___eid) { MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (flag == null) return; if (flag.plannedAttack != "") { __instance.SendMessage(flag.plannedAttack); flag.plannedAttack = ""; } } } // aka JUDGEMENT class MinosPrime_Dropkick { static bool Prefix(MinosPrime __instance,
EnemyIdentifier ___eid, ref bool ___inAction, Animator ___anim) {
MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (flag == null) return true; if (!flag.throwingProjectile) { if (ConfigManager.minosPrimeExplosionToggle.value && UnityEngine.Random.Range(0, 99.9f) < ConfigManager.minosPrimeExplosionChance.value) { __instance.TeleportAnywhere(); ___inAction = true; flag.explosionAttack = true; ___anim.speed = ___eid.totalSpeedModifier * ConfigManager.minosPrimeExplosionWindupSpeed.value; ___anim.Play("Outro", 0, 0.5f); __instance.PlayVoice(new AudioClip[] { __instance.phaseChangeVoice }); return false; } if (ConfigManager.minosPrimeComboToggle.value) { flag.throwingProjectile = true; flag.plannedAttack = "Dropkick"; __instance.SendMessage("ProjectilePunch"); } return false; } else { if (ConfigManager.minosPrimeComboToggle.value) { flag.plannedAttack = "ProjectilePunch"; flag.throwingProjectile = false; } } return true; } } // aka PREPARE THYSELF class MinosPrime_Combo { static float timing = 3f; static void Postfix(MinosPrime __instance, EnemyIdentifier ___eid) { if (!ConfigManager.minosPrimeComboToggle.value) return; MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (flag == null) return; flag.plannedAttack = "Uppercut"; } } // aka DIE class MinosPrime_RiderKick { static bool Prefix(MinosPrime __instance, ref bool ___previouslyRiderKicked) { if (UnityEngine.Random.Range(0, 99.9f) > ConfigManager.minosPrimeCrushAttackChance.value) return true; ___previouslyRiderKicked = true; Vector3 vector = MonoSingleton<PlayerTracker>.Instance.PredictPlayerPosition(0.5f); Transform target = MonoSingleton<PlayerTracker>.Instance.GetPlayer(); if (vector.y < target.position.y) { vector.y = target.position.y; } __instance.Teleport(vector + Vector3.up * 25f, __instance.transform.position); __instance.SendMessage("DropAttack"); return false; } } // End of PREPARE THYSELF class MinosPrime_ProjectileCharge { static bool Prefix(MinosPrime __instance, Animator ___anim) { string clipname = ___anim.GetCurrentAnimatorClipInfo(0)[0].clip.name; if (clipname != "Combo" || UnityEngine.Random.Range(0, 99.9f) > ConfigManager.minosPrimeComboExplosiveEndChance.value) return true; ___anim.Play("Dropkick", 0, (1.0815f - 0.4279f) / 2.65f); return false; } } class MinosPrime_Ascend { static bool Prefix(MinosPrime __instance, EnemyIdentifier ___eid, Animator ___anim, ref bool ___vibrating) { if (___eid.health <= 0) return true; MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (flag == null) return true; if (!flag.explosionAttack) return true; ___anim.speed = ___eid.totalSpeedModifier; ___vibrating = false; flag.explosionAttack = false; flag.BigExplosion(); __instance.Invoke("Uppercut", 0.5f); return false; } } class MinosPrime_Death { static bool Prefix(MinosPrime __instance, Animator ___anim, ref bool ___vibrating) { MinosPrimeFlag flag = __instance.GetComponent<MinosPrimeFlag>(); if (flag == null) return true; if (!flag.explosionAttack) return true; flag.explosionAttack = false; ___vibrating = false; ___anim.speed = 1f; ___anim.Play("Walk", 0, 0f); return true; } } }
Ultrapain/Patches/MinosPrime.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/MaliciousFace.cs", "retrieved_chunk": " flag.charging = false;\n }\n return true;\n }\n }\n class MaliciousFace_ShootProj_Patch\n {\n /*static bool Prefix(SpiderBody __instance, ref GameObject ___proj, out bool __state)\n {\n __state = false;", "score": 0.8835064172744751 }, { "filename": "Ultrapain/Patches/Mindflayer.cs", "retrieved_chunk": " }\n else\n patch.swingComboLeft = 2;*/\n }\n }\n class Mindflayer_MeleeTeleport_Patch\n {\n public static Vector3 deltaPosition = new Vector3(0, -10, 0);\n static bool Prefix(Mindflayer __instance, ref EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___goingLeft, ref Animator ___anim, ref bool ___enraged)\n {", "score": 0.8647876977920532 }, { "filename": "Ultrapain/Patches/Drone.cs", "retrieved_chunk": " return false;\n }\n Debug.LogError($\"Drone fire mode in impossible state. Current value: {mode} : {(int)mode}\");\n return true;\n }\n }\n class Drone_Update\n {\n static void Postfix(Drone __instance, EnemyIdentifier ___eid, ref float ___attackCooldown, int ___difficulty)\n {", "score": 0.8603504300117493 }, { "filename": "Ultrapain/Patches/Mindflayer.cs", "retrieved_chunk": " //___eid.SpeedBuff();\n }\n }\n class Mindflayer_ShootProjectiles_Patch\n {\n public static float maxProjDistance = 5;\n public static float initialProjectileDistance = -1f;\n public static float distancePerProjShot = 0.2f;\n static bool Prefix(Mindflayer __instance, ref EnemyIdentifier ___eid, ref LayerMask ___environmentMask, ref bool ___enraged)\n {", "score": 0.8603487014770508 }, { "filename": "Ultrapain/Patches/Leviathan.cs", "retrieved_chunk": " }\n return false;\n }\n }\n class Leviathan_ProjectileBurst\n {\n static bool Prefix(LeviathanHead __instance, Animator ___anim,\n ref int ___projectilesLeftInBurst, ref float ___projectileBurstCooldown, ref bool ___inAction)\n {\n if (!__instance.active)", "score": 0.8585516214370728 } ]
csharp
EnemyIdentifier ___eid, ref bool ___inAction, Animator ___anim) {
#nullable enable using System; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Mochineko.YouTubeLiveStreamingClient.Responses { [JsonObject] public sealed class LiveChatMessageSnippet { [JsonProperty("type"), JsonRequired, JsonConverter(typeof(StringEnumConverter))] public LiveChatMessageType Type { get; private set; } [JsonProperty("liveChatId"), JsonRequired] public string LiveChatId { get; private set; } = string.Empty; [JsonProperty("authorChannelId"), JsonRequired] public string AuthorChannelId { get; private set; } = string.Empty; [JsonProperty("publishedAt"), JsonRequired] public DateTime PublishedAt { get; private set; } [JsonProperty("hasDisplayContent"), JsonRequired] public bool HasDisplayContent { get; private set; } [JsonProperty("displayMessage"), JsonRequired] public string DisplayMessage { get; private set; } = string.Empty; [JsonProperty("textMessageDetails")] public
TextMessageDetails? TextMessageDetails {
get; private set; } [JsonProperty("messageDeletedDetails")] public MessageDeletedDetails? MessageDeletedDetails { get; private set; } [JsonProperty("userBannedDetails")] public UserBannedDetails? UserBannedDetails { get; private set; } [JsonProperty("memberMilestoneChatDetails")] public MemberMilestoneChatDetails? MemberMilestoneChatDetails { get; private set; } [JsonProperty("newSponsorDetails")] public NewSponsorDetails? NewSponsorDetails { get; private set; } [JsonProperty("superChatDetails")] public SuperChatDetails? SuperChatDetails { get; private set; } [JsonProperty("superStickerDetails")] public SuperStickerDetails? SuperStickerDetails { get; private set; } [JsonProperty("membershipGiftingDetails")] public MembershipGiftingDetails? MembershipGiftingDetails { get; private set; } [JsonProperty("giftMembershipReceivedDetails")] public GiftMembershipReceivedDetails? GiftMembershipReceivedDetails { get; private set; } } }
Assets/Mochineko/YouTubeLiveStreamingClient/Responses/LiveChatMessageSnippet.cs
mochi-neko-youtube-live-streaming-client-unity-b712d77
[ { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient/Responses/VideoSnippet.cs", "retrieved_chunk": " [JsonProperty(\"tags\")]\n public string[]? Tags { get; private set; }\n [JsonProperty(\"categoryId\"), JsonRequired]\n public string CategoryId { get; private set; } = string.Empty;\n [JsonProperty(\"liveBroadcastContent\"), JsonRequired]\n public string LiveBroadcastContent { get; private set; } = string.Empty;\n [JsonProperty(\"defaultLanguage\")]\n public string? DefaultLanguage { get; private set; }\n [JsonProperty(\"localized\"), JsonRequired]\n public Localized Localized { get; private set; } = new();", "score": 0.934601902961731 }, { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient/Responses/AuthorDetails.cs", "retrieved_chunk": " public string ChannelUrl { get; private set; } = string.Empty;\n [JsonProperty(\"displayName\"), JsonRequired]\n public string DisplayName { get; private set; } = string.Empty;\n [JsonProperty(\"profileImageUrl\"), JsonRequired]\n public string ProfileImageUrl { get; private set; } = string.Empty;\n [JsonProperty(\"isVerified\"), JsonRequired]\n public bool IsVerified { get; private set; }\n [JsonProperty(\"isChatOwner\"), JsonRequired]\n public bool IsChatOwner { get; private set; }\n [JsonProperty(\"isChatSponsor\"), JsonRequired]", "score": 0.9342026710510254 }, { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient/Responses/LiveChatMessagesAPIResponse.cs", "retrieved_chunk": " [JsonProperty(\"etag\"), JsonRequired]\n public string Etag { get; private set; } = string.Empty;\n [JsonProperty(\"nextPageToken\"), JsonRequired]\n public string NextPageToken { get; private set; } = string.Empty;\n [JsonProperty(\"pollingIntervalMillis\"), JsonRequired]\n public uint PollingIntervalMillis { get; private set; }\n [JsonProperty(\"pageInfo\"), JsonRequired]\n public PageInfo PageInfo { get; private set; } = new();\n [JsonProperty(\"items\"), JsonRequired]\n public List<LiveChatMessageItem> Items { get; private set; } = new();", "score": 0.9303499460220337 }, { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient/Responses/VideoSnippet.cs", "retrieved_chunk": " [JsonProperty(\"channelId\"), JsonRequired]\n public string ChannelId { get; private set; } = string.Empty;\n [JsonProperty(\"title\"), JsonRequired]\n public string Title { get; private set; } = string.Empty;\n [JsonProperty(\"description\"), JsonRequired]\n public string Description { get; private set; } = string.Empty;\n [JsonProperty(\"thumbnails\"), JsonRequired]\n public VideoThumbnails Thumbnails { get; private set; } = new();\n [JsonProperty(\"channelTitle\"), JsonRequired]\n public string ChannelTitle { get; private set; } = string.Empty;", "score": 0.9255431294441223 }, { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient/Responses/LiveChatMessageItem.cs", "retrieved_chunk": " public string Etag { get; private set; } = string.Empty;\n [JsonProperty(\"id\"), JsonRequired]\n public string Id { get; private set; } = string.Empty;\n [JsonProperty(\"snippet\"), JsonRequired]\n public LiveChatMessageSnippet Snippet { get; private set; } = new();\n [JsonProperty(\"authorDetails\"), JsonRequired]\n public AuthorDetails AuthorDetails { get; private set; } = new();\n }\n}", "score": 0.9251194000244141 } ]
csharp
TextMessageDetails? TextMessageDetails {
using System; namespace it { using it.Actions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Win32; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Reflection; using System.Web.Services.Description; using System.Windows; using System.Windows.Forms; /// <summary> /// The bootstrap class is provided to allow the application to run with out a form. We can use /// a form however in the future by adding it to here. /// </summary> internal sealed class Bootstrap : IDisposable { private readonly
ClipboardMonitor clipboardMonitor = new ClipboardMonitor();
private readonly ControlContainer container = new ControlContainer(); private readonly NotifyIcon notifyIcon; private readonly List<Question> questionList = Questions.LoadQuestions(); private bool clipboardPaused = false; private bool disposed = false; private IntPtr handle; private bool notifyPaused = false; // Container to hold the actions private ServiceProvider serviceProvider; public Bootstrap() { notifyIcon = new NotifyIcon(container) { Visible = true, }; ConfigureDependancies(); clipboardMonitor.ClipboardChanged += ClipboardMonitor_ClipboardChanged; } ~Bootstrap() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } internal static void EnsureWindowStartup(bool isStartingWithWindows) { const string keyName = "Clipboard Assistant"; using ( RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true)) { if (key is null) { return; } string value = key.GetValue(keyName, null) as string; if (isStartingWithWindows) { // key doesn't exist, add it if (string.IsNullOrWhiteSpace(value) && string.Equals(value, Assembly.GetExecutingAssembly().Location, StringComparison.Ordinal)) { key.SetValue(keyName, Assembly.GetExecutingAssembly().Location); } } else if (!string.IsNullOrWhiteSpace(value)) { key.DeleteValue(keyName); } } } internal void Startup(string clipboardText) { } [System.Runtime.InteropServices.DllImport("Kernel32")] private static extern Boolean CloseHandle(IntPtr handle); private static string GetClipboardText(string clipboardText) { return clipboardText; } private void ClipboardMonitor_ClipboardChanged(object sender, ClipboardChangedEventArgs e) { // retrieve the text from the clipboard if (e.DataObject.GetData(System.Windows.DataFormats.Text) is string clipboardText) { // the data is not a string. bail. if (string.IsNullOrWhiteSpace(clipboardText)) { return; } if (clipboardPaused) { if (clipboardText.Equals("hervat") || clipboardText.Equals("resume")) { clipboardPaused = false; } return; } if (clipboardText.Equals("pauze") || clipboardText.Equals("pause")) { clipboardPaused = true; return; } // if we get to here, we have text ProcessClipboardText(clipboardText); } } private void ConfigureDependancies() { // Add configure services Microsoft.Extensions.DependencyInjection.ServiceCollection serviceDescriptors = new Microsoft.Extensions.DependencyInjection.ServiceCollection(); _ = serviceDescriptors.AddSingleton<IAction, CurrencyConversion>(); _ = serviceDescriptors.AddSingleton<IAction, ConvertActions>(); _ = serviceDescriptors.AddSingleton<IAction, TryRomanActions>(); _ = serviceDescriptors.AddSingleton<IAction, CountdownActions>(); _ = serviceDescriptors.AddSingleton<IAction, DeviceActions>(); _ = serviceDescriptors.AddSingleton<IAction, RandomActions>(); _ = serviceDescriptors.AddSingleton<IAction, StopwatchActions>(); _ = serviceDescriptors.AddSingleton<IAction, TimespanActions>(); _ = serviceDescriptors.AddSingleton<IAction, numberToHex>(); _ = serviceDescriptors.AddSingleton<IAction, desktopCleaner>(); _ = serviceDescriptors.AddSingleton<IAction, TimezoneActions>(); _ = serviceDescriptors.AddSingleton<IAction, BmiActions>(); _ = serviceDescriptors.AddSingleton<IAction, tryBinary>(); _ = serviceDescriptors.AddSingleton<IAction, Currency>(); _ = serviceDescriptors.AddSingleton<IAction, Wallpaper>(); _ = serviceDescriptors.AddSingleton<IAction, autoClicker>(); _ = serviceDescriptors.AddSingleton<IAction, timeCalculations>(); //_ = serviceDescriptors.AddSingleton<IAction, Weatherforecast>(); _ = serviceDescriptors.AddSingleton<IAction, MathActions>(); (serviceProvider as IDisposable)?.Dispose(); serviceProvider = serviceDescriptors.BuildServiceProvider(); } private void Dispose(bool disposing) { if (disposed) { return; } if (disposing) { (serviceProvider as IDisposable)?.Dispose(); notifyIcon?.Dispose(); notifyIcon.Icon?.Dispose(); container?.Dispose(); clipboardMonitor?.Dispose(); } CloseHandle(handle); handle = IntPtr.Zero; disposed = true; } private IAction GetService(string clipboardText) { return serviceProvider.GetServices<IAction>().FirstOrDefault(s => s.Matches(GetClipboardText(clipboardText))); } private void ProcessClipboardText(string clipboardText) { if (clipboardText is null) { throw new ArgumentNullException(nameof(clipboardText)); } if (notifyPaused) { if (clipboardText.Equals("show notifications") || clipboardText.Equals("toon notificaties") || clipboardText.Equals("toon") || clipboardText.Equals("show")) { notifyPaused = false; } return; } if (clipboardText.Equals("hide notifications") || clipboardText.Equals("verberg notificaties") || clipboardText.Equals("verberg") || clipboardText.Equals("hide")) { notifyPaused = true; } try { IAction service = GetService(clipboardText); if (service is object) { clipboardMonitor.ClipboardChanged -= ClipboardMonitor_ClipboardChanged; ActionResult actionResult = service.TryExecute(clipboardText); clipboardMonitor.ClipboardChanged += ClipboardMonitor_ClipboardChanged; // re attach the event if (!string.IsNullOrWhiteSpace(actionResult.Title) || !string.IsNullOrWhiteSpace(actionResult.Description)) { ProcessResult(actionResult, clipboardText); } return; } if (clipboardText.Length > 2) { { for (int i = 0; i < questionList.Count; i++) { Question question = questionList[i]; if (question.Text.Contains(clipboardText)) { ProcessResult(new ActionResult(question.Text, question.Answer), clipboardText); return; } } } } } catch (Exception ex) { _ = System.Windows.Forms.MessageBox.Show(ex.ToString()); } } private void ProcessResult(ActionResult actionResult, string clipboardText) { notifyIcon.Icon = SystemIcons.Exclamation; notifyIcon.BalloonTipTitle = actionResult.Title; notifyIcon.BalloonTipText = actionResult.Description; notifyIcon.BalloonTipIcon = ToolTipIcon.Error; if (!notifyPaused) { notifyIcon.ShowBalloonTip(1000); } } } }
Bootstrap.cs
Teun-vdB-NotifySolver-88c06a6
[ { "filename": "KnownFolders.cs", "retrieved_chunk": "using System;\nusing System.Runtime.InteropServices;\n/// <summary>\n/// Standard folders registered with the system. These folders are installed with Windows Vista and\n/// later operating systems, and a computer will have only folders appropriate to it installed.\n/// </summary>\npublic enum KnownFolder\n{\n Contacts,\n Desktop,", "score": 0.8379676342010498 }, { "filename": "KnownFolders.cs", "retrieved_chunk": " NoAppcontainerRedirection = 0x00010000,\n AliasOnly = 0x80000000\n }\n /// <summary>\n /// Gets the current path to the specified known folder as currently configured. This does not\n /// require the folder to be existent.\n /// </summary>\n /// <param name=\"knownFolder\">\n /// The known folder which current path will be returned.\n /// </param>", "score": 0.8350893259048462 }, { "filename": "FastDirectoryEnumerator.cs", "retrieved_chunk": " /// <summary>\n /// Name of the file\n /// </summary>\n public readonly string Name;\n /// <summary>\n /// Full path to the file.\n /// </summary>\n public readonly string Path;\n /// <summary>\n /// Size of the file in bytes", "score": 0.8328441381454468 }, { "filename": "Actions/IAction.cs", "retrieved_chunk": " PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n }\n internal abstract class ActionBase : IAction, IEquatable<ActionBase>\n {\n public bool Equals(ActionBase other)\n {\n throw new NotImplementedException();\n }\n public abstract bool Matches(string clipboardText = null);", "score": 0.8288840055465698 }, { "filename": "KnownFolders.cs", "retrieved_chunk": " /// <summary>\n /// Gets the current path to the specified known folder as currently configured. This does not\n /// require the folder to be existent.\n /// </summary>\n /// <param name=\"knownFolder\">\n /// The known folder which current path will be returned.\n /// </param>\n /// <param name=\"defaultUser\">\n /// Specifies if the paths of the default user (user profile\n /// template) will be used. This requires administrative rights.", "score": 0.8282314538955688 } ]
csharp
ClipboardMonitor clipboardMonitor = new ClipboardMonitor();
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using Jamesnet.Wpf.Controls; using Jamesnet.Wpf.Mvvm; using Microsoft.Win32; using Newtonsoft.Json; using objective.Core; using objective.Core.Events; using objective.Forms.Local.Models; using objective.Models; using objective.SampleData; using Prism.Events; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Media.Imaging; using System.Windows.Media; using objective.Forms.UI.Views; using System.Windows.Controls; namespace objective.Forms.Local.ViewModels { public partial class MainContentViewModel : ObservableBase, IViewLoadable { private FrameworkElement aaa; [ObservableProperty] private bool isLoad = false; [ObservableProperty] private ReportObject _selectedObject; [ObservableProperty] private List<
ToolItem> _tools;
[ObservableProperty] private ObservableCollection<PageModel> pages; [ObservableProperty] ObservableCollection<ReportObject> multiObject = new (); [ObservableProperty] private List<ToolItem> _subTools; private readonly IEventAggregator _eh; public MainContentViewModel(IEventAggregator eh) { _eh = eh; Tools = GetTools (); SubTools = GetSubTools (); this.Pages = new (); this._eh.GetEvent<ClosedEvent> ().Subscribe (() => { this.Save (); }); } public void OnLoaded(IViewable smartWindow) { aaa = smartWindow.View; Task.Run (() => { OpenFileDialog ofd = new (); ofd.InitialDirectory = Environment.CurrentDirectory; ofd.Filter = "objective files(*.objective) | *.objective"; ofd.Multiselect = false; if (ofd.ShowDialog () == false) { FilePath = Environment.CurrentDirectory; FileLoadName = "Default.objective"; string PullPath = $@"{FilePath}\{FileLoadName}"; File.Create ("Default.objective"); Application.Current.Dispatcher.Invoke (() => { GetReportSource (EncryptData.Base64); }, null); return; } this.FileLoad (ofd); }); } private string FilePath; private string FileLoadName; private void GetReportSource(string base64) { byte[] bytes = Convert.FromBase64String (base64); string json = Encoding.UTF8.GetString (bytes); var objs = JsonConvert.DeserializeObject<List<ReportModel>> (json); if(objs == null) { bytes = Convert.FromBase64String (EncryptData.Base64); json = Encoding.UTF8.GetString (bytes); objs = JsonConvert.DeserializeObject<List<ReportModel>> (json); } if (objs.Count > 0) { this.Pages.Clear (); IsLoad = true; } foreach (var obj in objs) { this.Pages.Add (new PageModel ()); } Task.Run (() => { Thread.Sleep (1000); Application.Current.Dispatcher.Invoke (() => { for (int i = 0; i < this.Pages.Count; i++) { this.Pages[i].SetReportSource (objs[i]); } IsLoad = false; }, null); }); } [RelayCommand] private void Load() { OpenFileDialog ofd = new (); ofd.InitialDirectory = Environment.CurrentDirectory; ofd.Filter = "objective files(*.objective) | *.objective"; ofd.Multiselect = false; if (ofd.ShowDialog () == false) return; this.FileLoad (ofd); } private void FileLoad(OpenFileDialog ofd) { FilePath = Path.GetDirectoryName (ofd.FileName); FileLoadName = Path.GetFileName (ofd.FileName); string line = null; using (var reader = new StreamReader (ofd.FileName)) { // 파일 내용 한 줄씩 읽기 line = reader.ReadToEnd (); } IsLoad = false; if (!String.IsNullOrWhiteSpace (FilePath)) Application.Current.Dispatcher.Invoke (() => { GetReportSource (line); }, null); } [RelayCommand] private void NewPage() { this.Pages.Add (new PageModel ()); } [RelayCommand] private void RemovePage() { if(this.Pages.Count == 1) { this.Pages[0].Clear (); return; } var lastPages = this.Pages.Last (); this.Pages.Remove (lastPages); } [RelayCommand] private void Save() { List<ReportModel> reportModels = new List<ReportModel> (); foreach (var page in Pages) { reportModels.Add (page.Save ()); } string json = JsonConvert.SerializeObject (reportModels); byte[] bytes = Encoding.UTF8.GetBytes (json); string base64 = Convert.ToBase64String (bytes); string PullPath = $@"{FilePath}\{FileLoadName}"; Clipboard.SetText (base64); using (StreamWriter sw =File.CreateText(PullPath)) { sw.Write (base64); } } private List<ToolItem> GetTools() { List<ToolItem> source = new (); source.Add (new ToolItem ("Page")); source.Add (new ToolItem ("RemovePage")); source.Add (new ToolItem ("Title")); source.Add (new ToolItem ("Table")); source.Add (new ToolItem ("Horizontal Line")); source.Add (new ToolItem ("Image")); return source; } private List<ToolItem> GetSubTools() { List<ToolItem> source = new (); source.Add (new ToolItem ("좌정렬")); source.Add (new ToolItem ("위정렬")); source.Add (new ToolItem ("가로길이동기화")); source.Add (new ToolItem ("초기화")); source.Add (new ToolItem ("세이브!")); return source; } [RelayCommand] private void SelectItem(ReportObject item) { SelectedObject = item; if(isPress == true) { if (item.GetType ().Name == "CellField" || item.GetType ().Name == "PageCanvas") return; this.MultiObject.Add (item); } } private bool isPress = false; [RelayCommand] private void MultiSelectItem(bool isPress) { this.isPress = isPress; } [RelayCommand] private void SubTool(ToolItem item) { if(item.Name == "초기화") this.MultiObject.Clear (); else if(item.Name=="좌정렬") { foreach(var obj in this.MultiObject.Skip(1).ToList()) { obj.SetLeft (this.MultiObject[0].GetProperties ().Left); } } else if (item.Name == "위정렬") { foreach (var obj in this.MultiObject.Skip (1).ToList ()) { obj.SetTop (this.MultiObject[0].GetProperties ().Top); } } else if(item.Name == "가로길이동기화") { var FirstTable = this.MultiObject.FirstOrDefault (x => x.GetType().Name == "Table"); if (FirstTable == null) return; var TableList = this.MultiObject.Where (x => x.GetType ().Name == "Table").ToList (); if (TableList.Count == 1) return; foreach (var obj in TableList.Skip (1).ToList ()) { obj.WidthSync (this.MultiObject[0].GetProperties ().Width); } } else if (item.Name == "세이브!") { //for(int i=0; i <100; i++) //{ // var aabbba = obj.GetValue (Control.NameProperty) as string; // if (String.IsNullOrEmpty (aabbba)) // continue; // Console.WriteLine (""); //} ////SaveImage (test, "aaa.jpeg"); } } private void SaveImage(FrameworkElement frameworkElement, string filePath) { RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap ( (int)frameworkElement.ActualWidth, (int)frameworkElement.ActualHeight, 96d, 96d, PixelFormats.Default ); renderTargetBitmap.Render (frameworkElement); using (Stream stream = new FileStream (filePath, FileMode.Create, FileAccess.Write, FileShare.None)) { JpegBitmapEncoder encoder = new JpegBitmapEncoder (); encoder.Frames.Add (BitmapFrame.Create (renderTargetBitmap)); encoder.Save (stream); } } } }
objective/objective/objective.Forms/Local/ViewModels/MainContentViewModel.cs
jamesnet214-objective-0e60b6f
[ { "filename": "objective/objective/objective.Forms/Local/Models/PageModel.cs", "retrieved_chunk": "namespace objective.Forms.Local.Models\n{\n\t\tpublic partial class PageModel : ObservableBase\n\t\t{\n\t\t\t\t[ObservableProperty]\n\t\t\t\tprivate ObservableCollection<ReportObject> _reportSource;\n\t\t\t\tpublic PageModel()\n\t\t\t\t{\n\t\t\t\t\t\tthis.ReportSource = new ();\n\t\t\t\t}", "score": 0.7990292310714722 }, { "filename": "objective/objective/objective.Forms/Local/ViewModels/MainVIewModel.cs", "retrieved_chunk": "using System.IO;\nusing System.Threading.Tasks;\nnamespace objective.Forms.Local.ViewModels\n{\n\t\tpublic partial class MainViewModel : ObservableBase, IViewLoadable, IViewClosedable\n {\n private readonly IRegionManager _regionManager;\n private readonly IContainerProvider _containerProvider;\n\t\t\t\tprivate readonly IEventAggregator _eh;\n\t\t\t\tpublic MainViewModel(IRegionManager regionManager, ", "score": 0.7741134762763977 }, { "filename": "objective/objective/objective.Forms/UI/Units/Table.cs", "retrieved_chunk": "using System.Windows.Documents;\nusing System.Windows.Input;\nnamespace objective.Forms.UI.Units\n{\n\t\tpublic class Table : DragMoveContent\n\t\t{\n\t\t\t\tpublic static readonly DependencyProperty RowsProperty = DependencyProperty.Register (\"Rows\", typeof (string), typeof (Table), new PropertyMetadata (\"\"));\n\t\t\t\tpublic static readonly DependencyProperty ColumnsProperty = DependencyProperty.Register (\"Columns\", typeof (string), typeof (Table), new PropertyMetadata (\"\"));\n\t\t\t\tprivate JamesGrid _grid;\n\t\t\t\tprivate List<ReportObjectModel> _cellFields;", "score": 0.7363364696502686 }, { "filename": "objective/objective/objective.Forms/UI/Views/MainContent.cs", "retrieved_chunk": "\t\tpublic class MainContent : JamesContent, IViewAccess\n {\n\t\t\t\tpublic static readonly DependencyProperty MultiSelectItemCommandProperty = DependencyProperty.Register (\"MultiSelectItemCommand\", typeof (ICommand), typeof (MainContent), new PropertyMetadata (null));\n\t\t\t\tpublic ICommand MultiSelectItemCommand\n\t\t\t\t{\n\t\t\t\t\t\tget { return (ICommand)GetValue (MultiSelectItemCommandProperty); }\n\t\t\t\t\t\tset { SetValue (MultiSelectItemCommandProperty, value); }\n\t\t\t\t}\n\t\t\t\tstatic MainContent()\n {", "score": 0.724056601524353 }, { "filename": "objective/objective/objective.Forms/UI/Units/PageCanvas.cs", "retrieved_chunk": " {\n public static readonly DependencyProperty SelectItemCommandProperty = DependencyProperty.Register(\"SelectItemCommand\", typeof(ICommand), typeof(PageCanvas), new PropertyMetadata(null));\n public static readonly DependencyProperty ReportDataProperty = DependencyProperty.Register(\"ReportData\", typeof(ObservableCollection<ReportObject>), typeof(PageCanvas), new PropertyMetadata(null, ReportDataPropertyChanged));\n private Canvas _canvas;\n public ICommand SelectItemCommand\n {\n get { return (ICommand)GetValue(SelectItemCommandProperty); }\n set { SetValue(SelectItemCommandProperty, value); }\n }\n public ObservableCollection<ReportObject> ReportData", "score": 0.7142982482910156 } ]
csharp
ToolItem> _tools;
using LogDashboard.Models; using LogDashboard.Route; using System; using System.Threading.Tasks; namespace LogDashboard.Handle { public class AuthorizationHandle : LogDashboardHandleBase { private readonly LogdashboardAccountAuthorizeFilter _filter; public AuthorizationHandle( IServiceProvider serviceProvider, LogdashboardAccountAuthorizeFilter filter) : base(serviceProvider) { _filter = filter; } public async Task<string> Login(
LoginInput input) {
if (_filter.Password == input?.Password && _filter.UserName == input?.Name) { _filter.SetCookieValue(Context.HttpContext); //Redirect var homeUrl = LogDashboardRoutes.Routes.FindRoute(string.Empty).Key; Context.HttpContext.Response.Redirect($"{Context.Options.PathMatch}{homeUrl}"); return string.Empty; } return await View(); } } }
src/LogDashboard.Authorization/Handle/AuthorizationHandle.cs
Bryan-Cyf-LogDashboard.Authorization-14d4540
[ { "filename": "src/LogDashboard.Authorization/Authorization/LogdashboardAccountAuthorizeFilter.cs", "retrieved_chunk": " public class LogdashboardAccountAuthorizeFilter : ILogDashboardAuthorizationFilter\n {\n public string UserName { get; set; }\n public string Password { get; set; }\n public LogDashboardCookieOptions CookieOptions { get; set; }\n public LogdashboardAccountAuthorizeFilter(string userName, string password)\n {\n UserName = userName;\n Password = password;\n CookieOptions = new LogDashboardCookieOptions();", "score": 0.8697260618209839 }, { "filename": "src/LogDashboard.Authorization/Authorization/LogdashboardAccountAuthorizeFilter.cs", "retrieved_chunk": " }\n public LogdashboardAccountAuthorizeFilter(string userName, string password, Action<LogDashboardCookieOptions> cookieConfig)\n {\n UserName = userName;\n Password = password;\n CookieOptions = new LogDashboardCookieOptions();\n cookieConfig.Invoke(CookieOptions);\n }\n public bool Authorization(LogDashboardContext context)\n {", "score": 0.8670949339866638 }, { "filename": "src/LogDashboard.Authorization/LogDashboardAuthorizationMiddleware.cs", "retrieved_chunk": " private readonly RequestDelegate _next;\n public LogDashboardAuthorizationMiddleware(RequestDelegate next)\n {\n _next = next;\n }\n public async Task InvokeAsync(HttpContext httpContext)\n {\n using var scope = httpContext.RequestServices.CreateScope();\n var opts = scope.ServiceProvider.GetService<LogDashboardOptions>();\n var requestUrl = httpContext.Request.Path.Value;", "score": 0.8654845952987671 }, { "filename": "src/LogDashboard.Authorization/EmbeddedFiles/LogDashboardAuthorizationEmbeddedFiles.cs", "retrieved_chunk": " };\n private static readonly Assembly Assembly;\n static LogDashboardAuthorizationEmbeddedFiles()\n {\n Assembly = Assembly.GetExecutingAssembly();\n }\n public static async Task IncludeEmbeddedFile(HttpContext context, string path)\n {\n context.Response.OnStarting(() =>\n {", "score": 0.8309453725814819 }, { "filename": "src/LogDashboard.Authorization/LogDashboardCookieOptions.cs", "retrieved_chunk": "using Microsoft.AspNetCore.Http;\nnamespace LogDashboard\n{\n public class LogDashboardCookieOptions\n {\n public TimeSpan Expire { get; set; }\n public string TokenKey { get; set; }\n public string TimestampKey { get; set; }\n public Func<LogdashboardAccountAuthorizeFilter, string> Secure { get; set; }\n public LogDashboardCookieOptions()", "score": 0.8116555213928223 } ]
csharp
LoginInput input) {
using Sandland.SceneTool.Editor.Common.Data; using Sandland.SceneTool.Editor.Common.Utils; using Sandland.SceneTool.Editor.Services; using UnityEditor; using UnityEngine; using UnityEngine.UIElements; namespace Sandland.SceneTool.Editor.Views { internal class FavoritesButton : VisualElement { private const string FavoriteClassName = "favorite"; public bool IsFavorite { get; private set; } //private Image _starImage; private
AssetFileInfo _fileInfo;
public FavoritesButton() { this.AddManipulator(new Clickable(OnClick)); } public void Init(AssetFileInfo info) { _fileInfo = info; var isFavorite = _fileInfo.IsFavorite(); SetState(isFavorite); } private void OnClick() { SetState(!IsFavorite); if (IsFavorite) { _fileInfo.AddToFavorites(); } else { _fileInfo.RemoveFromFavorites(); } } public void SetState(bool isFavorite) { IsFavorite = isFavorite; if (IsFavorite) { AddToClassList(FavoriteClassName); } else { RemoveFromClassList(FavoriteClassName); } } public new class UxmlFactory : UxmlFactory<FavoritesButton, UxmlTraits> { } } }
Assets/SceneTools/Editor/Views/SceneSelectorWindow/FavoritesButton/FavoritesButton.cs
migus88-Sandland.SceneTools-64e9f8c
[ { "filename": "Assets/SceneTools/Editor/Common/Data/SceneInfo.cs", "retrieved_chunk": "using System.Collections.Generic;\nnamespace Sandland.SceneTool.Editor.Common.Data\n{\n internal class SceneInfo : AssetFileInfo\n {\n public int BuildIndex { get; set; }\n public string Address { get; set; }\n public SceneImportType ImportType { get; set; }\n private SceneInfo(string name, string path, string guid, string bundleName, List<string> labels) : base(name, path, guid, bundleName, labels)\n {", "score": 0.8499958515167236 }, { "filename": "Assets/SceneTools/Editor/Common/Utils/MenuItems.cs", "retrieved_chunk": "namespace Sandland.SceneTool.Editor.Common.Utils\n{\n internal static class MenuItems\n {\n public static class Tools\n {\n public const string Root = \"Tools/Sandland Games/\";\n public const string Actions = Root + \"Actions/\";\n }\n public static class Creation", "score": 0.8465803861618042 }, { "filename": "Assets/SceneTools/Editor/Common/Data/AssetFileInfo.cs", "retrieved_chunk": "using System.Collections.Generic;\nnamespace Sandland.SceneTool.Editor.Common.Data\n{\n internal class AssetFileInfo\n {\n public string Name { get; set; }\n public string Path { get; set; }\n public string Guid { get; set; }\n public string BundleName { get; set; }\n public List<string> Labels { get; set; }", "score": 0.8346514105796814 }, { "filename": "Assets/SceneTools/Editor/Views/SceneSelectorWindow/SceneListItem/SceneItemView.cs", "retrieved_chunk": " {\n public const float FixedHeight = 100;\n private readonly Image _iconImage;\n private readonly FavoritesButton _favoritesButton;\n private readonly Label _button;\n private readonly Label _typeLabel;\n private readonly VisualElement _textWrapper;\n private readonly Clickable _clickManipulator;\n private AssetFileInfo _sceneInfo;\n public SceneItemView()", "score": 0.8315467238426208 }, { "filename": "Assets/SceneTools/Editor/Listeners/SceneClassGenerationListener.cs", "retrieved_chunk": "using UnityEditor.AddressableAssets.Settings;\n#endif\nnamespace Sandland.SceneTool.Editor.Listeners\n{\n internal static class SceneClassGenerationListener\n {\n [InitializeOnLoadMethod]\n private static void Initialize()\n {\n EditorBuildSettings.sceneListChanged += GenerateScenesClass;", "score": 0.8263028860092163 } ]
csharp
AssetFileInfo _fileInfo;
// Copyright (c) 2023, João Matos // Check the end of the file for extended copyright notice. using System.Net.Sockets; using System.Text; using System.IO; using System.Linq; using System.Collections.Generic; using System; using ProtoIP.Common; using static ProtoIP.Packet; namespace ProtoIP { public class ProtoStream { const int BUFFER_SIZE = Common.Network.DEFAULT_BUFFER_SIZE; private NetworkStream _stream; private List<
Packet> _packets = new List<Packet>();
private byte[] _buffer; private string _LastError; /* CONSTRUCTORS */ public ProtoStream() { } public ProtoStream(NetworkStream stream) { this._stream = stream; } public ProtoStream(List<Packet> packets) { this._packets = packets; } public ProtoStream(List<Packet> packets, NetworkStream stream) { this._packets = packets; this._stream = stream; } /* PRIVATE METHODS & HELPER FUNCTIONS */ /* * Tries to read from the stream to construct a packet * Returns the deserialized packet */ private Packet receivePacket() { this._buffer = new byte[BUFFER_SIZE]; if (this.TryRead(this._buffer) < BUFFER_SIZE) { this._LastError = "Failed to receive the packet"; return null; } return Packet.Deserialize(this._buffer); } /* * Receives an ACK packet from the peer * Returns true if the packet was received successfully, false otherwise */ private bool peerReceiveAck() { Packet packet = this.receivePacket(); if (packet._GetType() != (int)Packet.Type.ACK) { this._LastError = "Invalid packet type"; return false; } return true; } /* * Sends the ACK packet to the peer * Returns true if the packet was sent successfully, false otherwise */ private bool peerSendAck() { Packet packet = new Packet(Packet.Type.ACK); this._buffer = Packet.Serialize(packet); if (this.TryWrite(this._buffer) < BUFFER_SIZE) { this._LastError = "Failed to send the ACK packet"; return false; } return true; } /* * Sends the SOT packet to the peer * Returns true if the packet was sent successfully, false otherwise */ private bool peerSendSot() { this._buffer = Packet.Serialize(new Packet(Packet.Type.SOT)); if (this.TryWrite(this._buffer) < BUFFER_SIZE) { this._LastError = "Failed to send the START_OF_TRANSMISSION packet"; return false; } return true; } /* * Receives the SOT packet from the peer * Returns true if the packet was received successfully, false otherwise */ private bool peerReceiveSot() { Packet packet = this.receivePacket(); if (packet != null && packet._GetType() != (int)Packet.Type.SOT) { this._LastError = "Invalid packet type"; return false; } return true; } /* * Sends the EOT packet to the peer * Returns true if the packet was sent successfully, false otherwise */ private bool peerSendEot() { this._buffer = Packet.Serialize(new Packet(Packet.Type.EOT)); if (this.TryWrite(this._buffer) < BUFFER_SIZE) { this._LastError = "Failed to send the END_OF_TRANSMISSION packet"; return false; } return true; } /* * Receives the EOT packet from the peer * Returns true if the packet was received successfully, false otherwise */ private bool peerReceiveEot() { Packet packet = this.receivePacket(); if (packet._GetType() != (int)Packet.Type.EOT) { this._LastError = "Invalid packet type"; return false; } return true; } /* * Sends a REPEAT packet with the missing packet IDs to the peer */ private bool peerSendRepeat(List<int> missingPackets) { Packet packet = new Packet(Packet.Type.REPEAT); byte[] payload = new byte[missingPackets.Count * sizeof(int)]; Buffer.BlockCopy(missingPackets.ToArray(), 0, payload, 0, payload.Length); packet.SetPayload(payload); this._buffer = Packet.Serialize(packet); if (this.TryWrite(this._buffer) < BUFFER_SIZE) { this._LastError = "Failed to send the REPEAT packet"; return false; } return true; } /* * Receives the REPEAT packet from the requesting peer * Returns the missing packet IDs */ private List<int> peerReceiveRepeat() { Packet packet = this.receivePacket(); if (packet._GetType() != (int)Packet.Type.REPEAT) { this._LastError = "Invalid packet type"; return null; } byte[] payload = packet.GetDataAs<byte[]>(); int[] missingPackets = new int[payload.Length / sizeof(int)]; Buffer.BlockCopy(payload, 0, missingPackets, 0, payload.Length); return new List<int>(missingPackets); } /* * Resends the missing packets to the peer */ private bool peerResendMissingPackets(List<int> packetIDs) { for (int i = 0; i < packetIDs.Count; i++) { this._buffer = Packet.Serialize(this._packets[packetIDs[i]]); if (this.TryWrite(this._buffer) < BUFFER_SIZE) { this._LastError = "Failed to send the packet " + packetIDs[i]; return false; } } return true; } /* * Receives the missing packets from the peer and adds them to the packet List */ private bool peerReceiveMissingPackets(int packetCount) { for (int i = 0; i < packetCount; i++) { this._buffer = new byte[BUFFER_SIZE]; if (this.TryRead(this._buffer) < BUFFER_SIZE) { this._LastError = "Failed to receive the packet " + i; return false; } Packet packet = Packet.Deserialize(this._buffer); this._packets.Add(packet); } return true; } /* * Validate the packet List * * Check if there are any null packets or if there are any ID jumps */ private bool ValidatePackets() { for (int i = 0; i < this._packets.Count; i++) { if (this._packets[i] == null) { this._LastError = "Packet " + i + " is null"; return false; } if (this._packets[i]._GetId() != i) { this._LastError = "Packet " + i + " has an invalid id (Expected: " + i + ", Actual: " + this._packets[i]._GetId() + ")"; return false; } } return true; } /* * Returns a list with the missing packet IDs * * Check for any ID jumps, if there is an ID jump, add the missing IDs to the list */ private List<int> GetMissingPacketIDs() { List<int> missingPackets = new List<int>(); int lastId = 0; foreach (Packet packet in this._packets) { if (packet._GetId() - lastId > 1) { for (int i = lastId + 1; i < packet._GetId(); i++) { missingPackets.Add(i); } } lastId = packet._GetId(); } return missingPackets; } /* * Orders the packets by id and assembles the data buffer * * Allocates a buffer with the total length of the data and copies the data from the packets to the buffer */ private int Assemble() { ProtoStream.OrderPackets(this._packets); if (!this.ValidatePackets()) { return -1; } int dataLength = 0; for (int i = 0; i < this._packets.Count; i++) { dataLength += this._packets[i].GetDataAs<byte[]>().Length; } byte[] data = new byte[dataLength]; int dataOffset = 0; for (int i = 0; i < this._packets.Count; i++) { byte[] packetData = this._packets[i].GetDataAs<byte[]>(); Array.Copy(packetData, 0, data, dataOffset, packetData.Length); dataOffset += packetData.Length; } this._buffer = data; return 0; } /* * Attemps to write the data to the stream until it succeeds or the number of tries is reached */ private int TryWrite(byte[] data, int tries = Network.MAX_TRIES) { int bytesWritten = 0; while (bytesWritten < data.Length && tries > 0) { try { if (this._stream.CanWrite) { this._stream.Write(data, bytesWritten, data.Length - bytesWritten); bytesWritten += data.Length - bytesWritten; } } catch (Exception e) { tries--; } } return bytesWritten; } /* * Attemps to read the data from the stream until it succeeds or the number of tries is reached */ private int TryRead(byte[] data, int tries = Network.MAX_TRIES) { int bytesRead = 0; while (bytesRead < data.Length && tries > 0) { try { if (this._stream.DataAvailable || this._stream.CanRead) bytesRead += this._stream.Read(data, bytesRead, data.Length - bytesRead); } catch (Exception e) { tries--; } } return bytesRead; } /* * Partitions the data into packets and adds them to the Packet list */ private void Partition(byte[] data) { if (data.Length > (BUFFER_SIZE) - Packet.HEADER_SIZE) { int numPackets = (int)Math.Ceiling((double)data.Length / ((BUFFER_SIZE) - Packet.HEADER_SIZE)); int packetSize = (int)Math.Ceiling((double)data.Length / numPackets); this._packets = new List<Packet>(); for (int i = 0; i < numPackets; i++) { int packetDataSize = (i == numPackets - 1) ? data.Length - (i * packetSize) : packetSize; byte[] packetData = new byte[packetDataSize]; Array.Copy(data, i * packetSize, packetData, 0, packetDataSize); this._packets.Add(new Packet(Packet.Type.BYTES, i, packetDataSize, packetData)); } } else { this._packets = new List<Packet>(); this._packets.Add(new Packet(Packet.Type.BYTES, 0, data.Length, data)); } } /* PUBLIC METHODS */ /* * Checks if a peer is connected to the stream */ public bool IsConnected() { return this._stream != null && this._stream.CanRead && this._stream.CanWrite; } /* * Transmits the data to the peer * * Ensures that the peer is ready to receive the data. * Partitions the data into packets and sends them to the peer. * Waits for the peer to acknowledge the data. * Allows the peer to request missing packets until all the data * has been received or the maximum number of tries has been reached. */ public int Transmit(byte[] data) { this.Partition(data); this.peerSendSot(); if (this.peerReceiveAck() == false) { return -1; } ProtoStream.SendPackets(this._stream, this._packets); this.peerSendEot(); int tries = 0; while (tries < Network.MAX_TRIES) { Packet response = this.receivePacket(); if (response == null) { return -1; } if (response._GetType() == (int)Packet.Type.ACK) { break; } else if (response._GetType() == (int)Packet.Type.REPEAT) { List<int> missingPacketIDs = this.peerReceiveRepeat(); if (missingPacketIDs.Any()) { this.peerResendMissingPackets(missingPacketIDs); } else { return -1; } } tries++; } this._packets = new List<Packet>(); return 0; } /* * Sends a string to the peer */ public int Transmit(string data) { return this.Transmit(Encoding.ASCII.GetBytes(data)); } /* * Receives data from the peer until the EOT packet is received */ public int Receive() { bool dataFullyReceived = false; int tries = Network.MAX_TRIES; if (this.peerReceiveSot() == false) { return -1; } if (this.peerSendAck() == false) { return -1; } while (true) { if (this.TryRead(this._buffer) < BUFFER_SIZE) { return -1; } Packet packet = Packet.Deserialize(this._buffer); if (packet._GetType() == (int)Packet.Type.EOT) { break; } this._packets.Add(packet); } while (!dataFullyReceived && tries > 0) { List<int> missingPacketIDs = GetMissingPacketIDs(); if (missingPacketIDs.Count > 0) { this.peerSendRepeat(missingPacketIDs); this.peerReceiveMissingPackets(missingPacketIDs.Count); } else { if (this.peerSendAck() == false) { return -1; } dataFullyReceived = true; } tries--; } return 0; } // Return the assembled data as a primitive type T public T GetDataAs<T>() { this.Assemble(); byte[] data = this._buffer; // Convert the data to the specified type switch (typeof(T).Name) { case "String": return (T)(object)Encoding.ASCII.GetString(data); case "Int32": return (T)(object)BitConverter.ToInt32(data, 0); case "Int64": return (T)(object)BitConverter.ToInt64(data, 0); case "Byte[]": return (T)(object)data; default: this._LastError = "Invalid type"; return default(T); } } /* STATIC METHODS */ /* * OrderPackets * Orders the packets by id */ static void OrderPackets(List<Packet> packets) { packets.Sort((x, y) => x._GetId().CompareTo(y._GetId())); } /* * SendPackets * Sends the packets to the peer */ static void SendPackets(NetworkStream stream, List<Packet> packets) { for (int i = 0; i < packets.Count; i++) { SendPacket(stream, packets[i]); } } public static void SendPacket(NetworkStream stream, Packet packet) { stream.Write(Packet.Serialize(packet), 0, BUFFER_SIZE); } } } // MIT License // // Copyright (c) 2023 João Matos // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE.
src/protoStream.cs
JoaoAJMatos-ProtoIP-84f8797
[ { "filename": "src/packet.cs", "retrieved_chunk": " }\n public const int HEADER_SIZE = 12;\n const int BUFFER_SIZE = Common.Network.DEFAULT_BUFFER_SIZE;\n /* MEMBER VARIABLES */\n private int _type;\n private int _id;\n private int _dataSize;\n private byte[] _data;\n /* CONSTRUCTORS */\n public Packet() { }", "score": 0.768342912197113 }, { "filename": "src/p2p.cs", "retrieved_chunk": "// Copyright (c) 2023, João Matos\n// Check the end of the file for extended copyright notice.\nusing System;\nnamespace ProtoIP\n{\n class Node\n {\n protected ProtoServer _server;\n protected ProtoClient _client;\n // Constructors", "score": 0.7623507976531982 }, { "filename": "src/ethernet.cs", "retrieved_chunk": " ipPacket._protocol = (byte)IP.IPProtocolPacketType.TCP;\n ipPacket._payload = tcpPacket.Serialize();\n ethernet._payload = ipPacket.Serialize();\n return ethernet;\n }\n // Encapsulate a UDP packet inside an IP packet inside an Ethernet frame.\n // ETH / IP / UDP\n public static Ethernet operator / (Ethernet ethernet, UDP udpPacket)\n {\n if (ethernet._payload == null || ethernet._payload.Length < IP.IP_HEADER_LENGTH)", "score": 0.7608882188796997 }, { "filename": "src/netPod.cs", "retrieved_chunk": " {\n private Ethernet _ethernet;\n private ARP _arp;\n private IP _ip;\n private UDP _udp;\n private TCP _tcp;\n private ICMP _icmp;\n // Creates a new NetPod instance.\n public NetPod()\n {", "score": 0.7557879686355591 }, { "filename": "src/packet.cs", "retrieved_chunk": "// Copyright (c) 2023, João Matos\n// Check the end of the file for extended copyright notice.\nusing System.Text;\nusing System;\nusing ProtoIP.Common;\nnamespace ProtoIP\n{\n public class Packet\n {\n // Default packet types for the ProtoIP library", "score": 0.7536457180976868 } ]
csharp
Packet> _packets = new List<Packet>();
using System.Diagnostics; using System.Text; using Gum.Blackboards; using Gum.Utilities; namespace Gum.InnerThoughts { [DebuggerDisplay("{DebuggerDisplay(),nq}")] public class DialogAction { public readonly Fact Fact = new(); public readonly BlackboardActionKind Kind = BlackboardActionKind.Set; public readonly string? StrValue = null; public readonly int? IntValue = null; public readonly bool? BoolValue = null; public readonly string? ComponentValue = null; public DialogAction() { } public DialogAction(
Fact fact, BlackboardActionKind kind, object value) {
bool? @bool = null; int? @int = null; string? @string = null; string? component = null; // Do not propagate previous values. switch (fact.Kind) { case FactKind.Bool: @bool = (bool)value; break; case FactKind.Int: @int = (int)value; break; case FactKind.String: @string = (string)value; break; case FactKind.Component: component = (string)value; break; } (Fact, Kind, StrValue, IntValue, BoolValue, ComponentValue) = (fact, kind, @string, @int, @bool, component); } public string DebuggerDisplay() { StringBuilder result = new(); if (Fact.Kind == FactKind.Component) { result = result.Append($"[c:"); } else { result = result.Append($"[{Fact.Name} {OutputHelpers.ToCustomString(Kind)} "); } switch (Fact.Kind) { case FactKind.Bool: result = result.Append(BoolValue); break; case FactKind.Int: result = result.Append(IntValue); break; case FactKind.String: result = result.Append(StrValue); break; case FactKind.Component: result = result.Append(ComponentValue); break; } result = result.Append(']'); return result.ToString(); } } }
src/Gum/InnerThoughts/DialogAction.cs
isadorasophia-gum-032cb2d
[ { "filename": "src/Gum/InnerThoughts/Criterion.cs", "retrieved_chunk": " public readonly string? StrValue = null;\n public readonly int? IntValue = null;\n public readonly bool? BoolValue = null;\n public Criterion() { }\n /// <summary>\n /// Creates a fact of type <see cref=\"FactKind.Weight\"/>.\n /// </summary>\n public static Criterion Weight => new(Fact.Weight, CriterionKind.Is, 1);\n /// <summary>\n /// Creates a fact of type <see cref=\"FactKind.Component\"/>.", "score": 0.8876545429229736 }, { "filename": "src/Gum/InnerThoughts/Fact.cs", "retrieved_chunk": " public readonly struct Fact\n {\n /// <summary>\n /// If null, the user did not especify any blackboard and can be assumed the default one.\n /// </summary>\n public readonly string? Blackboard = null;\n public readonly string Name = string.Empty;\n public readonly FactKind Kind = FactKind.Invalid;\n /// <summary>\n /// Set when the fact is of type <see cref=\"FactKind.Component\"/>", "score": 0.8847471475601196 }, { "filename": "src/Gum/InnerThoughts/Fact.cs", "retrieved_chunk": " /// </summary>\n public readonly string? ComponentType = null;\n public Fact() { }\n private Fact(FactKind kind) => Kind = kind;\n public Fact(string componentType) => (Kind, ComponentType) = (FactKind.Component, componentType);\n public Fact(string? blackboard, string name, FactKind kind) =>\n (Blackboard, Name, Kind) = (blackboard, name, kind);\n /// <summary>\n /// Creates a fact of type <see cref=\"FactKind.Weight\"/>.\n /// </summary>", "score": 0.8741351366043091 }, { "filename": "src/Gum/InnerThoughts/Block.cs", "retrieved_chunk": " /// </summary>\n public int? GoTo = null;\n public bool NonLinearNode = false;\n public bool IsChoice = false;\n public bool Conditional = false;\n public Block() { }\n public Block(int id) { Id = id; }\n public Block(int id, int playUntil) { (Id, PlayUntil) = (id, playUntil); }\n public void AddLine(string? speaker, string? portrait, string text)\n {", "score": 0.8737441301345825 }, { "filename": "src/Gum/InnerThoughts/Criterion.cs", "retrieved_chunk": " /// </summary>\n public static Criterion Component => new(Fact.Component, CriterionKind.Is, true);\n public Criterion(Fact fact, CriterionKind kind, object @value)\n {\n bool? @bool = null;\n int? @int = null;\n string? @string = null;\n // Do not propagate previous values.\n switch (fact.Kind)\n {", "score": 0.8723913431167603 } ]
csharp
Fact fact, BlackboardActionKind kind, object value) {
// Kaplan Copyright (c) DragonFruit Network <[email protected]> // Licensed under Apache-2. Refer to the LICENSE file for more info using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reactive.Linq; using System.Security.Principal; using System.Threading.Tasks; using System.Windows.Input; using Windows.ApplicationModel; using Windows.Management.Deployment; using Avalonia.Threading; using DragonFruit.Kaplan.ViewModels.Enums; using DragonFruit.Kaplan.ViewModels.Messages; using DynamicData; using DynamicData.Binding; using Microsoft.Extensions.Logging; using ReactiveUI; namespace DragonFruit.Kaplan.ViewModels { public class MainWindowViewModel : ReactiveObject, IDisposable { private readonly ILogger _logger; private readonly WindowsIdentity _currentUser; private readonly PackageManager _packageManager; private readonly IDisposable _packageRefreshListener; private readonly ObservableAsPropertyHelper<IEnumerable<PackageViewModel>> _displayedPackages; private string _searchQuery = string.Empty; private PackageInstallationMode _packageMode = PackageInstallationMode.User; private IReadOnlyCollection<PackageViewModel> _discoveredPackages = Array.Empty<PackageViewModel>(); public MainWindowViewModel() { _packageManager = new PackageManager(); _currentUser = WindowsIdentity.GetCurrent(); _logger = App.GetLogger<MainWindowViewModel>(); AvailablePackageModes = _currentUser.User != null ? Enum.GetValues<PackageInstallationMode>() : new[] {PackageInstallationMode.Machine}; // create observables var packagesSelected = SelectedPackages.ToObservableChangeSet() .ToCollection() .ObserveOn(RxApp.MainThreadScheduler) .Select(x => x.Any()); _packageRefreshListener = MessageBus.Current.Listen<UninstallEventArgs>().ObserveOn(RxApp.TaskpoolScheduler).Subscribe(x => RefreshPackagesImpl()); _displayedPackages = this.WhenAnyValue(x => x.DiscoveredPackages, x => x.SearchQuery, x => x.SelectedPackages) .ObserveOn(RxApp.TaskpoolScheduler) .Select(q => { // because filters remove selected entries, the search will split the listing into two groups, with the matches showing above var matches = q.Item1.ToLookup(x => x.IsSearchMatch(q.Item2)); return matches[true].Concat(matches[false]); }) .ToProperty(this, x => x.DisplayedPackages); // create commands RefreshPackages = ReactiveCommand.CreateFromTask(RefreshPackagesImpl); RemovePackages = ReactiveCommand.Create(RemovePackagesImpl, packagesSelected); ClearSelection = ReactiveCommand.Create(() => SelectedPackages.Clear(), packagesSelected); ShowAbout = ReactiveCommand.Create(() => MessageBus.Current.SendMessage(new ShowAboutWindowEventArgs())); // auto refresh the package list if the user package filter switch is changed this.WhenValueChanged(x => x.PackageMode).ObserveOn(RxApp.TaskpoolScheduler).Subscribe(_ => RefreshPackages.Execute(null)); } public IEnumerable<PackageInstallationMode> AvailablePackageModes { get; } public ObservableCollection<PackageViewModel> SelectedPackages { get; } = new(); public IEnumerable<
PackageViewModel> DisplayedPackages => _displayedPackages.Value;
private IReadOnlyCollection<PackageViewModel> DiscoveredPackages { get => _discoveredPackages; set => this.RaiseAndSetIfChanged(ref _discoveredPackages, value); } /// <summary> /// Gets or sets whether the <see cref="DiscoveredPackages"/> collection should show packages installed for the selected user /// </summary> public PackageInstallationMode PackageMode { get => _packageMode; set => this.RaiseAndSetIfChanged(ref _packageMode, value); } /// <summary> /// Gets or sets the search query used to filter <see cref="DisplayedPackages"/> /// </summary> public string SearchQuery { get => _searchQuery; set => this.RaiseAndSetIfChanged(ref _searchQuery, value); } public ICommand ShowAbout { get; } public ICommand ClearSelection { get; } public ICommand RemovePackages { get; } public ICommand RefreshPackages { get; } private async Task RefreshPackagesImpl() { IEnumerable<Package> packages; switch (PackageMode) { case PackageInstallationMode.User when _currentUser.User != null: _logger.LogInformation("Loading Packages for user {userId}", _currentUser.User.Value); packages = _packageManager.FindPackagesForUser(_currentUser.User.Value); break; case PackageInstallationMode.Machine: _logger.LogInformation("Loading machine-wide packages"); packages = _packageManager.FindPackages(); break; default: throw new ArgumentOutOfRangeException(); } var filteredPackageModels = packages.Where(x => x.SignatureKind != PackageSignatureKind.System) .Select(x => new PackageViewModel(x)) .ToList(); _logger.LogDebug("Discovered {x} packages", filteredPackageModels.Count); // ensure the ui doesn't have non-existent packages nominated through an intersection // ToList needed due to deferred nature of iterators used. var reselectedPackages = filteredPackageModels.IntersectBy(SelectedPackages.Select(x => x.Package.Id.FullName), x => x.Package.Id.FullName).ToList(); await Dispatcher.UIThread.InvokeAsync(() => { SelectedPackages.Clear(); SearchQuery = string.Empty; DiscoveredPackages = filteredPackageModels; SelectedPackages.AddRange(reselectedPackages); }); } private void RemovePackagesImpl() { var packages = SelectedPackages.Select(x => x.Package).ToList(); var args = new UninstallEventArgs(packages, PackageMode); _logger.LogInformation("Starting removal of {x} packages", packages.Count); MessageBus.Current.SendMessage(args); } public void Dispose() { _displayedPackages?.Dispose(); _packageRefreshListener?.Dispose(); } } }
DragonFruit.Kaplan/ViewModels/MainWindowViewModel.cs
dragonfruitnetwork-kaplan-13bdb39
[ { "filename": "DragonFruit.Kaplan/ViewModels/RemovalProgressViewModel.cs", "retrieved_chunk": " OperationState.Completed => Brushes.Green,\n OperationState.Canceled => Brushes.DarkGray,\n _ => throw new ArgumentOutOfRangeException(nameof(x), x, null)\n }).ToProperty(this, x => x.ProgressColor);\n var canCancelOperation = this.WhenAnyValue(x => x.CancellationRequested, x => x.Status)\n .ObserveOn(RxApp.MainThreadScheduler)\n .Select(x => !x.Item1 && x.Item2 == OperationState.Running);\n Packages = packages.ToList();\n RequestCancellation = ReactiveCommand.Create(CancelOperation, canCancelOperation);\n }", "score": 0.8195973038673401 }, { "filename": "DragonFruit.Kaplan/Views/MainWindow.axaml.cs", "retrieved_chunk": " {\n DataContext = new RemovalProgressViewModel(args.Packages, args.Mode)\n };\n await window.ShowDialog(this).ConfigureAwait(false);\n MessageBus.Current.SendMessage(new PackageRefreshEventArgs());\n }\n private void PackageListPropertyChanged(object sender, AvaloniaPropertyChangedEventArgs e)\n {\n if (e.Property.Name != nameof(ListBox.ItemsSource))\n {", "score": 0.8168524503707886 }, { "filename": "DragonFruit.Kaplan/Views/MainWindow.axaml.cs", "retrieved_chunk": " TitleBar.TitleBarHitTestType = TitleBarHitTestType.Complex;\n _messageListeners = new[]\n {\n MessageBus.Current.Listen<UninstallEventArgs>().Subscribe(OpenProgressDialog),\n MessageBus.Current.Listen<ShowAboutWindowEventArgs>().Subscribe(_ => new About().ShowDialog(this))\n };\n }\n private async void OpenProgressDialog(UninstallEventArgs args)\n {\n var window = new RemovalProgress", "score": 0.8098472952842712 }, { "filename": "DragonFruit.Kaplan/ViewModels/RemovalProgressViewModel.cs", "retrieved_chunk": " private PackageRemovalTask _current;\n public RemovalProgressViewModel(IEnumerable<Package> packages, PackageInstallationMode mode)\n {\n _mode = mode;\n _status = OperationState.Pending;\n _progressColor = this.WhenValueChanged(x => x.Status).Select(x => x switch\n {\n OperationState.Pending => Brushes.Gray,\n OperationState.Running => Brushes.DodgerBlue,\n OperationState.Errored => Brushes.Red,", "score": 0.7932504415512085 }, { "filename": "DragonFruit.Kaplan/ViewModels/RemovalProgressViewModel.cs", "retrieved_chunk": " public event Action CloseRequested;\n public PackageRemovalTask Current\n {\n get => _current;\n private set => this.RaiseAndSetIfChanged(ref _current, value);\n }\n public int CurrentPackageNumber\n {\n get => _currentPackageNumber;\n private set => this.RaiseAndSetIfChanged(ref _currentPackageNumber, value);", "score": 0.7927296161651611 } ]
csharp
PackageViewModel> DisplayedPackages => _displayedPackages.Value;
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System; using System.Collections.Generic; using osu.Framework.Allocation; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Textures; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Containers; using osu.Framework.Input.Bindings; using osu.Framework.Input.Events; using osu.Framework.Logging; using osu.Framework.Screens; using osu.Game.Audio; using osu.Game.Screens; using osu.Game.Graphics.Sprites; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Scoring; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Gengo.UI.Translation; using osu.Game.Rulesets.Gengo.Anki; using osu.Game.Rulesets.Gengo.Cards; using osuTK; using osuTK.Graphics; namespace osu.Game.Rulesets.Gengo.Objects.Drawables { public partial class DrawableGengoHitObject : DrawableHitObject<GengoHitObject>, IKeyBindingHandler<GengoAction> { private const double time_preempt = 600; private const double time_fadein = 400; public override bool HandlePositionalInput => true; public DrawableGengoHitObject(GengoHitObject hitObject) : base(hitObject) { Size = new Vector2(80); Origin = Anchor.Centre; Position = hitObject.Position; } [Resolved] protected TranslationContainer translationContainer { get; set; } [Resolved] protected AnkiAPI anki { get; set; } private Card assignedCard; private Card baitCard; private Box cardDesign; private OsuSpriteText cardText; [BackgroundDependencyLoader] private void load(TextureStore textures) { assignedCard = anki.FetchRandomCard(); baitCard = anki.FetchRandomCard(); translationContainer.AddCard(assignedCard, baitCard); AddInternal(new CircularContainer { AutoSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre, Masking = true, CornerRadius = 15f, Children = new Drawable[] { cardDesign = new Box { RelativeSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre, Colour = Color4.Black, }, cardText = new OsuSpriteText { Text = assignedCard.foreignText, Anchor = Anchor.Centre, Origin = Anchor.Centre, Colour = Color4.Red, Font = new FontUsage(size: 35f), Margin = new MarginPadding(8f), } } }); } public override IEnumerable<HitSampleInfo> GetSamples() => new[] { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }; protected void ApplyResult(HitResult result) { void resultApplication(JudgementResult r) => r.Type = result; ApplyResult(resultApplication); }
GengoAction pressedAction;
/// <summary> /// Checks whether or not the pressed button/action for the current HitObject was correct for (matching to) the assigned card. /// </summary> bool CorrectActionCheck() { if (pressedAction == GengoAction.LeftButton) return translationContainer.leftWordText.Text == assignedCard.translatedText; else if (pressedAction == GengoAction.RightButton) return translationContainer.rightWordText.Text == assignedCard.translatedText; return false; } protected override void CheckForResult(bool userTriggered, double timeOffset) { if (!userTriggered) { if (!HitObject.HitWindows.CanBeHit(timeOffset)) { translationContainer.RemoveCard(); ApplyResult(r => r.Type = r.Judgement.MinResult); } return; } var result = HitObject.HitWindows.ResultFor(timeOffset); if (result == HitResult.None) return; if (!CorrectActionCheck()) { translationContainer.RemoveCard(); ApplyResult(HitResult.Miss); return; } translationContainer.RemoveCard(); ApplyResult(r => r.Type = result); } protected override double InitialLifetimeOffset => time_preempt; protected override void UpdateHitStateTransforms(ArmedState state) { switch (state) { case ArmedState.Hit: cardText.FadeColour(Color4.White, 200, Easing.OutQuint); cardDesign.FadeColour(Color4.YellowGreen, 200, Easing.OutQuint); this.ScaleTo(2, 500, Easing.OutQuint).Expire(); break; default: this.ScaleTo(0.8f, 200, Easing.OutQuint); cardText.FadeColour(Color4.Black, 200, Easing.OutQuint); cardDesign.FadeColour(Color4.Red, 200, Easing.OutQuint); this.FadeOut(500, Easing.InQuint).Expire(); break; } } public bool OnPressed(KeyBindingPressEvent<GengoAction> e) { if (e.Action != GengoAction.LeftButton && e.Action != GengoAction.RightButton) return false; pressedAction = e.Action; return UpdateResult(true); } public void OnReleased(KeyBindingReleaseEvent<GengoAction> e) { } } }
osu.Game.Rulesets.Gengo/Objects/Drawables/DrawableGengoHitObject.cs
0xdeadbeer-gengo-dd4f78d
[ { "filename": "osu.Game.Rulesets.Gengo/GengoRuleset.cs", "retrieved_chunk": " public override string ShortName => \"gengo\";\n public override IEnumerable<KeyBinding> GetDefaultKeyBindings(int variant = 0) => new[]\n {\n new KeyBinding(InputKey.A, GengoAction.LeftButton),\n new KeyBinding(InputKey.S, GengoAction.RightButton),\n };\n public override Drawable CreateIcon() => new GengoRulesetIcon(this);\n public override RulesetSettingsSubsection CreateSettings() => new GengoSettingsSubsection(this);\n public override IRulesetConfigManager CreateConfig(SettingsStore? settings) => new GengoRulesetConfigManager(settings, RulesetInfo);\n // Leave this line intact. It will bake the correct version into the ruleset on each build/release.", "score": 0.8048648238182068 }, { "filename": "osu.Game.Rulesets.Gengo/GengoInputManager.cs", "retrieved_chunk": " public GengoInputManager(RulesetInfo ruleset)\n : base(ruleset, 0, SimultaneousBindingMode.Unique)\n {\n }\n protected override KeyBindingContainer<GengoAction> CreateKeyBindingContainer(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique)\n => new GengoKeyBindingContainer(ruleset, variant, unique);\n private partial class GengoKeyBindingContainer : RulesetKeyBindingContainer {\n public bool AllowUserPresses = true;\n public GengoKeyBindingContainer(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique) \n : base(ruleset, variant, unique) ", "score": 0.7879840731620789 }, { "filename": "osu.Game.Rulesets.Gengo/Replays/GengoAutoGenerator.cs", "retrieved_chunk": " public GengoAutoGenerator(IBeatmap beatmap)\n : base(beatmap)\n {\n }\n protected override void GenerateFrames()\n {\n Frames.Add(new GengoReplayFrame());\n foreach (GengoHitObject hitObject in Beatmap.HitObjects)\n {\n Frames.Add(new GengoReplayFrame", "score": 0.7776634693145752 }, { "filename": "osu.Game.Rulesets.Gengo/GengoInputManager.cs", "retrieved_chunk": " {\n }\n protected override bool Handle(UIEvent e)\n {\n return base.Handle(e);\n }\n }\n }\n public enum GengoAction\n {", "score": 0.7742109894752502 }, { "filename": "osu.Game.Rulesets.Gengo/Replays/GengoFramedReplayInputHandler.cs", "retrieved_chunk": " {\n public GengoFramedReplayInputHandler(Replay replay)\n : base(replay)\n {\n }\n protected override bool IsImportant(GengoReplayFrame frame) => true;\n protected override void CollectReplayInputs(List<IInput> inputs)\n {\n var position = Interpolation.ValueAt(CurrentTime, StartFrame.Position, EndFrame.Position, StartFrame.Time, EndFrame.Time);\n inputs.Add(new MousePositionAbsoluteInput", "score": 0.7723878622055054 } ]
csharp
GengoAction pressedAction;
#nullable enable using System.IO; using System.Net.Http; using Cysharp.Threading.Tasks; using Mochineko.YouTubeLiveStreamingClient.Responses; using UniRx; using UnityEngine; namespace Mochineko.YouTubeLiveStreamingClient.Samples { internal sealed class LiveChatMessagesCollectionDemo : MonoBehaviour { [SerializeField] private string apiKeyPath = string.Empty; [SerializeField] private string videoIDOrURL = string.Empty; [SerializeField, Range(200, 2000)] private uint maxResultsOfMessages = 500; [SerializeField] private float intervalSeconds = 5f; private static readonly HttpClient HttpClient = new(); private LiveChatMessagesCollector? collector; private async void Start() { // Get YouTube API key from file. var apiKey = await File.ReadAllTextAsync( apiKeyPath, this.GetCancellationTokenOnDestroy()); if (string.IsNullOrEmpty(apiKey)) { Debug.LogError("[YouTubeLiveStreamingClient.Samples] API Key is null or empty."); return; } // Extract video ID if URL. var result = YouTubeVideoIDExtractor.TryExtractVideoId(videoIDOrURL, out var videoID); if (result is false || string.IsNullOrEmpty(videoID)) { Debug.LogError($"[YouTubeLiveStreamingClient.Samples] Failed to extract video ID from:{videoIDOrURL}."); return; } // Initialize collector collector = new LiveChatMessagesCollector( HttpClient, apiKey, videoID, maxResultsOfMessages: maxResultsOfMessages, dynamicInterval: false, intervalSeconds: intervalSeconds, verbose: true); // Register events collector .OnVideoInformationUpdated .SubscribeOnMainThread() .Subscribe(OnVideoInformationUpdated) .AddTo(this); collector .OnMessageCollected .SubscribeOnMainThread() .Subscribe(OnMessageCollected) .AddTo(this); // Filter samples to super chats and super stickers collector .OnMessageCollected .Where(message => message.Snippet.Type is LiveChatMessageType.superChatEvent) .SubscribeOnMainThread() .Subscribe(OnSuperChatMessageCollected) .AddTo(this); collector .OnMessageCollected .Where(message => message.Snippet.Type is LiveChatMessageType.superStickerEvent) .SubscribeOnMainThread() .Subscribe(OnSuperStickerMessageCollected) .AddTo(this); // Begin collection collector.BeginCollection(); } private void OnDestroy() { collector?.Dispose(); } private void OnVideoInformationUpdated(VideosAPIResponse response) { Debug.Log( $"[YouTubeLiveStreamingClient.Samples] Update video information, title:{response.Items[0].Snippet.Title}, live chat ID:{response.Items[0].LiveStreamingDetails.ActiveLiveChatId}."); } private void OnMessageCollected(
LiveChatMessageItem message) {
Debug.Log( $"[YouTubeLiveStreamingClient.Samples] Collect message: [{message.Snippet.Type}] {message.Snippet.DisplayMessage} from {message.AuthorDetails.DisplayName} at {message.Snippet.PublishedAt}."); } private void OnSuperChatMessageCollected(LiveChatMessageItem message) { Debug.Log( $"<color=orange>[YouTubeLiveStreamingClient.Samples] Collect super chat message: {message.Snippet.DisplayMessage}, {message.Snippet.SuperChatDetails?.AmountDisplayString} from {message.AuthorDetails.DisplayName} at {message.Snippet.PublishedAt}.</color>"); } private void OnSuperStickerMessageCollected(LiveChatMessageItem message) { Debug.Log( $"<color=orange>[YouTubeLiveStreamingClient.Samples] Collect super chat message: {message.Snippet.DisplayMessage}, {message.Snippet.SuperStickerDetails?.AmountDisplayString} from {message.AuthorDetails.DisplayName} at {message.Snippet.PublishedAt}.</color>"); } } }
Assets/Mochineko/YouTubeLiveStreamingClient.Samples/LiveChatMessagesCollectionDemo.cs
mochi-neko-youtube-live-streaming-client-unity-b712d77
[ { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient/LiveChatMessagesCollector.cs", "retrieved_chunk": " if (!string.IsNullOrEmpty(liveChatID))\n {\n if (verbose)\n {\n Debug.Log(\n $\"[YouTubeLiveStreamingClient] Succeeded to get live chat ID:{liveChatID} from video ID:{videoID}.\");\n }\n this.liveChatID = liveChatID;\n onVideoInformationUpdated.OnNext(response);\n }", "score": 0.8566468358039856 }, { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient/LiveChatMessagesCollector.cs", "retrieved_chunk": " }\n if (response.Items.Count == 0)\n {\n if (verbose)\n {\n Debug.Log($\"[YouTubeLiveStreamingClient] No items are found in response from video ID:{videoID}.\");\n }\n return;\n }\n var liveChatID = response.Items[0].LiveStreamingDetails.ActiveLiveChatId;", "score": 0.8461058139801025 }, { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient/LiveChatMessagesCollector.cs", "retrieved_chunk": " LiveChatMessagesAPIResponse response;\n switch (result)\n {\n case IUncertainSuccessResult<LiveChatMessagesAPIResponse> success:\n {\n if (verbose)\n {\n Debug.Log(\n $\"[YouTubeLiveStreamingClient] Succeeded to get live chat messages: {success.Result.Items.Count} messages with next page token:{success.Result.NextPageToken}.\");\n }", "score": 0.8194376230239868 }, { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient/LiveChatMessagesCollector.cs", "retrieved_chunk": " // NOTE: Publish event on the main thread.\n await UniTask.SwitchToMainThread(cancellationToken);\n foreach (var item in response.Items)\n {\n if (verbose)\n {\n Debug.Log(\n $\"[YouTubeLiveStreamingClient] Collected live chat message: {item.Snippet.DisplayMessage} from {item.AuthorDetails.DisplayName} at {item.Snippet.PublishedAt}.\");\n }\n onMessageCollected.OnNext(item);", "score": 0.8177763223648071 }, { "filename": "Assets/Mochineko/YouTubeLiveStreamingClient.Tests/LiveChatMessagesAPITest.cs", "retrieved_chunk": " var liveChatMessages = liveChatMessagesResult.Unwrap().Items;\n foreach (var message in liveChatMessages)\n {\n Debug.Log($\"{message.Snippet.Type}:{message.AuthorDetails.DisplayName} -> {message.Snippet.DisplayMessage} at {message.Snippet.PublishedAt}.\");\n }\n }\n }\n}", "score": 0.7807728052139282 } ]
csharp
LiveChatMessageItem message) {
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using UserManagement.Data.Models; #nullable disable namespace UserManagement.Data.Migrations { [DbContext(typeof(
ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot {
protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "7.0.4") .HasAnnotation("Relational:MaxIdentifierLength", 128); SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasDatabaseName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles", (string)null); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id")); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims", (string)null); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id")); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims", (string)null); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasColumnType("nvarchar(450)"); b.Property<string>("ProviderKey") .HasColumnType("nvarchar(450)"); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins", (string)null); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("RoleId") .HasColumnType("nvarchar(450)"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles", (string)null); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(450)"); b.Property<string>("Name") .HasColumnType("nvarchar(450)"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens", (string)null); }); modelBuilder.Entity("UserManagement.Data.Models.ApplicationUser", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Email") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<bool>("EmailConfirmed") .HasColumnType("bit"); b.Property<string>("FirstName") .HasColumnType("nvarchar(max)"); b.Property<string>("LastName") .HasColumnType("nvarchar(max)"); b.Property<bool>("LockoutEnabled") .HasColumnType("bit"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("NormalizedEmail") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedUserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("PasswordHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("bit"); b.Property<string>("RefreshToken") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("RefreshTokenExpiryTime") .HasColumnType("datetime2"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("bit"); b.Property<string>("UserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasDatabaseName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasDatabaseName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers", (string)null); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("UserManagement.Data.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("UserManagement.Data.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("UserManagement.Data.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("UserManagement.Data.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
UserManagement.Data/Migrations/ApplicationDbContextModelSnapshot.cs
shahedbd-API.RefreshTokens-c4d606e
[ { "filename": "UserManagement.Data/Models/ApplicationDbContext.cs", "retrieved_chunk": "using Microsoft.AspNetCore.Identity.EntityFrameworkCore;\nusing Microsoft.EntityFrameworkCore;\nnamespace UserManagement.Data.Models\n{\n public class ApplicationDbContext : IdentityDbContext<ApplicationUser>\n {\n public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)\n {\n }\n }", "score": 0.8424546718597412 }, { "filename": "UserManagement.Data/Migrations/20230408103240_initcreate.Designer.cs", "retrieved_chunk": "// <auto-generated />\nusing System;\nusing Microsoft.EntityFrameworkCore;\nusing Microsoft.EntityFrameworkCore.Infrastructure;\nusing Microsoft.EntityFrameworkCore.Metadata;\nusing Microsoft.EntityFrameworkCore.Migrations;\nusing Microsoft.EntityFrameworkCore.Storage.ValueConversion;\nusing UserManagement.Data.Models;\n#nullable disable\nnamespace UserManagement.Data.Migrations", "score": 0.8344441652297974 }, { "filename": "UserManagement.Api/Services/AuthService.cs", "retrieved_chunk": "using Microsoft.AspNetCore.Identity;\nusing Microsoft.IdentityModel.Tokens;\nusing System.IdentityModel.Tokens.Jwt;\nusing System.Security.Claims;\nusing System.Security.Cryptography;\nusing System.Text;\nusing UserManagement.Data.Models;\nnamespace UserManagement.Api.Services\n{\n public class AuthService : IAuthService", "score": 0.78677898645401 }, { "filename": "UserManagement.Api/Controllers/AuthenticationController.cs", "retrieved_chunk": "using UserManagement.Api.Services;\nusing UserManagement.Data.Models;\nusing Microsoft.AspNetCore.Mvc;\nnamespace BloggingApis.Controllers\n{\n [Route(\"api/[controller]\")]\n [ApiController]\n public class AuthenticationController : ControllerBase\n {\n private readonly IAuthService _authService;", "score": 0.7827681303024292 }, { "filename": "UserManagement.Data/Models/RegistrationModel.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace UserManagement.Data.Models\n{\n public class RegistrationModel\n {", "score": 0.7736990451812744 } ]
csharp
ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot {
// Kaplan Copyright (c) DragonFruit Network <[email protected]> // Licensed under Apache-2. Refer to the LICENSE file for more info using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reactive.Linq; using System.Security.Principal; using System.Threading.Tasks; using System.Windows.Input; using Windows.ApplicationModel; using Windows.Management.Deployment; using Avalonia.Threading; using DragonFruit.Kaplan.ViewModels.Enums; using DragonFruit.Kaplan.ViewModels.Messages; using DynamicData; using DynamicData.Binding; using Microsoft.Extensions.Logging; using ReactiveUI; namespace DragonFruit.Kaplan.ViewModels { public class MainWindowViewModel : ReactiveObject, IDisposable { private readonly ILogger _logger; private readonly WindowsIdentity _currentUser; private readonly PackageManager _packageManager; private readonly IDisposable _packageRefreshListener; private readonly ObservableAsPropertyHelper<IEnumerable<PackageViewModel>> _displayedPackages; private string _searchQuery = string.Empty; private PackageInstallationMode _packageMode = PackageInstallationMode.User; private IReadOnlyCollection<PackageViewModel> _discoveredPackages = Array.Empty<PackageViewModel>(); public MainWindowViewModel() { _packageManager = new PackageManager(); _currentUser = WindowsIdentity.GetCurrent(); _logger = App.GetLogger<MainWindowViewModel>(); AvailablePackageModes = _currentUser.User != null ? Enum.GetValues<PackageInstallationMode>() : new[] {PackageInstallationMode.Machine}; // create observables var packagesSelected = SelectedPackages.ToObservableChangeSet() .ToCollection() .ObserveOn(RxApp.MainThreadScheduler) .Select(x => x.Any()); _packageRefreshListener = MessageBus.Current.Listen<UninstallEventArgs>().ObserveOn(RxApp.TaskpoolScheduler).Subscribe(x => RefreshPackagesImpl()); _displayedPackages = this.WhenAnyValue(x => x.DiscoveredPackages, x => x.SearchQuery, x => x.SelectedPackages) .ObserveOn(RxApp.TaskpoolScheduler) .Select(q => { // because filters remove selected entries, the search will split the listing into two groups, with the matches showing above var matches = q.Item1.ToLookup(x => x.IsSearchMatch(q.Item2)); return matches[true].Concat(matches[false]); }) .ToProperty(this, x => x.DisplayedPackages); // create commands RefreshPackages = ReactiveCommand.CreateFromTask(RefreshPackagesImpl); RemovePackages = ReactiveCommand.Create(RemovePackagesImpl, packagesSelected); ClearSelection = ReactiveCommand.Create(() => SelectedPackages.Clear(), packagesSelected); ShowAbout = ReactiveCommand.Create(() => MessageBus.Current.SendMessage(new ShowAboutWindowEventArgs())); // auto refresh the package list if the user package filter switch is changed this.WhenValueChanged(x => x.PackageMode).ObserveOn(RxApp.TaskpoolScheduler).Subscribe(_ => RefreshPackages.Execute(null)); } public IEnumerable<PackageInstallationMode> AvailablePackageModes { get; } public ObservableCollection<PackageViewModel> SelectedPackages { get; } = new(); public IEnumerable<PackageViewModel> DisplayedPackages => _displayedPackages.Value; private IReadOnlyCollection<
PackageViewModel> DiscoveredPackages {
get => _discoveredPackages; set => this.RaiseAndSetIfChanged(ref _discoveredPackages, value); } /// <summary> /// Gets or sets whether the <see cref="DiscoveredPackages"/> collection should show packages installed for the selected user /// </summary> public PackageInstallationMode PackageMode { get => _packageMode; set => this.RaiseAndSetIfChanged(ref _packageMode, value); } /// <summary> /// Gets or sets the search query used to filter <see cref="DisplayedPackages"/> /// </summary> public string SearchQuery { get => _searchQuery; set => this.RaiseAndSetIfChanged(ref _searchQuery, value); } public ICommand ShowAbout { get; } public ICommand ClearSelection { get; } public ICommand RemovePackages { get; } public ICommand RefreshPackages { get; } private async Task RefreshPackagesImpl() { IEnumerable<Package> packages; switch (PackageMode) { case PackageInstallationMode.User when _currentUser.User != null: _logger.LogInformation("Loading Packages for user {userId}", _currentUser.User.Value); packages = _packageManager.FindPackagesForUser(_currentUser.User.Value); break; case PackageInstallationMode.Machine: _logger.LogInformation("Loading machine-wide packages"); packages = _packageManager.FindPackages(); break; default: throw new ArgumentOutOfRangeException(); } var filteredPackageModels = packages.Where(x => x.SignatureKind != PackageSignatureKind.System) .Select(x => new PackageViewModel(x)) .ToList(); _logger.LogDebug("Discovered {x} packages", filteredPackageModels.Count); // ensure the ui doesn't have non-existent packages nominated through an intersection // ToList needed due to deferred nature of iterators used. var reselectedPackages = filteredPackageModels.IntersectBy(SelectedPackages.Select(x => x.Package.Id.FullName), x => x.Package.Id.FullName).ToList(); await Dispatcher.UIThread.InvokeAsync(() => { SelectedPackages.Clear(); SearchQuery = string.Empty; DiscoveredPackages = filteredPackageModels; SelectedPackages.AddRange(reselectedPackages); }); } private void RemovePackagesImpl() { var packages = SelectedPackages.Select(x => x.Package).ToList(); var args = new UninstallEventArgs(packages, PackageMode); _logger.LogInformation("Starting removal of {x} packages", packages.Count); MessageBus.Current.SendMessage(args); } public void Dispose() { _displayedPackages?.Dispose(); _packageRefreshListener?.Dispose(); } } }
DragonFruit.Kaplan/ViewModels/MainWindowViewModel.cs
dragonfruitnetwork-kaplan-13bdb39
[ { "filename": "DragonFruit.Kaplan/Views/MainWindow.axaml.cs", "retrieved_chunk": " {\n DataContext = new RemovalProgressViewModel(args.Packages, args.Mode)\n };\n await window.ShowDialog(this).ConfigureAwait(false);\n MessageBus.Current.SendMessage(new PackageRefreshEventArgs());\n }\n private void PackageListPropertyChanged(object sender, AvaloniaPropertyChangedEventArgs e)\n {\n if (e.Property.Name != nameof(ListBox.ItemsSource))\n {", "score": 0.8099357485771179 }, { "filename": "DragonFruit.Kaplan/ViewModels/PackageRemovalTask.cs", "retrieved_chunk": "namespace DragonFruit.Kaplan.ViewModels\n{\n public class PackageRemovalTask : ReactiveObject\n {\n private readonly ObservableAsPropertyHelper<string> _statusString;\n private readonly PackageInstallationMode _mode;\n private readonly PackageManager _manager;\n private DeploymentProgress? _progress;\n public PackageRemovalTask(PackageManager manager, Package package, PackageInstallationMode mode)\n {", "score": 0.8027240037918091 }, { "filename": "DragonFruit.Kaplan/ViewModels/RemovalProgressViewModel.cs", "retrieved_chunk": " public event Action CloseRequested;\n public PackageRemovalTask Current\n {\n get => _current;\n private set => this.RaiseAndSetIfChanged(ref _current, value);\n }\n public int CurrentPackageNumber\n {\n get => _currentPackageNumber;\n private set => this.RaiseAndSetIfChanged(ref _currentPackageNumber, value);", "score": 0.8002113699913025 }, { "filename": "DragonFruit.Kaplan/ViewModels/RemovalProgressViewModel.cs", "retrieved_chunk": "{\n public class RemovalProgressViewModel : ReactiveObject, IHandlesClosingEvent, IExecutesTaskPostLoad, ICanCloseWindow\n {\n private readonly ILogger _logger = App.GetLogger<RemovalProgressViewModel>();\n private readonly AsyncLock _lock = new();\n private readonly PackageInstallationMode _mode;\n private readonly CancellationTokenSource _cancellation = new();\n private readonly ObservableAsPropertyHelper<ISolidColorBrush> _progressColor;\n private OperationState _status;\n private int _currentPackageNumber;", "score": 0.7987523674964905 }, { "filename": "DragonFruit.Kaplan/ViewModels/RemovalProgressViewModel.cs", "retrieved_chunk": " }\n public OperationState Status\n {\n get => _status;\n private set => this.RaiseAndSetIfChanged(ref _status, value);\n }\n public bool CancellationRequested => _cancellation.IsCancellationRequested;\n public ISolidColorBrush ProgressColor => _progressColor.Value;\n public IReadOnlyList<Package> Packages { get; }\n public ICommand RequestCancellation { get; }", "score": 0.7937588691711426 } ]
csharp
PackageViewModel> DiscoveredPackages {
using LibreDteDotNet.Common.Models; using LibreDteDotNet.RestRequest.Interfaces; namespace LibreDteDotNet.RestRequest.Extensions { public static class DTEExtension { public static IDTE Conectar(this
IDTE folioService) {
IDTE instance = folioService; return instance.SetCookieCertificado().ConfigureAwait(false).GetAwaiter().GetResult(); } public static async Task<IDTE> Validar(this IDTE folioService, string pathfile) { if (!File.Exists(pathfile)) { throw new Exception($"El Documento no existe en la ruta {pathfile}"); } IDTE instance = folioService; return await instance.Validar<EnvioDTE>(pathfile); } public static async Task<string> Enviar( this Task<IDTE> folioService, string rutCompany, string DvCompany ) { IDTE instance = await folioService; return await instance.Enviar(rutCompany, DvCompany); } } }
LibreDteDotNet.RestRequest/Extensions/DTEExtension.cs
sergiokml-LibreDteDotNet.RestRequest-6843109
[ { "filename": "LibreDteDotNet.RestRequest/Services/DTEService.cs", "retrieved_chunk": "using LibreDteDotNet.Common;\nusing LibreDteDotNet.Common.Models;\nusing LibreDteDotNet.RestRequest.Infraestructure;\nusing LibreDteDotNet.RestRequest.Interfaces;\nusing Microsoft.Extensions.Configuration;\nnamespace LibreDteDotNet.RestRequest.Services\n{\n internal class DTEService : ComunEnum, IDTE\n {\n private readonly IRepositoryWeb repositoryWeb;", "score": 0.9148291349411011 }, { "filename": "LibreDteDotNet.RestRequest/Extensions/FolioCafExtension.cs", "retrieved_chunk": "using System.Xml.Linq;\nusing LibreDteDotNet.RestRequest.Interfaces;\nnamespace LibreDteDotNet.RestRequest.Extensions\n{\n public static class FolioCafExtension\n {\n private static CancellationToken CancellationToken { get; set; }\n public static IFolioCaf Conectar(this IFolioCaf instance)\n {\n return instance.SetCookieCertificado().Result;", "score": 0.883469820022583 }, { "filename": "LibreDteDotNet.RestRequest/Services/BoletaService.cs", "retrieved_chunk": "using System.Net;\nusing LibreDteDotNet.Common;\nusing LibreDteDotNet.RestRequest.Infraestructure;\nusing LibreDteDotNet.RestRequest.Interfaces;\nusing Microsoft.Extensions.Configuration;\nnamespace LibreDteDotNet.RestRequest.Services\n{\n internal class BoletaService : ComunEnum, IBoleta\n {\n private readonly IConfiguration configuration;", "score": 0.8810298442840576 }, { "filename": "LibreDteDotNet.RestRequest/Extensions/BoletaExtension.cs", "retrieved_chunk": "using LibreDteDotNet.RestRequest.Interfaces;\nnamespace LibreDteDotNet.RestRequest.Extensions\n{\n public static class BoletaExtension\n {\n public static IBoleta Conectar(this IBoleta folioService)\n {\n IBoleta instance = folioService;\n return instance.SetCookieCertificado().Result;\n }", "score": 0.8722130656242371 }, { "filename": "LibreDteDotNet.RestRequest/Services/ContribuyenteService.cs", "retrieved_chunk": "using System.Net;\nusing LibreDteDotNet.Common;\nusing LibreDteDotNet.RestRequest.Infraestructure;\nusing LibreDteDotNet.RestRequest.Interfaces;\nusing Microsoft.Extensions.Configuration;\nnamespace LibreDteDotNet.RestRequest.Services\n{\n internal class ContribuyenteService : ComunEnum, IContribuyente\n {\n private readonly IRepositoryWeb repositoryWeb;", "score": 0.8686898946762085 } ]
csharp
IDTE folioService) {
using System; using System.Collections.Generic; using System.Text; using XiaoFeng.Xml; using System.Xml; using System.Xml.Serialization; using XiaoFeng; using XiaoFeng.IO; using XiaoFeng.Cryptography; using System.Linq; using FayElf.Plugins.WeChat.Model; using FayElf.Plugins.WeChat.Cryptotraphy; /**************************************************************** * Copyright © (2022) www.fayelf.com All Rights Reserved. * * Author : jacky * * QQ : 7092734 * * Email : [email protected] * * Site : www.fayelf.com * * Create Time : 2022-03-14 17:53:45 * * Version : v 1.0.0 * * CLR Version : 4.0.30319.42000 * *****************************************************************/ namespace FayElf.Plugins.WeChat.OfficialAccount { /// <summary> /// 微信接收操作类 /// </summary> public class Receive { #region 构造器 /// <summary> /// 无参构造器 /// </summary> public Receive() { this.Config = Config.Current; } #endregion #region 属性 public Config Config { get; set; } #endregion #region 方法 #region 对请求进行signature校验 /// <summary> /// 对请求进行signature校验 /// </summary> /// <returns></returns> public Boolean CheckSignature(string signature, string nonce, string timestamp,string token) { if (signature.IsNullOrEmpty() || nonce.IsNullOrEmpty() || timestamp.IsNullOrEmpty() || timestamp.IsNotMatch(@"^\d+$")) return false; //LogHelper.WriteLog($"sign:{new string[] { token, nonce, timestamp }.OrderBy(a => a).Join("").SHA1Encrypt().ToLower()}"); return new string[] { token, nonce, timestamp }.OrderBy(a => a).Join("").SHA1Encrypt().ToLower() == signature.ToLower(); } #endregion #region 接收数据 /// <summary> /// 接收数据 /// </summary> /// <returns></returns> public string RequestMessage(Microsoft.AspNetCore.Http.HttpRequest request, Func<
BaseMessage?, XmlValue, string> func) {
var encrypt_type = request.Query["encrypt_type"].ToString().ToUpper() == "AES"; var signature = request.Query["signature"].ToString(); var timestamp = request.Query["timestamp"].ToString(); var nonce = request.Query["nonce"].ToString(); var echostr = request.Query["echostr"].ToString(); LogHelper.WriteLog($"encrypt_type:{encrypt_type},signature:{signature},timestamp:{timestamp},nonce:{nonce},echostr:{echostr},token:{this.Config.Token}"); if (request.Method == "GET") { return this.CheckSignature(signature, nonce, timestamp, this.Config.Token) ? echostr : "error"; } var msg_signature = request.Query["msg_signature"].ToString(); LogHelper.WriteLog($"msg_signature:{msg_signature}"); var msg = request.Body.ReadToEnd(); LogHelper.Warn(msg); if (encrypt_type) { var wxBizMsgCrypt = new WXBizMsgCrypt(this.Config.Token, this.Config.EncodingAESKey, this.Config.AppID); var _msg = ""; var ret = wxBizMsgCrypt.DecryptMsg(msg_signature, timestamp, nonce, msg, ref _msg); if (ret != 0)//解密失败 { //TODO:开发者解密失败的业务处理逻辑 LogHelper.Warn($"微信公众号数据解密失败.[decrypt message return {ret}, request body {msg}]"); } msg = _msg; } var data = msg.XmlToEntity() as XmlValue; if (data == null || data.ChildNodes == null || data.ChildNodes.Count < 1) return ""; var xml = data.ChildNodes.First(); var BaseMsg = xml.ToObject(typeof(BaseMessage)) as BaseMessage; var message = func.Invoke(BaseMsg, xml); if (encrypt_type) { var _msg = ""; var wxBizMsgCrypt = new WXBizMsgCrypt(this.Config.Token, this.Config.EncodingAESKey, this.Config.AppID); var ret = wxBizMsgCrypt.EncryptMsg(message, timestamp, nonce, ref _msg); if (ret != 0)//加密失败 { //TODO:开发者加密失败的业务处理逻辑 LogHelper.Warn($"微信公众号数据加密失败.[encrypt message return {ret}, response body {message}]"); } message= _msg; } return message; } #endregion #region 输出内容 /// <summary> /// 输出内容 /// </summary> /// <param name="messageType">内容类型</param> /// <param name="fromUserName">发送方帐号</param> /// <param name="toUserName">接收方帐号</param> /// <param name="func">委托</param> /// <returns></returns> private string ReplayContent(MessageType messageType, string fromUserName, string toUserName, Func<string> func) => $"<xml><ToUserName><![CDATA[{toUserName}]]></ToUserName><FromUserName><![CDATA[{fromUserName}]]></FromUserName><CreateTime>{DateTime.Now.ToTimeStamp()}</CreateTime><MsgType><![CDATA[{messageType.GetEnumName()}]]></MsgType>{func.Invoke()}</xml>"; #endregion #region 输出文本消息 /// <summary> /// 输出文本消息 /// </summary> /// <param name="fromUserName">发送方帐号</param> /// <param name="toUserName">接收方帐号</param> /// <param name="content">回复内容</param> /// <returns></returns> public string ReplayText(string fromUserName, string toUserName, string content) => this.ReplayContent(MessageType.text, fromUserName, toUserName, () => $"<Content><![CDATA[{content}]]></Content>"); #endregion #region 回复图片 /// <summary> /// 回复图片 /// </summary> /// <param name="fromUserName">发送方帐号</param> /// <param name="toUserName">接收方帐号</param> /// <param name="mediaId">通过素材管理中的接口上传多媒体文件,得到的id</param> /// <returns></returns> public string ReplayImage(string fromUserName, string toUserName, string mediaId) => this.ReplayContent(MessageType.image, fromUserName, toUserName, () => $"<Image><MediaId><![CDATA[{mediaId}]]></MediaId></Image>"); #endregion #region 回复语音消息 /// <summary> /// 回复语音消息 /// </summary> /// <param name="fromUserName">发送方帐号</param> /// <param name="toUserName">接收方帐号</param> /// <param name="mediaId">通过素材管理中的接口上传多媒体文件,得到的id</param> /// <returns></returns> public string ReplayVoice(string fromUserName, string toUserName, string mediaId) => this.ReplayContent(MessageType.voice, fromUserName, toUserName, () => $"<Voice><MediaId><![CDATA[{mediaId}]]></MediaId></Voice>"); #endregion #region 回复视频消息 /// <summary> /// 回复视频消息 /// </summary> /// <param name="fromUserName">发送方帐号</param> /// <param name="toUserName">接收方帐号</param> /// <param name="mediaId">通过素材管理中的接口上传多媒体文件,得到的id</param> /// <param name="title">视频消息的标题</param> /// <param name="description">视频消息的描述</param> /// <returns></returns> public string ReplayVideo(string fromUserName, string toUserName, string mediaId, string title, string description) => this.ReplayContent(MessageType.video, fromUserName, toUserName, () => $"<Video><MediaId><![CDATA[{mediaId}]]></MediaId><Title><![CDATA[{title}]]></Title><Description><![CDATA[{description}]]></Description></Video>"); #endregion #region 回复音乐消息 /// <summary> /// 回复视频消息 /// </summary> /// <param name="fromUserName">发送方帐号</param> /// <param name="toUserName">接收方帐号</param> /// <param name="title">视频消息的标题</param> /// <param name="description">视频消息的描述</param> /// <param name="musicUrl">音乐链接</param> /// <param name="HQmusicUrl">高质量音乐链接,WIFI环境优先使用该链接播放音乐</param> /// <param name="mediaId">通过素材管理中的接口上传多媒体文件,得到的id</param> /// <returns></returns> public string ReplayMusic(string fromUserName, string toUserName, string title, string description, string mediaId,string musicUrl,string HQmusicUrl) => this.ReplayContent(MessageType.music, fromUserName, toUserName, () => $"<Music><Title><![CDATA[{title}]]></Title><Description><![CDATA[{description}]]></Description><MusicUrl><![CDATA[{musicUrl}]]></MusicUrl><HQMusicUrl><![CDATA[{HQmusicUrl}]]></HQMusicUrl><ThumbMediaId><![CDATA[{mediaId}]]></ThumbMediaId></Music>"); #endregion #region 回复图文消息 /// <summary> /// 回复图文消息 /// </summary> /// <param name="fromUserName">发送方帐号</param> /// <param name="toUserName">接收方帐号</param> /// <param name="list">图文列表</param> /// <returns></returns> public string ReplayNews(string fromUserName, string toUserName, NewsModel news) => this.ReplayContent(MessageType.news, fromUserName, toUserName, () => { if (news == null || news.Item == null || news.Item.Count == 0) return ""; return $"<ArticleCount>{news.Item.Count}</ArticleCount>{news.EntityToXml(OmitXmlDeclaration: true, OmitComment: true, Indented: false)}"; }); #endregion #endregion } }
OfficialAccount/Receive.cs
zhuovi-FayElf.Plugins.WeChat-5725d1e
[ { "filename": "OfficialAccount/Model/IndustryTemplateSendData.cs", "retrieved_chunk": " [Description(\"模板数据\"), JsonElement(\"data\")] \n public Dictionary<string, ValueColor> Data { get; set; }\n #endregion\n #region 方法\n #endregion\n }\n /// <summary>\n /// 发送数据返回结果\n /// </summary>\n public class IndustryTemplateSendDataResult : BaseResult", "score": 0.840338945388794 }, { "filename": "OfficialAccount/Model/PubTemplateResult.cs", "retrieved_chunk": " #region 构造器\n /// <summary>\n /// 无参构造器\n /// </summary>\n public PubTemplateResult()\n {\n }\n #endregion\n #region 属性\n /// <summary>", "score": 0.8361572027206421 }, { "filename": "OfficialAccount/Model/AddTemplateResult.cs", "retrieved_chunk": " #region 构造器\n /// <summary>\n /// 无参构造器\n /// </summary>\n public AddTemplateResult()\n {\n }\n #endregion\n #region 属性\n /// <summary>", "score": 0.8322436809539795 }, { "filename": "Model/BaseMessage.cs", "retrieved_chunk": " /// <summary>\n /// 事件类型\n /// </summary>\n [XmlCData, XmlConverter(typeof(StringEnumConverter))]\n public EventType Event { get; set; }\n /// <summary>\n /// 消息ID\n /// </summary>\n [XmlCData]\n public string MsgId { get; set; }", "score": 0.8270547986030579 }, { "filename": "Model/BaseMessage.cs", "retrieved_chunk": " #region 属性\n /// <summary>\n /// 接收方用户Open ID\n /// </summary>\n [XmlCData]\n public string ToUserName { get; set; }\n /// <summary>\n /// 发送方用户Open ID\n /// </summary>\n [XmlCData]", "score": 0.8241879940032959 } ]
csharp
BaseMessage?, XmlValue, string> func) {
using System; using System.Linq; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows; using System.IO; using System.Diagnostics; using System.Data; using System.Threading.Tasks; using System.Windows.Media; using System.Windows.Shapes; using Path = System.IO.Path; using Playnite.SDK; using Playnite.SDK.Events; using Playnite.SDK.Models; using Playnite.SDK.Plugins; using NowPlaying.Utils; using NowPlaying.Models; using NowPlaying.Properties; using NowPlaying.Views; using NowPlaying.ViewModels; using System.Reflection; using System.Windows.Controls; using System.Threading; using Playnite.SDK.Data; namespace NowPlaying { public class NowPlaying : LibraryPlugin { public override Guid Id { get; } = Guid.Parse("0dbead64-b7ed-47e5-904c-0ccdb5d5ff59"); public override string LibraryIcon { get; } public override string Name => "NowPlaying Game Cacher"; public static readonly ILogger logger = LogManager.GetLogger(); public const string previewPlayActionName = "Preview (play from install directory)"; public const string nowPlayingActionName = "Play from game cache"; public NowPlayingSettings Settings { get; private set; } public readonly NowPlayingSettingsViewModel settingsViewModel; public readonly NowPlayingSettingsView settingsView; public readonly CacheRootsViewModel cacheRootsViewModel; public readonly CacheRootsView cacheRootsView; public readonly TopPanelViewModel topPanelViewModel; public readonly TopPanelView topPanelView; public readonly TopPanelItem topPanelItem; public readonly Rectangle sidebarIcon; public readonly SidebarItem sidebarItem; public readonly NowPlayingPanelViewModel panelViewModel; public readonly NowPlayingPanelView panelView; public readonly GameCacheManagerViewModel cacheManager; public bool IsGamePlaying = false; public WhilePlaying WhilePlayingMode { get; private set; } public int SpeedLimitIpg { get; private set; } = 0; private string formatStringXofY; public Queue<
NowPlayingGameEnabler> gameEnablerQueue;
public Queue<NowPlayingInstallController> cacheInstallQueue; public Queue<NowPlayingUninstallController> cacheUninstallQueue; public string cacheInstallQueueStateJsonPath; public bool cacheInstallQueuePaused; public NowPlaying(IPlayniteAPI api) : base(api) { Properties = new LibraryPluginProperties { HasCustomizedGameImport = true, CanShutdownClient = true, HasSettings = true }; LibraryIcon = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"icon.png"); cacheManager = new GameCacheManagerViewModel(this, logger); formatStringXofY = GetResourceFormatString("LOCNowPlayingProgressXofYFmt2", 2) ?? "{0} of {1}"; gameEnablerQueue = new Queue<NowPlayingGameEnabler>(); cacheInstallQueue = new Queue<NowPlayingInstallController>(); cacheUninstallQueue = new Queue<NowPlayingUninstallController>(); cacheInstallQueueStateJsonPath = Path.Combine(GetPluginUserDataPath(), "cacheInstallQueueState.json"); cacheInstallQueuePaused = false; Settings = LoadPluginSettings<NowPlayingSettings>() ?? new NowPlayingSettings(); settingsViewModel = new NowPlayingSettingsViewModel(this); settingsView = new NowPlayingSettingsView(settingsViewModel); cacheRootsViewModel = new CacheRootsViewModel(this); cacheRootsView = new CacheRootsView(cacheRootsViewModel); panelViewModel = new NowPlayingPanelViewModel(this); panelView = new NowPlayingPanelView(panelViewModel); panelViewModel.ResetShowState(); topPanelViewModel = new TopPanelViewModel(this); topPanelView = new TopPanelView(topPanelViewModel); topPanelItem = new TopPanelItem() { Title = GetResourceString("LOCNowPlayingTopPanelToolTip"), Icon = new TopPanelView(topPanelViewModel), Visible = false }; this.sidebarIcon = new Rectangle() { Fill = (Brush)PlayniteApi.Resources.GetResource("TextBrush"), Width = 256, Height = 256, OpacityMask = new ImageBrush() { ImageSource = ImageUtils.BitmapToBitmapImage(Resources.now_playing_icon) } }; this.sidebarItem = new SidebarItem() { Type = SiderbarItemType.View, Title = GetResourceString("LOCNowPlayingSideBarToolTip"), Visible = true, ProgressValue = 0, Icon = sidebarIcon, Opened = () => { sidebarIcon.Fill = (Brush)PlayniteApi.Resources.GetResource("GlyphBrush"); return panelView; }, Closed = () => sidebarIcon.Fill = (Brush)PlayniteApi.Resources.GetResource("TextBrush") }; } public void UpdateSettings(NowPlayingSettings settings) { Settings = settings; settingsViewModel.Settings = settings; } public override ISettings GetSettings(bool firstRunSettings) { return new NowPlayingSettingsViewModel(this); } public override UserControl GetSettingsView(bool firstRunSettings) { return new NowPlayingSettingsView(null); } public override void OnApplicationStarted(OnApplicationStartedEventArgs args) { cacheManager.LoadCacheRootsFromJson(); cacheRootsViewModel.RefreshCacheRoots(); cacheManager.LoadInstallAverageBpsFromJson(); cacheManager.LoadGameCacheEntriesFromJson(); cacheRootsViewModel.RefreshCacheRoots(); PlayniteApi.Database.Games.ItemCollectionChanged += CheckForRemovedNowPlayingGames; Task.Run(() => CheckForFixableGameCacheIssuesAsync()); // . if applicable, restore cache install queue state TryRestoreCacheInstallQueueState(); } public class InstallerInfo { public string title; public string cacheId; public int speedLimitIpg; public InstallerInfo() { this.title = string.Empty; this.cacheId = string.Empty; this.speedLimitIpg = 0; } } public void SaveCacheInstallQueueToJson() { Queue<InstallerInfo> installerRestoreQueue = new Queue<InstallerInfo>(); foreach (var ci in cacheInstallQueue) { var ii = new InstallerInfo() { title = ci.gameCache.Title, cacheId = ci.gameCache.Id, speedLimitIpg = ci.speedLimitIpg }; installerRestoreQueue.Enqueue(ii); } try { File.WriteAllText(cacheInstallQueueStateJsonPath, Serialization.ToJson(installerRestoreQueue)); } catch (Exception ex) { logger.Error($"SaveInstallerQueueToJson to '{cacheInstallQueueStateJsonPath}' failed: {ex.Message}"); } } public void TryRestoreCacheInstallQueueState() { if (File.Exists(cacheInstallQueueStateJsonPath)) { logger.Info("Attempting to restore cache installation queue state..."); var installersInfoList = new List<InstallerInfo>(); try { installersInfoList = Serialization.FromJsonFile<List<InstallerInfo>>(cacheInstallQueueStateJsonPath); } catch (Exception ex) { logger.Error($"TryRestoreCacheInstallQueueState from '{cacheInstallQueueStateJsonPath}' failed: {ex.Message}"); } foreach (var ii in installersInfoList) { if (!CacheHasInstallerQueued(ii.cacheId)) { if (cacheManager.GameCacheExists(ii.cacheId)) { var nowPlayingGame = FindNowPlayingGame(ii.cacheId); var gameCache = cacheManager.FindGameCache(ii.cacheId); if (nowPlayingGame != null && gameCache != null) { NotifyInfo($"Restored cache install/queue state of '{gameCache.Title}'"); var controller = new NowPlayingInstallController(this, nowPlayingGame, gameCache, SpeedLimitIpg); controller.Install(new InstallActionArgs()); } } } } File.Delete(cacheInstallQueueStateJsonPath); } } public override void OnApplicationStopped(OnApplicationStoppedEventArgs args) { // Add code to be executed when Playnite is shutting down. if (cacheInstallQueue.Count > 0) { // . create install queue details file, so it can be restored on Playnite restart. SaveCacheInstallQueueToJson(); var title = cacheInstallQueue.First().gameCache.Title; logger.Warn($"Playnite exit detected: pausing game cache installation of '{title}'..."); cacheInstallQueuePaused = true; cacheInstallQueue.First().PauseInstallOnPlayniteExit(); } cacheManager.Shutdown(); } public override void OnGameStarted(OnGameStartedEventArgs args) { // Add code to be executed when sourceGame is started running. if (args.Game.PluginId == Id) { Game nowPlayingGame = args.Game; string cacheId = nowPlayingGame.SourceId.ToString(); if (cacheManager.GameCacheExists(cacheId)) { cacheManager.SetGameCacheAndDirStateAsPlayed(cacheId); } } IsGamePlaying = true; // Save relevant settings just in case the are changed while a game is playing WhilePlayingMode = Settings.WhilePlayingMode; SpeedLimitIpg = WhilePlayingMode == WhilePlaying.SpeedLimit ? Settings.SpeedLimitIpg : 0; if (WhilePlayingMode == WhilePlaying.Pause) { PauseCacheInstallQueue(); } else if (SpeedLimitIpg > 0) { SpeedLimitCacheInstalls(SpeedLimitIpg); } panelViewModel.RefreshGameCaches(); } public override void OnGameStopped(OnGameStoppedEventArgs args) { base.OnGameStopped(args); if (IsGamePlaying) { IsGamePlaying = false; if (WhilePlayingMode == WhilePlaying.Pause) { ResumeCacheInstallQueue(); } else if (SpeedLimitIpg > 0) { SpeedLimitIpg = 0; ResumeFullSpeedCacheInstalls(); } panelViewModel.RefreshGameCaches(); } } public void CheckForRemovedNowPlayingGames(object o, ItemCollectionChangedEventArgs<Game> args) { if (args.RemovedItems.Count > 0) { foreach (var game in args.RemovedItems) { if (game != null && cacheManager.GameCacheExists(game.Id.ToString())) { var gameCache = cacheManager.FindGameCache(game.Id.ToString()); if (gameCache.CacheSize > 0) { NotifyWarning(FormatResourceString("LOCNowPlayingRemovedEnabledGameNonEmptyCacheFmt", game.Name)); } else { NotifyWarning(FormatResourceString("LOCNowPlayingRemovedEnabledGameFmt", game.Name)); } DirectoryUtils.DeleteDirectory(gameCache.CacheDir); cacheManager.RemoveGameCache(gameCache.Id); } } } } public async void CheckForFixableGameCacheIssuesAsync() { await CheckForBrokenNowPlayingGamesAsync(); CheckForOrphanedCacheDirectories(); } public async Task CheckForBrokenNowPlayingGamesAsync() { bool foundBroken = false; foreach (var game in PlayniteApi.Database.Games.Where(g => g.PluginId == this.Id)) { string cacheId = game.Id.ToString(); if (cacheManager.GameCacheExists(cacheId)) { // . check game platform and correct if necessary var platform = GetGameCachePlatform(game); var gameCache = cacheManager.FindGameCache(cacheId); if (gameCache.entry.Platform != platform) { logger.Warn($"Corrected {game.Name}'s game cache platform encoding: {gameCache.Platform} → {platform}"); gameCache.entry.Platform = platform; foundBroken = true; } } else { topPanelViewModel.NowProcessing(true, GetResourceString("LOCNowPlayingCheckBrokenGamesProgress")); // . NowPlaying game is missing the supporting game cache... attempt to recreate it if (await TryRecoverMissingGameCacheAsync(cacheId, game)) { NotifyWarning(FormatResourceString("LOCNowPlayingRestoredCacheInfoFmt", game.Name)); foundBroken = true; } else { NotifyWarning(FormatResourceString("LOCNowPlayingUnabletoRestoreCacheInfoFmt", game.Name), () => { string nl = Environment.NewLine; string caption = GetResourceString("LOCNowPlayingConfirmationCaption"); string message = FormatResourceString("LOCNowPlayingUnabletoRestoreCacheInfoFmt", game.Name) + "." + nl + nl; message += GetResourceString("LOCNowPlayingDisableBrokenGameCachingPrompt"); if (PlayniteApi.Dialogs.ShowMessage(message, caption, MessageBoxButton.YesNo) == MessageBoxResult.Yes) { DisableNowPlayingGameCaching(game); } }); } } } if (foundBroken) { cacheManager.SaveGameCacheEntriesToJson(); } topPanelViewModel.NowProcessing(false, GetResourceString("LOCNowPlayingCheckBrokenGamesProgress")); } public void CheckForOrphanedCacheDirectories() { foreach (var root in cacheManager.CacheRoots) { foreach (var subDir in DirectoryUtils.GetSubDirectories(root.Directory)) { string possibleCacheDir = Path.Combine(root.Directory, subDir); if (!cacheManager.IsGameCacheDirectory(possibleCacheDir)) { NotifyWarning(FormatResourceString("LOCNowPlayingUnknownOrphanedDirectoryFoundFmt2", subDir, root.Directory), () => { string caption = GetResourceString("LOCNowPlayingUnknownOrphanedDirectoryCaption"); string message = FormatResourceString("LOCNowPlayingUnknownOrphanedDirectoryMsgFmt", possibleCacheDir); if (PlayniteApi.Dialogs.ShowMessage(message, caption, MessageBoxButton.YesNo) == MessageBoxResult.Yes) { DirectoryUtils.DeleteDirectory(possibleCacheDir); } }); } } } } private class DummyInstaller : InstallController { public DummyInstaller(Game game) : base(game) { } public override void Install(InstallActionArgs args) { } } public override IEnumerable<InstallController> GetInstallActions(GetInstallActionsArgs args) { if (args.Game.PluginId != Id) return null; Game nowPlayingGame = args.Game; string cacheId = nowPlayingGame.Id.ToString(); if (!CacheHasInstallerQueued(cacheId)) { if (cacheManager.GameCacheExists(cacheId)) { var gameCache = cacheManager.FindGameCache(cacheId); if (gameCache.CacheWillFit) { var controller = new NowPlayingInstallController(this, nowPlayingGame, gameCache, SpeedLimitIpg); return new List<InstallController> { controller }; } else { string nl = Environment.NewLine; string message = FormatResourceString("LOCNowPlayingCacheWillNotFitFmt2", gameCache.Title, gameCache.CacheDir); message += nl + nl + GetResourceString("LOCNowPlayingCacheWillNotFitMsg"); PopupError(message); return new List<InstallController> { new DummyInstaller(nowPlayingGame) }; } } else { logger.Error($"Game cache information missing for '{nowPlayingGame.Name}'; skipping installation."); return new List<InstallController> { new DummyInstaller(nowPlayingGame) }; } } else { return new List<InstallController> { new DummyInstaller(nowPlayingGame) }; } } private class DummyUninstaller : UninstallController { public DummyUninstaller(Game game) : base(game) { } public override void Uninstall(UninstallActionArgs args) { } } public override void OnLibraryUpdated(OnLibraryUpdatedEventArgs args) { base.OnLibraryUpdated(args); } public override IEnumerable<UninstallController> GetUninstallActions(GetUninstallActionsArgs args) { if (args.Game.PluginId != Id) return null; Game nowPlayingGame = args.Game; string cacheId = nowPlayingGame.Id.ToString(); if (!CacheHasUninstallerQueued(cacheId)) { if (cacheManager.GameCacheExists(cacheId)) { return new List<UninstallController> { new NowPlayingUninstallController(this, nowPlayingGame, cacheManager.FindGameCache(cacheId)) }; } else { logger.Error($"Game cache information missing for '{nowPlayingGame.Name}'; skipping uninstall."); return new List<UninstallController> { new DummyUninstaller(nowPlayingGame) }; } } else { return new List<UninstallController> { new DummyUninstaller(nowPlayingGame) }; } } public async Task<bool> TryRecoverMissingGameCacheAsync(string cacheId, Game nowPlayingGame) { string title = nowPlayingGame.Name; string installDir = null; string exePath = null; string xtraArgs = null; var previewPlayAction = GetPreviewPlayAction(nowPlayingGame); var nowPlayingAction = GetNowPlayingAction(nowPlayingGame); var platform = GetGameCachePlatform(nowPlayingGame); switch (platform) { case GameCachePlatform.WinPC: installDir = previewPlayAction?.WorkingDir; exePath = GetIncrementalExePath(nowPlayingAction, nowPlayingGame) ?? GetIncrementalExePath(previewPlayAction, nowPlayingGame); xtraArgs = nowPlayingAction?.Arguments ?? previewPlayAction?.Arguments; break; case GameCachePlatform.PS2: case GameCachePlatform.PS3: case GameCachePlatform.Xbox: case GameCachePlatform.X360: case GameCachePlatform.GameCube: case GameCachePlatform.Wii: case GameCachePlatform.Switch: exePath = GetIncrementalRomPath(nowPlayingGame.Roms?.First()?.Path, nowPlayingGame.InstallDirectory, nowPlayingGame); var exePathIndex = previewPlayAction.Arguments.IndexOf(exePath); if (exePathIndex > 1) { // Note 1: skip leading '"' installDir = DirectoryUtils.TrimEndingSlash(previewPlayAction.Arguments.Substring(1, exePathIndex - 1)); // 1. } xtraArgs = nowPlayingAction?.AdditionalArguments; break; default: break; } if (installDir != null && exePath != null && await CheckIfGameInstallDirIsAccessibleAsync(title, installDir)) { // . Separate cacheDir into its cacheRootDir and cacheSubDir components, assuming nowPlayingGame matching Cache RootDir exists. (string cacheRootDir, string cacheSubDir) = cacheManager.FindCacheRootAndSubDir(nowPlayingGame.InstallDirectory); if (cacheRootDir != null && cacheSubDir != null) { cacheManager.AddGameCache(cacheId, title, installDir, exePath, xtraArgs, cacheRootDir, cacheSubDir, platform: platform); // . the best we can do is assume the current size on disk are all installed bytes (completed files) var gameCache = cacheManager.FindGameCache(cacheId); gameCache.entry.UpdateCacheDirStats(); gameCache.entry.CacheSize = gameCache.entry.CacheSizeOnDisk; gameCache.UpdateCacheSize(); return true; } else { return false; } } else { return false; } } public class SelectedGamesContext { private readonly NowPlaying plugin; public bool allEligible; public bool allEnabled; public bool allEnabledAndEmpty; public int count; public SelectedGamesContext(NowPlaying plugin, List<Game> games) { this.plugin = plugin; UpdateContext(games); } private void ResetContext() { allEligible = true; allEnabled = true; allEnabledAndEmpty = true; count = 0; } public void UpdateContext(List<Game> games) { ResetContext(); foreach (var game in games) { bool isEnabled = plugin.IsGameNowPlayingEnabled(game); bool isEligible = !isEnabled && plugin.IsGameNowPlayingEligible(game) != GameCachePlatform.InEligible; bool isEnabledAndEmpty = isEnabled && plugin.cacheManager.FindGameCache(game.Id.ToString())?.CacheSize == 0; allEligible &= isEligible; allEnabled &= isEnabled; allEnabledAndEmpty &= isEnabledAndEmpty; count++; } } } public override IEnumerable<GameMenuItem> GetGameMenuItems(GetGameMenuItemsArgs args) { var gameMenuItems = new List<GameMenuItem>(); // . get selected games context var context = new SelectedGamesContext(this, args.Games); // . Enable game caching menu if (context.allEligible) { string description = "NowPlaying: "; if (context.count > 1) { description += FormatResourceString("LOCNowPlayingEnableGameCachesFmt", context.count); } else { description += GetResourceString("LOCNowPlayingEnableGameCache"); } if (cacheManager.CacheRoots.Count > 1) { foreach (var cacheRoot in cacheManager.CacheRoots) { gameMenuItems.Add(new GameMenuItem { Icon = LibraryIcon, MenuSection = description, Description = GetResourceString("LOCNowPlayingTermsTo") + " " + cacheRoot.Directory, Action = async (a) => { foreach (var game in args.Games) { await EnableNowPlayingWithRootAsync(game, cacheRoot); } } }); } } else { var cacheRoot = cacheManager.CacheRoots.First(); gameMenuItems.Add(new GameMenuItem { Icon = LibraryIcon, Description = description, Action = async (a) => { foreach (var game in args.Games) { await EnableNowPlayingWithRootAsync(game, cacheRoot); } } }); } } // . Disable game caching menu else if (context.allEnabledAndEmpty) { string description = "NowPlaying: "; if (context.count > 1) { description += FormatResourceString("LOCNowPlayingDisableGameCachesFmt", context.count); } else { description += GetResourceString("LOCNowPlayingDisableGameCache"); } gameMenuItems.Add(new GameMenuItem { Icon = LibraryIcon, Description = description, Action = (a) => { foreach (var game in args.Games) { DisableNowPlayingGameCaching(game); cacheManager.RemoveGameCache(game.Id.ToString()); NotifyInfo(FormatResourceString("LOCNowPlayingMsgGameCachingDisabledFmt", game.Name)); } } }); } return gameMenuItems; } public override IEnumerable<SidebarItem> GetSidebarItems() { return new List<SidebarItem> { sidebarItem }; } /// <summary> /// Gets top panel items provided by this plugin. /// </summary> /// <returns></returns> public override IEnumerable<TopPanelItem> GetTopPanelItems() { return new List<TopPanelItem> { topPanelItem }; } public GameCachePlatform IsGameNowPlayingEligible(Game game) { bool preReq = ( game != null && game.PluginId == Guid.Empty && game.IsInstalled && game.IsCustomGame && game.Platforms?.Count == 1 && game.GameActions?.Where(a => a.IsPlayAction).Count() == 1 ); if (preReq && game.Platforms?.First().SpecificationId == "pc_windows" && (game.Roms == null || game.Roms?.Count == 0) && GetIncrementalExePath(game.GameActions?[0], game) != null) { return GameCachePlatform.WinPC; } else if (preReq && game.Roms?.Count == 1 && game.GameActions?[0].Type == GameActionType.Emulator && game.GameActions?[0].EmulatorId != Guid.Empty && game.GameActions?[0].OverrideDefaultArgs == false && GetIncrementalRomPath(game.Roms?[0].Path, game.InstallDirectory, game) != null) { return GetGameCachePlatform(game); } else { return GameCachePlatform.InEligible; } } static public GameCachePlatform GetGameCachePlatform(Game game) { var specId = game?.Platforms?.First().SpecificationId; if (specId == "pc_windows") { return GameCachePlatform.WinPC; } else if (specId == "sony_playstation2") { return GameCachePlatform.PS2; } else if (specId == "sony_playstation3") { return GameCachePlatform.PS3; } else if (specId == "xbox") { return GameCachePlatform.Xbox; } else if (specId == "xbox360") { return GameCachePlatform.X360; } else if (specId == "nintendo_gamecube") { return GameCachePlatform.GameCube; } else if (specId == "nintendo_wii") { return GameCachePlatform.Wii; } else if (specId == "nintendo_switch") { return GameCachePlatform.Switch; } else { return GameCachePlatform.InEligible; } } public bool IsGameNowPlayingEnabled(Game game) { return game.PluginId == this.Id && cacheManager.GameCacheExists(game.Id.ToString()); } public async Task EnableNowPlayingWithRootAsync(Game game, CacheRootViewModel cacheRoot) { string cacheId = game.Id.ToString(); // . Already a NowPlaying enabled game // -> change cache cacheRoot, if applicable // if (cacheManager.GameCacheExists(cacheId)) { var gameCache = cacheManager.FindGameCache(cacheId); if (gameCache.cacheRoot != cacheRoot) { bool noCacheDirOrEmpty = !Directory.Exists(gameCache.CacheDir) || DirectoryUtils.IsEmptyDirectory(gameCache.CacheDir); if (gameCache.IsUninstalled() && noCacheDirOrEmpty) { // . delete old, empty cache dir, if necessary if (Directory.Exists(gameCache.CacheDir)) { Directory.Delete(gameCache.CacheDir); } // . change cache cacheRoot, get updated cache directory (located under new cacheRoot) string cacheDir = cacheManager.ChangeGameCacheRoot(gameCache, cacheRoot); // . game install directory is now the NowPlaying cache directory game.InstallDirectory = cacheDir; GameAction playAction = GetNowPlayingAction(game); if (playAction != null) { // . Update play action Path/Work to point to new cache cacheRoot playAction.Path = Path.Combine(cacheDir, gameCache.ExePath); playAction.WorkingDir = cacheDir; // . Update whether game cache is currently installed or not game.IsInstalled = cacheManager.IsGameCacheInstalled(cacheId); PlayniteApi.Database.Games.Update(game); } else { PopupError(FormatResourceString("LOCNowPlayingPlayActionNotFoundFmt", game.Name)); } } else { PopupError(FormatResourceString("LOCNowPlayingNonEmptyRerootAttemptedFmt", game.Name)); } } } else if (await CheckIfGameInstallDirIsAccessibleAsync(game.Name, game.InstallDirectory)) { if (CheckAndConfirmOrAdjustInstallDirDepth(game)) { // . Enable source game for NowPlaying game caching (new NowPlayingGameEnabler(this, game, cacheRoot.Directory)).Activate(); } } } // . Applies a heuristic test to screen for whether a game's installation directory might be set too deeply. // . Screening is done by checking for 'problematic' subdirectories (e.g. "bin", "x64", etc.) in the // install dir path. // public bool CheckAndConfirmOrAdjustInstallDirDepth(Game game) { string title = game.Name; string installDirectory = DirectoryUtils.CollapseMultipleSlashes(game.InstallDirectory); var platform = GetGameCachePlatform(game); var problematicKeywords = platform == GameCachePlatform.PS3 ? Settings.ProblematicPS3InstDirKeywords : Settings.ProblematicInstallDirKeywords; List<string> matchedSubdirs = new List<string>(); string recommendedInstallDir = string.Empty; foreach (var subDir in installDirectory.Split(Path.DirectorySeparatorChar)) { foreach (var keyword in problematicKeywords) { if (String.Equals(subDir, keyword, StringComparison.OrdinalIgnoreCase)) { matchedSubdirs.Add(subDir); } } if (matchedSubdirs.Count == 0) { if (string.IsNullOrEmpty(recommendedInstallDir)) { recommendedInstallDir = subDir; } else { recommendedInstallDir += Path.DirectorySeparatorChar + subDir; } } } bool continueWithEnable = true; if (matchedSubdirs.Count > 0) { string nl = System.Environment.NewLine; string problematicSubdirs = string.Join("', '", matchedSubdirs); // . See if user wants to adopt the recommended, shallower Install Directory string message = FormatResourceString("LOCNowPlayingProblematicInstallDirFmt3", title, installDirectory, problematicSubdirs); message += nl + nl + FormatResourceString("LOCNowPlayingChangeInstallDirFmt1", recommendedInstallDir); string caption = GetResourceString("LOCNowPlayingConfirmationCaption"); bool changeInstallDir = ( Settings.ChangeProblematicInstallDir_DoWhen == DoWhen.Always || Settings.ChangeProblematicInstallDir_DoWhen == DoWhen.Ask && (PlayniteApi.Dialogs.ShowMessage(message, caption, MessageBoxButton.YesNo) == MessageBoxResult.Yes) ); if (changeInstallDir) { string exePath; string missingExePath; bool success = false; switch (platform) { case GameCachePlatform.WinPC: var sourcePlayAction = GetSourcePlayAction(game); exePath = GetIncrementalExePath(sourcePlayAction); if (sourcePlayAction != null && exePath != null) { missingExePath = installDirectory.Substring(recommendedInstallDir.Length + 1); game.InstallDirectory = recommendedInstallDir; sourcePlayAction.Path = Path.Combine(sourcePlayAction.WorkingDir, missingExePath, exePath); PlayniteApi.Database.Games.Update(game); success = true; } break; case GameCachePlatform.PS2: case GameCachePlatform.PS3: case GameCachePlatform.Xbox: case GameCachePlatform.X360: case GameCachePlatform.GameCube: case GameCachePlatform.Wii: case GameCachePlatform.Switch: var rom = game.Roms?.First(); if (rom != null && (exePath = GetIncrementalRomPath(rom.Path, installDirectory, game)) != null) { missingExePath = installDirectory.Substring(recommendedInstallDir.Length + 1); game.InstallDirectory = recommendedInstallDir; var exePathIndex = rom.Path.IndexOf(exePath); if (exePathIndex > 0) { rom.Path = Path.Combine(rom.Path.Substring(0, exePathIndex), missingExePath, exePath); PlayniteApi.Database.Games.Update(game); success = true; } } break; default: break; } if (success) { NotifyInfo(FormatResourceString("LOCNowPlayingChangedInstallDir", title, recommendedInstallDir)); continueWithEnable = true; } else { PopupError(FormatResourceString("LOCNowPlayingErrorChangingInstallDir", title, recommendedInstallDir)); continueWithEnable = false; } } else { // . See if user wants to continue enabling game, anyway message = FormatResourceString("LOCNowPlayingProblematicInstallDirFmt3", title, installDirectory, problematicSubdirs); message += nl + nl + GetResourceString("LOCNowPlayingConfirmOrEditInstallDir"); message += nl + nl + GetResourceString("LOCNowPlayingProblematicInstallDirConfirm"); continueWithEnable = PlayniteApi.Dialogs.ShowMessage(message, caption, MessageBoxButton.YesNo) == MessageBoxResult.Yes; } } return continueWithEnable; } // . Sanity check: make sure game's InstallDir is accessable (e.g. disk mounted, decrypted, etc?) public async Task<bool> CheckIfGameInstallDirIsAccessibleAsync(string title, string installDir, bool silentMode = false) { if (installDir != null) { // . This can take awhile (e.g. if the install directory is on a network drive and is having connectivity issues) // -> display topPanel status, unless caller is already doing so. // bool showInTopPanel = !topPanelViewModel.IsProcessing; if (showInTopPanel) { topPanelViewModel.NowProcessing(true, GetResourceString("LOCNowPlayingCheckInstallDirAccessibleProgress")); } var installRoot = await DirectoryUtils.TryGetRootDeviceAsync(installDir); var dirExists = await Task.Run(() => Directory.Exists(installDir)); if (showInTopPanel) { topPanelViewModel.NowProcessing(false, GetResourceString("LOCNowPlayingCheckInstallDirAccessibleProgress")); } if (installRoot != null && dirExists) { return true; } else { if (!silentMode) { PopupError(FormatResourceString("LOCNowPlayingGameInstallDirNotFoundFmt2", title, installDir)); } else { logger.Error(FormatResourceString("LOCNowPlayingGameInstallDirNotFoundFmt2", title, installDir)); } return false; } } else { return false; } } public bool EnqueueGameEnablerIfUnique(NowPlayingGameEnabler enabler) { // . enqueue our NowPlaying enabler (but don't add more than once) if (!GameHasEnablerQueued(enabler.Id)) { gameEnablerQueue.Enqueue(enabler); topPanelViewModel.QueuedEnabler(); return true; } return false; } public bool GameHasEnablerQueued(string id) { return gameEnablerQueue.Where(e => e.Id == id).Count() > 0; } public async void DequeueEnablerAndInvokeNextAsync(string id) { // Dequeue the enabler (and sanity check it was ours) var activeId = gameEnablerQueue.Dequeue().Id; Debug.Assert(activeId == id, $"Unexpected game enabler Id at head of the Queue ({activeId})"); // . update status of queued enablers topPanelViewModel.EnablerDoneOrCancelled(); // Invoke next in queue's enabler, if applicable. if (gameEnablerQueue.Count > 0) { await gameEnablerQueue.First().EnableGameForNowPlayingAsync(); } panelViewModel.RefreshGameCaches(); } public bool DisableNowPlayingGameCaching(Game game, string installDir = null, string exePath = null, string xtraArgs = null) { var previewPlayAction = GetPreviewPlayAction(game); var platform = GetGameCachePlatform(game); // . attempt to extract original install and play action parameters, if not provided by caller if (installDir == null || exePath == null) { if (previewPlayAction != null) { switch (platform) { case GameCachePlatform.WinPC: exePath = GetIncrementalExePath(previewPlayAction); installDir = previewPlayAction.WorkingDir; if (xtraArgs == null) { xtraArgs = previewPlayAction.Arguments; } break; case GameCachePlatform.PS2: case GameCachePlatform.PS3: case GameCachePlatform.Xbox: case GameCachePlatform.X360: case GameCachePlatform.GameCube: case GameCachePlatform.Wii: case GameCachePlatform.Switch: exePath = GetIncrementalRomPath(game.Roms?.First()?.Path, game.InstallDirectory, game); var exePathIndex = previewPlayAction.Arguments.IndexOf(exePath); if (exePathIndex > 1) { // Note 1: skip leading '"' installDir = DirectoryUtils.TrimEndingSlash(previewPlayAction.Arguments.Substring(1, exePathIndex - 1)); // 1. } break; default: break; } } } // . restore the game to Playnite library if (installDir != null && exePath != null) { game.InstallDirectory = installDir; game.IsInstalled = true; game.PluginId = Guid.Empty; // restore original Play action (or functionally equivalent): game.GameActions = new ObservableCollection<GameAction>(game.GameActions.Where(a => !a.IsPlayAction && a != previewPlayAction)); switch (platform) { case GameCachePlatform.WinPC: game.GameActions.Add ( new GameAction() { Name = game.Name, Path = Path.Combine("{InstallDir}", exePath), WorkingDir = "{InstallDir}", Arguments = xtraArgs?.Replace(installDir, "{InstallDir}"), IsPlayAction = true } ); break; case GameCachePlatform.PS2: case GameCachePlatform.PS3: case GameCachePlatform.Xbox: case GameCachePlatform.X360: case GameCachePlatform.GameCube: case GameCachePlatform.Wii: case GameCachePlatform.Switch: game.GameActions.Add ( new GameAction() { Name = game.Name, Type = GameActionType.Emulator, EmulatorId = previewPlayAction.EmulatorId, EmulatorProfileId = previewPlayAction.EmulatorProfileId, AdditionalArguments = xtraArgs?.Replace(installDir, "{InstallDir}"), IsPlayAction = true } ); break; default: break; } PlayniteApi.Database.Games.Update(game); return true; } else { return false; } } static public GameAction GetSourcePlayAction(Game game) { var actions = game.GameActions.Where(a => a.IsPlayAction); return actions.Count() == 1 ? actions.First() : null; } static public GameAction GetNowPlayingAction(Game game) { var actions = game.GameActions.Where(a => a.IsPlayAction && a.Name == nowPlayingActionName); return actions.Count() == 1 ? actions.First() : null; } static public GameAction GetPreviewPlayAction(Game game) { var actions = game.GameActions.Where(a => a.Name == previewPlayActionName); return actions.Count() == 1 ? actions.First() : null; } public Game FindNowPlayingGame(string id) { if (!string.IsNullOrEmpty(id)) { var games = PlayniteApi.Database.Games.Where(a => a.PluginId == this.Id && a.Id.ToString() == id); if (games.Count() > 0) { return games.First(); } else { return null; } } else { return null; } } public string GetIncrementalExePath(GameAction action, Game variableReferenceGame = null) { if (action != null) { string work, path; if (variableReferenceGame != null) { work = PlayniteApi.ExpandGameVariables(variableReferenceGame, action.WorkingDir); path = PlayniteApi.ExpandGameVariables(variableReferenceGame, action.Path); } else { work = action.WorkingDir; path = action.Path; } work = DirectoryUtils.CollapseMultipleSlashes(work); path = DirectoryUtils.CollapseMultipleSlashes(path); if (work != null && path != null && work == path.Substring(0, work.Length)) { return path.Substring(DirectoryUtils.TrimEndingSlash(work).Length + 1); } else { return null; } } else { return null; } } public string GetIncrementalRomPath(string romPath, string installDir, Game variableReferenceGame = null) { if (romPath != null && installDir != null) { string work, path; if (variableReferenceGame != null) { work = PlayniteApi.ExpandGameVariables(variableReferenceGame, installDir); path = PlayniteApi.ExpandGameVariables(variableReferenceGame, romPath); } else { work = installDir; path = romPath; } work = DirectoryUtils.CollapseMultipleSlashes(work); path = DirectoryUtils.CollapseMultipleSlashes(path); if (work != null && path != null && work.Length <= path.Length && work == path.Substring(0, work.Length)) { return path.Substring(DirectoryUtils.TrimEndingSlash(work).Length + 1); } else { return null; } } else { return null; } } public string GetInstallQueueStatus(NowPlayingInstallController controller) { // . Return queue index, excluding slot 0, which is the active installation controller int index = cacheInstallQueue.ToList().IndexOf(controller); int size = cacheInstallQueue.Count - 1; if (index > 0) { return string.Format(formatStringXofY, index, size); } else { return null; } } public string GetUninstallQueueStatus(NowPlayingUninstallController controller) { // . Return queue index, excluding slot 0, which is the active installation controller int index = cacheUninstallQueue.ToList().IndexOf(controller); int size = cacheUninstallQueue.Count - 1; if (index > 0) { return string.Format(formatStringXofY, index, size); } else { return null; } } public void UpdateInstallQueueStatuses() { foreach (var controller in cacheInstallQueue.ToList()) { controller.gameCache.UpdateInstallQueueStatus(GetInstallQueueStatus(controller)); } } public void UpdateUninstallQueueStatuses() { foreach (var controller in cacheUninstallQueue.ToList()) { controller.gameCache.UpdateUninstallQueueStatus(GetUninstallQueueStatus(controller)); } } public bool CacheHasInstallerQueued(string cacheId) { return cacheInstallQueue.Where(c => c.gameCache.Id == cacheId).Count() > 0; } public bool CacheHasUninstallerQueued(string cacheId) { return cacheUninstallQueue.Where(c => c.gameCache.Id == cacheId).Count() > 0; } public bool EnqueueCacheInstallerIfUnique(NowPlayingInstallController controller) { // . enqueue our controller (but don't add more than once) if (!CacheHasInstallerQueued(controller.gameCache.Id)) { cacheInstallQueue.Enqueue(controller); topPanelViewModel.QueuedInstall(controller.gameCache.InstallSize, controller.gameCache.InstallEtaTimeSpan); return true; } return false; } public bool EnqueueCacheUninstallerIfUnique(NowPlayingUninstallController controller) { // . enqueue our controller (but don't add more than once) if (!CacheHasUninstallerQueued(controller.gameCache.Id)) { cacheUninstallQueue.Enqueue(controller); topPanelViewModel.QueuedUninstall(); return true; } return false; } public void CancelQueuedInstaller(string cacheId) { if (CacheHasInstallerQueued(cacheId)) { // . remove entry from installer queue var controller = cacheInstallQueue.Where(c => c.gameCache.Id == cacheId).First(); cacheInstallQueue = new Queue<NowPlayingInstallController>(cacheInstallQueue.Where(c => c != controller)); // . update game cache state var gameCache = cacheManager.FindGameCache(cacheId); gameCache.UpdateInstallQueueStatus(null); UpdateInstallQueueStatuses(); topPanelViewModel.CancelledFromInstallQueue(gameCache.InstallSize, gameCache.InstallEtaTimeSpan); panelViewModel.RefreshGameCaches(); } } public async void DequeueInstallerAndInvokeNextAsync(string cacheId) { // Dequeue the controller (and sanity check it was ours) var activeId = cacheInstallQueue.Dequeue().gameCache.Id; Debug.Assert(activeId == cacheId, $"Unexpected install controller cacheId at head of the Queue ({activeId})"); // . update install queue status of queued installers & top panel status UpdateInstallQueueStatuses(); topPanelViewModel.InstallDoneOrCancelled(); // Invoke next in queue's controller, if applicable. if (cacheInstallQueue.Count > 0 && !cacheInstallQueuePaused) { await cacheInstallQueue.First().NowPlayingInstallAsync(); } else { topPanelViewModel.TopPanelVisible = false; } } public async void DequeueUninstallerAndInvokeNextAsync(string cacheId) { // Dequeue the controller (and sanity check it was ours) var activeId = cacheUninstallQueue.Dequeue().gameCache.Id; Debug.Assert(activeId == cacheId, $"Unexpected uninstall controller cacheId at head of the Queue ({activeId})"); // . update status of queued uninstallers UpdateUninstallQueueStatuses(); topPanelViewModel.UninstallDoneOrCancelled(); // Invoke next in queue's controller, if applicable. if (cacheUninstallQueue.Count > 0) { await cacheUninstallQueue.First().NowPlayingUninstallAsync(); } } private void PauseCacheInstallQueue(Action speedLimitChangeOnPaused = null) { if (cacheInstallQueue.Count > 0) { cacheInstallQueuePaused = true; cacheInstallQueue.First().RequestPauseInstall(speedLimitChangeOnPaused); } } private void ResumeCacheInstallQueue(int speedLimitIpg = 0, bool resumeFromSpeedLimitedMode = false) { cacheInstallQueuePaused = false; if (cacheInstallQueue.Count > 0) { foreach (var controller in cacheInstallQueue) { // . restore top panel queue state topPanelViewModel.QueuedInstall(controller.gameCache.InstallSize, controller.gameCache.InstallEtaTimeSpan); // . update transfer speed controller.speedLimitIpg = speedLimitIpg; } string title = cacheInstallQueue.First().gameCache.Title; if (speedLimitIpg > 0) { if (Settings.NotifyOnInstallWhilePlayingActivity) { NotifyInfo(FormatResourceString("LOCNowPlayingContinueWithSpeedLimitFmt2", title, speedLimitIpg)); } else { logger.Info($"Game started: NowPlaying installation for '{title}' continuing at limited speed (IPG={speedLimitIpg})."); } } else if (resumeFromSpeedLimitedMode) { if (Settings.NotifyOnInstallWhilePlayingActivity) { NotifyInfo(FormatResourceString("LOCNowPlayingContinueAtFullSpeedFmt", title)); } else { logger.Info($"Game stopped; NowPlaying installation for '{title}' continuing at full speed."); } } else { if (Settings.NotifyOnInstallWhilePlayingActivity) { NotifyInfo(FormatResourceString("LOCNowPlayingResumeGameStoppedFmt", title)); } else { logger.Info($"Game stopped; NowPlaying installation resumed for '{title}'."); } } cacheInstallQueue.First().progressViewModel.PrepareToInstall(speedLimitIpg); Task.Run(() => cacheInstallQueue.First().NowPlayingInstallAsync()); } } private void SpeedLimitCacheInstalls(int speedLimitIpg) { PauseCacheInstallQueue(() => ResumeCacheInstallQueue(speedLimitIpg: speedLimitIpg)); } private void ResumeFullSpeedCacheInstalls() { PauseCacheInstallQueue(() => ResumeCacheInstallQueue(resumeFromSpeedLimitedMode: true)); } public string GetResourceString(string key) { return key != null ? PlayniteApi.Resources.GetString(key) : null; } public string GetResourceFormatString(string key, int formatItemCount) { if (key != null) { string formatString = PlayniteApi.Resources.GetString(key); bool validFormat = !string.IsNullOrEmpty(formatString); for (int fi = 0; validFormat && fi < formatItemCount; fi++) { validFormat &= formatString.Contains("{" + fi + "}"); } if (validFormat) { return formatString; } else if (formatItemCount > 1) { PopupError($"Bad resource: key='{key}', value='{formatString}'; must contain '{{0}} - '{{{formatItemCount - 1}}}' patterns"); return null; } else { PopupError($"Bad resource: key='{key}', value='{formatString}'; must contain '{{0}}' pattern"); return null; } } return null; } public string FormatResourceString(string key, params object[] formatItems) { string formatString = GetResourceFormatString(key, formatItems.Count()); return formatString != null ? string.Format(formatString, formatItems) : null; } public void NotifyInfo(string message) { logger.Info(message); PlayniteApi.Notifications.Add(Guid.NewGuid().ToString(), message, NotificationType.Info); } public void NotifyWarning(string message, Action action = null) { logger.Warn(message); var notification = new NotificationMessage(Guid.NewGuid().ToString(), message, NotificationType.Info, action); PlayniteApi.Notifications.Add(notification); } public void NotifyError(string message, Action action = null) { logger.Error(message); var notification = new NotificationMessage(Guid.NewGuid().ToString(), message, NotificationType.Error, action); PlayniteApi.Notifications.Add(notification); } public void PopupError(string message) { logger.Error(message); PlayniteApi.Dialogs.ShowMessage(message, "NowPlaying Error:"); } public string SaveJobErrorLogAndGetMessage(GameCacheJob job, string logFileSuffix) { string seeLogFile = ""; if (job.errorLog != null) { // save error log string errorLogsDir = Path.Combine(GetPluginUserDataPath(), "errorLogs"); string errorLogFile = Path.Combine(errorLogsDir, job.entry.Id + " " + DirectoryUtils.ToSafeFileName(job.entry.Title) + logFileSuffix); if (DirectoryUtils.MakeDir(errorLogsDir)) { try { const int showMaxErrorLineCount = 10; File.Create(errorLogFile)?.Dispose(); File.WriteAllLines(errorLogFile, job.errorLog); string nl = System.Environment.NewLine; seeLogFile = nl + $"(See {errorLogFile})"; seeLogFile += nl + nl; seeLogFile += $"Last {Math.Min(showMaxErrorLineCount, job.errorLog.Count())} lines:" + nl; // . show at most the last 'showMaxErrorLineCount' lines of the error log in the popup foreach (var err in job.errorLog.Skip(Math.Max(0, job.errorLog.Count() - showMaxErrorLineCount))) { seeLogFile += err + nl; } } catch { } } } return seeLogFile; } } }
source/NowPlaying.cs
gittromney-Playnite-NowPlaying-23eec41
[ { "filename": "source/NowPlayingInstallController.cs", "retrieved_chunk": " public readonly RoboStats jobStats;\n public readonly GameCacheViewModel gameCache;\n public readonly GameCacheManagerViewModel cacheManager;\n public readonly InstallProgressViewModel progressViewModel;\n public readonly InstallProgressView progressView;\n private Action onPausedAction;\n public int speedLimitIpg;\n private bool deleteCacheOnJobCancelled { get; set; } = false;\n private bool pauseOnPlayniteExit { get; set; } = false;\n public NowPlayingInstallController(NowPlaying plugin, Game nowPlayingGame, GameCacheViewModel gameCache, int speedLimitIpg = 0) ", "score": 0.9391852617263794 }, { "filename": "source/NowPlayingGameEnabler.cs", "retrieved_chunk": "{\n public class NowPlayingGameEnabler\n {\n private readonly ILogger logger = NowPlaying.logger;\n private readonly NowPlaying plugin;\n private readonly IPlayniteAPI PlayniteApi;\n private readonly GameCacheManagerViewModel cacheManager;\n private readonly Game game;\n private readonly string cacheRootDir;\n public string Id => game.Id.ToString();", "score": 0.9001331925392151 }, { "filename": "source/ViewModels/GameCacheManagerViewModel.cs", "retrieved_chunk": " private readonly string gameCacheEntriesJsonPath;\n private readonly string installAverageBpsJsonPath;\n public readonly GameCacheManager gameCacheManager;\n public ObservableCollection<CacheRootViewModel> CacheRoots { get; private set; }\n public ObservableCollection<GameCacheViewModel> GameCaches { get; private set; }\n public SortedDictionary<string, long> InstallAverageBps { get; private set; }\n public GameCacheManagerViewModel(NowPlaying plugin, ILogger logger)\n {\n this.plugin = plugin;\n this.logger = logger;", "score": 0.8997435569763184 }, { "filename": "source/ViewModels/AddCacheRootViewModel.cs", "retrieved_chunk": "{\n public class AddCacheRootViewModel : ViewModelBase\n {\n private readonly NowPlaying plugin;\n private readonly GameCacheManagerViewModel cacheManager;\n private Dictionary<string, string> rootDevices;\n private List<string> existingRoots;\n public Window popup { get; set; }\n public bool DeviceIsValid { get; private set; }\n public bool RootIsValid { get; private set; }", "score": 0.8943187594413757 }, { "filename": "source/NowPlayingUninstallController.cs", "retrieved_chunk": "{\n public class NowPlayingUninstallController : UninstallController\n {\n private readonly ILogger logger = NowPlaying.logger;\n private readonly NowPlaying plugin;\n private readonly NowPlayingSettings settings;\n private readonly IPlayniteAPI PlayniteApi;\n private readonly GameCacheManagerViewModel cacheManager;\n private readonly Game nowPlayingGame;\n private readonly string cacheDir;", "score": 0.8902766704559326 } ]
csharp
NowPlayingGameEnabler> gameEnablerQueue;
using System.Collections.Generic; using UnityEditor; using UnityEditor.Timeline; using UnityEngine; using UnityEngine.Timeline; namespace dev.kemomimi.TimelineExtension.AbstractValueControlTrack.Editor { internal static class AbstractColorValueControlTrackEditorUtility { internal static Color PrimaryColor = new(0.5f, 0.5f, 1f); } [CustomTimelineEditor(typeof(AbstractColorValueControlTrack))] public class AbstractColorValueControlTrackCustomEditor : TrackEditor { public override TrackDrawOptions GetTrackOptions(TrackAsset track, Object binding) { track.name = "CustomTrack"; var options = base.GetTrackOptions(track, binding); options.trackColor = AbstractColorValueControlTrackEditorUtility.PrimaryColor; return options; } } [CustomTimelineEditor(typeof(
AbstractColorValueControlClip))] public class AbstractColorValueControlCustomEditor : ClipEditor {
Dictionary<AbstractColorValueControlClip, Texture2D> textures = new(); public override ClipDrawOptions GetClipOptions(TimelineClip clip) { var clipOptions = base.GetClipOptions(clip); clipOptions.icons = null; clipOptions.highlightColor = AbstractColorValueControlTrackEditorUtility.PrimaryColor; return clipOptions; } public override void DrawBackground(TimelineClip clip, ClipBackgroundRegion region) { var tex = GetGradientTexture(clip); if (tex) GUI.DrawTexture(region.position, tex); } public override void OnClipChanged(TimelineClip clip) { GetGradientTexture(clip, true); } Texture2D GetGradientTexture(TimelineClip clip, bool update = false) { var tex = Texture2D.whiteTexture; var customClip = clip.asset as AbstractColorValueControlClip; if (!customClip) return tex; var gradient = customClip.Value; if (gradient == null) return tex; if (update) { textures.Remove(customClip); } else { textures.TryGetValue(customClip, out tex); if (tex) return tex; } var b = (float)(clip.blendInDuration / clip.duration); tex = new Texture2D(128, 1); for (int i = 0; i < tex.width; ++i) { var t = (float)i / tex.width; var color = customClip.Value; //get max color element var max = Mathf.Max(color.r, color.g, color.b); if (max > 1f) { color.r /= max; color.g /= max; color.b /= max; } color.a = 1f; if (b > 0f) color.a = Mathf.Min(t / b, 1f); tex.SetPixel(i, 0, color); } tex.Apply(); if (textures.ContainsKey(customClip)) { textures[customClip] = tex; } else { textures.Add(customClip, tex); } return tex; } } [CanEditMultipleObjects] [CustomEditor(typeof(AbstractColorValueControlClip))] public class AbstractColorValueControlClipEditor : UnityEditor.Editor { public override void OnInspectorGUI() { DrawDefaultInspector(); } } }
Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractColorValueControlTrackCustomEditor.cs
nmxi-Unity_AbstractTimelineExtention-b518049
[ { "filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractBoolValueControlTrackCustomEditor.cs", "retrieved_chunk": " }\n [CustomTimelineEditor(typeof(AbstractBoolValueControlTrack))]\n public class AbstractBoolValueControlTrackCustomEditor : TrackEditor\n {\n public override TrackDrawOptions GetTrackOptions(TrackAsset track, Object binding)\n {\n track.name = \"CustomTrack\";\n var options = base.GetTrackOptions(track, binding);\n options.trackColor = AbstractBoolValueControlTrackEditorUtility.PrimaryColor;\n // Debug.Log(binding.GetType());", "score": 0.92527174949646 }, { "filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractIntValueControlTrackCustomEditor.cs", "retrieved_chunk": " [CustomTimelineEditor(typeof(AbstractIntValueControlTrack))]\n public class AbstractIntValueControlTrackCustomEditor : TrackEditor\n {\n public override TrackDrawOptions GetTrackOptions(TrackAsset track, Object binding)\n {\n track.name = \"CustomTrack\";\n var options = base.GetTrackOptions(track, binding);\n options.trackColor = AbstractIntValueControlTrackEditorUtility.PrimaryColor;\n return options;\n }", "score": 0.9103560447692871 }, { "filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractFloatValueControlTrackCustomEditor.cs", "retrieved_chunk": " [CustomTimelineEditor(typeof(AbstractFloatValueControlTrack))]\n public class AbstractFloatValueControlTrackCustomEditor : TrackEditor\n {\n public override TrackDrawOptions GetTrackOptions(TrackAsset track, Object binding)\n {\n track.name = \"CustomTrack\";\n var options = base.GetTrackOptions(track, binding);\n options.trackColor = AbstractFloatValueControlTrackEditorUtility.PrimaryColor;\n return options;\n }", "score": 0.9077674150466919 }, { "filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractIntValueControlTrackCustomEditor.cs", "retrieved_chunk": " }\n [CustomTimelineEditor(typeof(AbstractIntValueControlClip))]\n public class AbstractIntValueControlCustomEditor : ClipEditor\n {\n public override ClipDrawOptions GetClipOptions(TimelineClip clip)\n {\n var clipOptions = base.GetClipOptions(clip);\n clipOptions.icons = null;\n clipOptions.highlightColor = AbstractIntValueControlTrackEditorUtility.PrimaryColor;\n return clipOptions;", "score": 0.8928415775299072 }, { "filename": "Assets/TimelineExtension/Editor/AbstractValueControlTrackEditor/AbstractFloatValueControlTrackCustomEditor.cs", "retrieved_chunk": " }\n [CustomTimelineEditor(typeof(AbstractFloatValueControlClip))]\n public class AbstractFloatValueControlCustomEditor : ClipEditor\n {\n public override ClipDrawOptions GetClipOptions(TimelineClip clip)\n {\n var clipOptions = base.GetClipOptions(clip);\n clipOptions.icons = null;\n clipOptions.highlightColor = AbstractFloatValueControlTrackEditorUtility.PrimaryColor;\n return clipOptions;", "score": 0.8904504776000977 } ]
csharp
AbstractColorValueControlClip))] public class AbstractColorValueControlCustomEditor : ClipEditor {
using System; using Sandland.SceneTool.Editor.Common.Data; using Sandland.SceneTool.Editor.Common.Utils; using UnityEditor; using UnityEngine.UIElements; namespace Sandland.SceneTool.Editor.Views { internal class ThemeDisplay : RadioButton, IDisposable { public event Action<AssetFileInfo> Selected; private readonly
AssetFileInfo _themeInfo;
public ThemeDisplay(AssetFileInfo themeInfo) : base() { _themeInfo = themeInfo; var visualTree = AssetDatabaseUtils.FindAndLoadVisualTreeAsset(nameof(ThemeDisplay)); visualTree.CloneTree(this); AddToClassList("sandland-theme-button"); var mainStyleSheet = AssetDatabaseUtils.FindAndLoadStyleSheet(nameof(ThemeDisplay)); var styleSheet = AssetDatabase.LoadAssetAtPath<StyleSheet>(themeInfo.Path); styleSheets.Add(mainStyleSheet); styleSheets.Add(styleSheet); label = themeInfo.Name; this.RegisterValueChangedCallback(OnValueChanged); } private void OnValueChanged(ChangeEvent<bool> evt) { if (!evt.newValue) { return; } Selected?.Invoke(_themeInfo); } public void Dispose() { this.UnregisterValueChangedCallback(OnValueChanged); } } }
Assets/SceneTools/Editor/Views/SceneToolsSetupWindow/ThemeDisplay/ThemeDisplay.cs
migus88-Sandland.SceneTools-64e9f8c
[ { "filename": "Assets/SceneTools/Editor/Views/Base/SceneToolsWindowBase.cs", "retrieved_chunk": "using Sandland.SceneTool.Editor.Common.Utils;\nusing Sandland.SceneTool.Editor.Services;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityEngine.UIElements;\nnamespace Sandland.SceneTool.Editor.Views.Base\n{\n internal abstract class SceneToolsWindowBase : EditorWindow\n {\n private const string GlobalStyleSheetName = \"SceneToolsMain\";", "score": 0.9080576300621033 }, { "filename": "Assets/SceneTools/Editor/Views/SceneToolsSetupWindow/Handlers/SceneClassGenerationUiHandler.cs", "retrieved_chunk": "using System.IO;\nusing Sandland.SceneTool.Editor.Common.Utils;\nusing Sandland.SceneTool.Editor.Services;\nusing UnityEditor;\nusing UnityEngine.UIElements;\nnamespace Sandland.SceneTool.Editor.Views.Handlers\n{\n internal class SceneClassGenerationUiHandler : ISceneToolsSetupUiHandler\n {\n private const string HiddenContentClass = \"hidden\";", "score": 0.8961418867111206 }, { "filename": "Assets/SceneTools/Editor/Common/Utils/Icons.cs", "retrieved_chunk": "using System;\nusing Sandland.SceneTool.Editor.Common.Data;\nusing UnityEditor;\nusing UnityEngine;\nnamespace Sandland.SceneTool.Editor.Common.Utils\n{\n internal static class Icons\n {\n private const string IconsRoot = \"Sandland/Images/\";\n public static Texture2D BrightSceneToolIcon => _brightSceneToolIcon ??=", "score": 0.8804007768630981 }, { "filename": "Assets/SceneTools/Editor/Services/ThemesService.cs", "retrieved_chunk": "using System;\nusing System.Linq;\nusing Sandland.SceneTool.Editor.Common.Utils;\nusing UnityEditor;\nusing UnityEngine.UIElements;\nnamespace Sandland.SceneTool.Editor.Services\n{\n internal static class ThemesService\n {\n public const string DefaultThemeStyleSheetName = \"sandland-new-dark\";", "score": 0.8800519704818726 }, { "filename": "Assets/SceneTools/Editor/Views/SceneSelectorWindow/FavoritesButton/FavoritesButton.cs", "retrieved_chunk": "using Sandland.SceneTool.Editor.Common.Data;\nusing Sandland.SceneTool.Editor.Common.Utils;\nusing Sandland.SceneTool.Editor.Services;\nusing UnityEditor;\nusing UnityEngine;\nusing UnityEngine.UIElements;\nnamespace Sandland.SceneTool.Editor.Views\n{\n internal class FavoritesButton : VisualElement\n {", "score": 0.871097207069397 } ]
csharp
AssetFileInfo _themeInfo;
using UnityEngine; namespace SimplestarGame { public class TemplateTexts : MonoBehaviour { [SerializeField] ButtonPressDetection buttonHi; [SerializeField]
ButtonPressDetection buttonHello;
[SerializeField] ButtonPressDetection buttonGood; [SerializeField] ButtonPressDetection buttonOK; [SerializeField] TMPro.TMP_InputField inputField; void Start() { this.buttonHi.onReleased += this.OnClickHi; this.buttonHello.onReleased += this.OnClickHello; this.buttonGood.onReleased += this.OnClickGood; this.buttonOK.onReleased += this.OnClickOK; } void OnClickOK() { this.inputField.text = "OK!"; } void OnClickGood() { this.inputField.text = "Good!"; } void OnClickHello() { this.inputField.text = "Hello."; } void OnClickHi() { this.inputField.text = "Hi."; } } }
Assets/SimplestarGame/Network/Scripts/Sample/TemplateTexts.cs
simplestargame-SimpleChatPhoton-4ebfbd5
[ { "filename": "Assets/SimplestarGame/Network/Scripts/Scene/SceneContext.cs", "retrieved_chunk": "using UnityEngine;\nnamespace SimplestarGame\n{\n public class SceneContext : MonoBehaviour\n {\n [SerializeField] internal NetworkPlayerInput PlayerInput;\n [SerializeField] internal TMPro.TextMeshProUGUI fpsText;\n [SerializeField] internal TMPro.TextMeshProUGUI hostClientText;\n [SerializeField] internal ButtonPressDetection buttonUp;\n [SerializeField] internal ButtonPressDetection buttonDown;", "score": 0.8590278029441833 }, { "filename": "Assets/SimplestarGame/Network/Scripts/Tools/SimpleCameraController.cs", "retrieved_chunk": "#if ENABLE_INPUT_SYSTEM\nusing UnityEngine.InputSystem;\n#endif\nusing UnityEngine;\nnamespace UnityTemplateProjects\n{\n public class SimpleCameraController : MonoBehaviour\n {\n [SerializeField] TMPro.TMP_InputField inputField;\n class CameraState", "score": 0.8242941498756409 }, { "filename": "Assets/SimplestarGame/Network/Scripts/Tools/ButtonPressDetection.cs", "retrieved_chunk": "using UnityEngine;\nusing UnityEngine.EventSystems;\nusing System;\nnamespace SimplestarGame\n{\n public class ButtonPressDetection : MonoBehaviour, IPointerDownHandler, IPointerUpHandler\n {\n internal Action onPressed;\n internal Action onReleased;\n internal bool IsPressed { get; private set; } = false;", "score": 0.8195486068725586 }, { "filename": "Assets/SimplestarGame/Network/Scripts/Tools/FaceCamera.cs", "retrieved_chunk": "using UnityEngine;\nnamespace SimplestarGame\n{\n public class FaceCamera : MonoBehaviour\n {\n void Start()\n {\n this.mainCameraTransform = Camera.main.transform;\n }\n void LateUpdate()", "score": 0.8150075674057007 }, { "filename": "Assets/SimplestarGame/Network/Scripts/Runner/Game/NetworkGame.cs", "retrieved_chunk": "using Fusion;\nusing System;\nusing System.Linq;\nusing UnityEngine;\nnamespace SimplestarGame\n{\n public class NetworkGame : NetworkBehaviour\n {\n [SerializeField] Vector3[] spawnPoints;\n [SerializeField] Color[] playerColors;", "score": 0.8146954774856567 } ]
csharp
ButtonPressDetection buttonHello;
using CommunityToolkit.Mvvm.DependencyInjection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.UI.Xaml; using System; using System.Diagnostics; using System.Linq; using wingman.Interfaces; using wingman.Services; using wingman.Updates; using wingman.ViewModels; using wingman.Views; namespace wingman { public partial class App : Application, IDisposable { private readonly IHost _host; private readonly
AppUpdater _appUpdater;
public App() { InitializeComponent(); UnhandledException += App_UnhandledException; _host = BuildHost(); Ioc.Default.ConfigureServices(_host.Services); _appUpdater = new AppUpdater(); } public void Dispose() { var serviceTypes = _host.Services.GetType().Assembly.GetTypes() .Where(t => t.GetInterfaces().Contains(typeof(IDisposable)) && !t.IsInterface); foreach (var serviceType in serviceTypes) { var serviceInstance = _host.Services.GetService(serviceType); if (serviceInstance is IDisposable disposableService) { disposableService.Dispose(); } } Debug.WriteLine("Services disposed."); _host.Dispose(); Debug.WriteLine("Host disposed."); } private void App_UnhandledException(object sender, Microsoft.UI.Xaml.UnhandledExceptionEventArgs e) { var Logger = Ioc.Default.GetRequiredService<ILoggingService>(); Logger.LogException(e.Exception.ToString()); } protected override void OnLaunched(LaunchActivatedEventArgs args) { base.OnLaunched(args); Ioc.Default.GetRequiredService<StatusWindow>(); // make sure events are initialized Ioc.Default.GetRequiredService<IEventHandlerService>(); // make sure events are initialized IAppActivationService appWindowService = Ioc.Default.GetRequiredService<IAppActivationService>(); appWindowService.Activate(args); MainWindow mw = Ioc.Default.GetRequiredService<MainWindow>(); mw.SetApp(this); _ = _appUpdater.CheckForUpdatesAsync(mw.Dispatcher); } private static IHost BuildHost() => Host.CreateDefaultBuilder() .ConfigureServices((context, services) => { _ = services // Services .AddSingleton<IGlobalHotkeyService, GlobalHotkeyService>() .AddSingleton<ILoggingService, LoggingService>() .AddSingleton<IEventHandlerService, EventHandlerService>() .AddSingleton<IWindowingService, WindowingService>() .AddSingleton<IMicrophoneDeviceService, MicrophoneDeviceService>() .AddSingleton<IEditorService, EditorService>() .AddSingleton<IStdInService, StdInService>() .AddSingleton<ISettingsService, SettingsService>() .AddSingleton<IAppActivationService, AppActivationService>() .AddScoped<IOpenAIAPIService, OpenAIAPIService>() // ViewModels .AddSingleton<AudioInputControlViewModel>() .AddSingleton<OpenAIControlViewModel>() .AddSingleton<MainWindowViewModel>() .AddTransient<ModalControlViewModel>() .AddSingleton<MainPageViewModel>() .AddSingleton<FooterViewModel>() // Views .AddSingleton<StatusWindow>() .AddSingleton<MainWindow>(); }) .Build(); } }
App.xaml.cs
dannyr-git-wingman-41103f3
[ { "filename": "Services/AppActivationService.cs", "retrieved_chunk": "using System;\nusing System.Diagnostics;\nusing wingman.Interfaces;\nusing wingman.Views;\nnamespace wingman.Services\n{\n public class AppActivationService : IAppActivationService, IDisposable\n {\n private readonly MainWindow _mainWindow;\n private readonly ISettingsService _settingsService;", "score": 0.8853013515472412 }, { "filename": "Views/MainPage.xaml.cs", "retrieved_chunk": "using CommunityToolkit.Mvvm.DependencyInjection;\nusing Microsoft.UI.Xaml.Controls;\nusing wingman.ViewModels;\nnamespace wingman.Views\n{\n public sealed partial class MainPage : Page\n {\n public MainPage()\n {\n InitializeComponent();", "score": 0.8297945857048035 }, { "filename": "Views/Controls/ModalControl.xaml.cs", "retrieved_chunk": "using CommunityToolkit.Mvvm.DependencyInjection;\nusing Microsoft.UI.Xaml.Controls;\nusing wingman.ViewModels;\nnamespace wingman.Views\n{\n public sealed partial class ModalControl : UserControl\n {\n public ModalControl()\n {\n InitializeComponent();", "score": 0.8191657662391663 }, { "filename": "Services/LoggingService.cs", "retrieved_chunk": "using System;\nusing System.IO;\nusing System.Runtime.CompilerServices;\nusing wingman.Interfaces;\nusing wingman.Services;\nnamespace wingman.Interfaces\n{\n public interface ILoggingService\n {\n event EventHandler<string> UIOutputHandler;", "score": 0.8120604753494263 }, { "filename": "ViewModels/AudioInputControlViewModel.cs", "retrieved_chunk": "using Windows.Media.Devices;\nusing wingman.Interfaces;\nnamespace wingman.ViewModels\n{\n public class AudioInputControlViewModel : ObservableObject, IDisposable\n {\n private readonly IMicrophoneDeviceService _microphoneDeviceService;\n private readonly ISettingsService _settingsService;\n private List<MicrophoneDevice> _micDevices;\n private readonly DispatcherQueue _dispatcherQueue;", "score": 0.8101257681846619 } ]
csharp
AppUpdater _appUpdater;
#nullable enable using System; using System.IO; using System.Threading; using Cysharp.Threading.Tasks; using Mochineko.ChatGPT_API; using Mochineko.FacialExpressions.Blink; using Mochineko.FacialExpressions.Emotion; using Mochineko.FacialExpressions.Extensions.VRM; using Mochineko.FacialExpressions.LipSync; using Mochineko.FacialExpressions.Samples; using Mochineko.LLMAgent.Chat; using Mochineko.LLMAgent.Emotion; using Mochineko.LLMAgent.Memory; using Mochineko.LLMAgent.Speech; using Mochineko.LLMAgent.Summarization; using Mochineko.Relent.Extensions.NewtonsoftJson; using Mochineko.Relent.Result; using Mochineko.RelentStateMachine; using Mochineko.VOICEVOX_API.QueryCreation; using UnityEngine; using UniVRM10; using VRMShaders; namespace Mochineko.LLMAgent.Operation { internal sealed class DemoOperator : MonoBehaviour { [SerializeField] private Model model = Model.Turbo; [SerializeField, TextArea] private string prompt = string.Empty; [SerializeField, TextArea] private string defaultConversations = string.Empty; [SerializeField, TextArea] private string message = string.Empty; [SerializeField] private int speakerID; [SerializeField] private string vrmAvatarPath = string.Empty; [SerializeField] private float emotionFollowingTime = 1f; [SerializeField] private float emotionWeight = 1f; [SerializeField] private AudioSource? audioSource = null; [SerializeField] private RuntimeAnimatorController? animatorController = null; private IChatMemoryStore? store; private LongTermChatMemory? memory; internal LongTermChatMemory? Memory => memory; private ChatCompletion? chatCompletion; private ChatCompletion? stateCompletion; private VoiceVoxSpeechSynthesis? speechSynthesis; private IFiniteStateMachine<AgentEvent,
AgentContext>? agentStateMachine;
private async void Start() { await SetupAgentAsync(this.GetCancellationTokenOnDestroy()); } private async void Update() { if (agentStateMachine == null) { return; } var updateResult = await agentStateMachine .UpdateAsync(this.GetCancellationTokenOnDestroy()); if (updateResult is IFailureResult updateFailure) { Debug.LogError($"Failed to update agent state machine because -> {updateFailure.Message}."); } } private void OnDestroy() { agentStateMachine?.Dispose(); } private async UniTask SetupAgentAsync(CancellationToken cancellationToken) { if (audioSource == null) { throw new NullReferenceException(nameof(audioSource)); } if (animatorController == null) { throw new NullReferenceException(nameof(animatorController)); } var apiKeyPath = Path.Combine( Application.dataPath, "Mochineko/LLMAgent/Operation/OpenAI_API_Key.txt"); var apiKey = await File.ReadAllTextAsync(apiKeyPath, cancellationToken); if (string.IsNullOrEmpty(apiKey)) { throw new Exception($"[LLMAgent.Operation] Loaded API Key is empty from path:{apiKeyPath}"); } store = new NullChatMemoryStore(); memory = await LongTermChatMemory.InstantiateAsync( maxShortTermMemoriesTokenLength: 1000, maxBufferMemoriesTokenLength: 1000, apiKey, model, store, cancellationToken); chatCompletion = new ChatCompletion( apiKey, model, prompt + PromptTemplate.MessageResponseWithEmotion, memory); if (!string.IsNullOrEmpty(defaultConversations)) { var conversationsDeserializeResult = RelentJsonSerializer .Deserialize<ConversationCollection>(defaultConversations); if (conversationsDeserializeResult is ISuccessResult<ConversationCollection> successResult) { for (var i = 0; i < successResult.Result.Conversations.Count; i++) { await memory.AddMessageAsync( successResult.Result.Conversations[i], cancellationToken); } } else if (conversationsDeserializeResult is IFailureResult<ConversationCollection> failureResult) { Debug.LogError( $"[LLMAgent.Operation] Failed to deserialize default conversations because -> {failureResult.Message}"); } } speechSynthesis = new VoiceVoxSpeechSynthesis(speakerID); var binary = await File.ReadAllBytesAsync( vrmAvatarPath, cancellationToken); var instance = await LoadVRMAsync( binary, cancellationToken); var lipMorpher = new VRMLipMorpher(instance.Runtime.Expression); var lipAnimator = new FollowingLipAnimator(lipMorpher); var emotionMorpher = new VRMEmotionMorpher(instance.Runtime.Expression); var emotionAnimator = new ExclusiveFollowingEmotionAnimator<FacialExpressions.Emotion.Emotion>( emotionMorpher, followingTime: emotionFollowingTime); var eyelidMorpher = new VRMEyelidMorpher(instance.Runtime.Expression); var eyelidAnimator = new SequentialEyelidAnimator(eyelidMorpher); var eyelidAnimationFrames = ProbabilisticEyelidAnimationGenerator.Generate( Eyelid.Both, blinkCount: 20); var agentContext = new AgentContext( eyelidAnimator, eyelidAnimationFrames, lipMorpher, lipAnimator, audioSource, emotionAnimator); agentStateMachine = await AgentStateMachineFactory.CreateAsync( agentContext, cancellationToken); instance .GetComponent<Animator>() .runtimeAnimatorController = animatorController; } // ReSharper disable once InconsistentNaming private static async UniTask<Vrm10Instance> LoadVRMAsync( byte[] binaryData, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return await Vrm10.LoadBytesAsync( bytes: binaryData, canLoadVrm0X: true, controlRigGenerationOption: ControlRigGenerationOption.Generate, showMeshes: true, awaitCaller: new RuntimeOnlyAwaitCaller(), ct: cancellationToken ); } [ContextMenu(nameof(StartChatAsync))] public void StartChatAsync() { ChatAsync(message, this.GetCancellationTokenOnDestroy()) .Forget(); } public async UniTask ChatAsync(string message, CancellationToken cancellationToken) { if (chatCompletion == null) { throw new NullReferenceException(nameof(chatCompletion)); } if (speechSynthesis == null) { throw new NullReferenceException(nameof(speechSynthesis)); } if (agentStateMachine == null) { throw new NullReferenceException(nameof(agentStateMachine)); } string chatResponse; var chatResult = await chatCompletion.CompleteChatAsync(message, cancellationToken); switch (chatResult) { case ISuccessResult<string> chatSuccess: { Debug.Log($"[LLMAgent.Operation] Complete chat message:{chatSuccess.Result}."); chatResponse = chatSuccess.Result; break; } case IFailureResult<string> chatFailure: { Debug.LogError($"[LLMAgent.Operation] Failed to complete chat because of {chatFailure.Message}."); return; } default: throw new ResultPatternMatchException(nameof(chatResult)); } EmotionalMessage emotionalMessage; var deserializeResult = RelentJsonSerializer.Deserialize<EmotionalMessage>(chatResponse); switch (deserializeResult) { case ISuccessResult<EmotionalMessage> deserializeSuccess: { emotionalMessage = deserializeSuccess.Result; break; } case IFailureResult<EmotionalMessage> deserializeFailure: { Debug.LogError( $"[LLMAgent.Operation] Failed to deserialize emotional message:{chatResponse} because of {deserializeFailure.Message}."); return; } default: throw new ResultPatternMatchException(nameof(deserializeResult)); } var emotion = EmotionConverter.ExcludeHighestEmotion(emotionalMessage.Emotion); Debug.Log($"[LLMAgent.Operation] Exclude emotion:{emotion}."); var synthesisResult = await speechSynthesis.SynthesisSpeechAsync( HttpClientPool.PooledClient, emotionalMessage.Message, cancellationToken); switch (synthesisResult) { case ISuccessResult<(AudioQuery query, AudioClip clip)> synthesisSuccess: { agentStateMachine.Context.SpeechQueue.Enqueue(new SpeechCommand( synthesisSuccess.Result.query, synthesisSuccess.Result.clip, new EmotionSample<FacialExpressions.Emotion.Emotion>(emotion, emotionWeight))); if (agentStateMachine.IsCurrentState<AgentIdleState>()) { var sendEventResult = await agentStateMachine.SendEventAsync( AgentEvent.BeginSpeaking, cancellationToken); if (sendEventResult is IFailureResult sendEventFailure) { Debug.LogError( $"[LLMAgent.Operation] Failed to send event because of {sendEventFailure.Message}."); } } break; } case IFailureResult<(AudioQuery query, AudioClip clip)> synthesisFailure: { Debug.Log( $"[LLMAgent.Operation] Failed to synthesis speech because of {synthesisFailure.Message}."); return; } default: return; } } } }
Assets/Mochineko/LLMAgent/Operation/DemoOperator.cs
mochi-neko-llm-agent-sandbox-unity-6521c0b
[ { "filename": "Assets/Mochineko/LLMAgent/Memory/LongTermChatMemory.cs", "retrieved_chunk": " private readonly Queue<Message> shortTermMemories = new();\n internal IEnumerable<Message> ShortTermMemories => shortTermMemories.ToArray();\n private readonly Queue<Message> bufferMemories = new();\n internal IEnumerable<Message> BufferMemories => bufferMemories.ToArray();\n private readonly Summarizer summarizer;\n private readonly IChatMemoryStore store;\n private Message summary;\n internal Message Summary => summary;\n private readonly object lockObject = new();\n public static async UniTask<LongTermChatMemory> InstantiateAsync(", "score": 0.8378938436508179 }, { "filename": "Assets/Mochineko/KoeiromapAPI.Samples/KoeiromapAPISample.cs", "retrieved_chunk": " [SerializeField] private Style style;\n [SerializeField] private AudioSource? audioSource;\n private static readonly HttpClient HttpClient = new();\n private IPolicy<Stream>? policy;\n private void Awake()\n {\n Assert.IsNotNull(audioSource);\n policy = PolicyFactory.BuildPolicy();\n }\n [ContextMenu(nameof(Synthesis))]", "score": 0.8274513483047485 }, { "filename": "Assets/Mochineko/LLMAgent/Summarization/Summarizer.cs", "retrieved_chunk": " public sealed class Summarizer\n {\n private readonly Model model;\n private readonly TikToken tikToken;\n private readonly RelentChatCompletionAPIConnection connection;\n private readonly IChatMemory simpleChatMemory = new SimpleChatMemory();\n private readonly IPolicy<ChatCompletionResponseBody> policy;\n private readonly string summary = string.Empty;\n private const int MaxSummaryTokenLength = 2000;\n public Summarizer(", "score": 0.8223273158073425 }, { "filename": "Assets/Mochineko/LLMAgent/Chat/ChatCompletion.cs", "retrieved_chunk": "{\n public sealed class ChatCompletion\n {\n private readonly Model model;\n private readonly IChatMemory memory;\n private readonly RelentChatCompletionAPIConnection connection;\n private readonly IPolicy<ChatCompletionResponseBody> policy;\n public ChatCompletion(\n string apiKey,\n Model model,", "score": 0.8184064030647278 }, { "filename": "Assets/Mochineko/LLMAgent/Speech/VoiceVoxSpeechSynthesis.cs", "retrieved_chunk": "using UnityEngine;\nnamespace Mochineko.LLMAgent.Speech\n{\n public sealed class VoiceVoxSpeechSynthesis\n {\n private readonly int speakerID;\n private readonly IPolicy<AudioQuery> queryPolicy;\n private readonly IPolicy<Stream> synthesisPolicy;\n public VoiceVoxSpeechSynthesis(\n int speakerID)", "score": 0.8143149614334106 } ]
csharp
AgentContext>? agentStateMachine;
using System; using System.Collections.Generic; using Unity.Collections; using UnityEngine; namespace ZimGui { public class DockWindow { List<string> _names = new (16); List<WObject> _activeWObjects = new (16); public int Index; public bool Opened = true; public void Add(
WObject wObject) {
_activeWObjects.Add(wObject); } public void Clear() { Index = -1; _activeWObjects.Clear(); _names.Clear(); } public static KeyCode OpenKey=KeyCode.Escape; public void Draw() { var lockPosition = false; if (Input.GetKeyDown(OpenKey)) { Opened = true; lockPosition = true; } foreach (var _ in IM.BeginWindow("Dock",new Rect(0,0,100,100),ref Opened,!lockPosition,Coordinate.TopLeft)) { for (var i = 0; i < _activeWObjects.Count; i++) { var o = _activeWObjects[i]; var remove = false; if (!IM.Current.TryGetNextRect(out var rect)) { return; }; var foldWidth = rect.width - IMStyle.SpacedTextHeight; var foldRect = new Rect(rect.xMin, rect.yMin,foldWidth, rect.height); var buttonRect = new Rect(rect.xMin + foldWidth, rect.yMin, IMStyle.SpacedTextHeight, rect.height); if (IM.Button(buttonRect, "-")) { _activeWObjects.RemoveAt(i); IM.WObjects.Add(o); o.Opened = false; break; } if (!IM.Foldout(foldRect, o.Name, o.Opened)) { o.Opened=false; continue; } using (IM.Indent()) { if (! o.DrawAsElement()) { remove = true; } } if (remove) { _activeWObjects.RemoveAtSwapBack(Index); break; } o.Opened=true; } _names.Clear(); foreach (var w in IM.WObjects) { _names.Add(w.Name); } if (IM.InputDropdownButton("Add", _names, ref Index)) { _activeWObjects.Add( IM.WObjects[Index]); IM.WObjects.RemoveAt(Index); } if (IM.InputDropdownButton("Open", _names, ref Index)) { var w = IM.WObjects[Index]; w.Opened = true; var mousePos = IMInput.PointerPosition; w.Rect = new Rect(mousePos.x-50, mousePos.y-100+IMStyle.SpacedTextHeight/2, 100, 100); } } } } }
Assets/ZimGui/DockWindow.cs
Akeit0-ZimGui-Unity-cc82fb9
[ { "filename": "Assets/ZimGui/Window.cs", "retrieved_chunk": "using System;\nusing UnityEngine;\nnamespace ZimGui {\n public class Window {\n public string Name;\n public readonly int WindowID;\n static int _lastWindowID;\n public Rect Rect;\n public Vector2 NextPosition;\n public bool Opened;", "score": 0.8649263381958008 }, { "filename": "Assets/ZimGui/WindowState.cs", "retrieved_chunk": "using System;\nnamespace ZimGui {\n public readonly struct WindowState:IDisposable {\n public readonly bool IsActive;\n public WindowState(bool isActive) {\n IsActive = isActive;\n }\n public void Dispose() {\n if(IsActive)IM.EndWindow();\n }", "score": 0.8339153528213501 }, { "filename": "Assets/ZimGui/IMInput.cs", "retrieved_chunk": "using UnityEngine;\nnamespace ZimGui {\n public enum FocusState {\n NotFocus,\n NewFocus,\n Focus,\n }\n public static class IMInput {\n public struct ModalWindowData {\n public bool IsActive;", "score": 0.8324340581893921 }, { "filename": "Assets/ZimGui/InputFieldData.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing UnityEngine;\nnamespace ZimGui {\n public struct InputFieldData {\n public int Length;\n public int CaretPosition;\n public float FocusTime;\n //public bool IsDelayed;\n // public InputFieldData(int length,bool isDelayed) {", "score": 0.8323332071304321 }, { "filename": "Assets/ZimGui/IM.cs", "retrieved_chunk": " Debug.LogException(e);\n }\n }\n }\n public static List<WObject> WObjects = new (16);\n static List<WObject> _wObjectsCopy = new (16);\n public static void EndFrame() {\n try {\n OnEndFrame?.Invoke();\n }", "score": 0.8242213726043701 } ]
csharp
WObject wObject) {
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Numerics; using Keyframes; using Actors; using System.Diagnostics; using file_reader; using file_editor; using System.IO; namespace PFlender { public partial class Main_Application_Form : Form { Timer timer = new Timer();
File_Reader file_reader = new File_Reader();
File_Writer file_writer = new File_Writer(); int frame = 0; private DateTime lastTime = DateTime.MinValue; Actor_Manager actor_manager = new Actor_Manager(); public Main_Application_Form() { InitializeComponent(); //TEST //actor_manager.Add(new Actor(), "Birne"); //actor_manager.Add(new Actor(), "Apfel"); //actor_manager.Get("Birne").keyframes_manager.Add_Keyframe(10, "bezier", new Vector2(2, 1), 45, new Vector2(2, 1), Color.FromArgb(1, 1, 1, 1), true, "Birnenkey"); //actor_manager.Get("Apfel").keyframes_manager.Add_Keyframe(23, "bezier", new Vector2(2, 111), 3, new Vector2(1, 1), Color.FromArgb(1, 1, 1, 1), true, "Apfelkey"); //actor_manager.Get("Birne").keyframes_manager.Debug_Keyframes(); //actor_manager.Get("Apfel").keyframes_manager.Debug_Keyframes(); timer.Start(); timer.Tick += new EventHandler(timer1_Tick); timer.Interval = 1; file_reader.Read_File(actor_manager); actor_manager.Get("actor1").keyframes_manager.Debug_Keyframes(); actor_manager.Get("act2").keyframes_manager.Debug_Keyframes(); file_writer.Write_File("createtest"); } private void timer1_Tick(object sender, EventArgs e) { frame++; if (DateTime.Now - lastTime >= TimeSpan.FromSeconds(1)) { //Debug.WriteLine(frame); frame = 0; lastTime = DateTime.Now; } } } }
PFlender/PFlender/Main.cs
PFornax-PFlender-1569e05
[ { "filename": "PFlender/file_reader/File_Reader.cs", "retrieved_chunk": "using System.Drawing;\nnamespace file_reader\n{\n public class File_Reader\n {\n\t\t//path the PFlend file is saved in.\n string path = @\"C:\\Users\\Pascal\\Desktop\\...PFlender data\\file testing\\test1.PFlend\";\n public void Read_File(Actor_Manager actor_manager)\n {\n\t\t\tTextReader reader = new StreamReader(path);", "score": 0.7391645908355713 }, { "filename": "PFlender/PFlender/Program.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows.Forms;\nnamespace PFlender\n{\n\tinternal static class Program\n\t{\n\t\t/// <summary>", "score": 0.725561261177063 }, { "filename": "PFlender/PFlender/Main.Designer.cs", "retrieved_chunk": "namespace PFlender\n{\n\tpartial class Main_Application_Form\n\t{\n\t\t/// <summary>\n\t\t/// Required designer variable.\n\t\t/// </summary>\n\t\tprivate System.ComponentModel.IContainer components = null;\n\t\t/// <summary>\n\t\t/// Clean up any resources being used.", "score": 0.7186231017112732 }, { "filename": "PFlender/file_editor/File_Writer.cs", "retrieved_chunk": "{\n\tpublic class File_Writer\n\t{\n\t\tpublic void Write_File(string filename)\n\t\t{\n\t\t\tstring path = $@\"C:\\Users\\Pascal\\Desktop\\...PFlender data\\file testing\\{filename}.PFlend\"; // Replace with your desired file path\n\t\t\tstring app_version = \"a20230426\";\n\t\t\t// Create a new file or overwrite an existing file\n\t\t\tusing (StreamWriter writer = new StreamWriter(path))\n\t\t\t{", "score": 0.7034863233566284 }, { "filename": "PFlender/PFlender/Program.cs", "retrieved_chunk": "\t\t/// The main entry point for the application.\n\t\t/// </summary>\n\t\t[STAThread]\n\t\tstatic void Main()\n\t\t{\n\t\t\tApplication.EnableVisualStyles();\n\t\t\tApplication.SetCompatibleTextRenderingDefault(false);\n\t\t\tApplication.Run(new Main_Application_Form());\n\t\t}\n\t}", "score": 0.6865395307540894 } ]
csharp
File_Reader file_reader = new File_Reader();
using static QuizGenerator.Core.StringUtils; using Word = Microsoft.Office.Interop.Word; using Newtonsoft.Json; namespace QuizGenerator.Core { class QuizParser { private const string QuizStartTag = "~~~ Quiz:"; private const string QuizEndTag = "~~~ Quiz End ~~~"; private const string QuestionGroupTag = "~~~ Question Group:"; private const string QuestionTag = "~~~ Question ~~~"; private const string CorrectAnswerTag = "Correct."; private const string WrongAnswerTag = "Wrong."; private ILogger logger; public QuizParser(ILogger logger) { this.logger = logger; } public QuizDocument Parse(Word.Document doc) { var quiz = new QuizDocument(); quiz.QuestionGroups = new List<QuizQuestionGroup>(); QuizQuestionGroup? group = null; QuizQuestion? question = null; int quizHeaderStartPos = 0; int groupHeaderStartPos = 0; int questionHeaderStartPos = 0; int questionFooterStartPos = 0; Word.Paragraph paragraph; for (int paragraphIndex = 1; paragraphIndex <= doc.Paragraphs.Count; paragraphIndex++) { paragraph = doc.Paragraphs[paragraphIndex]; var text = paragraph.Range.Text.Trim(); if (text.StartsWith(QuizStartTag)) { // ~~~ Quiz: {"VariantsToGenerate":5, "AnswersPerQuestion":4, "Lang":"BG"} ~~~ this.logger.Log("Parsing: " + text, 1); var settings = ParseSettings(text, QuizStartTag); quiz.VariantsToGenerate = settings.VariantsToGenerate; quiz.AnswersPerQuestion = settings.AnswersPerQuestion; quiz.LangCode = settings.Lang; quizHeaderStartPos = paragraph.Range.End; } else if (text.StartsWith(QuestionGroupTag)) { // ~~~ Question Group: { "QuestionsToGenerate": 1, "SkipHeader": true } ~~~ this.logger.Log("Parsing: " + text, 1); SaveQuizHeader(); SaveGroupHeader(); SaveQuestionFooter(); group = new QuizQuestionGroup(); group.Questions = new List<QuizQuestion>(); var settings = ParseSettings(text, QuestionGroupTag); group.QuestionsToGenerate = settings.QuestionsToGenerate; group.SkipHeader = settings.SkipHeader; group.AnswersPerQuestion = settings.AnswersPerQuestion; if (group.AnswersPerQuestion == 0) group.AnswersPerQuestion = quiz.AnswersPerQuestion; quiz.QuestionGroups.Add(group); groupHeaderStartPos = paragraph.Range.End; } else if (text.StartsWith(QuestionTag)) { // ~~~ Question ~~~ this.logger.Log("Parsing: " + text, 1); SaveGroupHeader(); SaveQuestionFooter(); question = new QuizQuestion(); question.Answers = new List<QuestionAnswer>(); group.Questions.Add(question); questionHeaderStartPos = paragraph.Range.End; } else if (text.StartsWith(CorrectAnswerTag) || text.StartsWith(WrongAnswerTag)) { // Wrong. Some wrong answer // Correct. Some correct answer SaveQuestionHeader(); int answerStartRange; if (text.StartsWith(CorrectAnswerTag)) answerStartRange = CorrectAnswerTag.Length; else answerStartRange = WrongAnswerTag.Length; if (text.Length > answerStartRange && text[answerStartRange] == ' ') answerStartRange++; question.Answers.Add(new QuestionAnswer { Content = doc.Range( paragraph.Range.Start + answerStartRange, paragraph.Range.End), IsCorrect = text.StartsWith(CorrectAnswerTag) }); questionFooterStartPos = paragraph.Range.End; } else if (text.StartsWith(QuizEndTag)) { SaveGroupHeader(); SaveQuestionFooter(); // Take all following paragraphs to the end of the document var start = paragraph.Range.End; var end = doc.Content.End; quiz.FooterContent = doc.Range(start, end); break; } } return quiz; void SaveQuizHeader() { if (quiz != null && quiz.HeaderContent == null && quizHeaderStartPos != 0) { quiz.HeaderContent = doc.Range(quizHeaderStartPos, paragraph.Range.Start); } quizHeaderStartPos = 0; } void SaveGroupHeader() { if (group != null && group.HeaderContent == null && groupHeaderStartPos != 0) { group.HeaderContent = doc.Range(groupHeaderStartPos, paragraph.Range.Start); } groupHeaderStartPos = 0; } void SaveQuestionHeader() { if (question != null && question.HeaderContent == null && questionHeaderStartPos != 0) { question.HeaderContent = doc.Range(questionHeaderStartPos, paragraph.Range.Start); } questionHeaderStartPos = 0; } void SaveQuestionFooter() { if (question != null && question.FooterContent == null && questionFooterStartPos != 0 && questionFooterStartPos < paragraph.Range.Start) { question.FooterContent = doc.Range(questionFooterStartPos, paragraph.Range.Start); } questionFooterStartPos = 0; } } private static
QuizSettings ParseSettings(string text, string tag) {
var json = text.Substring(tag.Length).Trim(); json = json.Replace("~~~", "").Trim(); if (string.IsNullOrEmpty(json)) json = "{}"; QuizSettings settings = JsonConvert.DeserializeObject<QuizSettings>(json); return settings; } public void LogQuiz(QuizDocument quiz) { this.logger.LogNewLine(); this.logger.Log($"Parsed quiz document (from the input MS Word file):"); this.logger.Log($" - LangCode: {quiz.LangCode}"); this.logger.Log($" - VariantsToGenerate: {quiz.VariantsToGenerate}"); this.logger.Log($" - TotalAvailableQuestions: {quiz.TotalAvailableQuestions}"); this.logger.Log($" - AnswersPerQuestion: {quiz.AnswersPerQuestion}"); string quizHeaderText = TruncateString(quiz.HeaderContent.Text); this.logger.Log($"Quiz header: {quizHeaderText}", 1); this.logger.Log($"Question groups = {quiz.QuestionGroups.Count}", 1); for (int groupIndex = 0; groupIndex < quiz.QuestionGroups.Count; groupIndex++) { this.logger.Log($"[Question Group #{groupIndex+1}]", 1); QuizQuestionGroup group = quiz.QuestionGroups[groupIndex]; string groupHeaderText = TruncateString(group.HeaderContent?.Text); this.logger.Log($"Group header: {groupHeaderText}", 2); this.logger.Log($"Questions = {group.Questions.Count}", 2); for (int questionIndex = 0; questionIndex < group.Questions.Count; questionIndex++) { this.logger.Log($"[Question #{questionIndex+1}]", 2); QuizQuestion question = group.Questions[questionIndex]; string questionContent = TruncateString(question.HeaderContent?.Text); this.logger.Log($"Question content: {questionContent}", 3); this.logger.Log($"Answers = {question.Answers.Count}", 3); foreach (var answer in question.Answers) { string prefix = answer.IsCorrect ? "Correct answer" : "Wrong answer"; string answerText = TruncateString(answer.Content.Text); this.logger.Log($"{prefix}: {answerText}", 4); } string questionFooterText = TruncateString(question.FooterContent?.Text); if (questionFooterText == "") questionFooterText = "(empty)"; this.logger.Log($"Question footer: {questionFooterText}", 3); } } string quizFooterText = TruncateString(quiz.FooterContent?.Text); this.logger.Log($"Quiz footer: {quizFooterText}", 1); } } }
QuizGenerator.Core/QuizParser.cs
SoftUni-SoftUni-Quiz-Generator-b071448
[ { "filename": "QuizGenerator.Core/QuizGenerator.cs", "retrieved_chunk": "\t\t\t\t\tAppendRange(outputDoc, question.FooterContent);\n\t\t\t\t}\n\t\t\t}\n\t\t\tstring quizFooterText = TruncateString(quiz.FooterContent?.Text);\n\t\t\tthis.logger.Log($\"Quiz footer: {quizFooterText}\", 1);\n\t\t\tAppendRange(outputDoc, quiz.FooterContent);\n\t\t}\n\t\tprivate void ReplaceTextInRange(Word.Range range, string srcText, string replaceText)\n\t\t{\n\t\t\tWord.Find find = range.Find;", "score": 0.8346418142318726 }, { "filename": "QuizGenerator.Core/QuizGenerator.cs", "retrieved_chunk": "\t\t\tfinally\n\t\t\t{\n\t\t\t\toutputDoc.Save();\n\t\t\t\toutputDoc.Close();\n\t\t\t}\n\t\t}\n\t\tprivate void WriteRandomizedQuizToWordDoc(RandomizedQuiz quiz, int quizVariant,\n\t\t\tstring langCode, Word.Document outputDoc)\n\t\t{\n\t\t\t// Print the quiz header in the output MS Word document", "score": 0.7221347689628601 }, { "filename": "QuizGenerator.Core/QuizQuestion.cs", "retrieved_chunk": "\t\t\tthis.Answers.Where(a => !a.IsCorrect);\n\t\tpublic Word.Range FooterContent { get; set; }\n\t}\n}", "score": 0.7087493538856506 }, { "filename": "QuizGenerator.UI/Program.cs", "retrieved_chunk": "\t\t\tApplicationConfiguration.Initialize();\n\t\t\tApplication.Run(new FormQuizGenerator());\n\t\t}\n\t}\n}", "score": 0.7062042951583862 }, { "filename": "QuizGenerator.Core/QuizGenerator.cs", "retrieved_chunk": "\t\t{\n\t\t\t// Get the range at the end of the target document\n\t\t\tWord.Range targetRange = targetDocument.Content;\n\t\t\tobject wdColapseEnd = Word.WdCollapseDirection.wdCollapseEnd;\n\t\t\ttargetRange.Collapse(ref wdColapseEnd);\n\t\t\t// Insert the source range of formatted text to the target range\n\t\t\ttargetRange.Text = text;\n\t\t}\n\t\tprivate List<char> ExtractAnswersAsLetters(RandomizedQuiz randQuiz, string langCode)\n\t\t{", "score": 0.6902951002120972 } ]
csharp
QuizSettings ParseSettings(string text, string tag) {
using BepInEx; using UnityEngine; using UnityEngine.SceneManagement; using System; using HarmonyLib; using System.IO; using Ultrapain.Patches; using System.Linq; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Reflection; using Steamworks; using Unity.Audio; using System.Text; using System.Collections.Generic; using UnityEngine.AddressableAssets; using UnityEngine.AddressableAssets.ResourceLocators; using UnityEngine.ResourceManagement.ResourceLocations; using UnityEngine.UIElements; using PluginConfig.API; namespace Ultrapain { [BepInPlugin(PLUGIN_GUID, PLUGIN_NAME, PLUGIN_VERSION)] [BepInDependency("com.eternalUnion.pluginConfigurator", "1.6.0")] public class Plugin : BaseUnityPlugin { public const string PLUGIN_GUID = "com.eternalUnion.ultraPain"; public const string PLUGIN_NAME = "Ultra Pain"; public const string PLUGIN_VERSION = "1.1.0"; public static Plugin instance; private static bool addressableInit = false; public static T LoadObject<T>(string path) { if (!addressableInit) { Addressables.InitializeAsync().WaitForCompletion(); addressableInit = true; } return Addressables.LoadAssetAsync<T>(path).WaitForCompletion(); } public static Vector3 PredictPlayerPosition(Collider safeCollider, float speedMod) { Transform target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f) return target.position; RaycastHit raycastHit; if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == safeCollider) return target.position; else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide)) { return raycastHit.point; } else { Vector3 projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod; return new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z); } } public static GameObject projectileSpread; public static GameObject homingProjectile; public static GameObject hideousMassProjectile; public static GameObject decorativeProjectile2; public static GameObject shotgunGrenade; public static GameObject beam; public static GameObject turretBeam; public static GameObject lightningStrikeExplosiveSetup; public static GameObject lightningStrikeExplosive; public static GameObject lighningStrikeWindup; public static GameObject explosion; public static GameObject bigExplosion; public static GameObject sandExplosion; public static GameObject virtueInsignia; public static GameObject rocket; public static GameObject revolverBullet; public static GameObject maliciousCannonBeam; public static GameObject lightningBoltSFX; public static GameObject revolverBeam; public static GameObject blastwave; public static
GameObject cannonBall;
public static GameObject shockwave; public static GameObject sisyphiusExplosion; public static GameObject sisyphiusPrimeExplosion; public static GameObject explosionWaveKnuckleblaster; public static GameObject chargeEffect; public static GameObject maliciousFaceProjectile; public static GameObject hideousMassSpear; public static GameObject coin; public static GameObject sisyphusDestroyExplosion; //public static GameObject idol; public static GameObject ferryman; public static GameObject minosPrime; //public static GameObject maliciousFace; public static GameObject somethingWicked; public static Turret turret; public static GameObject turretFinalFlash; public static GameObject enrageEffect; public static GameObject v2flashUnparryable; public static GameObject ricochetSfx; public static GameObject parryableFlash; public static AudioClip cannonBallChargeAudio; public static Material gabrielFakeMat; public static Sprite blueRevolverSprite; public static Sprite greenRevolverSprite; public static Sprite redRevolverSprite; public static Sprite blueShotgunSprite; public static Sprite greenShotgunSprite; public static Sprite blueNailgunSprite; public static Sprite greenNailgunSprite; public static Sprite blueSawLauncherSprite; public static Sprite greenSawLauncherSprite; public static GameObject rocketLauncherAlt; public static GameObject maliciousRailcannon; // Variables public static float SoliderShootAnimationStart = 1.2f; public static float SoliderGrenadeForce = 10000f; public static float SwordsMachineKnockdownTimeNormalized = 0.8f; public static float SwordsMachineCoreSpeed = 80f; public static float MinGrenadeParryVelocity = 40f; public static GameObject _lighningBoltSFX; public static GameObject lighningBoltSFX { get { if (_lighningBoltSFX == null) _lighningBoltSFX = ferryman.gameObject.transform.Find("LightningBoltChimes").gameObject; return _lighningBoltSFX; } } private static bool loadedPrefabs = false; public void LoadPrefabs() { if (loadedPrefabs) return; loadedPrefabs = true; // Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab projectileSpread = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Spread.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab homingProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Homing.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab decorativeProjectile2 = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Decorative 2.prefab"); // Assets/Prefabs/Attacks and Projectiles/Grenade.prefab shotgunGrenade = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Grenade.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab turretBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Turret Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab beam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab lightningStrikeExplosiveSetup = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Lightning Strike Explosive.prefab"); // Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab lighningStrikeWindup = LoadObject<GameObject>("Assets/Particles/Environment/LightningBoltWindupFollow Variant.prefab"); //[bundle-0][assets/prefabs/enemies/idol.prefab] //idol = LoadObject<GameObject>("assets/prefabs/enemies/idol.prefab"); // Assets/Prefabs/Enemies/Ferryman.prefab ferryman = LoadObject<GameObject>("Assets/Prefabs/Enemies/Ferryman.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab explosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab bigExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Super.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab sandExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sand.prefab"); // Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab virtueInsignia = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Virtue Insignia.prefab"); // Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab hideousMassProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Projectile Explosive HH.prefab"); // Assets/Particles/Enemies/RageEffect.prefab enrageEffect = LoadObject<GameObject>("Assets/Particles/Enemies/RageEffect.prefab"); // Assets/Particles/Flashes/V2FlashUnparriable.prefab v2flashUnparryable = LoadObject<GameObject>("Assets/Particles/Flashes/V2FlashUnparriable.prefab"); // Assets/Prefabs/Attacks and Projectiles/Rocket.prefab rocket = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Rocket.prefab"); // Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab revolverBullet = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/RevolverBullet.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab maliciousCannonBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Railcannon Beam Malicious.prefab"); // Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab revolverBeam = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Revolver Beam.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab blastwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Enemy.prefab"); // Assets/Prefabs/Enemies/MinosPrime.prefab minosPrime = LoadObject<GameObject>("Assets/Prefabs/Enemies/MinosPrime.prefab"); // Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab cannonBall = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Cannonball.prefab"); // get from Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab cannonBallChargeAudio = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab").transform.Find("RocketLauncher/Armature/Body_Bone/HologramDisplay").GetComponent<AudioSource>().clip; // Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab shockwave = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/PhysicalShockwave.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab sisyphiusExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave Sisyphus.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab sisyphiusPrimeExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab explosionWaveKnuckleblaster = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Wave.prefab"); // Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab - [bundle-0][assets/prefabs/explosionlightning variant.prefab] lightningStrikeExplosive = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Lightning.prefab"); // Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab rocketLauncherAlt = LoadObject<GameObject>("Assets/Prefabs/Weapons/Rocket Launcher Cannonball.prefab"); // Assets/Prefabs/Weapons/Railcannon Malicious.prefab maliciousRailcannon = LoadObject<GameObject>("Assets/Prefabs/Weapons/Railcannon Malicious.prefab"); //Assets/Particles/SoundBubbles/Ricochet.prefab ricochetSfx = LoadObject<GameObject>("Assets/Particles/SoundBubbles/Ricochet.prefab"); //Assets/Particles/Flashes/Flash.prefab parryableFlash = LoadObject<GameObject>("Assets/Particles/Flashes/Flash.prefab"); //Assets/Prefabs/Attacks and Projectiles/Spear.prefab hideousMassSpear = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Spear.prefab"); //Assets/Prefabs/Enemies/Wicked.prefab somethingWicked = LoadObject<GameObject>("Assets/Prefabs/Enemies/Wicked.prefab"); //Assets/Textures/UI/SingleRevolver.png blueRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/SingleRevolver.png"); //Assets/Textures/UI/RevolverSpecial.png greenRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSpecial.png"); //Assets/Textures/UI/RevolverSharp.png redRevolverSprite = LoadObject<Sprite>("Assets/Textures/UI/RevolverSharp.png"); //Assets/Textures/UI/Shotgun.png blueShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun.png"); //Assets/Textures/UI/Shotgun1.png greenShotgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Shotgun1.png"); //Assets/Textures/UI/Nailgun2.png blueNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/Nailgun2.png"); //Assets/Textures/UI/NailgunOverheat.png greenNailgunSprite = LoadObject<Sprite>("Assets/Textures/UI/NailgunOverheat.png"); //Assets/Textures/UI/SawbladeLauncher.png blueSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncher.png"); //Assets/Textures/UI/SawbladeLauncherOverheat.png greenSawLauncherSprite = LoadObject<Sprite>("Assets/Textures/UI/SawbladeLauncherOverheat.png"); //Assets/Prefabs/Attacks and Projectiles/Coin.prefab coin = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Coin.prefab"); //Assets/Materials/GabrielFake.mat gabrielFakeMat = LoadObject<Material>("Assets/Materials/GabrielFake.mat"); //Assets/Prefabs/Enemies/Turret.prefab turret = LoadObject<GameObject>("Assets/Prefabs/Enemies/Turret.prefab").GetComponent<Turret>(); //Assets/Particles/Flashes/GunFlashDistant.prefab turretFinalFlash = LoadObject<GameObject>("Assets/Particles/Flashes/GunFlashDistant.prefab"); //Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab sisyphusDestroyExplosion = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Sisyphus Prime Charged.prefab"); //Assets/Prefabs/Effects/Charge Effect.prefab chargeEffect = LoadObject<GameObject>("Assets/Prefabs/Effects/Charge Effect.prefab"); //Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab maliciousFaceProjectile = LoadObject<GameObject>("Assets/Prefabs/Attacks and Projectiles/Hitscan Beams/Malicious Beam.prefab"); } public static bool ultrapainDifficulty = false; public static bool realUltrapainDifficulty = false; public static GameObject currentDifficultyButton; public static GameObject currentDifficultyPanel; public static Text currentDifficultyInfoText; public void OnSceneChange(Scene before, Scene after) { StyleIDs.RegisterIDs(); ScenePatchCheck(); string mainMenuSceneName = "b3e7f2f8052488a45b35549efb98d902"; string bootSequenceSceneName = "4f8ecffaa98c2614f89922daf31fa22d"; string currentSceneName = SceneManager.GetActiveScene().name; if (currentSceneName == mainMenuSceneName) { LoadPrefabs(); //Canvas/Difficulty Select (1)/Violent Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Difficulty Select (1)"); GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect); currentDifficultyButton = ultrapainButton; ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value; ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5; RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>(); ultrapainTrans.anchoredPosition = new Vector2(20f, -104f); //Canvas/Difficulty Select (1)/Violent Info GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect); currentDifficultyPanel = info; currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>(); currentDifficultyInfoText.text = ConfigManager.pluginInfo.value; Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>(); currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--"; currentDifficultyHeaderText.resizeTextForBestFit = true; currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap; currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate; info.SetActive(false); EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>(); evt.triggers.Clear(); /*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(false));*/ EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit }; trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false)); evt.triggers.Add(trigger1); evt.triggers.Add(trigger2); foreach(EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>()) { if (trigger.gameObject == ultrapainButton) continue; EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false)); trigger.triggers.Add(closeTrigger); } } else if(currentSceneName == bootSequenceSceneName) { LoadPrefabs(); //Canvas/Difficulty Select (1)/Violent Transform difficultySelect = SceneManager.GetActiveScene().GetRootGameObjects().Where(obj => obj.name == "Canvas").First().transform.Find("Intro/Difficulty Select"); GameObject ultrapainButton = GameObject.Instantiate(difficultySelect.Find("Violent").gameObject, difficultySelect); currentDifficultyButton = ultrapainButton; ultrapainButton.transform.Find("Name").GetComponent<Text>().text = ConfigManager.pluginName.value; ultrapainButton.GetComponent<DifficultySelectButton>().difficulty = 5; RectTransform ultrapainTrans = ultrapainButton.GetComponent<RectTransform>(); ultrapainTrans.anchoredPosition = new Vector2(20f, -104f); //Canvas/Difficulty Select (1)/Violent Info GameObject info = GameObject.Instantiate(difficultySelect.Find("Violent Info").gameObject, difficultySelect); currentDifficultyPanel = info; currentDifficultyInfoText = info.transform.Find("Text").GetComponent<Text>(); currentDifficultyInfoText.text = ConfigManager.pluginInfo.value; Text currentDifficultyHeaderText = info.transform.Find("Title (1)").GetComponent<Text>(); currentDifficultyHeaderText.text = $"--{ConfigManager.pluginName.value}--"; currentDifficultyHeaderText.resizeTextForBestFit = true; currentDifficultyHeaderText.horizontalOverflow = HorizontalWrapMode.Wrap; currentDifficultyHeaderText.verticalOverflow = VerticalWrapMode.Truncate; info.SetActive(false); EventTrigger evt = ultrapainButton.GetComponent<EventTrigger>(); evt.triggers.Clear(); /*EventTrigger.TriggerEvent activate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.TriggerEvent deactivate = new EventTrigger.TriggerEvent(); activate.AddListener((BaseEventData data) => info.SetActive(false));*/ EventTrigger.Entry trigger1 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; trigger1.callback.AddListener((BaseEventData data) => info.SetActive(true)); EventTrigger.Entry trigger2 = new EventTrigger.Entry() { eventID = EventTriggerType.PointerExit }; trigger2.callback.AddListener((BaseEventData data) => info.SetActive(false)); evt.triggers.Add(trigger1); evt.triggers.Add(trigger2); foreach (EventTrigger trigger in difficultySelect.GetComponentsInChildren<EventTrigger>()) { if (trigger.gameObject == ultrapainButton) continue; EventTrigger.Entry closeTrigger = new EventTrigger.Entry() { eventID = EventTriggerType.PointerEnter }; closeTrigger.callback.AddListener((BaseEventData data) => info.SetActive(false)); trigger.triggers.Add(closeTrigger); } } // LOAD CUSTOM PREFABS HERE TO AVOID MID GAME LAG MinosPrimeCharge.CreateDecoy(); GameObject shockwaveSisyphus = SisyphusInstructionist_Start.shockwave; } public static class StyleIDs { private static bool registered = false; public static void RegisterIDs() { registered = false; if (MonoSingleton<StyleHUD>.Instance == null) return; MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.grenadeBoostStyleText.guid, ConfigManager.grenadeBoostStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.rocketBoostStyleText.guid, ConfigManager.rocketBoostStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverStyleText.guid, ConfigManager.orbStrikeRevolverStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeRevolverChargedStyleText.guid, ConfigManager.orbStrikeRevolverChargedStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeElectricCannonStyleText.guid, ConfigManager.orbStrikeElectricCannonStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.orbStrikeMaliciousCannonStyleText.guid, ConfigManager.orbStrikeMaliciousCannonStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.maliciousChargebackStyleText.guid, ConfigManager.maliciousChargebackStyleText.formattedString); MonoSingleton<StyleHUD>.Instance.RegisterStyleItem(ConfigManager.sentryChargebackStyleText.guid, ConfigManager.sentryChargebackStyleText.formattedString); registered = true; Debug.Log("Registered all style ids"); } private static FieldInfo idNameDict = typeof(StyleHUD).GetField("idNameDict", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); public static void UpdateID(string id, string newName) { if (!registered || StyleHUD.Instance == null) return; (idNameDict.GetValue(StyleHUD.Instance) as Dictionary<string, string>)[id] = newName; } } public static Harmony harmonyTweaks; public static Harmony harmonyBase; private static MethodInfo GetMethod<T>(string name) { return typeof(T).GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } private static Dictionary<MethodInfo, HarmonyMethod> methodCache = new Dictionary<MethodInfo, HarmonyMethod>(); private static HarmonyMethod GetHarmonyMethod(MethodInfo method) { if (methodCache.TryGetValue(method, out HarmonyMethod harmonyMethod)) return harmonyMethod; else { harmonyMethod = new HarmonyMethod(method); methodCache.Add(method, harmonyMethod); return harmonyMethod; } } private static void PatchAllEnemies() { if (!ConfigManager.enemyTweakToggle.value) return; if (ConfigManager.friendlyFireDamageOverrideToggle.value) { harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Explosion_Collide_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<PhysicalShockwave>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<PhysicalShockwave_CheckCollision_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<VirtueInsignia>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<VirtueInsignia_OnTriggerEnter_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Projectile_Collided_FF>("Postfix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_FF>("Prefix"))); harmonyTweaks.Patch(GetMethod<Flammable>("Burn"), prefix: GetHarmonyMethod(GetMethod<Flammable_Burn_FF>("Prefix"))); harmonyTweaks.Patch(GetMethod<FireZone>("OnTriggerStay"), prefix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Prefix")), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Fire_FF>("Postfix"))); } harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("UpdateModifiers"), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_UpdateModifiers>("Postfix"))); harmonyTweaks.Patch(GetMethod<StatueBoss>("Start"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Start_Patch>("Postfix"))); if (ConfigManager.cerberusDashToggle.value) harmonyTweaks.Patch(GetMethod<StatueBoss>("StopDash"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopDash_Patch>("Postfix"))); if(ConfigManager.cerberusParryable.value) { harmonyTweaks.Patch(GetMethod<StatueBoss>("StopTracking"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_StopTracking_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<StatueBoss>("Stomp"), postfix: GetHarmonyMethod(GetMethod<StatueBoss_Stomp_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Statue>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Statue_GetHurt_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Drone_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Drone>("Shoot"), prefix: GetHarmonyMethod(GetMethod<Drone_Shoot_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("PlaySound"), prefix: GetHarmonyMethod(GetMethod<Drone_PlaySound_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Update"), postfix: GetHarmonyMethod(GetMethod<Drone_Update>("Postfix"))); if(ConfigManager.droneHomeToggle.value) { harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Drone_Death_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<Drone_GetHurt_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Ferryman>("Start"), postfix: GetHarmonyMethod(GetMethod<FerrymanStart>("Postfix"))); if(ConfigManager.ferrymanComboToggle.value) harmonyTweaks.Patch(GetMethod<Ferryman>("StopMoving"), postfix: GetHarmonyMethod(GetMethod<FerrymanStopMoving>("Postfix"))); if(ConfigManager.filthExplodeToggle.value) harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch2>("Prefix"))); if(ConfigManager.fleshPrisonSpinAttackToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<FleshPrisonShoot>("Postfix"))); if (ConfigManager.hideousMassInsigniaToggle.value) { harmonyTweaks.Patch(GetMethod<Projectile>("Explode"), postfix: GetHarmonyMethod(GetMethod<Projectile_Explode_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Mass>("ShootExplosive"), postfix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Postfix")), prefix: GetHarmonyMethod(GetMethod<HideousMassHoming>("Prefix"))); } harmonyTweaks.Patch(GetMethod<SpiderBody>("Start"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<SpiderBody>("ChargeBeam"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ChargeBeam>("Postfix"))); harmonyTweaks.Patch(GetMethod<SpiderBody>("BeamChargeEnd"), prefix: GetHarmonyMethod(GetMethod<MaliciousFace_BeamChargeEnd>("Prefix"))); if (ConfigManager.maliciousFaceHomingProjectileToggle.value) { harmonyTweaks.Patch(GetMethod<SpiderBody>("ShootProj"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_ShootProj_Patch>("Postfix"))); } if (ConfigManager.maliciousFaceRadianceOnEnrage.value) harmonyTweaks.Patch(GetMethod<SpiderBody>("Enrage"), postfix: GetHarmonyMethod(GetMethod<MaliciousFace_Enrage_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Mindflayer>("Start"), postfix: GetHarmonyMethod(GetMethod<Mindflayer_Start_Patch>("Postfix"))); if (ConfigManager.mindflayerShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<Mindflayer>("ShootProjectiles"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_ShootProjectiles_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage_MF>("Prefix"))); } if (ConfigManager.mindflayerTeleportComboToggle.value) { harmonyTweaks.Patch(GetMethod<SwingCheck2>("CheckCollision"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwingCheck2_CheckCollision_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Mindflayer>("MeleeTeleport"), prefix: GetHarmonyMethod(GetMethod<Mindflayer_MeleeTeleport_Patch>("Prefix"))); //harmonyTweaks.Patch(GetMethod<SwingCheck2>("DamageStop"), postfix: GetHarmonyMethod(GetMethod<SwingCheck2_DamageStop_Patch>("Postfix"))); } if (ConfigManager.minosPrimeRandomTeleportToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("Postfix"))); if (ConfigManager.minosPrimeTeleportTrail.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("Teleport"), postfix: GetHarmonyMethod(GetMethod<MinosPrimeCharge>("TeleportPostfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Start"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Dropkick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Dropkick>("Prefix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Combo"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_Combo>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("StopAction"), postfix: GetHarmonyMethod(GetMethod<MinosPrime_StopAction>("Postfix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Ascend"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Ascend>("Prefix"))); harmonyTweaks.Patch(GetMethod<MinosPrime>("Death"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_Death>("Prefix"))); if (ConfigManager.minosPrimeCrushAttackToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("RiderKick"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_RiderKick>("Prefix"))); if (ConfigManager.minosPrimeComboExplosiveEndToggle.value) harmonyTweaks.Patch(GetMethod<MinosPrime>("ProjectileCharge"), prefix: GetHarmonyMethod(GetMethod<MinosPrime_ProjectileCharge>("Prefix"))); if (ConfigManager.schismSpreadAttackToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ShootProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ShootProjectile_Patch>("Postfix"))); if (ConfigManager.soliderShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<Solider_Start_Patch>("Postfix"))); } if(ConfigManager.soliderCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_SpawnProjectile_Patch>("Postfix"))); if (ConfigManager.soliderShootGrenadeToggle.value || ConfigManager.soliderShootTweakToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<Solider_ThrowProjectile_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Stalker>("SandExplode"), prefix: GetHarmonyMethod(GetMethod<Stalker_SandExplode_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SandificationZone>("Enter"), postfix: GetHarmonyMethod(GetMethod<SandificationZone_Enter_Patch>("Postfix"))); if (ConfigManager.strayCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SpawnProjectile"), postfix: GetHarmonyMethod(GetMethod<Swing>("Postfix"))); if (ConfigManager.strayShootToggle.value) { harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("Start"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_Start_Patch1>("Postfix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("ThrowProjectile"), postfix: GetHarmonyMethod(GetMethod<ZombieProjectile_ThrowProjectile_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<SwingEnd>("Prefix"))); harmonyTweaks.Patch(GetMethod<ZombieProjectiles>("DamageEnd"), prefix: GetHarmonyMethod(GetMethod<DamageEnd>("Prefix"))); } if(ConfigManager.streetCleanerCoinsIgnoreWeakPointToggle.value) harmonyTweaks.Patch(GetMethod<Streetcleaner>("Start"), postfix: GetHarmonyMethod(GetMethod<StreetCleaner_Start_Patch>("Postfix"))); if(ConfigManager.streetCleanerPredictiveDodgeToggle.value) harmonyTweaks.Patch(GetMethod<BulletCheck>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<BulletCheck_OnTriggerEnter_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("Start"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Start>("Postfix"))); if (ConfigManager.swordsMachineNoLightKnockbackToggle.value || ConfigManager.swordsMachineSecondPhaseMode.value != ConfigManager.SwordsMachineSecondPhase.None) { harmonyTweaks.Patch(GetMethod<SwordsMachine>("Knockdown"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Knockdown_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("Down"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_Down_Patch>("Prefix"))); //harmonyTweaks.Patch(GetMethod<SwordsMachine>("SetSpeed"), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_SetSpeed_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<SwordsMachine>("EndFirstPhase"), postfix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Postfix")), prefix: GetHarmonyMethod(GetMethod<SwordsMachine_EndFirstPhase_Patch>("Prefix"))); } if (ConfigManager.swordsMachineExplosiveSwordToggle.value) { harmonyTweaks.Patch(GetMethod<ThrownSword>("Start"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<ThrownSword>("OnTriggerEnter"), postfix: GetHarmonyMethod(GetMethod<ThrownSword_OnTriggerEnter_Patch>("Postfix"))); } harmonyTweaks.Patch(GetMethod<Turret>("Start"), postfix: GetHarmonyMethod(GetMethod<TurretStart>("Postfix"))); if(ConfigManager.turretBurstFireToggle.value) { harmonyTweaks.Patch(GetMethod<Turret>("Shoot"), prefix: GetHarmonyMethod(GetMethod<TurretShoot>("Prefix"))); harmonyTweaks.Patch(GetMethod<Turret>("StartAiming"), postfix: GetHarmonyMethod(GetMethod<TurretAim>("Postfix"))); } harmonyTweaks.Patch(GetMethod<Explosion>("Start"), postfix: GetHarmonyMethod(GetMethod<V2CommonExplosion>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2FirstStart>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2FirstUpdate>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2FirstShootWeapon>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("Start"), postfix: GetHarmonyMethod(GetMethod<V2SecondStart>("Postfix"))); //if(ConfigManager.v2SecondStartEnraged.value) // harmonyTweaks.Patch(GetMethod<BossHealthBar>("OnEnable"), postfix: GetHarmonyMethod(GetMethod<V2SecondEnrage>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("Update"), prefix: GetHarmonyMethod(GetMethod<V2SecondUpdate>("Prefix"))); //harmonyTweaks.Patch(GetMethod<V2>("AltShootWeapon"), postfix: GetHarmonyMethod(GetMethod<V2AltShootWeapon>("Postfix"))); harmonyTweaks.Patch(GetMethod<V2>("SwitchWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondSwitchWeapon>("Prefix"))); harmonyTweaks.Patch(GetMethod<V2>("ShootWeapon"), prefix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Prefix")), postfix: GetHarmonyMethod(GetMethod<V2SecondShootWeapon>("Postfix"))); if(ConfigManager.v2SecondFastCoinToggle.value) harmonyTweaks.Patch(GetMethod<V2>("ThrowCoins"), prefix: GetHarmonyMethod(GetMethod<V2SecondFastCoin>("Prefix"))); harmonyTweaks.Patch(GetMethod<Cannonball>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<V2RocketLauncher>("CannonBallTriggerPrefix"))); if (ConfigManager.v2FirstSharpshooterToggle.value || ConfigManager.v2SecondSharpshooterToggle.value) { harmonyTweaks.Patch(GetMethod<EnemyRevolver>("PrepareAltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverPrepareAltFire>("Prefix"))); harmonyTweaks.Patch(GetMethod<Projectile>("Collided"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverBullet>("Prefix"))); harmonyTweaks.Patch(GetMethod<EnemyRevolver>("AltFire"), prefix: GetHarmonyMethod(GetMethod<V2CommonRevolverAltShoot>("Prefix"))); } harmonyTweaks.Patch(GetMethod<Drone>("Start"), postfix: GetHarmonyMethod(GetMethod<Virtue_Start_Patch>("Postfix"))); harmonyTweaks.Patch(GetMethod<Drone>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Virtue_SpawnInsignia_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Death"), prefix: GetHarmonyMethod(GetMethod<Virtue_Death_Patch>("Prefix"))); if (ConfigManager.sisyInstJumpShockwave.value) { harmonyTweaks.Patch(GetMethod<Sisyphus>("Start"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Sisyphus>("Update"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_Update>("Postfix"))); } if(ConfigManager.sisyInstBoulderShockwave.value) harmonyTweaks.Patch(GetMethod<Sisyphus>("SetupExplosion"), postfix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_SetupExplosion>("Postfix"))); if(ConfigManager.sisyInstStrongerExplosion.value) harmonyTweaks.Patch(GetMethod<Sisyphus>("StompExplosion"), prefix: GetHarmonyMethod(GetMethod<SisyphusInstructionist_StompExplosion>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("Awake"), postfix: GetHarmonyMethod(GetMethod<LeviathanTail_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("BigSplash"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_BigSplash>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanTail>("SwingEnd"), prefix: GetHarmonyMethod(GetMethod<LeviathanTail_SwingEnd>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("Start"), postfix: GetHarmonyMethod(GetMethod<Leviathan_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurst"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("ProjectileBurstStart"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurstStart>("Prefix"))); harmonyTweaks.Patch(GetMethod<LeviathanHead>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<Leviathan_FixedUpdate>("Prefix"))); if (ConfigManager.somethingWickedSpear.value) { harmonyTweaks.Patch(GetMethod<Wicked>("Start"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_GetHit>("Postfix"))); } if(ConfigManager.somethingWickedSpawnOn43.value) { harmonyTweaks.Patch(GetMethod<ObjectActivator>("Activate"), prefix: GetHarmonyMethod(GetMethod<ObjectActivator_Activate>("Prefix"))); harmonyTweaks.Patch(GetMethod<Wicked>("GetHit"), postfix: GetHarmonyMethod(GetMethod<JokeWicked_GetHit>("Postfix"))); } if (ConfigManager.panopticonFullPhase.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Panopticon_Start>("Postfix"))); if (ConfigManager.panopticonAxisBeam.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnInsignia"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnInsignia>("Prefix"))); if (ConfigManager.panopticonSpinAttackToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("HomingProjectileAttack"), postfix: GetHarmonyMethod(GetMethod<Panopticon_HomingProjectileAttack>("Postfix"))); if (ConfigManager.panopticonBlackholeProj.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnBlackHole"), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnBlackHole>("Postfix"))); if (ConfigManager.panopticonBalanceEyes.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("SpawnFleshDrones"), prefix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Panopticon_SpawnFleshDrones>("Postfix"))); if (ConfigManager.panopticonBlueProjToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Update"), transpiler: GetHarmonyMethod(GetMethod<Panopticon_BlueProjectile>("Transpiler"))); if (ConfigManager.idolExplosionToggle.value) harmonyTweaks.Patch(GetMethod<Idol>("Death"), postfix: GetHarmonyMethod(GetMethod<Idol_Death_Patch>("Postfix"))); // ADDME /* harmonyTweaks.Patch(GetMethod<GabrielSecond>("Start"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("BasicCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_BasicCombo>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("FastCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_FastCombo>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("CombineSwords"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_CombineSwords>("Postfix"))); harmonyTweaks.Patch(GetMethod<GabrielSecond>("ThrowCombo"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_ThrowCombo>("Postfix"))); */ } private static void PatchAllPlayers() { if (!ConfigManager.playerTweakToggle.value) return; harmonyTweaks.Patch(GetMethod<Punch>("CheckForProjectile"), prefix: GetHarmonyMethod(GetMethod<Punch_CheckForProjectile_Patch>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode_Patch1>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Collision"), prefix: GetHarmonyMethod(GetMethod<Grenade_Collision_Patch>("Prefix"))); if (ConfigManager.rocketBoostToggle.value) harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide_Patch>("Prefix"))); if (ConfigManager.rocketGrabbingToggle.value) harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), prefix: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate_Patch>("Prefix"))); if (ConfigManager.orbStrikeToggle.value) { harmonyTweaks.Patch(GetMethod<Coin>("Start"), postfix: GetHarmonyMethod(GetMethod<Coin_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<Punch>("BlastCheck"), prefix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Punch_BlastCheck>("Postfix"))); harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_Collide>("Prefix"))); harmonyTweaks.Patch(GetMethod<Coin>("DelayedReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_DelayedReflectRevolver>("Postfix"))); harmonyTweaks.Patch(GetMethod<Coin>("ReflectRevolver"), postfix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Coin_ReflectRevolver>("Prefix"))); harmonyTweaks.Patch(GetMethod<Grenade>("Explode"), prefix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Grenade_Explode>("Postfix"))); harmonyTweaks.Patch(GetMethod<EnemyIdentifier>("DeliverDamage"), prefix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Prefix")), postfix: GetHarmonyMethod(GetMethod<EnemyIdentifier_DeliverDamage>("Postfix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("ExecuteHits"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_ExecuteHits>("Prefix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("HitSomething"), postfix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Postfix")), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_HitSomething>("Prefix"))); harmonyTweaks.Patch(GetMethod<RevolverBeam>("Start"), prefix: GetHarmonyMethod(GetMethod<RevolverBeam_Start>("Prefix"))); harmonyTweaks.Patch(GetMethod<Cannonball>("Explode"), prefix: GetHarmonyMethod(GetMethod<Cannonball_Explode>("Prefix"))); harmonyTweaks.Patch(GetMethod<Explosion>("Collide"), prefix: GetHarmonyMethod(GetMethod<Explosion_CollideOrbital>("Prefix"))); } if(ConfigManager.chargedRevRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<Revolver>("Update"), prefix: GetHarmonyMethod(GetMethod<Revolver_Update>("Prefix"))); if(ConfigManager.coinRegSpeedMulti.value != 1 || ConfigManager.sharpshooterRegSpeedMulti.value != 1 || ConfigManager.railcannonRegSpeedMulti.value != 1 || ConfigManager.rocketFreezeRegSpeedMulti.value != 1 || ConfigManager.rocketCannonballRegSpeedMulti.value != 1 || ConfigManager.nailgunAmmoRegSpeedMulti.value != 1 || ConfigManager.sawAmmoRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<WeaponCharges>("Charge"), prefix: GetHarmonyMethod(GetMethod<WeaponCharges_Charge>("Prefix"))); if(ConfigManager.nailgunHeatsinkRegSpeedMulti.value != 1 || ConfigManager.sawHeatsinkRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<Nailgun>("Update"), prefix: GetHarmonyMethod(GetMethod<NailGun_Update>("Prefix"))); if(ConfigManager.staminaRegSpeedMulti.value != 1) harmonyTweaks.Patch(GetMethod<NewMovement>("Update"), prefix: GetHarmonyMethod(GetMethod<NewMovement_Update>("Prefix"))); if(ConfigManager.playerHpDeltaToggle.value || ConfigManager.maxPlayerHp.value != 100 || ConfigManager.playerHpSupercharge.value != 200 || ConfigManager.whiplashHardDamageCap.value != 50 || ConfigManager.whiplashHardDamageSpeed.value != 1) { harmonyTweaks.Patch(GetMethod<NewMovement>("GetHealth"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHealth>("Prefix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("SuperCharge"), prefix: GetHarmonyMethod(GetMethod<NewMovement_SuperCharge>("Prefix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("Respawn"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Respawn>("Postfix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("Start"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Transpiler"))); harmonyTweaks.Patch(GetMethod<HookArm>("FixedUpdate"), transpiler: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate>("Transpiler"))); harmonyTweaks.Patch(GetMethod<NewMovement>("ForceAntiHP"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_ForceAntiHP>("Transpiler"))); } // ADDME harmonyTweaks.Patch(GetMethod<Revolver>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Revolver_Shoot>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Shotgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Transpiler")), prefix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Shotgun_Shoot>("Postfix"))); harmonyTweaks.Patch(GetMethod<Shotgun>("ShootSinks"), transpiler: GetHarmonyMethod(GetMethod<Shotgun_ShootSinks>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Nailgun>("Shoot"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_Shoot>("Transpiler"))); harmonyTweaks.Patch(GetMethod<Nailgun>("SuperSaw"), transpiler: GetHarmonyMethod(GetMethod<Nailgun_SuperSaw>("Transpiler"))); if (ConfigManager.hardDamagePercent.normalizedValue != 1) harmonyTweaks.Patch(GetMethod<NewMovement>("GetHurt"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Prefix")), postfix: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>("Postfix"))); harmonyTweaks.Patch(GetMethod<HealthBar>("Start"), postfix: GetHarmonyMethod(GetMethod<HealthBar_Start>("Postfix"))); harmonyTweaks.Patch(GetMethod<HealthBar>("Update"), transpiler: GetHarmonyMethod(GetMethod<HealthBar_Update>("Transpiler"))); foreach (HealthBarTracker hb in HealthBarTracker.instances) { if (hb != null) hb.SetSliderRange(); } harmonyTweaks.Patch(GetMethod<Harpoon>("Start"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Start>("Postfix"))); if(ConfigManager.screwDriverHomeToggle.value) harmonyTweaks.Patch(GetMethod<Harpoon>("Punched"), postfix: GetHarmonyMethod(GetMethod<Harpoon_Punched>("Postfix"))); if(ConfigManager.screwDriverSplitToggle.value) harmonyTweaks.Patch(GetMethod<Harpoon>("OnTriggerEnter"), prefix: GetHarmonyMethod(GetMethod<Harpoon_OnTriggerEnter_Patch>("Prefix"))); } private static void PatchAllMemes() { if (ConfigManager.enrageSfxToggle.value) harmonyTweaks.Patch(GetMethod<EnrageEffect>("Start"), postfix: GetHarmonyMethod(GetMethod<EnrageEffect_Start>("Postfix"))); if(ConfigManager.funnyDruidKnightSFXToggle.value) { harmonyTweaks.Patch(GetMethod<Mandalore>("FullBurst"), postfix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Postfix")), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<Mandalore>("FullerBurst"), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullerBurst>("Prefix"))); harmonyTweaks.Patch(GetMethod<Drone>("Explode"), prefix: GetHarmonyMethod(GetMethod<Drone_Explode>("Prefix")), postfix: GetHarmonyMethod(GetMethod<Drone_Explode>("Postfix"))); } if (ConfigManager.fleshObamiumToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<FleshObamium_Start>("Prefix"))); if (ConfigManager.obamapticonToggle.value) harmonyTweaks.Patch(GetMethod<FleshPrison>("Start"), postfix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Postfix")), prefix: GetHarmonyMethod(GetMethod<Obamapticon_Start>("Prefix"))); } public static bool methodsPatched = false; public static void ScenePatchCheck() { if(methodsPatched && !ultrapainDifficulty) { harmonyTweaks.UnpatchSelf(); methodsPatched = false; } else if(!methodsPatched && ultrapainDifficulty) { PatchAll(); } } public static void PatchAll() { harmonyTweaks.UnpatchSelf(); methodsPatched = false; if (!ultrapainDifficulty) return; if(realUltrapainDifficulty && ConfigManager.discordRichPresenceToggle.value) harmonyTweaks.Patch(GetMethod<DiscordController>("SendActivity"), prefix: GetHarmonyMethod(GetMethod<DiscordController_SendActivity_Patch>("Prefix"))); if (realUltrapainDifficulty && ConfigManager.steamRichPresenceToggle.value) harmonyTweaks.Patch(GetMethod<SteamFriends>("SetRichPresence"), prefix: GetHarmonyMethod(GetMethod<SteamFriends_SetRichPresence_Patch>("Prefix"))); PatchAllEnemies(); PatchAllPlayers(); PatchAllMemes(); methodsPatched = true; } public static string workingPath; public static string workingDir; public static AssetBundle bundle; public static AudioClip druidKnightFullAutoAud; public static AudioClip druidKnightFullerAutoAud; public static AudioClip druidKnightDeathAud; public static AudioClip enrageAudioCustom; public static GameObject fleshObamium; public static GameObject obamapticon; public void Awake() { instance = this; workingPath = Assembly.GetExecutingAssembly().Location; workingDir = Path.GetDirectoryName(workingPath); Logger.LogInfo($"Working path: {workingPath}, Working dir: {workingDir}"); try { bundle = AssetBundle.LoadFromFile(Path.Combine(workingDir, "ultrapain")); druidKnightFullAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullauto.wav"); druidKnightFullerAutoAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/fullerauto.wav"); druidKnightDeathAud = bundle.LoadAsset<AudioClip>("assets/ultrapain/druidknight/death.wav"); enrageAudioCustom = bundle.LoadAsset<AudioClip>("assets/ultrapain/sfx/enraged.wav"); fleshObamium = bundle.LoadAsset<GameObject>("assets/ultrapain/fleshprison/fleshobamium.prefab"); obamapticon = bundle.LoadAsset<GameObject>("assets/ultrapain/panopticon/obamapticon.prefab"); } catch (Exception e) { Logger.LogError($"Could not load the asset bundle:\n{e}"); } // DEBUG /*string logPath = Path.Combine(Environment.CurrentDirectory, "log.txt"); Logger.LogInfo($"Saving to {logPath}"); List<string> assetPaths = new List<string>() { "fonts.bundle", "videos.bundle", "shaders.bundle", "particles.bundle", "materials.bundle", "animations.bundle", "prefabs.bundle", "physicsmaterials.bundle", "models.bundle", "textures.bundle", }; //using (FileStream log = File.Open(logPath, FileMode.OpenOrCreate, FileAccess.Write)) //{ foreach(string assetPath in assetPaths) { Logger.LogInfo($"Attempting to load {assetPath}"); AssetBundle bundle = AssetBundle.LoadFromFile(Path.Combine(bundlePath, assetPath)); bundles.Add(bundle); //foreach (string name in bundle.GetAllAssetNames()) //{ // string line = $"[{bundle.name}][{name}]\n"; // log.Write(Encoding.ASCII.GetBytes(line), 0, line.Length); //} bundle.LoadAllAssets(); } //} */ // Plugin startup logic Logger.LogInfo($"Plugin {PluginInfo.PLUGIN_GUID} is loaded!"); harmonyTweaks = new Harmony(PLUGIN_GUID + "_tweaks"); harmonyBase = new Harmony(PLUGIN_GUID + "_base"); harmonyBase.Patch(GetMethod<DifficultySelectButton>("SetDifficulty"), postfix: GetHarmonyMethod(GetMethod<DifficultySelectPatch>("Postfix"))); harmonyBase.Patch(GetMethod<DifficultyTitle>("Check"), postfix: GetHarmonyMethod(GetMethod<DifficultyTitle_Check_Patch>("Postfix"))); harmonyBase.Patch(typeof(PrefsManager).GetConstructor(new Type[0]), postfix: GetHarmonyMethod(GetMethod<PrefsManager_Ctor>("Postfix"))); harmonyBase.Patch(GetMethod<PrefsManager>("EnsureValid"), prefix: GetHarmonyMethod(GetMethod<PrefsManager_EnsureValid>("Prefix"))); harmonyBase.Patch(GetMethod<Grenade>("Explode"), prefix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Prefix")), postfix: new HarmonyMethod(GetMethod<GrenadeExplosionOverride>("Postfix"))); LoadPrefabs(); ConfigManager.Initialize(); SceneManager.activeSceneChanged += OnSceneChange; } } public static class Tools { private static Transform _target; private static Transform target { get { if(_target == null) _target = MonoSingleton<PlayerTracker>.Instance.GetTarget(); return _target; } } public static Vector3 PredictPlayerPosition(float speedMod, Collider enemyCol = null) { Vector3 projectedPlayerPos; if (MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude == 0f) { return target.position; } RaycastHit raycastHit; if (enemyCol != null && Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, 4096, QueryTriggerInteraction.Collide) && raycastHit.collider == enemyCol) { projectedPlayerPos = target.position; } else if (Physics.Raycast(target.position, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(), out raycastHit, MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity().magnitude * 0.35f / speedMod, LayerMaskDefaults.Get(LMD.EnvironmentAndBigEnemies), QueryTriggerInteraction.Collide)) { projectedPlayerPos = raycastHit.point; } else { projectedPlayerPos = target.position + MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity() * 0.35f / speedMod; projectedPlayerPos = new Vector3(projectedPlayerPos.x, target.transform.position.y + (target.transform.position.y - projectedPlayerPos.y) * 0.5f, projectedPlayerPos.z); } return projectedPlayerPos; } } // Asset destroyer tracker /*[HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object) })] public class TempClass1 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.Destroy), new Type[] { typeof(UnityEngine.Object), typeof(float) })] public class TempClass2 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object) })] public class TempClass3 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } } [HarmonyPatch(typeof(UnityEngine.Object), nameof(UnityEngine.Object.DestroyImmediate), new Type[] { typeof(UnityEngine.Object), typeof(bool) })] public class TempClass4 { static void Postfix(UnityEngine.Object __0) { if (__0 != null && __0 == Plugin.homingProjectile) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Debug.LogError("Projectile destroyed"); Debug.LogError(t.ToString()); throw new Exception("Attempted to destroy proj"); } } }*/ }
Ultrapain/Plugin.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static ConfigPanel cerberusPanel;\n public static ConfigPanel dronePanel;\n public static ConfigPanel filthPanel;\n public static ConfigPanel hideousMassPanel;\n public static ConfigPanel maliciousFacePanel;\n public static ConfigPanel mindflayerPanel;\n public static ConfigPanel schismPanel;\n public static ConfigPanel soliderPanel;\n public static ConfigPanel stalkerPanel;\n public static ConfigPanel strayPanel;", "score": 0.8766963481903076 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static ConfigPanel streetCleanerPanel;\n public static ConfigPanel swordsMachinePanel;\n public static ConfigPanel virtuePanel;\n public static ConfigPanel ferrymanPanel;\n public static ConfigPanel turretPanel;\n public static ConfigPanel fleshPrisonPanel;\n public static ConfigPanel minosPrimePanel;\n public static ConfigPanel v2FirstPanel;\n public static ConfigPanel v2SecondPanel;\n public static ConfigPanel sisyInstPanel;", "score": 0.8635172843933105 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " public static ConfigPanel leviathanPanel;\n public static ConfigPanel somethingWickedPanel;\n public static ConfigPanel panopticonPanel;\n public static ConfigPanel idolPanel;\n // GLOBAL ENEMY CONFIG\n public static BoolField friendlyFireDamageOverrideToggle;\n public static FloatSliderField friendlyFireDamageOverrideExplosion;\n public static FloatSliderField friendlyFireDamageOverrideProjectile;\n public static FloatSliderField friendlyFireDamageOverrideFire;\n public static FloatSliderField friendlyFireDamageOverrideMelee;", "score": 0.8399264812469482 }, { "filename": "Ultrapain/ConfigManager.cs", "retrieved_chunk": " }\n // ROOT PANEL\n public static BoolField enemyTweakToggle;\n private static ConfigPanel enemyPanel;\n public static BoolField playerTweakToggle;\n private static ConfigPanel playerPanel;\n public static BoolField discordRichPresenceToggle;\n public static BoolField steamRichPresenceToggle;\n public static StringField pluginName;\n public static StringMultilineField pluginInfo;", "score": 0.831994891166687 }, { "filename": "Ultrapain/Patches/Virtue.cs", "retrieved_chunk": " }\n }\n class VirtueFlag : MonoBehaviour\n {\n public AudioSource lighningBoltSFX;\n public GameObject ligtningBoltAud;\n public Transform windupObj;\n private EnemyIdentifier eid;\n public Drone virtue;\n public void Awake()", "score": 0.8266016244888306 } ]
csharp
GameObject cannonBall;
using LibreDteDotNet.Common.Models; using LibreDteDotNet.RestRequest.Interfaces; namespace LibreDteDotNet.RestRequest.Extensions { public static class DTEExtension { public static IDTE Conectar(this IDTE folioService) { IDTE instance = folioService; return instance.SetCookieCertificado().ConfigureAwait(false).GetAwaiter().GetResult(); } public static async Task<IDTE> Validar(this
IDTE folioService, string pathfile) {
if (!File.Exists(pathfile)) { throw new Exception($"El Documento no existe en la ruta {pathfile}"); } IDTE instance = folioService; return await instance.Validar<EnvioDTE>(pathfile); } public static async Task<string> Enviar( this Task<IDTE> folioService, string rutCompany, string DvCompany ) { IDTE instance = await folioService; return await instance.Enviar(rutCompany, DvCompany); } } }
LibreDteDotNet.RestRequest/Extensions/DTEExtension.cs
sergiokml-LibreDteDotNet.RestRequest-6843109
[ { "filename": "LibreDteDotNet.RestRequest/Extensions/BoletaExtension.cs", "retrieved_chunk": "using LibreDteDotNet.RestRequest.Interfaces;\nnamespace LibreDteDotNet.RestRequest.Extensions\n{\n public static class BoletaExtension\n {\n public static IBoleta Conectar(this IBoleta folioService)\n {\n IBoleta instance = folioService;\n return instance.SetCookieCertificado().Result;\n }", "score": 0.85304856300354 }, { "filename": "LibreDteDotNet.RestRequest/Extensions/FolioCafExtension.cs", "retrieved_chunk": " }\n public static async Task<XDocument> Descargar(this Task<IFolioCaf> instance)\n {\n return await (await instance).Descargar();\n }\n public static async Task<IFolioCaf> Confirmar(this Task<IFolioCaf> instance)\n {\n return await (await instance).Confirmar();\n }\n }", "score": 0.8390483856201172 }, { "filename": "LibreDteDotNet.RestRequest/Extensions/FolioCafExtension.cs", "retrieved_chunk": "using System.Xml.Linq;\nusing LibreDteDotNet.RestRequest.Interfaces;\nnamespace LibreDteDotNet.RestRequest.Extensions\n{\n public static class FolioCafExtension\n {\n private static CancellationToken CancellationToken { get; set; }\n public static IFolioCaf Conectar(this IFolioCaf instance)\n {\n return instance.SetCookieCertificado().Result;", "score": 0.8228462934494019 }, { "filename": "LibreDteDotNet.RestRequest/Services/DTEService.cs", "retrieved_chunk": " }\n public async Task<string> GetInfoDte(\n string rutCompany,\n string dvCompany,\n TipoDoc tipoDTE,\n string folioDTE\n )\n {\n _ = await SetCookieCertificado(Properties.Resources.UrlValidaDte);\n if (HttpStatCode != HttpStatusCode.OK)", "score": 0.8178913593292236 }, { "filename": "LibreDteDotNet.RestRequest/Extensions/ContribuyenteExtension.cs", "retrieved_chunk": "using LibreDteDotNet.RestRequest.Interfaces;\nnamespace LibreDteDotNet.RestRequest.Extensions\n{\n public static class ContribuyenteExtension\n {\n public static IContribuyente Conectar(this IContribuyente folioService)\n {\n IContribuyente instance = folioService;\n return instance.SetCookieCertificado().Result;\n }", "score": 0.8175048828125 } ]
csharp
IDTE folioService, string pathfile) {
/* Copyright (c) 2023 Xavier Arpa López Thomas Peter ('Kingdox') Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using UnityEngine; using Kingdox.UniFlux.Core; namespace Kingdox.UniFlux.Benchmark { public class Benchmark_UniFlux : MonoFlux { [SerializeField] private Marker _m_store_string_add = new Marker() { K = "store<string,Action> ADD" }; [SerializeField] private Marker _m_store_int_add = new Marker() { K = "store<int,Action> ADD" }; [SerializeField] private Marker _m_store_byte_add = new Marker() { K = "store<byte,Action> ADD" }; [SerializeField] private Marker _m_store_bool_add = new Marker() { K = "store<bool,Action> ADD" }; [SerializeField] private Marker _m_store_string_remove = new Marker() { K = "store<string,Action> REMOVE" }; [SerializeField] private Marker _m_store_int_remove = new Marker() { K = "store<int,Action> REMOVE" }; [SerializeField] private Marker _m_store_byte_remove = new Marker() { K = "store<byte,Action> REMOVE" }; [SerializeField] private Marker _m_store_bool_remove = new Marker() { K = "store<bool,Action> REMOVE" }; [SerializeField] private Marker _m_dispatch_string = new Marker() { K = $"dispatch<string>" }; [SerializeField] private Marker _m_dispatch_int = new Marker() { K = $"dispatch<int>" }; [SerializeField] private Marker _m_dispatch_byte = new Marker() { K = $"dispatch<byte>" }; [SerializeField] private Marker _m_dispatch_bool = new Marker() { K = $"dispatch<bool>" }; private const byte __m_store = 52; private const byte __m_dispatch = 250; private Rect rect_area; private readonly Lazy<GUIStyle> _style = new Lazy<GUIStyle>(() => new GUIStyle("label") { fontSize = 28, alignment = TextAnchor.MiddleLeft, padding = new RectOffset(10, 0, 0, 0) }); [SerializeField] private int _iterations = default; [SerializeField] private List<string> _Results = default; public bool draw=true; public bool isUpdated = false; public bool isUpdated_store = false; public bool isUpdated_dispatch = false; protected override void OnFlux(in bool condition) { StoreTest_Add(); StoreTest_Remove(); } public void Start() { DispatchTest(); } private void Update() { if(!isUpdated) return; if(isUpdated_store) StoreTest_Add(); if(isUpdated_store) StoreTest_Remove(); if(isUpdated_dispatch) DispatchTest(); } private void StoreTest_Add() { // Store String if(_m_store_string_add.Execute) { _m_store_string_add.iteration=_iterations; _m_store_string_add.Begin(); for (int i = 0; i < _iterations; i++) { "Store".Store(Example_OnFlux, true); } _m_store_string_add.End(); } // Store Int if(_m_store_int_add.Execute) { _m_store_int_add.iteration=_iterations; _m_store_int_add.Begin(); for (int i = 0; i < _iterations; i++) { 42.Store(Example_OnFlux, true); } _m_store_int_add.End(); } // Store Byte if(_m_store_byte_add.Execute) { _m_store_byte_add.iteration=_iterations; _m_store_byte_add.Begin(); for (int i = 0; i < _iterations; i++) { Flux.Store(__m_store, Example_OnFlux, true); } _m_store_byte_add.End(); } // Store Bool if(_m_store_bool_add.Execute) { _m_store_bool_add.iteration=_iterations; _m_store_bool_add.Begin(); for (int i = 0; i < _iterations; i++) { Flux.Store(true, Example_OnFlux, true); } _m_store_bool_add.End(); } } private void StoreTest_Remove() { // Store String if(_m_store_string_remove.Execute) { _m_store_string_remove.iteration=_iterations; _m_store_string_remove.Begin(); for (int i = 0; i < _iterations; i++) { "Store".Store(Example_OnFlux, false); } _m_store_string_remove.End(); } // Store Int if(_m_store_int_remove.Execute) { _m_store_int_remove.iteration=_iterations; _m_store_int_remove.Begin(); for (int i = 0; i < _iterations; i++) { 42.Store(Example_OnFlux, false); } _m_store_int_remove.End(); } // Store Byte if(_m_store_byte_remove.Execute) { _m_store_byte_remove.iteration=_iterations; _m_store_byte_remove.Begin(); for (int i = 0; i < _iterations; i++) { Flux.Store(__m_store, Example_OnFlux, false); } _m_store_byte_remove.End(); } // Store Bool if(_m_store_bool_remove.Execute) { _m_store_bool_remove.iteration=_iterations; _m_store_bool_remove.Begin(); for (int i = 0; i < _iterations; i++) { Flux.Store(true, Example_OnFlux, false); } _m_store_bool_remove.End(); } } private void DispatchTest() { // Dispatch String if(_m_dispatch_string.Execute) { _m_dispatch_string.iteration=_iterations; _m_dispatch_string.Begin(); for (int i = 0; i < _iterations; i++) "UniFlux.Dispatch".Dispatch(); _m_dispatch_string.End(); } // Dispatch Int if(_m_dispatch_int.Execute) { _m_dispatch_int.iteration=_iterations; _m_dispatch_int.Begin(); for (int i = 0; i < _iterations; i++) 0.Dispatch(); _m_dispatch_int.End(); } // Dispatch Byte if(_m_dispatch_byte.Execute) { _m_dispatch_byte.iteration=_iterations; _m_dispatch_byte.Begin(); for (int i = 0; i < _iterations; i++) Flux.Dispatch(__m_dispatch); _m_dispatch_byte.End(); } // Dispatch Boolean if(_m_dispatch_bool.Execute) { _m_dispatch_bool.iteration=_iterations; _m_dispatch_bool.Begin(); for (int i = 0; i < _iterations; i++) Flux.Dispatch(true); _m_dispatch_bool.End(); } } [Flux("UniFlux.Dispatch")] private void Example_Dispatch_String(){} [Flux("UniFlux.Dispatch")] private void Example_Dispatch_String2(){} [Flux(0)] private void Example_Dispatch_Int(){} [Flux(__m_dispatch)] private void Example_Dispatch_Byte(){} [
Flux(false)] private void Example_Dispatch_Boolean_2(){
} [Flux(false)] private void Example_Dispatch_Boolean_3(){} [Flux(false)] private void Example_Dispatch_Boolean_4(){} [Flux(false)] private void Example_Dispatch_Boolean_5(){} [Flux(false)] private void Example_Dispatch_Boolean_6(){} [Flux(true)] private void Example_Dispatch_Boolean(){} private void Example_OnFlux(){} private void OnGUI() { if(!draw)return; _Results.Clear(); _Results.Add(_m_store_string_add.Visual); _Results.Add(_m_store_int_add.Visual); _Results.Add(_m_store_byte_add.Visual); _Results.Add(_m_store_bool_add.Visual); _Results.Add(_m_store_string_remove.Visual); _Results.Add(_m_store_int_remove.Visual); _Results.Add(_m_store_byte_remove.Visual); _Results.Add(_m_store_bool_remove.Visual); _Results.Add(_m_dispatch_string.Visual); _Results.Add(_m_dispatch_int.Visual); _Results.Add(_m_dispatch_byte.Visual); _Results.Add(_m_dispatch_bool.Visual); var height = (float) Screen.height / 2; for (int i = 0; i < _Results.Count; i++) { rect_area = new Rect(0, _style.Value.lineHeight * i, Screen.width, height); GUI.Label(rect_area, _Results[i], _style.Value); } } } }
Benchmark/General/Benchmark_UniFlux.cs
xavierarpa-UniFlux-a2d46de
[ { "filename": "Benchmark/Nest/Benchmark_Nest_UniFlux.cs", "retrieved_chunk": " private void Update() \n {\n Sample();\n Sample_2();\n }\n [Flux(\"A\")] private void A() => \"B\".Dispatch();\n [Flux(\"B\")] private void B() => \"C\".Dispatch();\n [Flux(\"C\")] private void C() => \"D\".Dispatch();\n [Flux(\"D\")] private void D() => \"E\".Dispatch();\n [Flux(\"E\")] private void E() {}", "score": 0.8441215753555298 }, { "filename": "Tests/EditMode/EditMode_Test_1.cs", "retrieved_chunk": " Flux.Dispatch(\"OnTest\", true);\n }\n [Test] public void DispatchFunc()\n {\n var val = Flux.Dispatch<string,int>(\"OnTest\");\n }\n [Test] public void DispatchFuncParam()\n {\n var val_2 = Flux.Dispatch<string, float, float>(\"OnTest\", 3f);\n }", "score": 0.8146506547927856 }, { "filename": "Samples/UniFlux.Sample.Experimental/UniFlux_Exp_S_1_B.cs", "retrieved_chunk": "{\n public class UniFlux_Exp_S_1_B : MonoFlux\n {\n [SerializeField] KeyFluxBase k_doSample;\n [SerializeField] KeyFlux k_onSample;\n protected override void OnFlux(in bool condition) => k_doSample.Store(DoSample, condition);\n private void DoSample() => k_onSample.Dispatch();\n }\n}", "score": 0.809035062789917 }, { "filename": "Tests/EditMode/EditMode_Test_1.cs", "retrieved_chunk": " Flux.Store(\"OnTest\", OnTest_Action, true);\n }\n [Test] public void SubscribeActionParam()\n {\n Flux.Store<string,bool>(\"OnTest\", OnTest_ActionParam, true);\n }\n [Test] public void SubscribeFunc()\n {\n Flux.Store<string, int>(\"OnTest\", OnTest_Func, true);\n }", "score": 0.8047174215316772 }, { "filename": "Tests/EditMode/EditMode_Test_1.cs", "retrieved_chunk": " [Test] public void SubscribeFuncParam()\n {\n Flux.Store<string,float,float>(\"OnTest\", OnTest_FuncPatam, true);\n }\n [Test] public void DispatchAction()\n {\n Flux.Dispatch(\"OnTest\");\n }\n [Test] public void DispatchActionParam()\n {", "score": 0.7955899238586426 } ]
csharp
Flux(false)] private void Example_Dispatch_Boolean_2(){
using HarmonyLib; using Mono.Cecil; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Text; using UnityEngine; namespace Ultrapain.Patches { /* u = initial, f = final, d = delta, s = speed multiplier u = 40f * Time.deltaTime f = 40f * S * Time.deltaTime d = 40f * Time.deltaTime * (S - 1) revCharge += 40f * Time.deltaTime * (S - 1f) * (alt ? 0.5f : 1f) */ class Revolver_Update { static bool Prefix(Revolver __instance) { if(__instance.gunVariation == 0 && __instance.pierceCharge < 100f) { __instance.pierceCharge = Mathf.Min(100f, __instance.pierceCharge + 40f * Time.deltaTime * (ConfigManager.chargedRevRegSpeedMulti.value - 1f) * (__instance.altVersion ? 0.5f : 1f)); } return true; } } public class Revolver_Shoot { public static void RevolverBeamEdit(RevolverBeam beam) { beam.damage -= beam.strongAlt ? 1.25f : 1f; beam.damage += beam.strongAlt ? ConfigManager.revolverAltDamage.value : ConfigManager.revolverDamage.value; } public static void RevolverBeamSuperEdit(RevolverBeam beam) { if (beam.gunVariation == 0) { beam.damage -= beam.strongAlt ? 1.25f : 1f; beam.damage += beam.strongAlt ? ConfigManager.chargedAltRevDamage.value : ConfigManager.chargedRevDamage.value; beam.hitAmount = beam.strongAlt ? ConfigManager.chargedAltRevTotalHits.value : ConfigManager.chargedRevTotalHits.value; beam.maxHitsPerTarget = beam.strongAlt ? ConfigManager.chargedAltRevMaxHitsPerTarget.value : ConfigManager.chargedRevMaxHitsPerTarget.value; } else if (beam.gunVariation == 2) { beam.damage -= beam.strongAlt ? 1.25f : 1f; beam.damage += beam.strongAlt ? ConfigManager.sharpshooterAltDamage.value : ConfigManager.sharpshooterDamage.value; beam.maxHitsPerTarget = beam.strongAlt ? ConfigManager.sharpshooterAltMaxHitsPerTarget.value : ConfigManager.sharpshooterMaxHitsPerTarget.value; } } static FieldInfo f_RevolverBeam_gunVariation = typeof(RevolverBeam).GetField("gunVariation", UnityUtils.instanceFlag); static MethodInfo m_Revolver_Shoot_RevolverBeamEdit = typeof(Revolver_Shoot).GetMethod("RevolverBeamEdit", UnityUtils.staticFlag); static MethodInfo m_Revolver_Shoot_RevolverBeamSuperEdit = typeof(Revolver_Shoot).GetMethod("RevolverBeamSuperEdit", UnityUtils.staticFlag); static MethodInfo m_GameObject_GetComponent_RevolverBeam = typeof(GameObject).GetMethod("GetComponent", new Type[0], new ParameterModifier[0]).MakeGenericMethod(new Type[1] { typeof(RevolverBeam) }); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); object normalBeamLocalIndex = null; object superBeamLocalIndex = null; // Get local indexes of components for RevolverBeam references for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Callvirt && code[i].OperandIs(m_GameObject_GetComponent_RevolverBeam)) { object localIndex = ILUtils.GetLocalIndex(code[i + 1]); if (localIndex == null) continue; if (normalBeamLocalIndex == null) { normalBeamLocalIndex = localIndex; } else { superBeamLocalIndex = localIndex; break; } } } Debug.Log($"Normal beam index: {normalBeamLocalIndex}"); Debug.Log($"Super beam index: {superBeamLocalIndex}"); // Modify normal beam for (int i = 3; i < code.Count; i++) { if (code[i].opcode == OpCodes.Stfld && code[i].OperandIs(f_RevolverBeam_gunVariation)) { object localIndex = ILUtils.GetLocalIndex(code[i - 3]); if (localIndex == null) continue; if (localIndex.Equals(normalBeamLocalIndex)) { Debug.Log($"Patching normal beam"); i += 1; code.Insert(i, ILUtils.LoadLocalInstruction(localIndex)); i += 1; code.Insert(i, new CodeInstruction(OpCodes.Call, m_Revolver_Shoot_RevolverBeamEdit)); break; } } } // Modify super beam for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Stfld && code[i].OperandIs(f_RevolverBeam_gunVariation)) { object localIndex = ILUtils.GetLocalIndex(code[i - 3]); if (localIndex == null) continue; if (localIndex.Equals(superBeamLocalIndex)) { Debug.Log($"Patching super beam"); i += 1; code.Insert(i, ILUtils.LoadLocalInstruction(localIndex)); i += 1; code.Insert(i, new CodeInstruction(OpCodes.Call, m_Revolver_Shoot_RevolverBeamSuperEdit)); break; } } } return code.AsEnumerable(); } } public class Shotgun_Shoot { public static void ModifyShotgunPellet(Projectile proj, Shotgun shotgun, int primaryCharge) { if (shotgun.variation == 0) { proj.damage = ConfigManager.shotgunBlueDamagePerPellet.value; } else { if (primaryCharge == 0) proj.damage = ConfigManager.shotgunGreenPump1Damage.value; else if (primaryCharge == 1) proj.damage = ConfigManager.shotgunGreenPump2Damage.value; else if (primaryCharge == 2) proj.damage = ConfigManager.shotgunGreenPump3Damage.value; } } public static void ModifyPumpExplosion(Explosion exp) { exp.damage = ConfigManager.shotgunGreenExplosionDamage.value; exp.playerDamageOverride = ConfigManager.shotgunGreenExplosionPlayerDamage.value; float sizeMulti = ConfigManager.shotgunGreenExplosionSize.value / 9f; exp.maxSize *= sizeMulti; exp.speed *= sizeMulti; exp.speed *= ConfigManager.shotgunGreenExplosionSpeed.value; } static MethodInfo m_GameObject_GetComponent_Projectile = typeof(GameObject).GetMethod("GetComponent", new Type[0], new ParameterModifier[0]).MakeGenericMethod(new Type[1] { typeof(Projectile) }); static MethodInfo m_GameObject_GetComponentsInChildren_Explosion = typeof(GameObject).GetMethod("GetComponentsInChildren", new Type[0], new ParameterModifier[0]).MakeGenericMethod(new Type[1] { typeof(Explosion) }); static MethodInfo m_Shotgun_Shoot_ModifyShotgunPellet = typeof(Shotgun_Shoot).GetMethod("ModifyShotgunPellet", UnityUtils.staticFlag); static MethodInfo m_Shotgun_Shoot_ModifyPumpExplosion = typeof(Shotgun_Shoot).GetMethod("ModifyPumpExplosion", UnityUtils.staticFlag); static FieldInfo f_Shotgun_primaryCharge = typeof(Shotgun).GetField("primaryCharge", UnityUtils.instanceFlag); static FieldInfo f_Explosion_damage = typeof(Explosion).GetField("damage", UnityUtils.instanceFlag); static bool Prefix(
Shotgun __instance, int ___primaryCharge) {
if (__instance.variation == 0) { __instance.spread = ConfigManager.shotgunBlueSpreadAngle.value; } else { if (___primaryCharge == 0) __instance.spread = ConfigManager.shotgunGreenPump1Spread.value * 1.5f; else if (___primaryCharge == 1) __instance.spread = ConfigManager.shotgunGreenPump2Spread.value; else if (___primaryCharge == 2) __instance.spread = ConfigManager.shotgunGreenPump3Spread.value / 2f; } return true; } static void Postfix(Shotgun __instance) { __instance.spread = 10f; } static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); CodeInstruction pelletStoreInst = new CodeInstruction(OpCodes.Stloc_0); int pelletCodeIndex = 0; // Find pellet local variable index for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Ldc_I4_S && code[i].OperandIs(12)) { if (ConfigManager.shotgunBluePelletCount.value > sbyte.MaxValue) code[i].opcode = OpCodes.Ldc_I4; code[i].operand = ConfigManager.shotgunBluePelletCount.value; i += 1; pelletCodeIndex = i; pelletStoreInst = code[i]; break; } } // Debug.Log($"Pellet store instruction: {ILUtils.TurnInstToString(pelletStoreInst)}"); // Modify pellet counts for (int i = pelletCodeIndex + 1; i < code.Count; i++) { if (code[i].opcode == pelletStoreInst.opcode && (pelletStoreInst.operand == null ? true : pelletStoreInst.operand.Equals(code[i].operand)) && ILUtils.IsConstI4LoadWithOperand(code[i - 1].opcode)) { int constIndex = i - 1; int pelletCount = ILUtils.GetI4LoadOperand(code[constIndex]); if (pelletCount == 10) pelletCount = ConfigManager.shotgunGreenPump1Count.value; else if (pelletCount == 16) pelletCount = ConfigManager.shotgunGreenPump2Count.value; else if (pelletCount == 24) pelletCount = ConfigManager.shotgunGreenPump3Count.value; if (ILUtils.TryEfficientLoadI4(pelletCount, out OpCode efficientOpcode)) { code[constIndex].operand = null; code[constIndex].opcode = efficientOpcode; } else { if (pelletCount > sbyte.MaxValue) code[constIndex].opcode = OpCodes.Ldc_I4; else code[constIndex].opcode = OpCodes.Ldc_I4_S; code[constIndex].operand = pelletCount; } } } // Modify projectile damage for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Callvirt && code[i].OperandIs(m_GameObject_GetComponent_Projectile)) { i += 1; // Duplicate component (arg 0) code.Insert(i, new CodeInstruction(OpCodes.Dup)); i += 1; // Add instance to stack (arg 1) code.Insert(i, new CodeInstruction(OpCodes.Ldarg_0)); i += 1; // Load instance then get primary field (arg 2) code.Insert(i, new CodeInstruction(OpCodes.Ldarg_0)); i += 1; code.Insert(i, new CodeInstruction(OpCodes.Ldfld, f_Shotgun_primaryCharge)); i += 1; // Call the static method code.Insert(i, new CodeInstruction(OpCodes.Call, m_Shotgun_Shoot_ModifyShotgunPellet)); break; } } // Modify pump explosion int pumpExplosionIndex = 0; while (code[pumpExplosionIndex].opcode != OpCodes.Callvirt && !code[pumpExplosionIndex].OperandIs(m_GameObject_GetComponentsInChildren_Explosion)) pumpExplosionIndex += 1; for (int i = pumpExplosionIndex; i < code.Count; i++) { if (code[i].opcode == OpCodes.Stfld) { if (code[i].OperandIs(f_Explosion_damage)) { // Duplicate before damage assignment code.Insert(i - 1, new CodeInstruction(OpCodes.Dup)); i += 2; // Argument 0 already loaded, call the method code.Insert(i, new CodeInstruction(OpCodes.Call, m_Shotgun_Shoot_ModifyPumpExplosion)); // Stack is now clear break; } } } return code.AsEnumerable(); } } // Core eject class Shotgun_ShootSinks { public static void ModifyCoreEject(GameObject core) { GrenadeExplosionOverride ovr = core.AddComponent<GrenadeExplosionOverride>(); ovr.normalMod = true; ovr.normalDamage = (float)ConfigManager.shotgunCoreExplosionDamage.value / 35f; ovr.normalSize = (float)ConfigManager.shotgunCoreExplosionSize.value / 6f * ConfigManager.shotgunCoreExplosionSpeed.value; ovr.normalPlayerDamageOverride = ConfigManager.shotgunCoreExplosionPlayerDamage.value; ovr.superMod = true; ovr.superDamage = (float)ConfigManager.shotgunCoreExplosionDamage.value / 35f; ovr.superSize = (float)ConfigManager.shotgunCoreExplosionSize.value / 6f * ConfigManager.shotgunCoreExplosionSpeed.value; ovr.superPlayerDamageOverride = ConfigManager.shotgunCoreExplosionPlayerDamage.value; } static FieldInfo f_Grenade_sourceWeapon = typeof(Grenade).GetField("sourceWeapon", UnityUtils.instanceFlag); static MethodInfo m_Shotgun_ShootSinks_ModifyCoreEject = typeof(Shotgun_ShootSinks).GetMethod("ModifyCoreEject", UnityUtils.staticFlag); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Stfld && code[i].OperandIs(f_Grenade_sourceWeapon)) { i += 1; // Add arg 0 code.Insert(i, new CodeInstruction(OpCodes.Dup)); i += 1; // Call mod method code.Insert(i, new CodeInstruction(OpCodes.Call, m_Shotgun_ShootSinks_ModifyCoreEject)); break; } } return code.AsEnumerable(); } } class Nailgun_Shoot { static FieldInfo f_Nailgun_heatSinks = typeof(Nailgun).GetField("heatSinks", UnityUtils.instanceFlag); static FieldInfo f_Nailgun_heatUp = typeof(Nailgun).GetField("heatUp", UnityUtils.instanceFlag); public static void ModifyNail(Nailgun inst, GameObject nail) { Nail comp = nail.GetComponent<Nail>(); if (inst.altVersion) { // Blue saw launcher if (inst.variation == 1) { comp.damage = ConfigManager.sawBlueDamage.value; comp.hitAmount = ConfigManager.sawBlueHitAmount.value; } // Green saw launcher else { comp.damage = ConfigManager.sawGreenDamage.value; float maxHit = ConfigManager.sawGreenHitAmount.value; float heatSinks = (float)f_Nailgun_heatSinks.GetValue(inst); float heatUp = (float)f_Nailgun_heatUp.GetValue(inst); if (heatSinks >= 1) comp.hitAmount = Mathf.Lerp(maxHit, Mathf.Max(1f, maxHit), (maxHit - 2f) * heatUp); else comp.hitAmount = 1f; } } else { // Blue nailgun if (inst.variation == 1) { comp.damage = ConfigManager.nailgunBlueDamage.value; } else { if (comp.heated) comp.damage = ConfigManager.nailgunGreenBurningDamage.value; else comp.damage = ConfigManager.nailgunGreenDamage.value; } } } static FieldInfo f_Nailgun_nail = typeof(Nailgun).GetField("nail", UnityUtils.instanceFlag); static MethodInfo m_Nailgun_Shoot_ModifyNail = typeof(Nailgun_Shoot).GetMethod("ModifyNail", UnityUtils.staticFlag); static MethodInfo m_Transform_set_forward = typeof(Transform).GetProperty("forward", UnityUtils.instanceFlag).GetSetMethod(); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); CodeInstruction localObjectStoreInst = null; for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Ldfld && code[i].OperandIs(f_Nailgun_nail)) { for (; i < code.Count; i++) if (ILUtils.IsStoreLocalOpcode(code[i].opcode)) break; localObjectStoreInst = code[i]; } } Debug.Log($"Nail local reference: {ILUtils.TurnInstToString(localObjectStoreInst)}"); int insertIndex = 0; for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Callvirt && code[i].OperandIs(m_Transform_set_forward)) { insertIndex = i + 1; break; } } // Push instance reference code.Insert(insertIndex, new CodeInstruction(OpCodes.Ldarg_0)); insertIndex += 1; // Push local nail object code.Insert(insertIndex, new CodeInstruction(ILUtils.GetLoadLocalFromStoreLocal(localObjectStoreInst.opcode), localObjectStoreInst.operand)); insertIndex += 1; // Call the method code.Insert(insertIndex, new CodeInstruction(OpCodes.Call, m_Nailgun_Shoot_ModifyNail)); return code.AsEnumerable(); } } class Nailgun_SuperSaw { public static void ModifySupersaw(GameObject supersaw) { Nail saw = supersaw.GetComponent<Nail>(); saw.damage = ConfigManager.sawGreenBurningDamage.value; saw.hitAmount = ConfigManager.sawGreenBurningHitAmount.value; } static FieldInfo f_Nailgun_heatedNail = typeof(Nailgun).GetField("heatedNail", UnityUtils.instanceFlag); static MethodInfo m_Nailgun_SuperSaw_ModifySupersaw = typeof(Nailgun_SuperSaw).GetMethod("ModifySupersaw", UnityUtils.staticFlag); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); CodeInstruction localObjectStoreInst = null; for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Ldfld && code[i].OperandIs(f_Nailgun_heatedNail)) { for (; i < code.Count; i++) if (ILUtils.IsStoreLocalOpcode(code[i].opcode)) break; localObjectStoreInst = code[i]; } } Debug.Log($"Supersaw local reference: {ILUtils.TurnInstToString(localObjectStoreInst)}"); int insertIndex = code.Count - 1; // Push local nail object code.Insert(insertIndex, new CodeInstruction(ILUtils.GetLoadLocalFromStoreLocal(localObjectStoreInst.opcode), localObjectStoreInst.operand)); insertIndex += 1; // Call the method code.Insert(insertIndex, new CodeInstruction(OpCodes.Call, m_Nailgun_SuperSaw_ModifySupersaw)); return code.AsEnumerable(); } } class NailGun_Update { static bool Prefix(Nailgun __instance, ref float ___heatSinks) { if(__instance.variation == 0) { float maxSinks = (__instance.altVersion ? 1f : 2f); float multi = (__instance.altVersion ? ConfigManager.sawHeatsinkRegSpeedMulti.value : ConfigManager.nailgunHeatsinkRegSpeedMulti.value); float rate = 0.125f; if (___heatSinks < maxSinks && multi != 1) ___heatSinks = Mathf.Min(maxSinks, ___heatSinks + Time.deltaTime * rate * (multi - 1f)); } return true; } } class NewMovement_Update { static bool Prefix(NewMovement __instance, int ___difficulty) { if (__instance.boostCharge < 300f && !__instance.sliding && !__instance.slowMode) { float multi = 1f; if (___difficulty == 1) multi = 1.5f; else if (___difficulty == 0f) multi = 2f; __instance.boostCharge = Mathf.Min(300f, __instance.boostCharge + Time.deltaTime * 70f * multi * (ConfigManager.staminaRegSpeedMulti.value - 1f)); } return true; } } class WeaponCharges_Charge { static bool Prefix(WeaponCharges __instance, float __0) { if (__instance.rev1charge < 400f) __instance.rev1charge = Mathf.Min(400f, __instance.rev1charge + 25f * __0 * (ConfigManager.coinRegSpeedMulti.value - 1f)); if (__instance.rev2charge < 300f) __instance.rev2charge = Mathf.Min(300f, __instance.rev2charge + (__instance.rev2alt ? 35f : 15f) * __0 * (ConfigManager.sharpshooterRegSpeedMulti.value - 1f)); if(!__instance.naiAmmoDontCharge) { if (__instance.naiAmmo < 100f) __instance.naiAmmo = Mathf.Min(100f, __instance.naiAmmo + __0 * 3.5f * (ConfigManager.nailgunAmmoRegSpeedMulti.value - 1f)); ; if (__instance.naiSaws < 10f) __instance.naiSaws = Mathf.Min(10f, __instance.naiSaws + __0 * 0.5f * (ConfigManager.sawAmmoRegSpeedMulti.value - 1f)); } if (__instance.raicharge < 5f) __instance.raicharge = Mathf.Min(5f, __instance.raicharge + __0 * 0.25f * (ConfigManager.railcannonRegSpeedMulti.value - 1f)); if (!__instance.rocketFrozen && __instance.rocketFreezeTime < 5f) __instance.rocketFreezeTime = Mathf.Min(5f, __instance.rocketFreezeTime + __0 * 0.5f * (ConfigManager.rocketFreezeRegSpeedMulti.value - 1f)); if (__instance.rocketCannonballCharge < 1f) __instance.rocketCannonballCharge = Mathf.Min(1f, __instance.rocketCannonballCharge + __0 * 0.125f * (ConfigManager.rocketCannonballRegSpeedMulti.value - 1f)); return true; } } class NewMovement_GetHurt { static bool Prefix(NewMovement __instance, out float __state) { __state = __instance.antiHp; return true; } static void Postfix(NewMovement __instance, float __state) { float deltaAnti = __instance.antiHp - __state; if (deltaAnti <= 0) return; deltaAnti *= ConfigManager.hardDamagePercent.normalizedValue; __instance.antiHp = __state + deltaAnti; } static FieldInfo hpField = typeof(NewMovement).GetField("hp"); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Ldfld && (FieldInfo)code[i].operand == hpField) { i += 1; if (code[i].opcode == OpCodes.Ldc_I4_S) { code[i] = new CodeInstruction(OpCodes.Ldc_I4, (Int32)ConfigManager.maxPlayerHp.value); } } else if (code[i].opcode == OpCodes.Ldc_R4 && (Single)code[i].operand == (Single)99f) { code[i] = new CodeInstruction(OpCodes.Ldc_R4, (Single)(ConfigManager.maxPlayerHp.value - 1)); } } return code.AsEnumerable(); } } class HookArm_FixedUpdate { static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Ldc_R4 && (Single)code[i].operand == 66f) { code[i] = new CodeInstruction(OpCodes.Ldc_R4, (Single)(66f * (ConfigManager.maxPlayerHp.value / 100f) * ConfigManager.whiplashHardDamageSpeed.value)); } else if (code[i].opcode == OpCodes.Ldc_R4 && (Single)code[i].operand == 50f) { code[i] = new CodeInstruction(OpCodes.Ldc_R4, (Single)(ConfigManager.whiplashHardDamageCap.value)); } } return code.AsEnumerable(); } } class NewMovement_ForceAntiHP { static FieldInfo hpField = typeof(NewMovement).GetField("hp"); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Ldfld && (FieldInfo)code[i].operand == hpField) { i += 1; if (i < code.Count && code[i].opcode == OpCodes.Ldc_I4_S && (SByte)code[i].operand == (SByte)100) { code[i] = new CodeInstruction(OpCodes.Ldc_I4, (Int32)ConfigManager.maxPlayerHp.value); } } else if (code[i].opcode == OpCodes.Ldarg_1) { i += 2; if (i < code.Count && code[i].opcode == OpCodes.Ldc_R4 && (Single)code[i].operand == 99f) { code[i] = new CodeInstruction(OpCodes.Ldc_R4, (Single)(ConfigManager.maxPlayerHp.value - 1)); } } else if (code[i].opcode == OpCodes.Ldc_R4 && (Single)code[i].operand == 100f) { code[i] = new CodeInstruction(OpCodes.Ldc_R4, (Single)ConfigManager.maxPlayerHp.value); } else if (code[i].opcode == OpCodes.Ldc_R4 && (Single)code[i].operand == 50f) { code[i] = new CodeInstruction(OpCodes.Ldc_R4, (Single)ConfigManager.maxPlayerHp.value / 2); } else if (code[i].opcode == OpCodes.Ldc_I4_S && (SByte)code[i].operand == (SByte)100) { code[i] = new CodeInstruction(OpCodes.Ldc_I4, (Int32)ConfigManager.maxPlayerHp.value); } } return code.AsEnumerable(); } } class NewMovement_GetHealth { static bool Prefix(NewMovement __instance, int __0, bool __1, ref AudioSource ___greenHpAud, Canvas ___fullHud) { if (__instance.dead || __instance.exploded) return false; int maxHp = Mathf.RoundToInt(ConfigManager.maxPlayerHp.value - __instance.antiHp); int maxDelta = maxHp - __instance.hp; if (maxDelta <= 0) return true; if (!__1 && __0 > 5 && MonoSingleton<PrefsManager>.Instance.GetBoolLocal("bloodEnabled", false)) { GameObject.Instantiate<GameObject>(__instance.scrnBlood, ___fullHud.transform); } __instance.hp = Mathf.Min(maxHp, __instance.hp + __0); __instance.hpFlash.Flash(1f); if (!__1 && __0 > 5) { if (___greenHpAud == null) { ___greenHpAud = __instance.hpFlash.GetComponent<AudioSource>(); } ___greenHpAud.Play(); } return false; } } class NewMovement_SuperCharge { static bool Prefix(NewMovement __instance) { __instance.hp = Mathf.Max(ConfigManager.maxPlayerHp.value, ConfigManager.playerHpSupercharge.value); return false; } } class NewMovement_Respawn { static void Postfix(NewMovement __instance) { __instance.hp = ConfigManager.maxPlayerHp.value; } } class NewMovement_DeltaHpComp : MonoBehaviour { public static NewMovement_DeltaHpComp instance; private NewMovement player; private AudioSource hurtAud; private bool levelMap = false; private void Awake() { instance = this; player = NewMovement.Instance; hurtAud = player.hurtScreen.GetComponent<AudioSource>(); levelMap = SceneHelper.CurrentLevelNumber > 0; UpdateEnabled(); } public void UpdateEnabled() { if (!ConfigManager.playerHpDeltaToggle.value) enabled = false; if (SceneHelper.CurrentScene == "uk_construct") enabled = ConfigManager.playerHpDeltaSandbox.value; else if (SceneHelper.CurrentScene == "Endless") enabled = ConfigManager.playerHpDeltaCybergrind.value; else { enabled = SceneHelper.CurrentLevelNumber > 0; } } public void ResetCooldown() { deltaCooldown = ConfigManager.playerHpDeltaDelay.value; } public float deltaCooldown = ConfigManager.playerHpDeltaDelay.value; public void Update() { if (player.dead || !ConfigManager.playerHpDeltaToggle.value || !StatsManager.Instance.timer) { ResetCooldown(); return; } if (levelMap) { // Calm if (MusicManager.Instance.requestedThemes == 0) { if (!ConfigManager.playerHpDeltaCalm.value) { ResetCooldown(); return; } } // Combat else { if (!ConfigManager.playerHpDeltaCombat.value) { ResetCooldown(); return; } } } deltaCooldown = Mathf.MoveTowards(deltaCooldown, 0f, Time.deltaTime); if (deltaCooldown == 0f) { ResetCooldown(); int deltaHp = ConfigManager.playerHpDeltaAmount.value; int limit = ConfigManager.playerHpDeltaLimit.value; if (deltaHp == 0) return; if (deltaHp > 0) { if (player.hp > limit) return; player.GetHealth(deltaHp, true); } else { if (player.hp < limit) return; if (player.hp - deltaHp <= 0) player.GetHurt(-deltaHp, false, 0, false, false); else { player.hp += deltaHp; if (ConfigManager.playerHpDeltaHurtAudio.value) { hurtAud.pitch = UnityEngine.Random.Range(0.8f, 1f); hurtAud.PlayOneShot(hurtAud.clip); } } } } } } class NewMovement_Start { static void Postfix(NewMovement __instance) { __instance.gameObject.AddComponent<NewMovement_DeltaHpComp>(); __instance.hp = ConfigManager.maxPlayerHp.value; } } class HealthBarTracker : MonoBehaviour { public static List<HealthBarTracker> instances = new List<HealthBarTracker>(); private HealthBar hb; private void Awake() { if (hb == null) hb = GetComponent<HealthBar>(); instances.Add(this); for (int i = instances.Count - 1; i >= 0; i--) { if (instances[i] == null) instances.RemoveAt(i); } } private void OnDestroy() { if (instances.Contains(this)) instances.Remove(this); } public void SetSliderRange() { if (hb == null) hb = GetComponent<HealthBar>(); if (hb.hpSliders.Length != 0) { hb.hpSliders[0].maxValue = hb.afterImageSliders[0].maxValue = ConfigManager.maxPlayerHp.value; hb.hpSliders[1].minValue = hb.afterImageSliders[1].minValue = ConfigManager.maxPlayerHp.value; hb.hpSliders[1].maxValue = hb.afterImageSliders[1].maxValue = Mathf.Max(ConfigManager.maxPlayerHp.value, ConfigManager.playerHpSupercharge.value); hb.antiHpSlider.maxValue = ConfigManager.maxPlayerHp.value; } } } class HealthBar_Start { static void Postfix(HealthBar __instance) { __instance.gameObject.AddComponent<HealthBarTracker>().SetSliderRange(); } } class HealthBar_Update { static FieldInfo f_HealthBar_hp = typeof(HealthBar).GetField("hp", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); static FieldInfo f_HealthBar_antiHp = typeof(HealthBar).GetField("antiHp", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> code = new List<CodeInstruction>(instructions); for (int i = 0; i < code.Count; i++) { CodeInstruction inst = code[i]; if (inst.opcode == OpCodes.Ldc_R4 && code[i - 1].OperandIs(f_HealthBar_hp)) { float operand = (Single)inst.operand; if (operand == 30f) code[i].operand = (Single)(ConfigManager.maxPlayerHp.value * 0.3f); else if (operand == 50f) code[i].operand = (Single)(ConfigManager.maxPlayerHp.value * 0.5f); } else if (inst.opcode == OpCodes.Ldstr) { string operand = (string)inst.operand; if (operand == "/200") code[i].operand = $"/{ConfigManager.playerHpSupercharge}"; } else if (inst.opcode == OpCodes.Ldc_R4 && i + 2 < code.Count && code[i + 2].OperandIs(f_HealthBar_antiHp)) { code[i].operand = (Single)ConfigManager.maxPlayerHp.value; } } return code.AsEnumerable(); } } }
Ultrapain/Patches/PlayerStatTweaks.cs
eternalUnion-UltraPain-ad924af
[ { "filename": "Ultrapain/Patches/Panopticon.cs", "retrieved_chunk": " comp.turningSpeedMultiplier *= ConfigManager.panopticonBlueProjTurnSpeed.value;\n comp.speed = ConfigManager.panopticonBlueProjInitialSpeed.value;\n }\n }\n static MethodInfo m_Panopticon_BlueProjectile_BlueProjectileSpawn = typeof(Panopticon_BlueProjectile).GetMethod(\"BlueProjectileSpawn\", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);\n static MethodInfo m_GameObject_GetComponent_Projectile = typeof(GameObject).GetMethod(\"GetComponent\", new Type[0]).MakeGenericMethod(new Type[1] { typeof(Projectile) });\n static IEnumerable Transpiler(IEnumerable<CodeInstruction> instructions)\n {\n List<CodeInstruction> code = new List<CodeInstruction>(instructions);\n for (int i = 0; i < code.Count; i++)", "score": 0.8091391324996948 }, { "filename": "Ultrapain/Plugin.cs", "retrieved_chunk": " harmonyTweaks.Patch(GetMethod<GabrielSecond>(\"FastCombo\"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_FastCombo>(\"Postfix\")));\n harmonyTweaks.Patch(GetMethod<GabrielSecond>(\"CombineSwords\"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_CombineSwords>(\"Postfix\")));\n harmonyTweaks.Patch(GetMethod<GabrielSecond>(\"ThrowCombo\"), postfix: GetHarmonyMethod(GetMethod<GabrielSecond_ThrowCombo>(\"Postfix\")));\n */\n }\n private static void PatchAllPlayers()\n {\n if (!ConfigManager.playerTweakToggle.value)\n return;\n harmonyTweaks.Patch(GetMethod<Punch>(\"CheckForProjectile\"), prefix: GetHarmonyMethod(GetMethod<Punch_CheckForProjectile_Patch>(\"Prefix\")));", "score": 0.7754932641983032 }, { "filename": "Ultrapain/Plugin.cs", "retrieved_chunk": " if(ConfigManager.staminaRegSpeedMulti.value != 1)\n harmonyTweaks.Patch(GetMethod<NewMovement>(\"Update\"), prefix: GetHarmonyMethod(GetMethod<NewMovement_Update>(\"Prefix\")));\n if(ConfigManager.playerHpDeltaToggle.value || ConfigManager.maxPlayerHp.value != 100 || ConfigManager.playerHpSupercharge.value != 200 || ConfigManager.whiplashHardDamageCap.value != 50 || ConfigManager.whiplashHardDamageSpeed.value != 1)\n {\n harmonyTweaks.Patch(GetMethod<NewMovement>(\"GetHealth\"), prefix: GetHarmonyMethod(GetMethod<NewMovement_GetHealth>(\"Prefix\")));\n harmonyTweaks.Patch(GetMethod<NewMovement>(\"SuperCharge\"), prefix: GetHarmonyMethod(GetMethod<NewMovement_SuperCharge>(\"Prefix\")));\n harmonyTweaks.Patch(GetMethod<NewMovement>(\"Respawn\"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Respawn>(\"Postfix\")));\n harmonyTweaks.Patch(GetMethod<NewMovement>(\"Start\"), postfix: GetHarmonyMethod(GetMethod<NewMovement_Start>(\"Postfix\")));\n harmonyTweaks.Patch(GetMethod<NewMovement>(\"GetHurt\"), transpiler: GetHarmonyMethod(GetMethod<NewMovement_GetHurt>(\"Transpiler\")));\n harmonyTweaks.Patch(GetMethod<HookArm>(\"FixedUpdate\"), transpiler: GetHarmonyMethod(GetMethod<HookArm_FixedUpdate>(\"Transpiler\")));", "score": 0.7687885761260986 }, { "filename": "Ultrapain/Plugin.cs", "retrieved_chunk": " harmonyTweaks.Patch(GetMethod<LeviathanHead>(\"ProjectileBurstStart\"), prefix: GetHarmonyMethod(GetMethod<Leviathan_ProjectileBurstStart>(\"Prefix\")));\n harmonyTweaks.Patch(GetMethod<LeviathanHead>(\"FixedUpdate\"), prefix: GetHarmonyMethod(GetMethod<Leviathan_FixedUpdate>(\"Prefix\")));\n if (ConfigManager.somethingWickedSpear.value)\n {\n harmonyTweaks.Patch(GetMethod<Wicked>(\"Start\"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_Start>(\"Postfix\")));\n harmonyTweaks.Patch(GetMethod<Wicked>(\"GetHit\"), postfix: GetHarmonyMethod(GetMethod<SomethingWicked_GetHit>(\"Postfix\")));\n }\n if(ConfigManager.somethingWickedSpawnOn43.value)\n {\n harmonyTweaks.Patch(GetMethod<ObjectActivator>(\"Activate\"), prefix: GetHarmonyMethod(GetMethod<ObjectActivator_Activate>(\"Prefix\")));", "score": 0.7679765224456787 }, { "filename": "Ultrapain/Plugin.cs", "retrieved_chunk": " harmonyTweaks.Patch(GetMethod<Mandalore>(\"FullerBurst\"), prefix: GetHarmonyMethod(GetMethod<DruidKnight_FullerBurst>(\"Prefix\")));\n harmonyTweaks.Patch(GetMethod<Drone>(\"Explode\"), prefix: GetHarmonyMethod(GetMethod<Drone_Explode>(\"Prefix\")), postfix: GetHarmonyMethod(GetMethod<Drone_Explode>(\"Postfix\")));\n }\n if (ConfigManager.fleshObamiumToggle.value)\n harmonyTweaks.Patch(GetMethod<FleshPrison>(\"Start\"), postfix: GetHarmonyMethod(GetMethod<FleshObamium_Start>(\"Postfix\")), prefix: GetHarmonyMethod(GetMethod<FleshObamium_Start>(\"Prefix\")));\n if (ConfigManager.obamapticonToggle.value)\n harmonyTweaks.Patch(GetMethod<FleshPrison>(\"Start\"), postfix: GetHarmonyMethod(GetMethod<Obamapticon_Start>(\"Postfix\")), prefix: GetHarmonyMethod(GetMethod<Obamapticon_Start>(\"Prefix\")));\n }\n public static bool methodsPatched = false;\n public static void ScenePatchCheck()", "score": 0.765912652015686 } ]
csharp
Shotgun __instance, int ___primaryCharge) {
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using GetSomeInput; using RosettaStone.Core; using RosettaStone.Core.Services; using SyslogLogging; using Watson.ORM; using WatsonWebserver; namespace RosettaStone.Server { public static class Program { #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously #region Public-Members #endregion #region Private-Members private static string _Header = "[RosettaStone] "; private static SerializationHelper _Serializer = new SerializationHelper(); private static string _SettingsFile = "./rosettastone.json"; private static Settings _Settings = new Settings(); private static bool _CreateDefaultRecords = false; private static LoggingModule _Logging = null; private static WatsonORM _ORM = null; private static
CodecMetadataService _Codecs = null;
private static VendorMetadataService _Vendors = null; private static WatsonWebserver.Server _Server = null; #endregion #region Entrypoint public static void Main(string[] args) { Welcome(); InitializeSettings(args); InitializeGlobals(); if (_Settings.EnableConsole) { RunConsoleWorker(); } else { EventWaitHandle waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset); bool waitHandleSignal = false; do { waitHandleSignal = waitHandle.WaitOne(1000); } while (!waitHandleSignal); } } #endregion #region Public-Methods #endregion #region Private-Methods private static void Welcome() { Console.WriteLine( Environment.NewLine + Constants.Logo + Constants.ProductName + Environment.NewLine); } private static void InitializeSettings(string[] args) { if (args != null && args.Length > 0) { foreach (string arg in args) { if (arg.StartsWith("--config=")) { _SettingsFile = arg.Substring(9); } else if (arg.Equals("--setup")) { _CreateDefaultRecords = true; } } } if (!File.Exists(_SettingsFile)) { Console.WriteLine("Settings file '" + _SettingsFile + "' does not exist, creating with defaults"); File.WriteAllBytes(_SettingsFile, Encoding.UTF8.GetBytes(_Serializer.SerializeJson(_Settings, true))); } else { _Settings = _Serializer.DeserializeJson<Settings>(File.ReadAllText(_SettingsFile)); Console.WriteLine("Loaded settings from file '" + _SettingsFile + "'"); } } private static void InitializeGlobals() { #region Logging Console.WriteLine("Initializing logging to " + _Settings.Logging.SyslogServerIp + ":" + _Settings.Logging.SyslogServerPort); _Logging = new LoggingModule( _Settings.Logging.SyslogServerIp, _Settings.Logging.SyslogServerPort, _Settings.EnableConsole); if (!String.IsNullOrEmpty(_Settings.Logging.LogDirectory) && !Directory.Exists(_Settings.Logging.LogDirectory)) { Directory.CreateDirectory(_Settings.Logging.LogDirectory); } if (!String.IsNullOrEmpty(_Settings.Logging.LogDirectory) && !String.IsNullOrEmpty(_Settings.Logging.LogFilename)) { _Settings.Logging.LogDirectory = _Settings.Logging.LogDirectory.Replace("\\", "/"); if (!_Settings.Logging.LogDirectory.EndsWith("/")) _Settings.Logging.LogDirectory += "/"; _Settings.Logging.LogFilename = _Settings.Logging.LogDirectory + _Settings.Logging.LogFilename; } if (!String.IsNullOrEmpty(_Settings.Logging.LogFilename)) { _Logging.Settings.FileLogging = FileLoggingMode.FileWithDate; _Logging.Settings.LogFilename = _Settings.Logging.LogFilename; } Console.WriteLine("Logging to file " + _Settings.Logging.LogFilename); #endregion #region ORM Console.WriteLine("Initializing database"); _ORM = new WatsonORM(_Settings.Database); _ORM.InitializeDatabase(); _ORM.InitializeTables(new List<Type> { typeof(CodecMetadata), typeof(VendorMetadata) }); #endregion #region Services _Codecs = new CodecMetadataService(_Logging, _ORM); _Vendors = new VendorMetadataService(_Logging, _ORM); #endregion #region Default-Records if (_CreateDefaultRecords) { VendorMetadata vendor1 = new VendorMetadata { Key = "ACTGACTGACTGACTGACTGACTGACTGAC", Name = "Vendor 1", ContactInformation = "100 S Main St, San Jose, CA 95128", }; VendorMetadata vendor2 = new VendorMetadata { Key = "GTCAGTCAGTCAGTCAGTCAGTCAGTCAAC", Name = "Vendor 2", ContactInformation = "200 S Vine St, Campbell, CA 95008", }; VendorMetadata vendor3 = new VendorMetadata { Key = "CATGCATGCATGCATGCATGCATGCATGAC", Name = "Vendor 3", ContactInformation = "300 N 1st St, San Jose, CA 95128", }; vendor1 = _Vendors.Add(vendor1); Console.WriteLine("Creating vendor " + vendor1.Key + " " + vendor1.Name); vendor2 = _Vendors.Add(vendor2); Console.WriteLine("Creating vendor " + vendor2.Key + " " + vendor2.Name); vendor3 = _Vendors.Add(vendor3); Console.WriteLine("Creating vendor " + vendor3.Key + " " + vendor3.Name); CodecMetadata codec1 = new CodecMetadata { VendorGUID = vendor1.GUID, Key = "CAGTCAGTCAGTCAGTCAGTCAGTCAGTAC", Name = "My CODEC", Version = "v1.0.0", Uri = "https://codec1.com" }; CodecMetadata codec2 = new CodecMetadata { VendorGUID = vendor2.GUID, Key = "TCAGTCAGTCAGTCAGTCAGTCAGTCAGAC", Name = "My CODEC", Version = "v2.0.0", Uri = "https://codec1.com" }; CodecMetadata codec3 = new CodecMetadata { VendorGUID = vendor3.GUID, Key = "TAGCTAGCTAGCTAGCTAGCTAGCTAGCAC", Name = "My CODEC", Version = "v3.0.0", Uri = "https://codec1.com" }; codec1 = _Codecs.Add(codec1); Console.WriteLine("Creating CODEC " + codec1.Key + " " + codec1.Name); codec2 = _Codecs.Add(codec2); Console.WriteLine("Creating CODEC " + codec2.Key + " " + codec2.Name); codec3 = _Codecs.Add(codec3); Console.WriteLine("Creating CODEC " + codec3.Key + " " + codec3.Name); } #endregion #region Webserver _Server = new WatsonWebserver.Server( _Settings.Webserver.DnsHostname, _Settings.Webserver.Port, _Settings.Webserver.Ssl, DefaultRoute); _Server.Routes.PreRouting = PreRouting; _Server.Routes.PostRouting = PostRouting; _Server.Routes.Static.Add(HttpMethod.GET, "/", GetRootRoute); _Server.Routes.Static.Add(HttpMethod.GET, "/favicon.ico", GetFaviconRoute); _Server.Routes.Static.Add(HttpMethod.GET, "/v1.0/vendor", GetAllVendorsV1); _Server.Routes.Static.Add(HttpMethod.GET, "/v1.0/codec", GetAllCodecsV1); _Server.Routes.Parameter.Add(HttpMethod.GET, "/v1.0/vendor/{key}", GetVendorByKeyV1); _Server.Routes.Parameter.Add(HttpMethod.GET, "/v1.0/codec/{key}", GetCodecByKeyV1); _Server.Routes.Parameter.Add(HttpMethod.GET, "/v1.0/vendor/match/{key}", GetVendorMatchV1); _Server.Routes.Parameter.Add(HttpMethod.GET, "/v1.0/codec/match/{key}", GetCodecMatchV1); _Server.Routes.Parameter.Add(HttpMethod.GET, "/v1.0/vendor/matches/{key}", GetVendorMatchesV1); _Server.Routes.Parameter.Add(HttpMethod.GET, "/v1.0/codec/matches/{key}", GetCodecMatchesV1); _Server.Routes.Parameter.Add(HttpMethod.GET, "/v1.0/full/match/{key}", GetFullMatchV1); _Server.Routes.Parameter.Add(HttpMethod.GET, "/v1.0/full/matches/{key}", GetFullMatchesV1); _Server.Start(); Console.WriteLine("Webserver started on " + (_Settings.Webserver.Ssl ? "https://" : "http://") + _Settings.Webserver.DnsHostname + ":" + _Settings.Webserver.Port); #endregion } private static void RunConsoleWorker() { bool runForever = true; while (runForever) { string userInput = Inputty.GetString("Command [?/help]:", null, false); switch (userInput) { case "q": runForever = false; break; case "c": case "cls": Console.Clear(); break; case "?": Console.WriteLine(""); Console.WriteLine("Available commands:"); Console.WriteLine("q quit, exit the application"); Console.WriteLine("cls clear the screen"); Console.WriteLine("? help, this menu"); Console.WriteLine(""); break; } } } private static async Task<bool> PreRouting(HttpContext ctx) { ctx.Response.ContentType = Constants.JsonContentType; return false; } private static async Task PostRouting(HttpContext ctx) { ctx.Timestamp.End = DateTime.UtcNow; _Logging.Debug( _Header + ctx.Request.Source.IpAddress + ":" + ctx.Request.Source.Port + " " + ctx.Request.Method.ToString() + " " + ctx.Request.Url.RawWithQuery + ": " + ctx.Response.StatusCode + " " + "(" + ctx.Timestamp.TotalMs + "ms)"); } private static async Task DefaultRoute(HttpContext ctx) { ctx.Response.StatusCode = 400; await ctx.Response.Send(_Serializer.SerializeJson( new ApiErrorResponse() { Message = Constants.BadRequestError, StatusCode = 400, Context = "Unknown URL or HTTP method." }, true)); } private static async Task GetRootRoute(HttpContext ctx) { ctx.Response.StatusCode = 200; ctx.Response.ContentType = Constants.HtmlContentType; await ctx.Response.Send(Constants.RootHtml); return; } private static async Task GetFaviconRoute(HttpContext ctx) { ctx.Response.StatusCode = 200; await ctx.Response.Send(); return; } private static async Task GetAllVendorsV1(HttpContext ctx) { List<VendorMetadata> vendors = _Vendors.All(); ctx.Response.StatusCode = 200; await ctx.Response.Send(_Serializer.SerializeJson(vendors, true)); return; } private static async Task GetAllCodecsV1(HttpContext ctx) { List<CodecMetadata> codecs = _Codecs.All(); ctx.Response.StatusCode = 200; await ctx.Response.Send(_Serializer.SerializeJson(codecs, true)); return; } private static async Task GetVendorByKeyV1(HttpContext ctx) { VendorMetadata vendor = _Vendors.GetByKey(ctx.Request.Url.Parameters["key"]); if (vendor == null) { ctx.Response.StatusCode = 404; await ctx.Response.Send(_Serializer.SerializeJson( new ApiErrorResponse() { Message = Constants.NotFoundError, StatusCode = 404, Context = null }, true)); return; } else { ctx.Response.StatusCode = 200; await ctx.Response.Send(_Serializer.SerializeJson(vendor, true)); return; } } private static async Task GetCodecByKeyV1(HttpContext ctx) { CodecMetadata codec = _Codecs.GetByKey(ctx.Request.Url.Parameters["key"]); if (codec == null) { ctx.Response.StatusCode = 404; await ctx.Response.Send(_Serializer.SerializeJson( new ApiErrorResponse() { Message = Constants.NotFoundError, StatusCode = 404, Context = null }, true)); return; } else { ctx.Response.StatusCode = 200; await ctx.Response.Send(_Serializer.SerializeJson(codec, true)); return; } } private static async Task GetVendorMatchV1(HttpContext ctx) { VendorMetadata vendor = _Vendors.FindClosestMatch(ctx.Request.Url.Parameters["key"]); ctx.Response.StatusCode = 200; await ctx.Response.Send(_Serializer.SerializeJson(vendor, true)); return; } private static async Task GetCodecMatchV1(HttpContext ctx) { CodecMetadata codec = _Codecs.FindClosestMatch(ctx.Request.Url.Parameters["key"]); ctx.Response.StatusCode = 200; await ctx.Response.Send(_Serializer.SerializeJson(codec, true)); return; } private static async Task GetVendorMatchesV1(HttpContext ctx) { List<VendorMetadata> vendors = _Vendors.FindClosestMatches(ctx.Request.Url.Parameters["key"], GetMaxResults(ctx)); ctx.Response.StatusCode = 200; await ctx.Response.Send(_Serializer.SerializeJson(vendors, true)); return; } private static async Task GetCodecMatchesV1(HttpContext ctx) { List<CodecMetadata> codecs = _Codecs.FindClosestMatches(ctx.Request.Url.Parameters["key"], GetMaxResults(ctx)); ctx.Response.StatusCode = 200; await ctx.Response.Send(_Serializer.SerializeJson(codecs, true)); return; } private static async Task GetFullMatchV1(HttpContext ctx) { string key = ctx.Request.Url.Parameters["key"]; if (key.Length < 36) { _Logging.Warn(_Header + "supplied key is 35 characters or less"); ctx.Response.StatusCode = 404; await ctx.Response.Send(_Serializer.SerializeJson( new ApiErrorResponse() { Message = Constants.BadRequestError, StatusCode = 404, Context = "Supplied key must be greater than 35 characters." }, true)); return; } // left 35, right 35 string left = key.Substring(0, 35); string right = key.Substring((key.Length - 35), 35); ResultSet resultSet = new ResultSet { Key = key, Left = left, Right = right, Vendor = _Vendors.FindClosestMatch(left), Codec = _Codecs.FindClosestMatch(right) }; ctx.Response.StatusCode = 200; await ctx.Response.Send(_Serializer.SerializeJson(resultSet, true)); return; } private static async Task GetFullMatchesV1(HttpContext ctx) { string key = ctx.Request.Url.Parameters["key"]; if (key.Length < 36) { _Logging.Warn(_Header + "supplied key is 35 characters or less"); ctx.Response.StatusCode = 404; await ctx.Response.Send(_Serializer.SerializeJson( new ApiErrorResponse() { Message = Constants.BadRequestError, StatusCode = 404, Context = "Supplied key must be greater than 35 characters." }, true)); return; } // left 35, right 35 string left = key.Substring(0, 35); string right = key.Substring((key.Length - 35), 35); int maxResults = GetMaxResults(ctx); ResultSet resultSet = new ResultSet { Key = key, Left = left, Right = right, Vendors = _Vendors.FindClosestMatches(left, maxResults), Codecs = _Codecs.FindClosestMatches(right, maxResults) }; ctx.Response.StatusCode = 200; await ctx.Response.Send(_Serializer.SerializeJson(resultSet, true)); return; } private static int GetMaxResults(HttpContext ctx) { int maxResults = 10; string maxResultsStr = ctx.Request.Query.Elements.Get("results"); if (!String.IsNullOrEmpty(maxResultsStr)) maxResults = Convert.ToInt32(maxResultsStr); if (maxResults < 1) maxResults = 1; return maxResults; } #endregion #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously } }
src/RosettaStone.Server/Program.cs
jchristn-RosettaStone-898982c
[ { "filename": "src/RosettaStone.Core/Services/CodecMetadataService.cs", "retrieved_chunk": "namespace RosettaStone.Core.Services\n{\n public class CodecMetadataService\n {\n #region Public-Members\n #endregion\n #region Private-Members\n private LoggingModule _Logging = null;\n private WatsonORM _ORM = null;\n #endregion", "score": 0.8701079487800598 }, { "filename": "src/RosettaStone.Core/Settings.cs", "retrieved_chunk": " #region Public-Members\n public bool EnableConsole { get; set; } = true;\n public WebserverSettings Webserver { get; set; } = new WebserverSettings();\n public LoggingSettings Logging { get; set; } = new LoggingSettings();\n public DatabaseSettings Database { get; set; } = new DatabaseSettings(\"./rosettastone.db\");\n #endregion\n #region Private-Members\n #endregion\n #region Constructors-and-Factories\n public Settings()", "score": 0.8650405406951904 }, { "filename": "src/RosettaStone.Core/Services/VendorMetadataService.cs", "retrieved_chunk": "{\n public class VendorMetadataService\n {\n #region Public-Members\n #endregion\n #region Private-Members\n private LoggingModule _Logging = null;\n private WatsonORM _ORM = null;\n #endregion\n #region Constructors-and-Factories", "score": 0.8580598831176758 }, { "filename": "src/RosettaStone.Core/CodecMetadata.cs", "retrieved_chunk": " public int? EditDistance { get; set; } = null;\n #endregion\n #region Private-Members\n #endregion\n #region Constructors-and-Factories\n public CodecMetadata()\n {\n }\n public CodecMetadata(string key, string name, string version, string uri)\n {", "score": 0.8201574087142944 }, { "filename": "src/RosettaStone.Core/Services/CodecMetadataService.cs", "retrieved_chunk": " #region Constructors-and-Factories\n public CodecMetadataService(LoggingModule logging, WatsonORM orm)\n {\n _Logging = logging ?? throw new ArgumentNullException(nameof(logging));\n _ORM = orm ?? throw new ArgumentNullException(nameof(orm));\n }\n #endregion\n #region Public-Methods\n public List<CodecMetadata> All()\n {", "score": 0.8196997046470642 } ]
csharp
CodecMetadataService _Codecs = null;
using Microsoft.Extensions.DependencyInjection; using Microsoft.JSInterop; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static System.Runtime.InteropServices.JavaScript.JSType; namespace Magic.IndexedDb { public class EncryptionFactory: IEncryptionFactory { readonly IJSRuntime _jsRuntime; readonly
IndexedDbManager _indexDbManager;
public EncryptionFactory(IJSRuntime jsRuntime, IndexedDbManager indexDbManager) { _jsRuntime = jsRuntime; _indexDbManager = indexDbManager; } public async Task<string> Encrypt(string data, string key) { var mod = await _indexDbManager.GetModule(_jsRuntime); string encryptedData = await mod.InvokeAsync<string>("encryptString", new[] { data, key }); return encryptedData; } public async Task<string> Decrypt(string encryptedData, string key) { var mod = await _indexDbManager.GetModule(_jsRuntime); string decryptedData = await mod.InvokeAsync<string>("decryptString", new[] { encryptedData, key }); return decryptedData; } } }
Magic.IndexedDb/Factories/EncryptionFactory.cs
magiccodingman-Magic.IndexedDb-a279d6d
[ { "filename": "Magic.IndexedDb/Models/JsSettings.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Magic.IndexedDb.Models\n{\n public class JsSettings\n {\n public double Timeout { get; set; } = 100000;", "score": 0.8525839447975159 }, { "filename": "Magic.IndexedDb/Models/JsResponse.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Magic.IndexedDb.Models\n{\n public class JsResponse<T>\n {\n public JsResponse(T data, bool success, string message)", "score": 0.8519476056098938 }, { "filename": "Magic.IndexedDb/Models/IndexFilterValue.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Magic.IndexedDb.Models\n{\n public class IndexFilterValue\n {\n public IndexFilterValue(string indexName, object filterValue)", "score": 0.8506341576576233 }, { "filename": "Magic.IndexedDb/Factories/MagicDbFactory.cs", "retrieved_chunk": "using System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Collections.Generic;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.JSInterop;\nnamespace Magic.IndexedDb\n{\n public class MagicDbFactory : IMagicDbFactory\n {", "score": 0.8499524593353271 }, { "filename": "Magic.IndexedDb/Models/BlazorEvent.cs", "retrieved_chunk": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nnamespace Magic.IndexedDb\n{\n public class BlazorDbEvent\n {\n public Guid Transaction { get; set; }", "score": 0.8447321653366089 } ]
csharp
IndexedDbManager _indexDbManager;
using System.Collections; using System.Collections.Generic; using UnityEngine; using QuestSystem.SaveSystem; using System.Linq; namespace QuestSystem { [CreateAssetMenu(fileName = "New Quest", menuName = "QuestSystem/QuestLog")] [System.Serializable] public class QuestLog : ScriptableObject { public List<
Quest> curentQuests = new List<Quest>();
public List<Quest> doneQuest = new List<Quest>(); public List<Quest> failedQuest = new List<Quest>(); public int businessDay; public bool IsCurrent(Quest q) => curentQuests.Contains(q); public bool IsDoned(Quest q) => doneQuest.Contains(q); public bool IsFailed(Quest q) => failedQuest.Contains(q); public void LoadUpdate(QuestLogSaveData qls) { //Coger el dia businessDay = qls.dia; //Actualizar currents curentQuests = new List<Quest>(); foreach (QuestSaveData qs in qls.currentQuestSave) { Quest q = Resources.Load(QuestConstants.MISIONS_NAME + "/" + qs.name + "/" + qs.name) as Quest; q.state = qs.states; q.AdvanceToCurrentNode(); q.nodeActual.nodeObjectives = qs.actualNodeData.objectives; curentQuests.Add(q); } //Done i failed add doneQuest = new List<Quest>(); foreach (QuestSaveData qs in qls.doneQuestSave) { Quest q = Resources.Load(QuestConstants.MISIONS_NAME + "/" + qs.name + "/" + qs.name) as Quest; doneQuest.Add(q); } failedQuest = new List<Quest>(); foreach (QuestSaveData qs in qls.failedQuestSave) { Quest q = Resources.Load(QuestConstants.MISIONS_NAME + "/" + qs.name + "/" + qs.name) as Quest; failedQuest.Add(q); } } public void RemoveQuest(Quest q) { if (IsCurrent(q)) curentQuests.Remove(q); else if (IsDoned(q)) doneQuest.Remove(q); else if (IsFailed(q)) failedQuest.Remove(q); } public void ResetAllQuest() { List<Quest> quests = curentQuests.Concat(doneQuest).Concat(failedQuest).ToList(); foreach (Quest q in quests) { q.Reset(); RemoveQuest(q); } } } }
Runtime/QuestLog.cs
lluispalerm-QuestSystem-cd836cc
[ { "filename": "Runtime/NodeQuest.cs", "retrieved_chunk": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nnamespace QuestSystem\n{\n [CreateAssetMenu(fileName = \"New NodeQuest\", menuName = \"QuestSystem/NodeQuest\")]\n [System.Serializable]\n public class NodeQuest : ScriptableObject\n {\n public List<NodeQuest> nextNode = new List<NodeQuest>();", "score": 0.9202605485916138 }, { "filename": "Runtime/Quest.cs", "retrieved_chunk": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEditor;\nnamespace QuestSystem\n{\n [CreateAssetMenu(fileName = \"New Quest\", menuName = \"QuestSystem/Quest\")]\n [System.Serializable]\n public class Quest : ScriptableObject\n {", "score": 0.9071110486984253 }, { "filename": "Runtime/QuestManager.cs", "retrieved_chunk": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEditor;\nusing QuestSystem.SaveSystem;\nnamespace QuestSystem\n{\n public class QuestManager\n {\n public QuestLog misionLog;", "score": 0.8264598846435547 }, { "filename": "Editor/CustomInspector/QuestObjectiveUpdaterEditor.cs", "retrieved_chunk": "using UnityEngine;\nusing UnityEditor;\nusing System;\nusing System.Collections.Generic;\nnamespace QuestSystem.QuestEditor\n{\n [CustomEditor(typeof(QuestObjectiveUpdater))]\n public class QuestObjectiveUpdaterEditor : Editor\n { \n private int selectedValue = 0;", "score": 0.8220970630645752 }, { "filename": "Runtime/QuestObjectiveUpdater.cs", "retrieved_chunk": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.Events;\nnamespace QuestSystem\n{\n public class QuestObjectiveUpdater : MonoBehaviour, IQuestInteraction\n {\n public Quest questToUpdate;\n [HideInInspector] public NodeQuest nodeToUpdate;", "score": 0.8217847347259521 } ]
csharp
Quest> curentQuests = new List<Quest>();
using System.Xml.Linq; using EnumsNET; using LibreDteDotNet.Common; using LibreDteDotNet.RestRequest.Help; using LibreDteDotNet.RestRequest.Infraestructure; using LibreDteDotNet.RestRequest.Interfaces; namespace LibreDteDotNet.RestRequest.Services { internal class FolioCafService : ComunEnum, IFolioCaf { public Dictionary<string, string> InputsText { get; set; } = new Dictionary<string, string>(); private readonly IRepositoryWeb repositoryWeb; private const string input = "input[type='text'],input[type='hidden']"; public FolioCafService(IRepositoryWeb repositoryWeb) { this.repositoryWeb = repositoryWeb; } public async Task<string> GetHistorial(string rut, string dv, TipoDoc tipodoc) { using HttpResponseMessage? msg = await repositoryWeb.Send( new HttpRequestMessage(HttpMethod.Post, Properties.Resources.UrlCafHistorial) { Content = new FormUrlEncodedContent( new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("RUT_EMP", rut), new KeyValuePair<string, string>("DV_EMP", dv), new KeyValuePair<string, string>("PAGINA", "1"), // PÁG. 2,3 ETC. new KeyValuePair<string, string>( "COD_DOCTO", ((int)tipodoc).ToString() ), } ) } )!; return await msg.Content.ReadAsStringAsync(); } public async Task<IFolioCaf> ReObtener( string rut, string dv, string cant, string dia, string mes, string year, string folioini, string foliofin, TipoDoc tipodoc ) { using HttpResponseMessage? msg = await repositoryWeb.Send( new HttpRequestMessage(HttpMethod.Post, Properties.Resources.UrlCafReobtiene) { Content = new FormUrlEncodedContent( new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("RUT_EMP", rut), new KeyValuePair<string, string>("DV_EMP", dv), new KeyValuePair<string, string>( "COD_DOCTO", ((int)tipodoc).ToString() ), new KeyValuePair<string, string>("FOLIO_INI", folioini), new KeyValuePair<string, string>("FOLIO_FIN", foliofin), new KeyValuePair<string, string>("CANT_DOCTOS", cant), new KeyValuePair<string, string>("DIA", dia), new KeyValuePair<string, string>("MES", mes), new KeyValuePair<string, string>("ANO", year), } ) } )!; InputsText = await HtmlParse.GetValuesFromTag(input, msg, CancellationToken.None); return this; } public async Task<IFolioCaf> Obtener( string rut, string dv, string cant, string cantmax, TipoDoc tipodoc ) { using HttpResponseMessage? msg = await repositoryWeb.Send( new HttpRequestMessage(HttpMethod.Post, Properties.Resources.UrlCafConfirma) { Content = new FormUrlEncodedContent( new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("RUT_EMP", rut), new KeyValuePair<string, string>("DV_EMP", dv), new KeyValuePair<string, string>("FOLIO_INICIAL", "0"), new KeyValuePair<string, string>( "COD_DOCTO", ((int)tipodoc).ToString() ), new KeyValuePair<string, string>("AFECTO_IVA", "S"), new KeyValuePair<string, string>("ANOTACION", "N"), new KeyValuePair<string, string>("CON_CREDITO", "1"), new KeyValuePair<string, string>("CON_AJUSTE", "0"), new KeyValuePair<string, string>("FACTOR", "1.00"), new KeyValuePair<string, string>("MAX_AUTOR", cantmax), new KeyValuePair<string, string>("ULT_TIMBRAJE", "1"), new KeyValuePair<string, string>("CON_HISTORIA", "0"), new KeyValuePair<string, string>("FOLIO_INICRE", ""), new KeyValuePair<string, string>("FOLIO_FINCRE", ""), new KeyValuePair<string, string>("FECHA_ANT", ""), new KeyValuePair<string, string>("ESTADO_TIMBRAJE", ""), new KeyValuePair<string, string>("CONTROL", ""), new KeyValuePair<string, string>("CANT_TIMBRAJES", ""), new KeyValuePair<string, string>("CANT_DOCTOS", cant), new KeyValuePair<string, string>("FOLIOS_DISP", "21") } ) } )!; InputsText = await HtmlParse.GetValuesFromTag(input, msg, CancellationToken.None); return this; } public async Task<XDocument> Descargar() { using HttpResponseMessage? msg = await repositoryWeb.Send( new HttpRequestMessage(HttpMethod.Post, Properties.Resources.UrlCafGeneraFile) { Content = new FormUrlEncodedContent( new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>( "RUT_EMP", InputsText.GetValueOrDefault("RUT_EMP")! ), new KeyValuePair<string, string>( "DV_EMP", InputsText.GetValueOrDefault("DV_EMP")! ), new KeyValuePair<string, string>( "COD_DOCTO", InputsText.GetValueOrDefault("COD_DOCTO")! ), new KeyValuePair<string, string>( "FOLIO_INI", InputsText.GetValueOrDefault("FOLIO_INI")! ), new KeyValuePair<string, string>( "FOLIO_FIN", InputsText.GetValueOrDefault("FOLIO_FIN")! ), new KeyValuePair<string, string>( "FECHA", $"{InputsText.GetValueOrDefault("FECHA")!}" ) } ) } )!; using StreamReader reader = new(await msg.Content.ReadAsStreamAsync()); return XDocument.Load(reader); } public async Task<
IFolioCaf> SetCookieCertificado() {
HttpStatCode = await repositoryWeb.Conectar(Properties.Resources.UrlBasePalena); return this; } public async Task<Dictionary<string, string>> GetRangoMax( string rut, string dv, TipoDoc tipodoc ) { using HttpResponseMessage? msg = await repositoryWeb.Send( new HttpRequestMessage(HttpMethod.Post, Properties.Resources.UrlCafMaxRango) { Content = new FormUrlEncodedContent( new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>( "AFECTO_IVA", tipodoc.AsString(EnumFormat.Description)! ), new KeyValuePair<string, string>("RUT_EMP", rut), new KeyValuePair<string, string>("DV_EMP", dv), new KeyValuePair<string, string>("COD_DOCTO", ((int)tipodoc).ToString()) } ) } )!; InputsText = await HtmlParse.GetValuesFromTag(input, msg, CancellationToken.None); return InputsText; } public async Task<IFolioCaf> Confirmar() { using HttpResponseMessage? msg = await repositoryWeb.Send( new HttpRequestMessage(HttpMethod.Post, Properties.Resources.UrlCafConfirmaFile) { Content = new FormUrlEncodedContent( new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>( "NOMUSU", InputsText.GetValueOrDefault("NOMUSU")! ), new KeyValuePair<string, string>( "CON_CREDITO", InputsText.GetValueOrDefault("CON_CREDITO")! ), new KeyValuePair<string, string>( "CON_AJUSTE", InputsText.GetValueOrDefault("CON_AJUSTE")! ), new KeyValuePair<string, string>( "FOLIOS_DISP", InputsText.GetValueOrDefault("FOLIOS_DISP")! ), new KeyValuePair<string, string>( "MAX_AUTOR", InputsText.GetValueOrDefault("MAX_AUTOR")! ), new KeyValuePair<string, string>( "ULT_TIMBRAJE", InputsText.GetValueOrDefault("ULT_TIMBRAJE")! ), new KeyValuePair<string, string>( "CON_HISTORIA", InputsText.GetValueOrDefault("CON_HISTORIA")! ), new KeyValuePair<string, string>( "CANT_TIMBRAJES", InputsText.GetValueOrDefault("CANT_TIMBRAJES")! ), new KeyValuePair<string, string>( "CON_AJUSTE", InputsText.GetValueOrDefault("CON_AJUSTE")! ), new KeyValuePair<string, string>( "FOLIO_INICRE", InputsText.GetValueOrDefault("FOLIO_INICRE")! ), new KeyValuePair<string, string>( "FOLIO_FINCRE", InputsText.GetValueOrDefault("FOLIO_FINCRE")! ), new KeyValuePair<string, string>( "FECHA_ANT", InputsText.GetValueOrDefault("FECHA_ANT")! ), new KeyValuePair<string, string>( "ESTADO_TIMBRAJE", InputsText.GetValueOrDefault("ESTADO_TIMBRAJE")! ), new KeyValuePair<string, string>( "CONTROL", InputsText.GetValueOrDefault("CONTROL")! ), new KeyValuePair<string, string>( "FOLIO_INI", InputsText.GetValueOrDefault("FOLIO_INI")! ), new KeyValuePair<string, string>( "FOLIO_FIN", InputsText.GetValueOrDefault("FOLIO_FIN")! ), new KeyValuePair<string, string>( "DIA", InputsText.GetValueOrDefault("DIA")! ), new KeyValuePair<string, string>( "MES", InputsText.GetValueOrDefault("MES")! ), new KeyValuePair<string, string>( "ANO", InputsText.GetValueOrDefault("ANO")! ), new KeyValuePair<string, string>( "HORA", InputsText.GetValueOrDefault("HORA")! ), new KeyValuePair<string, string>( "MINUTO", InputsText.GetValueOrDefault("MINUTO")! ), new KeyValuePair<string, string>( "RUT_EMP", InputsText.GetValueOrDefault("RUT_EMP")! ), new KeyValuePair<string, string>( "DV_EMP", InputsText.GetValueOrDefault("DV_EMP")! ), new KeyValuePair<string, string>( "COD_DOCTO", InputsText.GetValueOrDefault("COD_DOCTO")! ), new KeyValuePair<string, string>( "CANT_DOCTOS", InputsText.GetValueOrDefault("CANT_DOCTOS")! ) } ) } )!; InputsText = await HtmlParse.GetValuesFromTag(input, msg, CancellationToken.None); return this; } } }
LibreDteDotNet.RestRequest/Services/FolioCafService.cs
sergiokml-LibreDteDotNet.RestRequest-6843109
[ { "filename": "LibreDteDotNet.RestRequest/Services/BoletaService.cs", "retrieved_chunk": " new KeyValuePair<string, string>(\"AREA\", \"P\")\n }\n )\n }\n )!;\n return await msg.Content.ReadAsStringAsync();\n }\n public async Task<IBoleta> SetCookieCertificado()\n {\n HttpStatCode = await repositoryWeb.Conectar(Properties.Resources.UrlBasePalena);", "score": 0.8640791773796082 }, { "filename": "LibreDteDotNet.RestRequest/Services/ContribuyenteService.cs", "retrieved_chunk": " }\n )\n }\n )!;\n return await msg.Content.ReadAsStringAsync();\n }\n public async Task<IContribuyente> SetCookieCertificado()\n {\n HttpStatCode = await repositoryWeb.Conectar(Properties.Resources.UrlConsultaRut);\n return this;", "score": 0.8459699153900146 }, { "filename": "LibreDteDotNet.RestRequest/Services/DTEService.cs", "retrieved_chunk": " HttpMethod.Get,\n $\"{Properties.Resources.UrlEstadoDte}?{query}\"\n )\n )!;\n Dispose();\n return await msg.Content.ReadAsStringAsync();\n }\n public async Task<IDTE> SetCookieCertificado(string url)\n {\n HttpStatCode = await repositoryWeb.Conectar(url);", "score": 0.8447082042694092 }, { "filename": "LibreDteDotNet.RestRequest/Services/DTEService.cs", "retrieved_chunk": " MensajeError!.Add(e.Message);\n }\n }\n public async Task<IDTE> Validar<T>(string path)\n {\n PathFile = path;\n using FileStream stream = File.OpenRead(path);\n XDocument r = await XDocument.LoadAsync(\n stream,\n LoadOptions.None,", "score": 0.8422794938087463 }, { "filename": "LibreDteDotNet.RestRequest/Services/DTEService.cs", "retrieved_chunk": " );\n HttpResponseMessage response = await repositoryWeb.Send(request)!;\n using StreamReader reader =\n new(await response.EnsureSuccessStatusCode().Content.ReadAsStreamAsync());\n return EnvioDTEStatus(XDocument.Load(reader));\n }\n public async Task<string> Enviar2(string pathfile, string rutCompany, string DvCompany)\n {\n if (HttpStatCode != HttpStatusCode.OK)\n {", "score": 0.8365249633789062 } ]
csharp
IFolioCaf> SetCookieCertificado() {
using Octokit; using WebApi.Configurations; using WebApi.Helpers; using WebApi.Models; namespace WebApi.Services { public interface IGitHubService { Task<
GitHubIssueCollectionResponse> GetIssuesAsync(GitHubApiRequestHeaders headers, GitHubApiRequestQueries req);
Task<GitHubIssueItemResponse> GetIssueAsync(int id, GitHubApiRequestHeaders headers, GitHubApiRequestQueries req); Task<GitHubIssueItemSummaryResponse> GetIssueSummaryAsync(int id, GitHubApiRequestHeaders headers, GitHubApiRequestQueries req); } public class GitHubService : IGitHubService { private readonly GitHubSettings _settings; private readonly IOpenAIHelper _helper; public GitHubService(GitHubSettings settings, IOpenAIHelper helper) { this._settings = settings ?? throw new ArgumentNullException(nameof(settings)); this._helper = helper ?? throw new ArgumentNullException(nameof(helper)); } public async Task<GitHubIssueCollectionResponse> GetIssuesAsync(GitHubApiRequestHeaders headers, GitHubApiRequestQueries req) { var user = req.User; var repository = req.Repository; var github = this.GetGitHubClient(headers); var issues = await github.Issue.GetAllForRepository(user, repository); var res = new GitHubIssueCollectionResponse() { Items = issues.Select(p => new GitHubIssueItemResponse() { Id = p.Id, Number = p.Number, Title = p.Title, Body = p.Body, }) }; return res; } public async Task<GitHubIssueItemResponse> GetIssueAsync(int id, GitHubApiRequestHeaders headers, GitHubApiRequestQueries req) { var user = req.User; var repository = req.Repository; var github = this.GetGitHubClient(headers); var issue = await github.Issue.Get(user, repository, id); var res = new GitHubIssueItemResponse() { Id = issue.Id, Number = issue.Number, Title = issue.Title, Body = issue.Body, }; return res; } public async Task<GitHubIssueItemSummaryResponse> GetIssueSummaryAsync(int id, GitHubApiRequestHeaders headers, GitHubApiRequestQueries req) { var issue = await this.GetIssueAsync(id, headers, req); var prompt = issue.Body; var completion = await this._helper.GetChatCompletionAsync(prompt); var res = new GitHubIssueItemSummaryResponse() { Id = issue.Id, Number = issue.Number, Title = issue.Title, Body = issue.Body, Summary = completion.Completion, }; return res; } private IGitHubClient GetGitHubClient(GitHubApiRequestHeaders headers) { var accessToken = headers.GitHubToken; var credentials = new Credentials(accessToken, AuthenticationType.Bearer); var agent = this._settings.Agent.Replace(" ", "").Trim(); var github = new GitHubClient(new ProductHeaderValue(agent)) { Credentials = credentials }; return github; } } }
src/IssueSummaryApi/Services/GitHubService.cs
Azure-Samples-vs-apim-cuscon-powerfx-500a170
[ { "filename": "src/IssueSummaryApi/Helpers/OpenAIHelper.cs", "retrieved_chunk": "using Azure.AI.OpenAI;\nusing Azure;\nusing WebApi.Configurations;\nusing WebApi.Models;\nnamespace WebApi.Helpers\n{\n public interface IOpenAIHelper\n {\n Task<ChatCompletionResponse> GetChatCompletionAsync(string prompt);\n }", "score": 0.8295578956604004 }, { "filename": "src/IssueSummaryApi/Services/OpenAIService.cs", "retrieved_chunk": "using WebApi.Models;\nusing WebApi.Helpers;\nnamespace WebApi.Services\n{\n public interface IOpenAIService\n {\n Task<ChatCompletionResponse> GetChatCompletionAsync(string prompt);\n }\n public class OpenAIService : IOpenAIService\n {", "score": 0.8144779801368713 }, { "filename": "src/IssueSummaryApi/Controllers/GitHubController.cs", "retrieved_chunk": "using Microsoft.AspNetCore.Mvc;\nusing WebApi.Models;\nusing WebApi.Services;\nnamespace WebApi.Controllers\n{\n [Route(\"api/[controller]\")]\n [ApiController]\n public class GitHubController : ControllerBase\n {\n private readonly IValidationService _validation;", "score": 0.811811089515686 }, { "filename": "src/IssueSummaryApi/Services/ValidationService.cs", "retrieved_chunk": "using Microsoft.AspNetCore.Mvc;\nusing WebApi.Configurations;\nusing WebApi.Extensions;\nusing WebApi.Models;\nnamespace WebApi.Services\n{\n public interface IValidationService\n {\n HeaderValidationResult<T> ValidateHeaders<T>(IHeaderDictionary requestHeaders) where T : ApiRequestHeaders;\n QueryValidationResult<T> ValidateQueries<T>(T requestQueries) where T : ApiRequestQueries;", "score": 0.7969998121261597 }, { "filename": "src/IssueSummaryApi/Models/GitHubApiRequestHeaders.cs", "retrieved_chunk": "using System.Text.Json.Serialization;\nnamespace WebApi.Models\n{\n public class GitHubApiRequestHeaders : ApiRequestHeaders\n {\n [JsonPropertyName(\"x-github-token\")]\n public virtual string? GitHubToken { get; set; }\n }\n}", "score": 0.7898687124252319 } ]
csharp
GitHubIssueCollectionResponse> GetIssuesAsync(GitHubApiRequestHeaders headers, GitHubApiRequestQueries req);
// <copyright file="Loading.cs" company="algernon (K. Algernon A. Sheppard)"> // Copyright (c) algernon (K. Algernon A. Sheppard). All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. // </copyright> namespace LineToolMod { using System.Collections.Generic; using AlgernonCommons.Patching; using ICities; /// <summary> /// Main loading class: the mod runs from here. /// </summary> public sealed class Loading : PatcherLoadingBase<
OptionsPanel, Patcher> {
/// <summary> /// Gets a list of permitted loading modes. /// </summary> protected override List<AppMode> PermittedModes => new List<AppMode> { AppMode.Game, AppMode.MapEditor, AppMode.AssetEditor, AppMode.ScenarioEditor }; /// <summary> /// Performs any actions upon successful creation of the mod. /// E.g. Can be used to patch any other mods. /// </summary> /// <param name="loading">Loading mode (e.g. game or editor).</param> protected override void CreatedActions(ILoading loading) { base.CreatedActions(loading); // Patch Find it. PatcherManager<Patcher>.Instance.PatchFindIt(); } /// <summary> /// Performs any actions upon successful level loading completion. /// </summary> /// <param name="mode">Loading mode (e.g. game, editor, scenario, etc.).</param> protected override void LoadedActions(LoadMode mode) { base.LoadedActions(mode); // Set up line tool. ToolsModifierControl.toolController.gameObject.AddComponent<LineTool>(); } } }
Code/Loading.cs
algernon-A-LineTool-f63b447
[ { "filename": "Code/Mod.cs", "retrieved_chunk": " using ICities;\n /// <summary>\n /// The base mod class for instantiation by the game.\n /// </summary>\n public sealed class Mod : PatcherMod<OptionsPanel, Patcher>, IUserMod\n {\n /// <summary>\n /// Gets the mod's base display name (name only).\n /// </summary>\n public override string BaseName => \"Line Tool\";", "score": 0.8891329765319824 }, { "filename": "Code/Patches/Patcher.cs", "retrieved_chunk": " using HarmonyLib;\n /// <summary>\n /// Class to manage the mod's Harmony patches.\n /// </summary>\n public sealed class Patcher : PatcherBase\n {\n /// <summary>\n /// Applies patches to Find It for prefab selection management.\n /// </summary>\n internal void PatchFindIt()", "score": 0.8839555978775024 }, { "filename": "Code/ConflictDetection.cs", "retrieved_chunk": " using AlgernonCommons.Translation;\n using ColossalFramework.Plugins;\n using ColossalFramework.UI;\n /// <summary>\n /// Mod conflict detection.\n /// </summary>\n internal sealed class ConflictDetection\n {\n // List of conflicting mods.\n private List<string> _conflictingModNames;", "score": 0.8580012917518616 }, { "filename": "Code/Tool/LineTool.cs", "retrieved_chunk": " using ColossalFramework;\n using ColossalFramework.Math;\n using ColossalFramework.UI;\n using HarmonyLib;\n using LineToolMod.Modes;\n using UnityEngine;\n using TreeInstance = global::TreeInstance;\n /// <summary>\n /// The line tool itslef.\n /// </summary>", "score": 0.8501009941101074 }, { "filename": "Code/Patches/PanelPatches.cs", "retrieved_chunk": " using HarmonyLib;\n /// <summary>\n /// Harmony patches for prefab selection panels to implement seamless prefab selection when line tool is active.\n /// </summary>\n [HarmonyPatch]\n [System.Diagnostics.CodeAnalysis.SuppressMessage(\"StyleCop.CSharp.NamingRules\", \"SA1313:Parameter names should begin with lower-case letter\", Justification = \"Harmony\")]\n internal static class PanelPatches\n {\n /// <summary>\n /// Determines list of target methods to patch.", "score": 0.8277809023857117 } ]
csharp
OptionsPanel, Patcher> {
using JdeJabali.JXLDataTableExtractor.Configuration; using JdeJabali.JXLDataTableExtractor.DataExtraction; using JdeJabali.JXLDataTableExtractor.Exceptions; using JdeJabali.JXLDataTableExtractor.JXLExtractedData; using System; using System.Collections.Generic; using System.Data; using System.Linq; namespace JdeJabali.JXLDataTableExtractor { public class DataTableExtractor : IDataTableExtractorConfiguration, IDataTableExtractorWorkbookConfiguration, IDataTableExtractorSearchConfiguration, IDataTableExtractorWorksheetConfiguration { private bool _readAllWorksheets; private int _searchLimitRow; private int _searchLimitColumn; private readonly List<string> _workbooks = new List<string>(); private readonly List<int> _worksheetIndexes = new List<int>(); private readonly List<string> _worksheets = new List<string>(); private readonly List<HeaderToSearch> _headersToSearch = new List<HeaderToSearch>(); private
HeaderToSearch _headerToSearch;
private DataReader _reader; private DataTableExtractor() { } public static IDataTableExtractorConfiguration Configure() { return new DataTableExtractor(); } public IDataTableExtractorWorkbookConfiguration Workbook(string workbook) { if (string.IsNullOrEmpty(workbook)) { throw new ArgumentException($"{nameof(workbook)} cannot be null or empty."); } // You can't add more than one workbook anyway, so there is no need to check for duplicates. // This would imply that there is a configuration for each workbook. _workbooks.Add(workbook); return this; } public IDataTableExtractorWorkbookConfiguration Workbooks(string[] workbooks) { if (workbooks is null) { throw new ArgumentNullException($"{nameof(workbooks)} cannot be null."); } foreach (string workbook in workbooks) { if (_workbooks.Contains(workbook)) { throw new DuplicateWorkbookException("Cannot search for more than one workbook with the same name: " + $@"""{workbook}""."); } _workbooks.Add(workbook); } return this; } public IDataTableExtractorSearchConfiguration SearchLimits(int searchLimitRow, int searchLimitColumn) { _searchLimitRow = searchLimitRow; _searchLimitColumn = searchLimitColumn; return this; } public IDataTableExtractorSearchConfiguration Worksheet(int worksheetIndex) { if (worksheetIndex < 0) { throw new ArgumentException($"{nameof(worksheetIndex)} cannot be less than zero."); } if (_worksheetIndexes.Contains(worksheetIndex)) { throw new ArgumentException("Cannot search for more than one worksheet with the same name: " + $@"""{worksheetIndex}""."); } _worksheetIndexes.Add(worksheetIndex); return this; } public IDataTableExtractorSearchConfiguration Worksheets(int[] worksheetIndexes) { if (worksheetIndexes is null) { throw new ArgumentException($"{nameof(worksheetIndexes)} cannot be null or empty."); } _worksheetIndexes.AddRange(worksheetIndexes); return this; } public IDataTableExtractorSearchConfiguration Worksheet(string worksheet) { if (string.IsNullOrEmpty(worksheet)) { throw new ArgumentException($"{nameof(worksheet)} cannot be null or empty."); } if (_worksheets.Contains(worksheet)) { throw new ArgumentException("Cannot search for more than one worksheet with the same name: " + $@"""{worksheet}""."); } _worksheets.Add(worksheet); return this; } public IDataTableExtractorSearchConfiguration Worksheets(string[] worksheets) { if (worksheets is null) { throw new ArgumentException($"{nameof(worksheets)} cannot be null or empty."); } _worksheets.AddRange(worksheets); return this; } public IDataTableExtractorWorksheetConfiguration ReadOnlyTheIndicatedSheets() { _readAllWorksheets = false; if (_worksheetIndexes.Count == 0 && _worksheets.Count == 0) { throw new InvalidOperationException("No worksheets selected."); } return this; } public IDataTableExtractorWorksheetConfiguration ReadAllWorksheets() { _readAllWorksheets = true; return this; } IDataTableExtractorWorksheetConfiguration IDataTableColumnsToSearch.ColumnHeader(string columnHeader) { if (string.IsNullOrEmpty(columnHeader)) { throw new ArgumentException($"{nameof(columnHeader)} cannot be null or empty."); } if (_headersToSearch.FirstOrDefault(h => h.ColumnHeaderName == columnHeader) != null) { throw new DuplicateColumnException("Cannot search for more than one column header with the same name: " + $@"""{columnHeader}""."); } _headerToSearch = new HeaderToSearch() { ColumnHeaderName = columnHeader, }; _headersToSearch.Add(_headerToSearch); return this; } IDataTableExtractorWorksheetConfiguration IDataTableColumnsToSearch.ColumnIndex(int columnIndex) { if (columnIndex < 0) { throw new ArgumentException($"{nameof(columnIndex)} cannot be less than zero."); } if (_headersToSearch.FirstOrDefault(h => h.ColumnIndex == columnIndex) != null) { throw new DuplicateColumnException("Cannot search for more than one column with the same index: " + $@"""{columnIndex}""."); } _headerToSearch = new HeaderToSearch() { ColumnIndex = columnIndex, }; _headersToSearch.Add(_headerToSearch); return this; } IDataTableExtractorWorksheetConfiguration IDataTableColumnsToSearch.CustomColumnHeaderMatch(Func<string, bool> conditional) { if (conditional is null) { throw new ArgumentNullException("Conditional cannot be null."); } _headerToSearch = new HeaderToSearch() { ConditionalToReadColumnHeader = conditional, }; _headersToSearch.Add(_headerToSearch); return this; } IDataTableExtractorWorksheetConfiguration IDataTableExtractorColumnConfiguration.ConditionToExtractRow(Func<string, bool> conditional) { if (conditional is null) { throw new ArgumentNullException("Conditional cannot be null."); } if (_headerToSearch is null) { throw new InvalidOperationException(nameof(_headerToSearch)); } _headerToSearch.ConditionalToReadRow = conditional; return this; } public List<JXLWorkbookData> GetWorkbooksData() { _reader = new DataReader() { Workbooks = _workbooks, SearchLimitRow = _searchLimitRow, SearchLimitColumn = _searchLimitColumn, WorksheetIndexes = _worksheetIndexes, Worksheets = _worksheets, ReadAllWorksheets = _readAllWorksheets, HeadersToSearch = _headersToSearch, }; return _reader.GetWorkbooksData(); } public List<JXLExtractedRow> GetExtractedRows() { _reader = new DataReader() { Workbooks = _workbooks, SearchLimitRow = _searchLimitRow, SearchLimitColumn = _searchLimitColumn, WorksheetIndexes = _worksheetIndexes, Worksheets = _worksheets, ReadAllWorksheets = _readAllWorksheets, HeadersToSearch = _headersToSearch, }; return _reader.GetJXLExtractedRows(); } public DataTable GetDataTable() { _reader = new DataReader() { Workbooks = _workbooks, SearchLimitRow = _searchLimitRow, SearchLimitColumn = _searchLimitColumn, WorksheetIndexes = _worksheetIndexes, Worksheets = _worksheets, ReadAllWorksheets = _readAllWorksheets, HeadersToSearch = _headersToSearch, }; return _reader.GetDataTable(); } } }
JdeJabali.JXLDataTableExtractor/DataTableExtractor.cs
JdeJabali-JXLDataTableExtractor-90a12f4
[ { "filename": "JdeJabali.JXLDataTableExtractor/DataExtraction/DataReader.cs", "retrieved_chunk": " {\n public List<string> Workbooks { get; set; } = new List<string>();\n public int SearchLimitRow { get; set; }\n public int SearchLimitColumn { get; set; }\n public List<int> WorksheetIndexes { get; set; } = new List<int>();\n public List<string> Worksheets { get; set; } = new List<string>();\n public bool ReadAllWorksheets { get; set; }\n public List<HeaderToSearch> HeadersToSearch { get; set; } = new List<HeaderToSearch>();\n public DataTable GetDataTable()\n {", "score": 0.7942739725112915 }, { "filename": "JdeJabali.JXLDataTableExtractor/DataExtraction/DataReader.cs", "retrieved_chunk": " }\n return extractedRow;\n }\n private void GetHeadersCoordinates(ExcelWorksheet sheet)\n {\n AddHeaderCoordsFromWorksheetColumnConfigurations(sheet);\n AddHeaderCoordsFromWorksheetColumnIndexesConfigurations();\n AddHeaderCoordsFromCustomColumnHeaderMatch(sheet);\n }\n private void AddHeaderCoordsFromWorksheetColumnConfigurations(ExcelWorksheet sheet)", "score": 0.7213826179504395 }, { "filename": "JdeJabali.JXLDataTableExtractor/DataExtraction/DataReader.cs", "retrieved_chunk": " headerToSearch.HeaderCoord = new HeaderCoord\n {\n Row = 1,\n Column = headerToSearch.ColumnIndex.Value,\n };\n }\n }\n private void AddHeaderCoordsFromCustomColumnHeaderMatch(ExcelWorksheet sheet)\n {\n List<HeaderToSearch> headersToSearch = HeadersToSearch", "score": 0.7156962156295776 }, { "filename": "JdeJabali.JXLDataTableExtractor/Configuration/IDataTableExtractorSearchConfiguration.cs", "retrieved_chunk": " /// <exception cref=\"ArgumentException\"/>\n IDataTableExtractorSearchConfiguration Worksheets(string[] worksheets);\n /// <summary>\n /// Read all the worksheets in the workbook(s) specified.\n /// </summary>\n /// <returns></returns>\n IDataTableExtractorWorksheetConfiguration ReadAllWorksheets();\n IDataTableExtractorWorksheetConfiguration ReadOnlyTheIndicatedSheets();\n }\n}", "score": 0.7099475264549255 }, { "filename": "JdeJabali.JXLDataTableExtractor/JXLExtractedData/JXLWorkbookData.cs", "retrieved_chunk": "using System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLWorkbookData\n {\n public string WorkbookPath { get; set; } = string.Empty;\n public string WorkbookName { get; set; } = string.Empty;\n public List<JXLWorksheetData> WorksheetsData { get; set; } = new List<JXLWorksheetData>();\n }\n}", "score": 0.7093048691749573 } ]
csharp
HeaderToSearch _headerToSearch;